react-glide-table 2.3.5 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,160 @@
1
+ // src/components/ui/table/features/inline-search/inlineSearch.ts
2
+ var INLINE_SEARCH_MAX_RESULTS = 1e3;
3
+ var INLINE_SEARCH_TARGET_TICK_MS = 10;
4
+ var INLINE_SEARCH_INITIAL_STRIDE = 10;
5
+ function escapeSearchRegex(value) {
6
+ return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
7
+ }
8
+ function createSearchRegex(query) {
9
+ const trimmed = query.trim();
10
+ if (!trimmed) return null;
11
+ return new RegExp(escapeSearchRegex(trimmed), "i");
12
+ }
13
+ function cellValueToSearchText(value) {
14
+ if (value == null) return void 0;
15
+ if (typeof value === "string") return value;
16
+ if (typeof value === "number" || typeof value === "boolean") {
17
+ return String(value);
18
+ }
19
+ if (Array.isArray(value)) {
20
+ return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
21
+ }
22
+ if (typeof value === "object") {
23
+ try {
24
+ return JSON.stringify(value);
25
+ } catch {
26
+ return String(value);
27
+ }
28
+ }
29
+ return String(value);
30
+ }
31
+ function formatSearchResultLabel(status) {
32
+ const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
33
+ if (status.selectedIndex >= 0 && status.results > 0) {
34
+ return `${status.selectedIndex + 1} of ${countLabel}`;
35
+ }
36
+ return countLabel;
37
+ }
38
+ function nextSearchIndex(selectedIndex, results) {
39
+ if (results <= 0) return -1;
40
+ if (selectedIndex < 0) return 0;
41
+ return (selectedIndex + 1) % results;
42
+ }
43
+ function previousSearchIndex(selectedIndex, results) {
44
+ if (results <= 0) return -1;
45
+ if (selectedIndex < 0) return results - 1;
46
+ let next = (selectedIndex - 1) % results;
47
+ if (next < 0) next += results;
48
+ return next;
49
+ }
50
+ function buildSearchMatchKey(colIndex, rowIndex) {
51
+ return `${colIndex}:${rowIndex}`;
52
+ }
53
+ function buildSearchMatchKeys(results) {
54
+ const keys = /* @__PURE__ */ new Set();
55
+ for (const [colIndex, rowIndex] of results) {
56
+ keys.add(buildSearchMatchKey(colIndex, rowIndex));
57
+ }
58
+ return keys;
59
+ }
60
+ function collectSearchMatchesInRange(options) {
61
+ const {
62
+ query,
63
+ startRow,
64
+ rowCount,
65
+ columnCount,
66
+ getCellValue,
67
+ maxResults = INLINE_SEARCH_MAX_RESULTS
68
+ } = options;
69
+ const regex = createSearchRegex(query);
70
+ if (!regex || rowCount <= 0 || columnCount <= 0) return [];
71
+ const matches = [];
72
+ for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
73
+ const rowIndex = startRow + rowOffset;
74
+ for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
75
+ const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
76
+ if (text !== void 0 && regex.test(text)) {
77
+ matches.push([colIndex, rowIndex]);
78
+ if (matches.length >= maxResults) {
79
+ return matches;
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return matches;
85
+ }
86
+ function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
87
+ const rounded = Math.max(elapsedMs, 1);
88
+ const scalar = targetMs / rounded;
89
+ return Math.max(1, Math.ceil(currentStride * scalar));
90
+ }
91
+ function buildFlatSearchCorpus(rows, getRowId) {
92
+ return rows.map((data, index) => ({
93
+ id: getRowId(data, index),
94
+ data,
95
+ ancestorToggleKeys: []
96
+ }));
97
+ }
98
+ function buildTreeSearchCorpus(visibleRows, options) {
99
+ const { toggleField, getRowId } = options;
100
+ const corpus = [];
101
+ const seen = /* @__PURE__ */ new Set();
102
+ const walk = (node, ancestorToggleKeys) => {
103
+ const id = getRowId(node, corpus.length);
104
+ if (seen.has(id)) return;
105
+ seen.add(id);
106
+ corpus.push({
107
+ id,
108
+ data: node,
109
+ ancestorToggleKeys
110
+ });
111
+ const children = node.children;
112
+ if (!Array.isArray(children) || children.length === 0) return;
113
+ const toggleValue = node[toggleField];
114
+ const toggleKey = toggleValue === null || toggleValue === void 0 ? "" : String(toggleValue);
115
+ const childAncestors = toggleKey.length > 0 ? [...ancestorToggleKeys, toggleKey] : ancestorToggleKeys;
116
+ for (const child of children) {
117
+ if (child && typeof child === "object") {
118
+ walk(child, childAncestors);
119
+ }
120
+ }
121
+ };
122
+ for (const row of visibleRows) {
123
+ const level = row.level;
124
+ if (level === 0 || level === void 0) {
125
+ walk(row, []);
126
+ }
127
+ }
128
+ for (const row of visibleRows) {
129
+ const id = getRowId(row, corpus.length);
130
+ if (seen.has(id)) continue;
131
+ walk(row, []);
132
+ }
133
+ return corpus;
134
+ }
135
+ function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
136
+ const keys = /* @__PURE__ */ new Set();
137
+ for (const [colIndex, corpusRowIndex] of results) {
138
+ const corpusRow = corpus[corpusRowIndex];
139
+ if (!corpusRow) continue;
140
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
141
+ if (visibleRowIndex === void 0) continue;
142
+ keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
143
+ }
144
+ return keys;
145
+ }
146
+ function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
147
+ const [colIndex, corpusRowIndex] = item;
148
+ const corpusRow = corpus[corpusRowIndex];
149
+ if (!corpusRow) return null;
150
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
151
+ if (visibleRowIndex === void 0) return null;
152
+ return [colIndex, visibleRowIndex];
153
+ }
154
+ function collectAncestorKeysToExpand(corpusRow, expandedRows) {
155
+ return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
156
+ }
157
+
1
158
  // src/core/labels.ts
2
159
  var DEFAULT_DATA_TABLE_LABELS = {
3
160
  empty: "No data",
@@ -11,7 +168,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
11
168
  searchResultHint: "Type to search",
12
169
  searchPrevious: "Previous result",
13
170
  searchNext: "Next result",
14
- searchClose: "Close search"
171
+ searchClose: "Close search",
172
+ searchResultCount: formatSearchResultLabel,
173
+ protectedCell: "protected",
174
+ paginationPrevious: "Previous page",
175
+ paginationNext: "Next page"
15
176
  };
16
177
  function resolveDataTableLabels(partial) {
17
178
  return {
@@ -37,7 +198,7 @@ import {
37
198
  import {
38
199
  useCallback as useCallback4,
39
200
  useEffect as useEffect5,
40
- useMemo as useMemo3,
201
+ useMemo as useMemo5,
41
202
  useRef as useRef5,
42
203
  useState as useState4
43
204
  } from "react";
@@ -60,7 +221,62 @@ var DATA_TABLE_COLUMN_MAX_SIZE = 800;
60
221
  var DATA_TABLE_COLUMN_REORDER_THRESHOLD = 4;
61
222
 
62
223
  // src/components/ui/table/features/cell-edit/useCellEdit.ts
63
- import { useCallback, useEffect, useRef, useState } from "react";
224
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
225
+
226
+ // src/components/ui/table/features/data-patch/dataPatch.ts
227
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
228
+ function getTreeSource(row) {
229
+ if (!row || typeof row !== "object") return void 0;
230
+ return row[TREE_SOURCE];
231
+ }
232
+ function getTreeRowKey(row) {
233
+ const source = getTreeSource(row);
234
+ if (!source) return void 0;
235
+ return `tree:${source.path.join(".")}`;
236
+ }
237
+ function setValueAtAccessor(record, accessorKey, value) {
238
+ if (!accessorKey.includes(".") || accessorKey in record) {
239
+ return { ...record, [accessorKey]: value };
240
+ }
241
+ const [head, ...rest] = accessorKey.split(".");
242
+ const current = record[head];
243
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
244
+ return {
245
+ ...record,
246
+ [head]: setValueAtAccessor(child, rest.join("."), value)
247
+ };
248
+ }
249
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
250
+ const [head, ...rest] = path;
251
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
252
+ const node = nodes[head];
253
+ if (!node || typeof node !== "object") return null;
254
+ const record = node;
255
+ let nextNode;
256
+ if (rest.length === 0) {
257
+ nextNode = setValueAtAccessor(record, accessorKey, value);
258
+ } else {
259
+ const children = record[childrenField];
260
+ if (!Array.isArray(children)) return null;
261
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
262
+ if (!nextChildren) return null;
263
+ nextNode = { ...record, [childrenField]: nextChildren };
264
+ }
265
+ const next = nodes.slice();
266
+ next[head] = nextNode;
267
+ return next;
268
+ }
269
+ function applyCellChangesToData(data, changes) {
270
+ let next = data;
271
+ for (const change of changes) {
272
+ const source = getTreeSource(change.original);
273
+ const path = source ? source.path : [change.index];
274
+ const childrenField = source?.childrenField ?? "";
275
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
276
+ if (patched) next = patched;
277
+ }
278
+ return next === data ? data.slice() : next;
279
+ }
64
280
 
65
281
  // src/components/ui/table/features/cell-edit/cellEdit.ts
66
282
  function getColumnAccessorKey(columnDef) {
@@ -69,7 +285,11 @@ function getColumnAccessorKey(columnDef) {
69
285
  }
70
286
  return columnDef.id;
71
287
  }
288
+ function isProtectedColumn(columnDef) {
289
+ return columnDef.meta?.kind === "protected";
290
+ }
72
291
  function isColumnEditable(columnDef) {
292
+ if (isProtectedColumn(columnDef)) return false;
73
293
  return Boolean(columnDef.meta?.editable);
74
294
  }
75
295
  function getColumnEditType(columnDef) {
@@ -102,10 +322,11 @@ function applyCellEdit(data, rows, rowIndex, colIndex, raw) {
102
322
  if (!accessorKey) return null;
103
323
  const parsed = parseCellEditValue(raw, getColumnEditType(columnDef));
104
324
  if (!parsed.ok) return null;
105
- const newData = data.map((row) => ({ ...row }));
106
- if (!newData[rowIndex]) return null;
107
- newData[rowIndex][accessorKey] = parsed.value;
108
- return newData;
325
+ const row = rows[rowIndex];
326
+ if (!row) return null;
327
+ return applyCellChangesToData(data, [
328
+ { original: row.original, index: row.index, accessorKey, value: parsed.value }
329
+ ]);
109
330
  }
110
331
 
111
332
  // src/components/ui/table/features/cell-render/commitCellValue.ts
@@ -129,12 +350,12 @@ function commitCellValue({
129
350
  if (!cell) return false;
130
351
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
131
352
  if (!accessorKey) return false;
132
- const dataIndex = row.index;
133
- if (dataIndex < 0 || dataIndex >= data.length) return false;
134
- const next = data.map((item) => ({ ...item }));
135
- const target = next[dataIndex];
136
- if (!target) return false;
137
- target[accessorKey] = value;
353
+ const next = applyCellChangesToData(data, [
354
+ { original: row.original, index: row.index, accessorKey, value }
355
+ ]);
356
+ if (next === data || next.every((item, index) => item === data[index])) {
357
+ return false;
358
+ }
138
359
  onDataChange?.(next);
139
360
  return true;
140
361
  }
@@ -146,19 +367,36 @@ function useCellEdit({
146
367
  onDataChange,
147
368
  onCellChange
148
369
  }) {
149
- const [editingCell, setEditingCell] = useState(null);
370
+ const [editingKey, setEditingKey] = useState(null);
150
371
  const [draftValue, setDraftValue] = useState("");
151
372
  const draftValueRef = useRef(draftValue);
152
- const editingCellRef = useRef(editingCell);
373
+ const [draftInvalid, setDraftInvalidState] = useState(false);
374
+ const draftInvalidRef = useRef(false);
375
+ const setDraftInvalid = useCallback((invalid) => {
376
+ draftInvalidRef.current = invalid;
377
+ setDraftInvalidState(invalid);
378
+ }, []);
153
379
  useEffect(() => {
154
380
  draftValueRef.current = draftValue;
155
381
  }, [draftValue]);
382
+ const editingCell = useMemo(
383
+ () => resolveEditingCell(rows, editingKey),
384
+ [rows, editingKey]
385
+ );
386
+ const editingCellRef = useRef(editingCell);
387
+ editingCellRef.current = editingCell;
156
388
  useEffect(() => {
157
- editingCellRef.current = editingCell;
158
- }, [editingCell]);
389
+ if (editingKey && !editingCell) {
390
+ setEditingKey(null);
391
+ setDraftValue("");
392
+ }
393
+ }, [editingCell, editingKey]);
159
394
  const cancelEdit = useCallback(() => {
160
- setEditingCell(null);
395
+ editingCellRef.current = null;
396
+ setEditingKey(null);
161
397
  setDraftValue("");
398
+ draftInvalidRef.current = false;
399
+ setDraftInvalidState(false);
162
400
  }, []);
163
401
  const commitEdit = useCallback(
164
402
  (raw) => {
@@ -178,6 +416,7 @@ function useCellEdit({
178
416
  cancelEdit();
179
417
  return true;
180
418
  }
419
+ if (draftInvalidRef.current) return false;
181
420
  const value = raw ?? draftValueRef.current;
182
421
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
183
422
  if (!parsed.ok) return false;
@@ -198,13 +437,15 @@ function useCellEdit({
198
437
  );
199
438
  const startEdit = useCallback(
200
439
  (rowIndex, colIndex) => {
201
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
202
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
440
+ const row = rows[rowIndex];
441
+ const cell = row?.getVisibleCells()[colIndex];
442
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
443
+ if (!isTextEditableValue(cell.getValue())) return;
203
444
  const current = editingCellRef.current;
204
445
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
205
446
  return;
206
447
  }
207
- setEditingCell({ rowIndex, colIndex });
448
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
208
449
  setDraftValue(getCellEditDraftValue(cell.getValue()));
209
450
  },
210
451
  [commitEdit, rows]
@@ -212,12 +453,55 @@ function useCellEdit({
212
453
  return {
213
454
  editingCell,
214
455
  draftValue,
456
+ draftInvalid,
457
+ setDraftInvalid,
215
458
  setDraftValue,
216
459
  startEdit,
217
460
  commitEdit,
218
461
  cancelEdit
219
462
  };
220
463
  }
464
+ function resolveEditingCell(rows, key) {
465
+ if (!key) return null;
466
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
467
+ if (rowIndex < 0) return null;
468
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
469
+ if (colIndex < 0) return null;
470
+ return { rowIndex, colIndex };
471
+ }
472
+ function isTextEditableValue(value) {
473
+ return value === null || value === void 0 || typeof value !== "object";
474
+ }
475
+
476
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
477
+ function formatObjectValue(value) {
478
+ const text = value.text ?? value.label ?? value.name ?? value.title;
479
+ if (text != null && text !== "") {
480
+ return formatCellValue(text);
481
+ }
482
+ try {
483
+ return JSON.stringify(value);
484
+ } catch {
485
+ return "";
486
+ }
487
+ }
488
+ function formatCellValue(value) {
489
+ if (value === null || value === void 0) return "";
490
+ if (value instanceof Date) {
491
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
492
+ }
493
+ if (Array.isArray(value)) {
494
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
495
+ }
496
+ if (typeof value === "object") {
497
+ return formatObjectValue(value);
498
+ }
499
+ if (typeof value === "string") return value;
500
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
501
+ return String(value);
502
+ }
503
+ return "";
504
+ }
221
505
 
222
506
  // src/components/ui/table/features/cell-render/builtins.tsx
223
507
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -241,8 +525,9 @@ function asDrilldownItems(value) {
241
525
  const record = item;
242
526
  const text = asString(record.text ?? record.label ?? "");
243
527
  if (!text) return [];
244
- const img = record.img ?? record.image;
245
- return [{ text, ...typeof img === "string" ? { img } : {} }];
528
+ const rawImg = record.img ?? record.image;
529
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
530
+ return [{ text, ...img ? { img } : {} }];
246
531
  }
247
532
  return [{ text: asString(item) }];
248
533
  });
@@ -303,6 +588,22 @@ function sanitizeUriHref(raw) {
303
588
  return href;
304
589
  }
305
590
  }
591
+ function sanitizeImageSrc(raw) {
592
+ const src = raw.trim();
593
+ if (!src) return null;
594
+ try {
595
+ const parsed = new URL(src);
596
+ const protocol = parsed.protocol.toLowerCase();
597
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
598
+ return src;
599
+ }
600
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
601
+ return null;
602
+ } catch {
603
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
604
+ return src;
605
+ }
606
+ }
306
607
  function UriCell({ value }) {
307
608
  const raw = asString(value);
308
609
  if (!raw) return null;
@@ -324,7 +625,10 @@ function UriCell({ value }) {
324
625
  );
325
626
  }
326
627
  function ImageCell({ value }) {
327
- const urls = asStringList(value);
628
+ const urls = asStringList(value).flatMap((url) => {
629
+ const src = sanitizeImageSrc(url);
630
+ return src ? [src] : [];
631
+ });
328
632
  if (urls.length === 0) return null;
329
633
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ jsx(
330
634
  "img",
@@ -377,8 +681,33 @@ function DrilldownCell({ value }) {
377
681
  function LoadingCell() {
378
682
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-loading", "aria-busy": "true" });
379
683
  }
380
- function ProtectedCell() {
381
- return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
684
+ function ProtectedCell({ cellProps }) {
685
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
686
+ return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
687
+ }
688
+ function RowSelectCell({ row, cellProps }) {
689
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
690
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
691
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
692
+ return /* @__PURE__ */ jsx(
693
+ "input",
694
+ {
695
+ type: "checkbox",
696
+ className: "data-table-cell-row-select",
697
+ checked,
698
+ disabled: !canSelect,
699
+ "aria-label": label,
700
+ onChange: () => {
701
+ if (canSelect) row.toggleSelected();
702
+ },
703
+ onClick: (event) => {
704
+ event.stopPropagation();
705
+ },
706
+ onMouseDown: (event) => {
707
+ event.stopPropagation();
708
+ }
709
+ }
710
+ );
382
711
  }
383
712
  function RowIdCell({ value }) {
384
713
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -394,7 +723,8 @@ var BUILTIN_RENDER_MAP = {
394
723
  drilldown: DrilldownCell,
395
724
  loading: LoadingCell,
396
725
  protected: ProtectedCell,
397
- "row-id": RowIdCell
726
+ "row-id": RowIdCell,
727
+ "row-select": RowSelectCell
398
728
  };
399
729
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
400
730
  kind,
@@ -428,760 +758,780 @@ function formatDefaultCellValue(value) {
428
758
  return String(value);
429
759
  }
430
760
  if (typeof value === "bigint") return value.toString();
431
- return String(value);
432
- }
433
-
434
- // src/components/ui/table/features/cell-render/withCellUpdate.ts
435
- function withCellUpdate(context, commitValue) {
436
- return {
437
- ...context,
438
- update: (next) => {
439
- commitValue(context.row.id, context.column.id, next);
440
- }
441
- };
761
+ return formatCellValue(value);
442
762
  }
443
763
 
444
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
445
- import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
764
+ // src/components/ui/table/features/cell-selection/copyData.ts
765
+ import { isValidElement } from "react";
446
766
 
447
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
448
- var activeOwner = null;
449
- var clearByOwner = /* @__PURE__ */ new Map();
450
- function createCellSelectionOwner() {
451
- return /* @__PURE__ */ Symbol("cell-selection-owner");
767
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
768
+ var lastSubtreeCopy = null;
769
+ function normalize(text) {
770
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
452
771
  }
453
- function registerCellSelectionOwner(owner, clearSelection) {
454
- clearByOwner.set(owner, clearSelection);
455
- return () => {
456
- clearByOwner.delete(owner);
457
- if (activeOwner === owner) {
458
- activeOwner = null;
459
- }
460
- };
772
+ function rememberSubtreeCopy(text) {
773
+ lastSubtreeCopy = normalize(text);
461
774
  }
462
- function claimCellSelectionOwner(owner) {
463
- if (activeOwner === owner) return;
464
- activeOwner = owner;
465
- for (const [id, clearSelection] of clearByOwner) {
466
- if (id !== owner) {
467
- clearSelection();
468
- }
469
- }
775
+ function isOwnSubtreeCopy(text) {
776
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
470
777
  }
471
- function isActiveCellSelectionOwner(owner) {
472
- return activeOwner === owner;
778
+
779
+ // src/components/ui/table/features/cell-selection/copyData.ts
780
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
781
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
782
+ function escapeSpreadsheetFormula(text) {
783
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
784
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
785
+ return `'${text}`;
473
786
  }
474
- function releaseCellSelectionOwner(owner) {
475
- if (activeOwner === owner) {
476
- activeOwner = null;
787
+ function isReactNodeIterable(node) {
788
+ return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
789
+ }
790
+ function getElementTypeName(type) {
791
+ if (typeof type === "string") return type;
792
+ if (typeof type === "function") {
793
+ const fn = type;
794
+ return fn.displayName || fn.name || "";
795
+ }
796
+ if (typeof type === "object" && type !== null) {
797
+ const component = type;
798
+ return component.displayName || component.render?.displayName || component.render?.name || "";
477
799
  }
800
+ return "";
478
801
  }
479
-
480
- // src/components/ui/table/features/cell-selection/cellSelection.ts
481
- var INITIAL_DRAG_STATE = {
482
- isSelecting: false,
483
- isFillDragging: false,
484
- start: null,
485
- end: null,
486
- fillAnchor: null,
487
- fillEnd: null
488
- };
489
- function getCellSelectionBounds(start, end) {
490
- if (!start || !end) return null;
491
- return {
492
- startRow: Math.min(start.row, end.row),
493
- endRow: Math.max(start.row, end.row),
494
- startCol: Math.min(start.col, end.col),
495
- endCol: Math.max(start.col, end.col)
496
- };
802
+ function isButtonReactElement(node) {
803
+ const typeName = getElementTypeName(node.type);
804
+ if (typeName === "button" || /button/i.test(typeName)) return true;
805
+ const props = node.props;
806
+ if (props.role === "button") return true;
807
+ if (typeName === "input" && props.type === "button") return true;
808
+ return false;
497
809
  }
498
- function getCellNavigationDelta(key) {
499
- switch (key) {
500
- case "ArrowUp":
501
- case "w":
502
- case "W":
503
- return { row: -1, col: 0 };
504
- case "ArrowDown":
505
- case "s":
506
- case "S":
507
- return { row: 1, col: 0 };
508
- case "ArrowLeft":
509
- case "a":
510
- case "A":
511
- return { row: 0, col: -1 };
512
- case "ArrowRight":
513
- case "d":
514
- case "D":
515
- return { row: 0, col: 1 };
516
- default:
517
- return null;
518
- }
810
+ function isImageReactElement(node) {
811
+ const typeName = getElementTypeName(node.type);
812
+ return typeName === "img" || typeName === "image" || /image/i.test(typeName);
519
813
  }
520
- function clampCellPosition(position, rowCount, columnCount) {
521
- const maxRow = Math.max(rowCount - 1, 0);
522
- const maxCol = Math.max(columnCount - 1, 0);
523
- return {
524
- row: Math.min(Math.max(position.row, 0), maxRow),
525
- col: Math.min(Math.max(position.col, 0), maxCol)
526
- };
814
+ var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
815
+ function isLikelyUrl(value) {
816
+ const trimmed = value.trim();
817
+ if (!trimmed) return false;
818
+ if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
819
+ if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
820
+ return false;
527
821
  }
528
- function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
529
- if (rowSpan <= 1) return void 0;
530
- const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
531
- if (!tbody) return void 0;
532
- const rows = tbody.querySelectorAll(":scope > tr");
533
- if (rows.length < rowIndex + rowSpan) return void 0;
534
- const heights = [];
535
- for (let i = 0; i < rowSpan; i++) {
536
- const row = rows[rowIndex + i];
537
- const height = row?.getBoundingClientRect().height ?? 0;
538
- if (height <= 0) return void 0;
539
- heights.push(height);
822
+ function pickUrlFromUnknown(value) {
823
+ if (typeof value === "string") {
824
+ return isLikelyUrl(value) ? value.trim() : "";
540
825
  }
541
- return heights;
542
- }
543
- function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
544
- if (rowSpan <= 1) return rowIndex;
545
- const rect = cellElement.getBoundingClientRect();
546
- const relativeY = clientY - rect.top;
547
- const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
548
- if (heights && heights.length === rowSpan) {
549
- let accrued = 0;
550
- for (let i = 0; i < rowSpan; i++) {
551
- accrued += heights[i];
552
- if (relativeY < accrued) {
553
- return rowIndex + i;
826
+ if (Array.isArray(value)) {
827
+ return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
828
+ }
829
+ if (value && typeof value === "object") {
830
+ const record = value;
831
+ for (const key of IMAGE_URL_PROP_KEYS) {
832
+ const candidate = record[key];
833
+ if (typeof candidate === "string" && candidate.trim()) {
834
+ return candidate.trim();
554
835
  }
555
836
  }
556
- return rowIndex + rowSpan - 1;
557
837
  }
558
- const rowHeight = rect.height / rowSpan;
559
- const offset = Math.min(
560
- Math.max(Math.floor(relativeY / rowHeight), 0),
561
- rowSpan - 1
562
- );
563
- return rowIndex + offset;
838
+ return "";
564
839
  }
565
- function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
566
- if (!bounds) return false;
567
- const cellEndRow = rowIndex + rowSpan - 1;
568
- return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
840
+ function imageElementText(node) {
841
+ const props = node.props;
842
+ for (const key of IMAGE_URL_PROP_KEYS) {
843
+ const candidate = props[key];
844
+ if (typeof candidate === "string" && candidate.trim()) {
845
+ return candidate.trim();
846
+ }
847
+ }
848
+ return "";
569
849
  }
570
- function getActiveSelectionBounds(dragState, selectionBounds) {
571
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
572
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
850
+ function reactNodeContainsImage(node) {
851
+ if (isValidElement(node)) {
852
+ if (isImageReactElement(node)) return true;
853
+ return reactNodeContainsImage(node.props.children);
573
854
  }
574
- return selectionBounds;
855
+ if (isReactNodeIterable(node)) {
856
+ for (const child of node) {
857
+ if (reactNodeContainsImage(child)) return true;
858
+ }
859
+ }
860
+ return false;
575
861
  }
576
- var SELECTION_EDGE_WIDTH_PX = 2;
577
- var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
578
- var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
579
- function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
580
- const clampedFrom = Math.max(fromRow, rowIndex);
581
- const clampedTo = Math.min(toRowExclusive, rowIndex + span);
582
- if (clampedTo <= clampedFrom) {
583
- return { offsetRatio: 0, lengthRatio: 0 };
862
+ function readImgUrl(img) {
863
+ const attr = img.getAttribute("src")?.trim() ?? "";
864
+ if (attr) return attr;
865
+ if (img instanceof HTMLImageElement) {
866
+ const current = img.currentSrc?.trim() ?? "";
867
+ if (current && current !== img.baseURI) return current;
584
868
  }
585
- if (!rowHeights || rowHeights.length !== span) {
586
- return {
587
- offsetRatio: (clampedFrom - rowIndex) / span,
588
- lengthRatio: (clampedTo - clampedFrom) / span
589
- };
869
+ return "";
870
+ }
871
+ function readDomImageUrls(rowIndex, colIndex, root) {
872
+ const scope = root ?? (typeof document === "undefined" ? null : document);
873
+ if (!scope) return "";
874
+ const cells = scope.querySelectorAll(
875
+ `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
876
+ );
877
+ for (const cell of cells) {
878
+ const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
879
+ const url = readImgUrl(img);
880
+ return url ? [url] : [];
881
+ });
882
+ if (urls.length > 0) return urls.join(", ");
590
883
  }
591
- const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
592
- let offsetPx = 0;
593
- for (let i = 0; i < clampedFrom - rowIndex; i++) {
594
- offsetPx += rowHeights[i] ?? 0;
884
+ return "";
885
+ }
886
+ function reactNodeToText(node) {
887
+ if (node == null || typeof node === "boolean") return "";
888
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
889
+ return String(node);
595
890
  }
596
- let lengthPx = 0;
597
- for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
598
- lengthPx += rowHeights[i] ?? 0;
891
+ if (isReactNodeIterable(node)) {
892
+ let text = "";
893
+ for (const child of node) {
894
+ text += reactNodeToText(child);
895
+ }
896
+ return text;
897
+ }
898
+ if (isValidElement(node)) {
899
+ if (isButtonReactElement(node)) return "";
900
+ const props = node.props;
901
+ const childText = reactNodeToText(props.children);
902
+ if (childText) return childText;
903
+ const fromImage = imageElementText(node);
904
+ if (fromImage) return fromImage;
905
+ if (isImageReactElement(node)) return "";
906
+ if (typeof props.alt === "string" && props.alt) return props.alt;
907
+ if (typeof props.title === "string" && props.title) return props.title;
908
+ return "";
599
909
  }
910
+ return "";
911
+ }
912
+ function quoteTsvCell(text) {
913
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
914
+ return `"${text.replace(/"/g, '""')}"`;
915
+ }
916
+ function sanitizeClipboardCell(text) {
917
+ return text.replace(/\s+/g, " ").trim();
918
+ }
919
+ function createCopyRenderRow(rowData, index) {
600
920
  return {
601
- offsetRatio: offsetPx / total,
602
- lengthRatio: lengthPx / total,
603
- offsetPx,
604
- lengthPx
921
+ id: getOriginalRowId(rowData) || String(index),
922
+ index,
923
+ original: rowData,
924
+ getIsCellDragSelected: () => false
605
925
  };
606
926
  }
607
- function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
608
- const cellEndRow = rowIndex + rowSpan - 1;
609
- const span = cellEndRow - rowIndex + 1;
610
- if (span <= 1) return [];
611
- const edges = [];
612
- const isNeighborSelected = (row, neighborCol) => {
613
- if (isVisuallySelectedAt) {
614
- return isVisuallySelectedAt(row, neighborCol);
615
- }
616
- return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
617
- };
618
- const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
619
- let runStart = null;
620
- for (let row = fromRow; row < toRowExclusive; row++) {
621
- if (!isNeighborSelected(row, neighborCol)) {
622
- if (runStart === null) runStart = row;
623
- continue;
624
- }
625
- if (runStart !== null) {
626
- const ratios = rowRangeToHeightRatios(
627
- rowIndex,
628
- span,
629
- runStart,
630
- row,
631
- rowHeights
632
- );
633
- if (ratios.lengthRatio > 0) {
634
- edges.push({ side, ...ratios });
635
- }
636
- runStart = null;
637
- }
638
- }
639
- if (runStart !== null) {
640
- const ratios = rowRangeToHeightRatios(
641
- rowIndex,
642
- span,
643
- runStart,
644
- toRowExclusive,
645
- rowHeights
646
- );
647
- if (ratios.lengthRatio > 0) {
648
- edges.push({ side, ...ratios });
649
- }
650
- }
651
- };
652
- const collectSide = (side, neighborCol) => {
653
- if (bounds.startRow > rowIndex) {
654
- pushUnselectedRuns(
655
- side,
656
- neighborCol,
657
- rowIndex,
658
- Math.min(bounds.startRow, cellEndRow + 1)
659
- );
660
- }
661
- if (bounds.endRow < cellEndRow) {
662
- pushUnselectedRuns(
663
- side,
664
- neighborCol,
665
- Math.max(bounds.endRow + 1, rowIndex),
666
- cellEndRow + 1
667
- );
668
- }
669
- };
670
- if (colIndex < bounds.endCol) {
671
- collectSide("right", colIndex + 1);
927
+ function buildVisibleRowLookup(visibleRows) {
928
+ const lookup = /* @__PURE__ */ new Map();
929
+ for (const row of visibleRows) {
930
+ lookup.set(row.original, row);
672
931
  }
673
- if (colIndex > bounds.startCol) {
674
- collectSide("left", colIndex - 1);
932
+ return lookup;
933
+ }
934
+ function resolveCopyColumnId(cell) {
935
+ if (cell.column.id) return cell.column.id;
936
+ const columnDef = cell.column.columnDef;
937
+ if (columnDef.id) return columnDef.id;
938
+ if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
939
+ return String(columnDef.accessorKey);
675
940
  }
676
- return edges;
941
+ return "";
677
942
  }
678
- function buildPartialEdgeGradient(edge) {
679
- const usePx = edge.offsetPx != null && edge.lengthPx != null;
680
- const startPct = edge.offsetRatio * 100;
681
- const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
682
- const startPx = edge.offsetPx ?? 0;
683
- const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
684
- const overlapPx = SELECTION_EDGE_WIDTH_PX;
685
- const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
686
- const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
687
- const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
688
- const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
689
- const xPos = edge.side === "left" ? "0" : "100%";
690
- const layers = [
691
- {
692
- image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
693
- size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
694
- position: `${xPos} 0`
695
- }
696
- ];
697
- if (isTopProtrusion || isBottomProtrusion) {
698
- const capTop = usePx ? isTopProtrusion ? `${Math.max(0, endPx - SELECTION_EDGE_WIDTH_PX)}px` : `${Math.max(0, startPx - SELECTION_EDGE_WIDTH_PX)}px` : isTopProtrusion ? `calc(${endPct}% - ${SELECTION_EDGE_WIDTH_PX}px)` : `calc(${startPct}% - ${SELECTION_EDGE_WIDTH_PX}px)`;
699
- layers.push({
700
- image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
701
- size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
702
- position: `${xPos} ${capTop}`
703
- });
943
+ function isPrimitiveCopyValue(value) {
944
+ return value == null || typeof value !== "object";
945
+ }
946
+ function extractRenderedCopyText(node, value, cellPosition, root) {
947
+ const rendered = sanitizeClipboardCell(reactNodeToText(node));
948
+ if (reactNodeContainsImage(node)) {
949
+ const fromDom = cellPosition != null ? sanitizeClipboardCell(
950
+ readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
951
+ ) : "";
952
+ if (fromDom) return fromDom;
953
+ if (rendered && isLikelyUrl(rendered)) return rendered;
954
+ return sanitizeClipboardCell(pickUrlFromUnknown(value));
704
955
  }
705
- return layers;
956
+ return rendered;
706
957
  }
707
- function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
708
- if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
709
- return void 0;
710
- const cellEndRow = rowIndex + rowSpan - 1;
711
- const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
712
- const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
713
- const isLeftEdge = colIndex === bounds.startCol;
714
- const isRightEdge = colIndex === bounds.endCol;
715
- const selectionContinuesBelow = cellEndRow < bounds.endRow;
716
- const stepEdges = getMergedCellStepEdges(
717
- rowIndex,
718
- colIndex,
719
- bounds,
720
- rowSpan,
721
- isVisuallySelectedAt,
722
- rowHeights
723
- );
724
- const shadows = [];
725
- const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
726
- if (hasFullPerimeter) {
727
- shadows.push(
728
- `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
729
- );
730
- } else {
731
- if (isTopEdge) {
732
- shadows.push(
733
- `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
734
- );
735
- }
736
- if (isBottomEdge) {
737
- shadows.push(
738
- `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
739
- );
740
- }
741
- if (isLeftEdge) {
742
- shadows.push(
743
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
744
- );
958
+ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
959
+ const meta = columnDef.meta;
960
+ const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
961
+ const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
962
+ const ctx = {
963
+ value,
964
+ row,
965
+ index: row.index,
966
+ columnId,
967
+ cellProps: meta?.cellProps,
968
+ update: () => {
745
969
  }
746
- if (isRightEdge) {
747
- shadows.push(
748
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
749
- );
970
+ };
971
+ const copyValue = meta?.copyValue;
972
+ if (typeof copyValue === "function") {
973
+ try {
974
+ return sanitizeClipboardCell(copyValue(ctx));
975
+ } catch {
976
+ return formatCellValue(value);
750
977
  }
751
978
  }
752
- const gradients = [];
753
- const sizes = [];
754
- const positions = [];
755
- for (const edge of stepEdges) {
756
- for (const partial of buildPartialEdgeGradient(edge)) {
757
- gradients.push(partial.image);
758
- sizes.push(partial.size);
759
- positions.push(partial.position);
760
- }
979
+ if (copyValue === "value") {
980
+ return formatCellValue(value);
761
981
  }
762
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
763
- return void 0;
982
+ const cellRender = meta?.cellRender;
983
+ if (typeof cellRender === "function") {
984
+ try {
985
+ const node = cellRender(ctx);
986
+ return extractRenderedCopyText(node, value, cellPosition, options?.root);
987
+ } catch {
988
+ return formatCellValue(value);
989
+ }
764
990
  }
765
- const style = {};
766
- if (shadows.length > 0) {
767
- style["--selection-edge-shadows"] = shadows.join(", ");
991
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
992
+ try {
993
+ const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
994
+ if (renderer) {
995
+ const node = renderer.render(ctx);
996
+ const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
997
+ if (rendered) return rendered;
998
+ }
999
+ } catch {
1000
+ return formatCellValue(value);
1001
+ }
768
1002
  }
769
- if (gradients.length > 0) {
770
- style["--selection-edge-gradients"] = gradients.join(", ");
771
- style["--selection-edge-sizes"] = sizes.join(", ");
772
- style["--selection-edge-positions"] = positions.join(", ");
1003
+ return formatCellValue(value);
1004
+ }
1005
+ function getNestedValue(row, path) {
1006
+ if (!path.includes(".")) return row[path];
1007
+ return path.split(".").reduce((current, key) => {
1008
+ if (current === null || current === void 0 || typeof current !== "object") {
1009
+ return void 0;
1010
+ }
1011
+ return current[key];
1012
+ }, row);
1013
+ }
1014
+ function readRowColumnValue(rowData, columnDef) {
1015
+ if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1016
+ return columnDef.accessorFn(rowData, 0);
773
1017
  }
774
- if (selectionContinuesBelow) {
775
- style.borderBottomColor = "var(--color-brand-surface)";
1018
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1019
+ return getNestedValue(rowData, String(columnDef.accessorKey));
776
1020
  }
777
- return style;
1021
+ return void 0;
778
1022
  }
779
- function hasCellSelectionEdges(style) {
780
- return Boolean(
781
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
782
- );
1023
+ function flattenSubtreeRows(row) {
1024
+ const children = row.children;
1025
+ if (!Array.isArray(children) || children.length === 0) return [];
1026
+ const result = [];
1027
+ const walk = (nodes) => {
1028
+ for (const node of nodes) {
1029
+ result.push(node);
1030
+ const nested = node.children;
1031
+ if (Array.isArray(nested) && nested.length > 0) {
1032
+ walk(nested);
1033
+ }
1034
+ }
1035
+ };
1036
+ walk(children);
1037
+ return result;
783
1038
  }
784
-
785
- // src/components/ui/table/features/cell-selection/copyData.ts
786
- import { isValidElement } from "react";
787
- function isReactNodeIterable(node) {
788
- return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
1039
+ function hasSubtree(row) {
1040
+ const children = row.children;
1041
+ return Array.isArray(children) && children.length > 0;
789
1042
  }
790
- function getElementTypeName(type) {
791
- if (typeof type === "string") return type;
792
- if (typeof type === "function") {
793
- const fn = type;
794
- return fn.displayName || fn.name || "";
1043
+ function getOriginalRowId(original) {
1044
+ return String(original.id ?? original.uniqueId ?? "");
1045
+ }
1046
+ function getRowDepth(original) {
1047
+ return typeof original.level === "number" ? original.level : 0;
1048
+ }
1049
+ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1050
+ const { startRow, endRow } = bounds;
1051
+ const result = [];
1052
+ if (mode !== "subtree") {
1053
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1054
+ const row = visibleRows[rowIndex];
1055
+ if (row) result.push({ row: row.original, depth: 0 });
1056
+ }
1057
+ return result;
795
1058
  }
796
- if (typeof type === "object" && type !== null) {
797
- const component = type;
798
- return component.displayName || component.render?.displayName || component.render?.name || "";
1059
+ const included = /* @__PURE__ */ new Set();
1060
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
1061
+ const appendSubtree = (node, depth) => {
1062
+ const children = node.children;
1063
+ if (!Array.isArray(children) || children.length === 0) return;
1064
+ for (const child of children) {
1065
+ const key = keyOf(child);
1066
+ if (!included.has(key)) {
1067
+ result.push({ row: child, depth });
1068
+ included.add(key);
1069
+ }
1070
+ appendSubtree(child, depth + 1);
1071
+ }
1072
+ };
1073
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1074
+ const row = visibleRows[rowIndex];
1075
+ if (!row) continue;
1076
+ const key = keyOf(row.original);
1077
+ if (included.has(key)) continue;
1078
+ const depth = getRowDepth(row.original);
1079
+ result.push({ row: row.original, depth });
1080
+ included.add(key);
1081
+ if (!hasSubtree(row.original)) continue;
1082
+ appendSubtree(row.original, depth + 1);
799
1083
  }
800
- return "";
1084
+ return result;
801
1085
  }
802
- function isButtonReactElement(node) {
803
- const typeName = getElementTypeName(node.type);
804
- if (typeName === "button" || /button/i.test(typeName)) return true;
805
- const props = node.props;
806
- if (props.role === "button") return true;
807
- if (typeName === "input" && props.type === "button") return true;
808
- return false;
1086
+ function collectCopyRows(visibleRows, bounds, mode = "visible") {
1087
+ return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
809
1088
  }
810
- function isImageReactElement(node) {
811
- const typeName = getElementTypeName(node.type);
812
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
1089
+ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1090
+ if (copyRows.length === 0) return "";
1091
+ const { startCol, endCol } = bounds;
1092
+ const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1093
+ if (columnCells.length === 0) return "";
1094
+ const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1095
+ const minDepth = Math.min(...resolvedDepths);
1096
+ const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1097
+ const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1098
+ const meta = templateCell.column.columnDef.meta;
1099
+ if (meta?.copyValue === "omit") return [];
1100
+ return [{ templateCell, colOffset }];
1101
+ });
1102
+ return copyRows.map((rowData, index) => {
1103
+ const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1104
+ const visibleRow = visibleRowByOriginal.get(rowData);
1105
+ const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1106
+ const line = copyableColumns.map(({ templateCell, colOffset }) => {
1107
+ const sourceCell = matchingCells?.[colOffset];
1108
+ const column = sourceCell?.column ?? templateCell.column;
1109
+ const text = formatCopyCellText(
1110
+ rowData,
1111
+ column.columnDef,
1112
+ resolveCopyColumnId(sourceCell ?? templateCell),
1113
+ visibleRow,
1114
+ visibleRow?.index ?? index,
1115
+ sourceCell,
1116
+ visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1117
+ options
1118
+ );
1119
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
1120
+ return quoteTsvCell(escaped);
1121
+ }).join(" ");
1122
+ return `${" ".repeat(relativeDepth)}${line}`;
1123
+ }).join("\n");
813
1124
  }
814
- var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
815
- function isLikelyUrl(value) {
816
- const trimmed = value.trim();
817
- if (!trimmed) return false;
818
- if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
819
- if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
820
- return false;
1125
+ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1126
+ const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1127
+ return serializeCopyRowsToTSV(
1128
+ entries.map((entry) => entry.row),
1129
+ visibleRows,
1130
+ bounds,
1131
+ entries.map((entry) => entry.depth),
1132
+ options
1133
+ );
821
1134
  }
822
- function pickUrlFromUnknown(value) {
823
- if (typeof value === "string") {
824
- return isLikelyUrl(value) ? value.trim() : "";
1135
+ function writeTextWithExecCommand(text) {
1136
+ if (typeof document === "undefined") return false;
1137
+ const textarea = document.createElement("textarea");
1138
+ textarea.value = text;
1139
+ textarea.setAttribute("readonly", "");
1140
+ textarea.style.position = "fixed";
1141
+ textarea.style.top = "0";
1142
+ textarea.style.left = "0";
1143
+ textarea.style.opacity = "0";
1144
+ textarea.style.pointerEvents = "none";
1145
+ document.body.appendChild(textarea);
1146
+ const previouslyFocused = document.activeElement;
1147
+ try {
1148
+ textarea.focus();
1149
+ textarea.select();
1150
+ return document.execCommand("copy");
1151
+ } catch {
1152
+ return false;
1153
+ } finally {
1154
+ document.body.removeChild(textarea);
1155
+ previouslyFocused?.focus?.();
825
1156
  }
826
- if (Array.isArray(value)) {
827
- return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
1157
+ }
1158
+ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1159
+ const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1160
+ if (!text) return false;
1161
+ if (mode === "subtree") rememberSubtreeCopy(text);
1162
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1163
+ return writeTextWithExecCommand(text);
828
1164
  }
829
- if (value && typeof value === "object") {
830
- const record = value;
831
- for (const key of IMAGE_URL_PROP_KEYS) {
832
- const candidate = record[key];
833
- if (typeof candidate === "string" && candidate.trim()) {
834
- return candidate.trim();
835
- }
836
- }
1165
+ try {
1166
+ await navigator.clipboard.writeText(text);
1167
+ return true;
1168
+ } catch {
1169
+ return false;
837
1170
  }
838
- return "";
839
1171
  }
840
- function imageElementText(node) {
841
- const props = node.props;
842
- for (const key of IMAGE_URL_PROP_KEYS) {
843
- const candidate = props[key];
844
- if (typeof candidate === "string" && candidate.trim()) {
845
- return candidate.trim();
1172
+
1173
+ // src/components/ui/table/features/cell-render/withCellUpdate.ts
1174
+ function withCellUpdate(context, commitValue) {
1175
+ return {
1176
+ ...context,
1177
+ update: (next) => {
1178
+ commitValue(context.row.id, context.column.id, next);
846
1179
  }
847
- }
848
- return "";
1180
+ };
849
1181
  }
850
- function reactNodeContainsImage(node) {
851
- if (isValidElement(node)) {
852
- if (isImageReactElement(node)) return true;
853
- return reactNodeContainsImage(node.props.children);
854
- }
855
- if (isReactNodeIterable(node)) {
856
- for (const child of node) {
857
- if (reactNodeContainsImage(child)) return true;
1182
+
1183
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
1184
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
1185
+
1186
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
1187
+ var activeOwner = null;
1188
+ var clearByOwner = /* @__PURE__ */ new Map();
1189
+ function createCellSelectionOwner() {
1190
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
1191
+ }
1192
+ function registerCellSelectionOwner(owner, clearSelection) {
1193
+ clearByOwner.set(owner, clearSelection);
1194
+ return () => {
1195
+ clearByOwner.delete(owner);
1196
+ if (activeOwner === owner) {
1197
+ activeOwner = null;
858
1198
  }
859
- }
860
- return false;
1199
+ };
861
1200
  }
862
- function readImgUrl(img) {
863
- const attr = img.getAttribute("src")?.trim() ?? "";
864
- if (attr) return attr;
865
- if (img instanceof HTMLImageElement) {
866
- const current = img.currentSrc?.trim() ?? "";
867
- if (current && current !== img.baseURI) return current;
1201
+ function claimCellSelectionOwner(owner) {
1202
+ if (activeOwner === owner) return;
1203
+ activeOwner = owner;
1204
+ for (const [id, clearSelection] of clearByOwner) {
1205
+ if (id !== owner) {
1206
+ clearSelection();
1207
+ }
868
1208
  }
869
- return "";
870
1209
  }
871
- function readDomImageUrls(rowIndex, colIndex, root) {
872
- const scope = root ?? (typeof document === "undefined" ? null : document);
873
- if (!scope) return "";
874
- const cells = scope.querySelectorAll(
875
- `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
876
- );
877
- for (const cell of cells) {
878
- const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
879
- const url = readImgUrl(img);
880
- return url ? [url] : [];
881
- });
882
- if (urls.length > 0) return urls.join(", ");
883
- }
884
- return "";
1210
+ function isActiveCellSelectionOwner(owner) {
1211
+ return activeOwner === owner;
885
1212
  }
886
- function reactNodeToText(node) {
887
- if (node == null || typeof node === "boolean") return "";
888
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
889
- return String(node);
890
- }
891
- if (isReactNodeIterable(node)) {
892
- let text = "";
893
- for (const child of node) {
894
- text += reactNodeToText(child);
895
- }
896
- return text;
897
- }
898
- if (isValidElement(node)) {
899
- if (isButtonReactElement(node)) return "";
900
- const props = node.props;
901
- const childText = reactNodeToText(props.children);
902
- if (childText) return childText;
903
- const fromImage = imageElementText(node);
904
- if (fromImage) return fromImage;
905
- if (isImageReactElement(node)) return "";
906
- if (typeof props.alt === "string" && props.alt) return props.alt;
907
- if (typeof props.title === "string" && props.title) return props.title;
908
- return "";
1213
+ function releaseCellSelectionOwner(owner) {
1214
+ if (activeOwner === owner) {
1215
+ activeOwner = null;
909
1216
  }
910
- return "";
911
- }
912
- function sanitizeClipboardCell(text) {
913
- return text.replace(/\s+/g, " ").trim();
914
1217
  }
915
- function createCopyRenderRow(rowData, index) {
1218
+
1219
+ // src/components/ui/table/features/cell-selection/cellSelection.ts
1220
+ var INITIAL_DRAG_STATE = {
1221
+ isSelecting: false,
1222
+ isFillDragging: false,
1223
+ start: null,
1224
+ end: null,
1225
+ fillAnchor: null,
1226
+ fillEnd: null
1227
+ };
1228
+ function getCellSelectionBounds(start, end) {
1229
+ if (!start || !end) return null;
916
1230
  return {
917
- id: getOriginalRowId(rowData) || String(index),
918
- index,
919
- original: rowData,
920
- getIsCellDragSelected: () => false
1231
+ startRow: Math.min(start.row, end.row),
1232
+ endRow: Math.max(start.row, end.row),
1233
+ startCol: Math.min(start.col, end.col),
1234
+ endCol: Math.max(start.col, end.col)
921
1235
  };
922
1236
  }
923
- function buildVisibleRowLookup(visibleRows) {
924
- const lookup = /* @__PURE__ */ new Map();
925
- for (const row of visibleRows) {
926
- lookup.set(row.original, row);
927
- }
928
- return lookup;
929
- }
930
- function resolveCopyColumnId(cell) {
931
- if (cell.column.id) return cell.column.id;
932
- const columnDef = cell.column.columnDef;
933
- if (columnDef.id) return columnDef.id;
934
- if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
935
- return String(columnDef.accessorKey);
1237
+ function getCellNavigationDelta(key) {
1238
+ switch (key) {
1239
+ case "ArrowUp":
1240
+ case "w":
1241
+ case "W":
1242
+ return { row: -1, col: 0 };
1243
+ case "ArrowDown":
1244
+ case "s":
1245
+ case "S":
1246
+ return { row: 1, col: 0 };
1247
+ case "ArrowLeft":
1248
+ case "a":
1249
+ case "A":
1250
+ return { row: 0, col: -1 };
1251
+ case "ArrowRight":
1252
+ case "d":
1253
+ case "D":
1254
+ return { row: 0, col: 1 };
1255
+ default:
1256
+ return null;
936
1257
  }
937
- return "";
938
1258
  }
939
- function isPrimitiveCopyValue(value) {
940
- return value == null || typeof value !== "object";
1259
+ function clampCellPosition(position, rowCount, columnCount) {
1260
+ const maxRow = Math.max(rowCount - 1, 0);
1261
+ const maxCol = Math.max(columnCount - 1, 0);
1262
+ return {
1263
+ row: Math.min(Math.max(position.row, 0), maxRow),
1264
+ col: Math.min(Math.max(position.col, 0), maxCol)
1265
+ };
941
1266
  }
942
- function extractRenderedCopyText(node, value, cellPosition, root) {
943
- const rendered = sanitizeClipboardCell(reactNodeToText(node));
944
- if (reactNodeContainsImage(node)) {
945
- const fromDom = cellPosition != null ? sanitizeClipboardCell(
946
- readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
947
- ) : "";
948
- if (fromDom) return fromDom;
949
- if (rendered && isLikelyUrl(rendered)) return rendered;
950
- return sanitizeClipboardCell(pickUrlFromUnknown(value));
1267
+ function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
1268
+ if (rowSpan <= 1) return void 0;
1269
+ const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
1270
+ if (!tbody) return void 0;
1271
+ const rows = tbody.querySelectorAll(":scope > tr");
1272
+ if (rows.length < rowIndex + rowSpan) return void 0;
1273
+ const heights = [];
1274
+ for (let i = 0; i < rowSpan; i++) {
1275
+ const row = rows[rowIndex + i];
1276
+ const height = row?.getBoundingClientRect().height ?? 0;
1277
+ if (height <= 0) return void 0;
1278
+ heights.push(height);
951
1279
  }
952
- return rendered;
1280
+ return heights;
953
1281
  }
954
- function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
955
- const meta = columnDef.meta;
956
- const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
957
- const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
958
- const ctx = {
959
- value,
960
- row,
961
- index: row.index,
962
- columnId,
963
- cellProps: meta?.cellProps,
964
- update: () => {
965
- }
966
- };
967
- const copyValue = meta?.copyValue;
968
- if (typeof copyValue === "function") {
969
- try {
970
- return sanitizeClipboardCell(copyValue(ctx));
971
- } catch {
972
- return formatCellValue(value);
973
- }
974
- }
975
- if (copyValue === "value") {
976
- return formatCellValue(value);
977
- }
978
- const cellRender = meta?.cellRender;
979
- if (typeof cellRender === "function") {
980
- try {
981
- const node = cellRender(ctx);
982
- return extractRenderedCopyText(node, value, cellPosition, options?.root);
983
- } catch {
984
- return formatCellValue(value);
985
- }
986
- }
987
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
988
- try {
989
- const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
990
- if (renderer) {
991
- const node = renderer.render(ctx);
992
- const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
993
- if (rendered) return rendered;
1282
+ function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
1283
+ if (rowSpan <= 1) return rowIndex;
1284
+ const rect = cellElement.getBoundingClientRect();
1285
+ const relativeY = clientY - rect.top;
1286
+ const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
1287
+ if (heights && heights.length === rowSpan) {
1288
+ let accrued = 0;
1289
+ for (let i = 0; i < rowSpan; i++) {
1290
+ accrued += heights[i];
1291
+ if (relativeY < accrued) {
1292
+ return rowIndex + i;
994
1293
  }
995
- } catch {
996
- return formatCellValue(value);
997
1294
  }
1295
+ return rowIndex + rowSpan - 1;
998
1296
  }
999
- return formatCellValue(value);
1297
+ const rowHeight = rect.height / rowSpan;
1298
+ const offset = Math.min(
1299
+ Math.max(Math.floor(relativeY / rowHeight), 0),
1300
+ rowSpan - 1
1301
+ );
1302
+ return rowIndex + offset;
1000
1303
  }
1001
- function formatPrimitive(value) {
1002
- if (value === null || value === void 0) return "";
1003
- if (typeof value === "string") return value;
1004
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1005
- return String(value);
1006
- }
1007
- return "";
1304
+ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
1305
+ if (!bounds) return false;
1306
+ const cellEndRow = rowIndex + rowSpan - 1;
1307
+ return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
1008
1308
  }
1009
- function formatObjectValue(value) {
1010
- const text = value.text ?? value.label ?? value.name ?? value.title;
1011
- if (text != null && text !== "") {
1012
- return formatCellValue(text);
1309
+ function resolveFillBounds(source, pointer) {
1310
+ const below = pointer.row - source.endRow;
1311
+ const above = source.startRow - pointer.row;
1312
+ const right = pointer.col - source.endCol;
1313
+ const left = source.startCol - pointer.col;
1314
+ const vertical = Math.max(below, above, 0);
1315
+ const horizontal = Math.max(right, left, 0);
1316
+ if (vertical === 0 && horizontal === 0) return { ...source };
1317
+ if (vertical >= horizontal) {
1318
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
1013
1319
  }
1014
- try {
1015
- return JSON.stringify(value);
1016
- } catch {
1017
- return "";
1320
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1321
+ }
1322
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1323
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1324
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1018
1325
  }
1326
+ return selectionBounds;
1019
1327
  }
1020
- function formatCellValue(value) {
1021
- if (value === null || value === void 0) return "";
1022
- if (Array.isArray(value)) {
1023
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
1328
+ var SELECTION_EDGE_WIDTH_PX = 2;
1329
+ var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
1330
+ var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
1331
+ function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
1332
+ const clampedFrom = Math.max(fromRow, rowIndex);
1333
+ const clampedTo = Math.min(toRowExclusive, rowIndex + span);
1334
+ if (clampedTo <= clampedFrom) {
1335
+ return { offsetRatio: 0, lengthRatio: 0 };
1024
1336
  }
1025
- if (typeof value === "object") {
1026
- return formatObjectValue(value);
1337
+ if (!rowHeights || rowHeights.length !== span) {
1338
+ return {
1339
+ offsetRatio: (clampedFrom - rowIndex) / span,
1340
+ lengthRatio: (clampedTo - clampedFrom) / span
1341
+ };
1027
1342
  }
1028
- return formatPrimitive(value);
1029
- }
1030
- function getNestedValue(row, path) {
1031
- if (!path.includes(".")) return row[path];
1032
- return path.split(".").reduce((current, key) => {
1033
- if (current === null || current === void 0 || typeof current !== "object") {
1034
- return void 0;
1035
- }
1036
- return current[key];
1037
- }, row);
1038
- }
1039
- function readRowColumnValue(rowData, columnDef) {
1040
- if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1041
- return columnDef.accessorFn(rowData, 0);
1343
+ const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
1344
+ let offsetPx = 0;
1345
+ for (let i = 0; i < clampedFrom - rowIndex; i++) {
1346
+ offsetPx += rowHeights[i] ?? 0;
1042
1347
  }
1043
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1044
- return getNestedValue(rowData, String(columnDef.accessorKey));
1348
+ let lengthPx = 0;
1349
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1350
+ lengthPx += rowHeights[i] ?? 0;
1045
1351
  }
1046
- return void 0;
1352
+ return {
1353
+ offsetRatio: offsetPx / total,
1354
+ lengthRatio: lengthPx / total,
1355
+ offsetPx,
1356
+ lengthPx
1357
+ };
1047
1358
  }
1048
- function flattenSubtreeRows(row) {
1049
- const children = row.children;
1050
- if (!Array.isArray(children) || children.length === 0) return [];
1051
- const result = [];
1052
- const walk = (nodes) => {
1053
- for (const node of nodes) {
1054
- result.push(node);
1055
- const nested = node.children;
1056
- if (Array.isArray(nested) && nested.length > 0) {
1057
- walk(nested);
1058
- }
1359
+ function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
1360
+ const cellEndRow = rowIndex + rowSpan - 1;
1361
+ const span = cellEndRow - rowIndex + 1;
1362
+ if (span <= 1) return [];
1363
+ const edges = [];
1364
+ const isNeighborSelected = (row, neighborCol) => {
1365
+ if (isVisuallySelectedAt) {
1366
+ return isVisuallySelectedAt(row, neighborCol);
1059
1367
  }
1368
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
1060
1369
  };
1061
- walk(children);
1062
- return result;
1063
- }
1064
- function hasSubtree(row) {
1065
- const children = row.children;
1066
- return Array.isArray(children) && children.length > 0;
1067
- }
1068
- function getOriginalRowId(original) {
1069
- return String(original.id ?? original.uniqueId ?? "");
1070
- }
1071
- function getRowDepth(original) {
1072
- return typeof original.level === "number" ? original.level : 0;
1073
- }
1074
- function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1075
- const { startRow, endRow } = bounds;
1076
- const result = [];
1077
- const includedOriginalIds = /* @__PURE__ */ new Set();
1078
- const appendSubtree = (node, depth) => {
1079
- const children = node.children;
1080
- if (!Array.isArray(children) || children.length === 0) return;
1081
- for (const child of children) {
1082
- const childId = getOriginalRowId(child);
1083
- if (!(childId && includedOriginalIds.has(childId))) {
1084
- result.push({ row: child, depth });
1085
- if (childId) includedOriginalIds.add(childId);
1370
+ const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
1371
+ let runStart = null;
1372
+ for (let row = fromRow; row < toRowExclusive; row++) {
1373
+ if (!isNeighborSelected(row, neighborCol)) {
1374
+ if (runStart === null) runStart = row;
1375
+ continue;
1086
1376
  }
1087
- appendSubtree(child, depth + 1);
1377
+ if (runStart !== null) {
1378
+ const ratios = rowRangeToHeightRatios(
1379
+ rowIndex,
1380
+ span,
1381
+ runStart,
1382
+ row,
1383
+ rowHeights
1384
+ );
1385
+ if (ratios.lengthRatio > 0) {
1386
+ edges.push({ side, ...ratios });
1387
+ }
1388
+ runStart = null;
1389
+ }
1390
+ }
1391
+ if (runStart !== null) {
1392
+ const ratios = rowRangeToHeightRatios(
1393
+ rowIndex,
1394
+ span,
1395
+ runStart,
1396
+ toRowExclusive,
1397
+ rowHeights
1398
+ );
1399
+ if (ratios.lengthRatio > 0) {
1400
+ edges.push({ side, ...ratios });
1401
+ }
1402
+ }
1403
+ };
1404
+ const collectSide = (side, neighborCol) => {
1405
+ if (bounds.startRow > rowIndex) {
1406
+ pushUnselectedRuns(
1407
+ side,
1408
+ neighborCol,
1409
+ rowIndex,
1410
+ Math.min(bounds.startRow, cellEndRow + 1)
1411
+ );
1412
+ }
1413
+ if (bounds.endRow < cellEndRow) {
1414
+ pushUnselectedRuns(
1415
+ side,
1416
+ neighborCol,
1417
+ Math.max(bounds.endRow + 1, rowIndex),
1418
+ cellEndRow + 1
1419
+ );
1088
1420
  }
1089
1421
  };
1090
- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1091
- const row = visibleRows[rowIndex];
1092
- if (!row) continue;
1093
- const originalId = getOriginalRowId(row.original);
1094
- if (originalId && includedOriginalIds.has(originalId)) continue;
1095
- const depth = getRowDepth(row.original);
1096
- result.push({ row: row.original, depth });
1097
- if (originalId) includedOriginalIds.add(originalId);
1098
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
1099
- appendSubtree(row.original, depth + 1);
1422
+ if (colIndex < bounds.endCol) {
1423
+ collectSide("right", colIndex + 1);
1100
1424
  }
1101
- return result;
1102
- }
1103
- function collectCopyRows(visibleRows, bounds, mode = "visible") {
1104
- return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1425
+ if (colIndex > bounds.startCol) {
1426
+ collectSide("left", colIndex - 1);
1427
+ }
1428
+ return edges;
1105
1429
  }
1106
- function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1107
- if (copyRows.length === 0) return "";
1108
- const { startCol, endCol } = bounds;
1109
- const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1110
- if (columnCells.length === 0) return "";
1111
- const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1112
- const minDepth = Math.min(...resolvedDepths);
1113
- const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1114
- const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1115
- const meta = templateCell.column.columnDef.meta;
1116
- if (meta?.copyValue === "omit") return [];
1117
- return [{ templateCell, colOffset }];
1118
- });
1119
- return copyRows.map((rowData, index) => {
1120
- const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1121
- const visibleRow = visibleRowByOriginal.get(rowData);
1122
- const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1123
- const line = copyableColumns.map(({ templateCell, colOffset }) => {
1124
- const sourceCell = matchingCells?.[colOffset];
1125
- const column = sourceCell?.column ?? templateCell.column;
1126
- return formatCopyCellText(
1127
- rowData,
1128
- column.columnDef,
1129
- resolveCopyColumnId(sourceCell ?? templateCell),
1130
- visibleRow,
1131
- visibleRow?.index ?? index,
1132
- sourceCell,
1133
- visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1134
- options
1135
- );
1136
- }).join(" ");
1137
- return `${" ".repeat(relativeDepth)}${line}`;
1138
- }).join("\n");
1430
+ function buildPartialEdgeGradient(edge) {
1431
+ const usePx = edge.offsetPx != null && edge.lengthPx != null;
1432
+ const startPct = edge.offsetRatio * 100;
1433
+ const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
1434
+ const startPx = edge.offsetPx ?? 0;
1435
+ const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
1436
+ const overlapPx = SELECTION_EDGE_WIDTH_PX;
1437
+ const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
1438
+ const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
1439
+ const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
1440
+ const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
1441
+ const xPos = edge.side === "left" ? "0" : "100%";
1442
+ const layers = [
1443
+ {
1444
+ image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
1445
+ size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
1446
+ position: `${xPos} 0`
1447
+ }
1448
+ ];
1449
+ if (isTopProtrusion || isBottomProtrusion) {
1450
+ const capTop = usePx ? isTopProtrusion ? `${Math.max(0, endPx - SELECTION_EDGE_WIDTH_PX)}px` : `${Math.max(0, startPx - SELECTION_EDGE_WIDTH_PX)}px` : isTopProtrusion ? `calc(${endPct}% - ${SELECTION_EDGE_WIDTH_PX}px)` : `calc(${startPct}% - ${SELECTION_EDGE_WIDTH_PX}px)`;
1451
+ layers.push({
1452
+ image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
1453
+ size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
1454
+ position: `${xPos} ${capTop}`
1455
+ });
1456
+ }
1457
+ return layers;
1139
1458
  }
1140
- function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1141
- const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1142
- return serializeCopyRowsToTSV(
1143
- entries.map((entry) => entry.row),
1144
- visibleRows,
1459
+ function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
1460
+ if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
1461
+ return void 0;
1462
+ const cellEndRow = rowIndex + rowSpan - 1;
1463
+ const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
1464
+ const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
1465
+ const isLeftEdge = colIndex === bounds.startCol;
1466
+ const isRightEdge = colIndex === bounds.endCol;
1467
+ const selectionContinuesBelow = cellEndRow < bounds.endRow;
1468
+ const stepEdges = getMergedCellStepEdges(
1469
+ rowIndex,
1470
+ colIndex,
1145
1471
  bounds,
1146
- entries.map((entry) => entry.depth),
1147
- options
1472
+ rowSpan,
1473
+ isVisuallySelectedAt,
1474
+ rowHeights
1148
1475
  );
1149
- }
1150
- function writeTextWithExecCommand(text) {
1151
- if (typeof document === "undefined") return false;
1152
- const textarea = document.createElement("textarea");
1153
- textarea.value = text;
1154
- textarea.setAttribute("readonly", "");
1155
- textarea.style.position = "fixed";
1156
- textarea.style.top = "0";
1157
- textarea.style.left = "0";
1158
- textarea.style.opacity = "0";
1159
- textarea.style.pointerEvents = "none";
1160
- document.body.appendChild(textarea);
1161
- const previouslyFocused = document.activeElement;
1162
- try {
1163
- textarea.focus();
1164
- textarea.select();
1165
- return document.execCommand("copy");
1166
- } catch {
1167
- return false;
1168
- } finally {
1169
- document.body.removeChild(textarea);
1170
- previouslyFocused?.focus?.();
1476
+ const shadows = [];
1477
+ const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
1478
+ if (hasFullPerimeter) {
1479
+ shadows.push(
1480
+ `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
1481
+ );
1482
+ } else {
1483
+ if (isTopEdge) {
1484
+ shadows.push(
1485
+ `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1486
+ );
1487
+ }
1488
+ if (isBottomEdge) {
1489
+ shadows.push(
1490
+ `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1491
+ );
1492
+ }
1493
+ if (isLeftEdge) {
1494
+ shadows.push(
1495
+ `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1496
+ );
1497
+ }
1498
+ if (isRightEdge) {
1499
+ shadows.push(
1500
+ `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1501
+ );
1502
+ }
1171
1503
  }
1172
- }
1173
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1174
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1175
- if (!text) return false;
1176
- if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1177
- return writeTextWithExecCommand(text);
1504
+ const gradients = [];
1505
+ const sizes = [];
1506
+ const positions = [];
1507
+ for (const edge of stepEdges) {
1508
+ for (const partial of buildPartialEdgeGradient(edge)) {
1509
+ gradients.push(partial.image);
1510
+ sizes.push(partial.size);
1511
+ positions.push(partial.position);
1512
+ }
1178
1513
  }
1179
- try {
1180
- await navigator.clipboard.writeText(text);
1181
- return true;
1182
- } catch {
1183
- return false;
1514
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1515
+ return void 0;
1516
+ }
1517
+ const style = {};
1518
+ if (shadows.length > 0) {
1519
+ style["--selection-edge-shadows"] = shadows.join(", ");
1520
+ }
1521
+ if (gradients.length > 0) {
1522
+ style["--selection-edge-gradients"] = gradients.join(", ");
1523
+ style["--selection-edge-sizes"] = sizes.join(", ");
1524
+ style["--selection-edge-positions"] = positions.join(", ");
1525
+ }
1526
+ if (selectionContinuesBelow) {
1527
+ style.borderBottomColor = "var(--color-brand-surface)";
1184
1528
  }
1529
+ return style;
1530
+ }
1531
+ function hasCellSelectionEdges(style) {
1532
+ return Boolean(
1533
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1534
+ );
1185
1535
  }
1186
1536
 
1187
1537
  // src/components/ui/table/features/cell-selection/fillData.ts
@@ -1206,6 +1556,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1206
1556
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1207
1557
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1208
1558
  if (!targetRow || !targetCell || !sourceCell) continue;
1559
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1560
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1209
1561
  const accessorKey = getColumnAccessorKey2(
1210
1562
  targetCell.column.columnDef
1211
1563
  );
@@ -1227,13 +1579,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1227
1579
  );
1228
1580
  }
1229
1581
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1230
- const newData = data.map((row) => ({ ...row }));
1231
1582
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1232
- for (const target of targets) {
1233
- if (!newData[target.rowIndex]) continue;
1234
- newData[target.rowIndex][target.accessorKey] = target.value;
1235
- }
1236
- return newData;
1583
+ return applyCellChangesToData(
1584
+ data,
1585
+ targets.flatMap((target) => {
1586
+ const row = rows[target.rowIndex];
1587
+ if (!row) return [];
1588
+ return [
1589
+ {
1590
+ original: row.original,
1591
+ index: row.index,
1592
+ accessorKey: target.accessorKey,
1593
+ value: target.value
1594
+ }
1595
+ ];
1596
+ })
1597
+ );
1237
1598
  }
1238
1599
  function hasFillExtension(sourceBounds, fillBounds) {
1239
1600
  if (!sourceBounds) return false;
@@ -1254,17 +1615,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1254
1615
  if (firstDepth !== 0) return false;
1255
1616
  return leadingEmptyCounts.some((depth) => depth > 0);
1256
1617
  }
1618
+ function splitTSV(text) {
1619
+ const rows = [];
1620
+ let row = [];
1621
+ let index = 0;
1622
+ while (index <= text.length) {
1623
+ let cell = "";
1624
+ if (text[index] === '"') {
1625
+ index += 1;
1626
+ while (index < text.length) {
1627
+ const char = text[index];
1628
+ if (char === '"') {
1629
+ if (text[index + 1] === '"') {
1630
+ cell += '"';
1631
+ index += 2;
1632
+ continue;
1633
+ }
1634
+ index += 1;
1635
+ break;
1636
+ }
1637
+ cell += char;
1638
+ index += 1;
1639
+ }
1640
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1641
+ cell += text[index];
1642
+ index += 1;
1643
+ }
1644
+ } else {
1645
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1646
+ cell += text[index];
1647
+ index += 1;
1648
+ }
1649
+ }
1650
+ row.push(cell);
1651
+ if (index >= text.length) {
1652
+ rows.push(row);
1653
+ break;
1654
+ }
1655
+ if (text[index] === "\n") {
1656
+ rows.push(row);
1657
+ row = [];
1658
+ }
1659
+ index += 1;
1660
+ }
1661
+ return rows;
1662
+ }
1257
1663
  function parseClipboardTSV(text) {
1258
1664
  return parseClipboardTSVWithDepths(text).values;
1259
1665
  }
1260
- function parseClipboardTSVWithDepths(text) {
1666
+ function parseClipboardTSVWithDepths(text, options) {
1261
1667
  if (!text) return { values: [], depths: [] };
1262
1668
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1263
1669
  const withoutTrailing = normalized.replace(/\n+$/, "");
1264
1670
  if (!withoutTrailing) return { values: [], depths: [] };
1265
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1671
+ const rows = splitTSV(withoutTrailing);
1266
1672
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1267
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1673
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1268
1674
  const values = [];
1269
1675
  const depths = [];
1270
1676
  for (let index = 0; index < rows.length; index += 1) {
@@ -1291,8 +1697,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1291
1697
  }
1292
1698
  return columnIds;
1293
1699
  }
1294
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1295
- const { values, depths } = parseClipboardTSVWithDepths(text);
1700
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1701
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1296
1702
  if (values.length === 0) return null;
1297
1703
  const width = Math.max(...values.map((row) => row.length), 0);
1298
1704
  if (width === 0) return null;
@@ -1325,6 +1731,19 @@ function isEditablePasteTarget(target) {
1325
1731
  }
1326
1732
 
1327
1733
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
1734
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
1735
+ function isInteractiveFocus() {
1736
+ const active = document.activeElement;
1737
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
1738
+ }
1739
+ function hasPageTextSelectionOutside(root) {
1740
+ if (typeof window.getSelection !== "function") return false;
1741
+ const selection = window.getSelection();
1742
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
1743
+ if (!selection.toString()) return false;
1744
+ const anchor = selection.anchorNode;
1745
+ return !(root && anchor && root.contains(anchor));
1746
+ }
1328
1747
  function isFocusOutsideRoot(rootRef) {
1329
1748
  const root = rootRef?.current;
1330
1749
  if (!root) return false;
@@ -1337,29 +1756,50 @@ function useCellSelection({
1337
1756
  rows,
1338
1757
  enabled = true,
1339
1758
  columnCount = 0,
1759
+ columnSignature,
1340
1760
  enableSubtreeCopy = false,
1761
+ escapeCopyFormulas = false,
1341
1762
  enableInsertPaste = true,
1342
1763
  onDataChange,
1343
1764
  onBatchChange,
1344
1765
  onRowsPaste,
1345
1766
  onCellNavigate,
1346
1767
  cellRendererRegistry,
1347
- rootRef
1768
+ rootRef,
1769
+ enableWasdNavigation = true,
1770
+ onEditKey,
1771
+ onClearKey
1348
1772
  }) {
1349
1773
  const ownerRef = useRef2(createCellSelectionOwner());
1350
1774
  const [dragState, setDragState] = useState2(INITIAL_DRAG_STATE);
1351
1775
  const pendingPasteModeRef = useRef2(null);
1352
1776
  const dragStateRef = useRef2(dragState);
1353
1777
  const onCellNavigateRef = useRef2(onCellNavigate);
1778
+ const onEditKeyRef = useRef2(onEditKey);
1779
+ const onClearKeyRef = useRef2(onClearKey);
1354
1780
  dragStateRef.current = dragState;
1355
1781
  onCellNavigateRef.current = onCellNavigate;
1356
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1357
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
1782
+ onEditKeyRef.current = onEditKey;
1783
+ onClearKeyRef.current = onClearKey;
1784
+ const updateDragState = useCallback2((update) => {
1785
+ const prev = dragStateRef.current;
1786
+ const next = update(prev);
1787
+ if (next === prev) return;
1788
+ dragStateRef.current = next;
1789
+ setDragState(next);
1790
+ }, []);
1791
+ const activeSelectionBounds = useMemo2(() => {
1792
+ if (!enabled) return null;
1793
+ return getActiveSelectionBounds(
1794
+ dragState,
1795
+ getCellSelectionBounds(dragState.start, dragState.end)
1796
+ );
1797
+ }, [dragState, enabled]);
1358
1798
  const handleCellMouseDown = useCallback2(
1359
1799
  (rowIndex, colIndex, options) => {
1360
1800
  if (!enabled) return;
1361
1801
  claimCellSelectionOwner(ownerRef.current);
1362
- setDragState((prev) => {
1802
+ updateDragState((prev) => {
1363
1803
  if (options?.shiftKey && prev.start) {
1364
1804
  return {
1365
1805
  ...prev,
@@ -1380,28 +1820,30 @@ function useCellSelection({
1380
1820
  };
1381
1821
  });
1382
1822
  },
1383
- [enabled]
1823
+ [enabled, updateDragState]
1384
1824
  );
1385
1825
  const handleCellMouseEnter = useCallback2(
1386
1826
  (rowIndex, colIndex) => {
1387
1827
  if (!enabled) return;
1388
- setDragState((prev) => {
1828
+ updateDragState((prev) => {
1389
1829
  if (prev.isSelecting) {
1830
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1390
1831
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1391
1832
  }
1392
1833
  if (prev.isFillDragging) {
1834
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1393
1835
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1394
1836
  }
1395
1837
  return prev;
1396
1838
  });
1397
1839
  },
1398
- [enabled]
1840
+ [enabled, updateDragState]
1399
1841
  );
1400
1842
  const handleFillHandleMouseDown = useCallback2(
1401
1843
  (rowIndex, colIndex) => {
1402
1844
  if (!enabled) return;
1403
1845
  claimCellSelectionOwner(ownerRef.current);
1404
- setDragState((prev) => {
1846
+ updateDragState((prev) => {
1405
1847
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1406
1848
  if (!bounds) return prev;
1407
1849
  return {
@@ -1413,7 +1855,7 @@ function useCellSelection({
1413
1855
  };
1414
1856
  });
1415
1857
  },
1416
- [enabled]
1858
+ [enabled, updateDragState]
1417
1859
  );
1418
1860
  const clearSelection = useCallback2(() => {
1419
1861
  const prev = dragStateRef.current;
@@ -1432,6 +1874,130 @@ function useCellSelection({
1432
1874
  useEffect2(() => {
1433
1875
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1434
1876
  }, [clearSelection]);
1877
+ const previousColumnSignatureRef = useRef2(columnSignature);
1878
+ useEffect2(() => {
1879
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
1880
+ previousColumnSignatureRef.current = columnSignature;
1881
+ const prev = dragStateRef.current;
1882
+ if (!prev.start || !prev.end) return;
1883
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1884
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
1885
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
1886
+ if (columnsChanged || outOfRange) {
1887
+ clearSelection();
1888
+ }
1889
+ }, [clearSelection, columnCount, columnSignature, rows]);
1890
+ useEffect2(() => {
1891
+ if (!enabled) return;
1892
+ const handlePointerDown = (event) => {
1893
+ const root = rootRef?.current;
1894
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
1895
+ if (event.target instanceof Node && root.contains(event.target)) return;
1896
+ releaseCellSelectionOwner(ownerRef.current);
1897
+ };
1898
+ document.addEventListener("pointerdown", handlePointerDown, true);
1899
+ document.addEventListener("mousedown", handlePointerDown, true);
1900
+ return () => {
1901
+ document.removeEventListener("pointerdown", handlePointerDown, true);
1902
+ document.removeEventListener("mousedown", handlePointerDown, true);
1903
+ };
1904
+ }, [enabled, rootRef]);
1905
+ const getColumnCount = useCallback2(
1906
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
1907
+ [columnCount, rows]
1908
+ );
1909
+ const selectCell = useCallback2(
1910
+ (row, col) => {
1911
+ if (!enabled) return;
1912
+ const resolvedColumnCount = getColumnCount();
1913
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
1914
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
1915
+ claimCellSelectionOwner(ownerRef.current);
1916
+ const nextState = {
1917
+ isSelecting: false,
1918
+ isFillDragging: false,
1919
+ start: position,
1920
+ end: position,
1921
+ fillAnchor: null,
1922
+ fillEnd: null
1923
+ };
1924
+ dragStateRef.current = nextState;
1925
+ setDragState(nextState);
1926
+ onCellNavigateRef.current?.(position);
1927
+ },
1928
+ [enabled, getColumnCount, rows.length]
1929
+ );
1930
+ const focusSelection = useCallback2(() => {
1931
+ if (!enabled) return;
1932
+ const prev = dragStateRef.current;
1933
+ if (prev.start && prev.end) {
1934
+ claimCellSelectionOwner(ownerRef.current);
1935
+ return;
1936
+ }
1937
+ selectCell(0, 0);
1938
+ }, [enabled, selectCell]);
1939
+ useEffect2(() => {
1940
+ if (!enabled) return;
1941
+ const handleKeyDown = (e) => {
1942
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1943
+ if (e.altKey) return;
1944
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
1945
+ return;
1946
+ }
1947
+ if (isFocusOutsideRoot(rootRef)) return;
1948
+ const prev = dragStateRef.current;
1949
+ if (!prev.start || !prev.end) return;
1950
+ if (prev.isSelecting || prev.isFillDragging) return;
1951
+ const rowCount = rows.length;
1952
+ const resolvedColumnCount = getColumnCount();
1953
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
1954
+ const withModifier = e.ctrlKey || e.metaKey;
1955
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
1956
+ e.preventDefault();
1957
+ claimCellSelectionOwner(ownerRef.current);
1958
+ const nextState = {
1959
+ isSelecting: false,
1960
+ isFillDragging: false,
1961
+ start: { row: 0, col: 0 },
1962
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
1963
+ fillAnchor: null,
1964
+ fillEnd: null
1965
+ };
1966
+ dragStateRef.current = nextState;
1967
+ setDragState(nextState);
1968
+ return;
1969
+ }
1970
+ if (e.key === "Home" || e.key === "End") {
1971
+ e.preventDefault();
1972
+ const toEnd = e.key === "End";
1973
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
1974
+ if (e.shiftKey) {
1975
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
1976
+ dragStateRef.current = nextState;
1977
+ setDragState(nextState);
1978
+ onCellNavigateRef.current?.(target);
1979
+ } else {
1980
+ selectCell(target.row, target.col);
1981
+ }
1982
+ return;
1983
+ }
1984
+ if (withModifier || isInteractiveFocus()) return;
1985
+ if (e.key === "Enter" || e.key === "F2") {
1986
+ if (!onEditKeyRef.current) return;
1987
+ e.preventDefault();
1988
+ onEditKeyRef.current(prev.end);
1989
+ return;
1990
+ }
1991
+ if (e.key === "Delete" || e.key === "Backspace") {
1992
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1993
+ if (!bounds || !onClearKeyRef.current) return;
1994
+ e.preventDefault();
1995
+ onClearKeyRef.current(bounds);
1996
+ }
1997
+ };
1998
+ window.addEventListener("keydown", handleKeyDown);
1999
+ return () => window.removeEventListener("keydown", handleKeyDown);
2000
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
1435
2001
  useEffect2(() => {
1436
2002
  if (!enabled) return;
1437
2003
  const handleKeyDown = (e) => {
@@ -1441,6 +2007,7 @@ function useCellSelection({
1441
2007
  return;
1442
2008
  }
1443
2009
  if (isFocusOutsideRoot(rootRef)) return;
2010
+ if (!enableWasdNavigation && e.key.length === 1) return;
1444
2011
  const delta = getCellNavigationDelta(e.key);
1445
2012
  if (!delta) return;
1446
2013
  const prev = dragStateRef.current;
@@ -1480,14 +2047,15 @@ function useCellSelection({
1480
2047
  };
1481
2048
  window.addEventListener("keydown", handleKeyDown);
1482
2049
  return () => window.removeEventListener("keydown", handleKeyDown);
1483
- }, [columnCount, enabled, rows]);
2050
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1484
2051
  const copySelection = useCallback2(
1485
2052
  async (options) => {
1486
2053
  if (!enabled || !activeSelectionBounds) return false;
1487
2054
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1488
2055
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1489
2056
  registry: cellRendererRegistry,
1490
- root: rootRef?.current
2057
+ root: rootRef?.current,
2058
+ escapeFormulas: escapeCopyFormulas
1491
2059
  });
1492
2060
  },
1493
2061
  [
@@ -1495,6 +2063,7 @@ function useCellSelection({
1495
2063
  cellRendererRegistry,
1496
2064
  enableSubtreeCopy,
1497
2065
  enabled,
2066
+ escapeCopyFormulas,
1498
2067
  rootRef,
1499
2068
  rows
1500
2069
  ]
@@ -1512,6 +2081,7 @@ function useCellSelection({
1512
2081
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1513
2082
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1514
2083
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2084
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1515
2085
  e.preventDefault();
1516
2086
  void copySelection({ includeDescendants: isSubtreeShortcut });
1517
2087
  };
@@ -1527,9 +2097,17 @@ function useCellSelection({
1527
2097
  activeSelectionBounds.startCol,
1528
2098
  text,
1529
2099
  mode,
1530
- activeSelectionBounds.endRow
2100
+ activeSelectionBounds.endRow,
2101
+ // Leading blank cells are tree depth only in this table's own subtree
2102
+ // copy; from a spreadsheet they are real (empty) cells.
2103
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
1531
2104
  );
1532
2105
  if (!payload) return false;
2106
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
2107
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
2108
+ const cell = cells.find((item) => item.column.id === columnId);
2109
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
2110
+ });
1533
2111
  onRowsPaste(payload);
1534
2112
  return true;
1535
2113
  },
@@ -1560,7 +2138,10 @@ function useCellSelection({
1560
2138
  void (async () => {
1561
2139
  try {
1562
2140
  const text = await navigator.clipboard.readText();
1563
- if (pasteHandledRef.current) return;
2141
+ if (pasteHandledRef.current) {
2142
+ pasteHandledRef.current = false;
2143
+ return;
2144
+ }
1564
2145
  if (pendingPasteModeRef.current !== mode) return;
1565
2146
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1566
2147
  if (!text) return;
@@ -1585,6 +2166,7 @@ function useCellSelection({
1585
2166
  }
1586
2167
  const mode = pendingPasteModeRef.current ?? "overwrite";
1587
2168
  if (pasteHandledRef.current) {
2169
+ pasteHandledRef.current = false;
1588
2170
  e.preventDefault();
1589
2171
  return;
1590
2172
  }
@@ -1611,39 +2193,41 @@ function useCellSelection({
1611
2193
  useEffect2(() => {
1612
2194
  if (!enabled) return;
1613
2195
  const handleMouseUp = () => {
1614
- setDragState((prev) => {
1615
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1616
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1617
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1618
- if (newBounds) {
1619
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1620
- if (onBatchChange) {
1621
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1622
- if (changes.length > 0) {
1623
- onBatchChange(changes);
1624
- }
1625
- } else if (onDataChange) {
1626
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
2196
+ const prev = dragStateRef.current;
2197
+ let next = prev;
2198
+ if (prev.isFillDragging && prev.fillEnd) {
2199
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
2200
+ if (sourceBounds) {
2201
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
2202
+ if (hasFillExtension(sourceBounds, newBounds)) {
2203
+ if (onBatchChange) {
2204
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
2205
+ if (changes.length > 0) {
2206
+ onBatchChange(changes);
1627
2207
  }
2208
+ } else if (onDataChange) {
2209
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1628
2210
  }
1629
- return {
1630
- isSelecting: false,
1631
- isFillDragging: false,
1632
- start: { row: newBounds.startRow, col: newBounds.startCol },
1633
- end: { row: newBounds.endRow, col: newBounds.endCol },
1634
- fillAnchor: null,
1635
- fillEnd: null
1636
- };
1637
2211
  }
2212
+ next = {
2213
+ isSelecting: false,
2214
+ isFillDragging: false,
2215
+ start: { row: newBounds.startRow, col: newBounds.startCol },
2216
+ end: { row: newBounds.endRow, col: newBounds.endCol },
2217
+ fillAnchor: null,
2218
+ fillEnd: null
2219
+ };
2220
+ } else {
2221
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1638
2222
  }
1639
- if (prev.isSelecting) {
1640
- return { ...prev, isSelecting: false };
1641
- }
1642
- if (prev.isFillDragging) {
1643
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1644
- }
1645
- return prev;
1646
- });
2223
+ } else if (prev.isSelecting) {
2224
+ next = { ...prev, isSelecting: false };
2225
+ } else if (prev.isFillDragging) {
2226
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
2227
+ }
2228
+ if (next === prev) return;
2229
+ dragStateRef.current = next;
2230
+ setDragState(next);
1647
2231
  };
1648
2232
  window.addEventListener("mouseup", handleMouseUp);
1649
2233
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1655,10 +2239,37 @@ function useCellSelection({
1655
2239
  handleCellMouseEnter,
1656
2240
  handleFillHandleMouseDown,
1657
2241
  clearSelection,
1658
- copySelection
2242
+ copySelection,
2243
+ selectCell,
2244
+ focusSelection
1659
2245
  };
1660
2246
  }
1661
2247
 
2248
+ // src/components/ui/table/features/row-hover/rowHover.ts
2249
+ function createRowHoverStore() {
2250
+ let hoveredRowIndex = null;
2251
+ const listeners = /* @__PURE__ */ new Set();
2252
+ return {
2253
+ getHoveredRowIndex: () => hoveredRowIndex,
2254
+ setHoveredRowIndex: (nextRowIndex) => {
2255
+ if (nextRowIndex === hoveredRowIndex) return;
2256
+ hoveredRowIndex = nextRowIndex;
2257
+ listeners.forEach((listener) => listener());
2258
+ },
2259
+ subscribe: (listener) => {
2260
+ listeners.add(listener);
2261
+ return () => listeners.delete(listener);
2262
+ }
2263
+ };
2264
+ }
2265
+ function isRowHovered(hoveredRowIndex, rowIndex) {
2266
+ return hoveredRowIndex === rowIndex;
2267
+ }
2268
+ function isRowGroupHovered(hoveredRowIndex, enableRowSpan, groupStart, groupSpan) {
2269
+ if (!enableRowSpan || hoveredRowIndex === null) return false;
2270
+ return hoveredRowIndex >= groupStart && hoveredRowIndex <= groupStart + groupSpan - 1;
2271
+ }
2272
+
1662
2273
  // src/components/ui/table/features/selection-dismiss/isOutsideDismissTarget.ts
1663
2274
  var OVERLAY_DISMISS_IGNORE_SELECTOR = [
1664
2275
  '[role="dialog"]',
@@ -1884,231 +2495,75 @@ function buildColumnFreezeOffsets(columns) {
1884
2495
  for (let index = columns.length - 1; index >= 0; index -= 1) {
1885
2496
  const column = columns[index];
1886
2497
  if (!column || column.side !== "right") continue;
1887
- rightIds.push(column.id);
1888
- result.set(column.id, {
1889
- side: "right",
1890
- offset: rightOffset,
1891
- isEdge: false,
1892
- edgeLeft: false,
1893
- edgeRight: false,
1894
- stack: 0
1895
- });
1896
- rightOffset += column.size;
1897
- }
1898
- rightIds.forEach((id, index) => {
1899
- const entry = result.get(id);
1900
- if (!entry) return;
1901
- entry.stack = rightIds.length - index;
1902
- });
1903
- columns.forEach((column, index) => {
1904
- if (!column.side) return;
1905
- const entry = result.get(column.id);
1906
- if (!entry) return;
1907
- const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
1908
- const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
1909
- entry.edgeLeft = prevSide !== column.side;
1910
- entry.edgeRight = nextSide !== column.side;
1911
- if (index === 0) entry.edgeLeft = false;
1912
- if (index === columns.length - 1) entry.edgeRight = false;
1913
- entry.isEdge = entry.edgeLeft || entry.edgeRight;
1914
- });
1915
- return result;
1916
- }
1917
- function getColumnFreezeStyle(offset, options) {
1918
- if (!offset) return void 0;
1919
- const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
1920
- return {
1921
- position: "sticky",
1922
- ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
1923
- zIndex: zBase + offset.stack
1924
- };
1925
- }
1926
- function resolveHeaderFreezeOffset(column, freezeOffsets) {
1927
- const direct = freezeOffsets.get(column.id);
1928
- if (direct) return direct;
1929
- const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
1930
- if (leaves.length === 0) return void 0;
1931
- const leafOffsets = [];
1932
- for (const leaf of leaves) {
1933
- const offset2 = freezeOffsets.get(leaf.id);
1934
- if (!offset2) return void 0;
1935
- leafOffsets.push(offset2);
1936
- }
1937
- const side = leafOffsets[0]?.side;
1938
- if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
1939
- return void 0;
1940
- }
1941
- const offset = Math.min(...leafOffsets.map((item) => item.offset));
1942
- const leftmost = leafOffsets[0];
1943
- const rightmost = leafOffsets[leafOffsets.length - 1];
1944
- return {
1945
- side,
1946
- offset,
1947
- edgeLeft: leftmost.edgeLeft,
1948
- edgeRight: rightmost.edgeRight,
1949
- isEdge: leftmost.edgeLeft || rightmost.edgeRight,
1950
- stack: Math.max(...leafOffsets.map((item) => item.stack))
1951
- };
1952
- }
1953
- function flattenHeaderLeaves(column) {
1954
- if (!column.columns || column.columns.length === 0) return [column];
1955
- return column.columns.flatMap((child) => flattenHeaderLeaves(child));
1956
- }
1957
-
1958
- // src/components/ui/table/features/inline-search/inlineSearch.ts
1959
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
1960
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
1961
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
1962
- function escapeSearchRegex(value) {
1963
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
1964
- }
1965
- function createSearchRegex(query) {
1966
- const trimmed = query.trim();
1967
- if (!trimmed) return null;
1968
- return new RegExp(escapeSearchRegex(trimmed), "i");
1969
- }
1970
- function cellValueToSearchText(value) {
1971
- if (value == null) return void 0;
1972
- if (typeof value === "string") return value;
1973
- if (typeof value === "number" || typeof value === "boolean") {
1974
- return String(value);
1975
- }
1976
- if (Array.isArray(value)) {
1977
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
1978
- }
1979
- if (typeof value === "object") {
1980
- try {
1981
- return JSON.stringify(value);
1982
- } catch {
1983
- return String(value);
1984
- }
1985
- }
1986
- return String(value);
1987
- }
1988
- function formatSearchResultLabel(status) {
1989
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
1990
- if (status.selectedIndex >= 0 && status.results > 0) {
1991
- return `${status.selectedIndex + 1} of ${countLabel}`;
1992
- }
1993
- return countLabel;
1994
- }
1995
- function nextSearchIndex(selectedIndex, results) {
1996
- if (results <= 0) return -1;
1997
- if (selectedIndex < 0) return 0;
1998
- return (selectedIndex + 1) % results;
1999
- }
2000
- function previousSearchIndex(selectedIndex, results) {
2001
- if (results <= 0) return -1;
2002
- if (selectedIndex < 0) return results - 1;
2003
- let next = (selectedIndex - 1) % results;
2004
- if (next < 0) next += results;
2005
- return next;
2006
- }
2007
- function buildSearchMatchKey(colIndex, rowIndex) {
2008
- return `${colIndex}:${rowIndex}`;
2009
- }
2010
- function buildSearchMatchKeys(results) {
2011
- const keys = /* @__PURE__ */ new Set();
2012
- for (const [colIndex, rowIndex] of results) {
2013
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
2014
- }
2015
- return keys;
2016
- }
2017
- function collectSearchMatchesInRange(options) {
2018
- const {
2019
- query,
2020
- startRow,
2021
- rowCount,
2022
- columnCount,
2023
- getCellValue,
2024
- maxResults = INLINE_SEARCH_MAX_RESULTS
2025
- } = options;
2026
- const regex = createSearchRegex(query);
2027
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
2028
- const matches = [];
2029
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2030
- const rowIndex = startRow + rowOffset;
2031
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2032
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2033
- if (text !== void 0 && regex.test(text)) {
2034
- matches.push([colIndex, rowIndex]);
2035
- if (matches.length >= maxResults) {
2036
- return matches;
2037
- }
2038
- }
2039
- }
2040
- }
2041
- return matches;
2042
- }
2043
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2044
- const rounded = Math.max(elapsedMs, 1);
2045
- const scalar = targetMs / rounded;
2046
- return Math.max(1, Math.ceil(currentStride * scalar));
2047
- }
2048
- function buildFlatSearchCorpus(rows, getRowId) {
2049
- return rows.map((data, index) => ({
2050
- id: getRowId(data, index),
2051
- data,
2052
- ancestorToggleKeys: []
2053
- }));
2054
- }
2055
- function buildTreeSearchCorpus(visibleRows, options) {
2056
- const { toggleField, getRowId } = options;
2057
- const corpus = [];
2058
- const seen = /* @__PURE__ */ new Set();
2059
- const walk = (node, ancestorToggleKeys) => {
2060
- const id = getRowId(node, corpus.length);
2061
- if (seen.has(id)) return;
2062
- seen.add(id);
2063
- corpus.push({
2064
- id,
2065
- data: node,
2066
- ancestorToggleKeys
2067
- });
2068
- const children = node.children;
2069
- if (!Array.isArray(children) || children.length === 0) return;
2070
- const toggleValue = node[toggleField];
2071
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2072
- for (const child of children) {
2073
- if (child && typeof child === "object") {
2074
- walk(child, childAncestors);
2075
- }
2076
- }
2077
- };
2078
- for (const row of visibleRows) {
2079
- const level = row.level;
2080
- if (level === 0 || level === void 0) {
2081
- walk(row, []);
2082
- }
2083
- }
2084
- for (const row of visibleRows) {
2085
- const id = getRowId(row, corpus.length);
2086
- if (seen.has(id)) continue;
2087
- walk(row, []);
2498
+ rightIds.push(column.id);
2499
+ result.set(column.id, {
2500
+ side: "right",
2501
+ offset: rightOffset,
2502
+ isEdge: false,
2503
+ edgeLeft: false,
2504
+ edgeRight: false,
2505
+ stack: 0
2506
+ });
2507
+ rightOffset += column.size;
2088
2508
  }
2089
- return corpus;
2509
+ rightIds.forEach((id, index) => {
2510
+ const entry = result.get(id);
2511
+ if (!entry) return;
2512
+ entry.stack = rightIds.length - index;
2513
+ });
2514
+ columns.forEach((column, index) => {
2515
+ if (!column.side) return;
2516
+ const entry = result.get(column.id);
2517
+ if (!entry) return;
2518
+ const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
2519
+ const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
2520
+ entry.edgeLeft = prevSide !== column.side;
2521
+ entry.edgeRight = nextSide !== column.side;
2522
+ if (index === 0) entry.edgeLeft = false;
2523
+ if (index === columns.length - 1) entry.edgeRight = false;
2524
+ entry.isEdge = entry.edgeLeft || entry.edgeRight;
2525
+ });
2526
+ return result;
2090
2527
  }
2091
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2092
- const keys = /* @__PURE__ */ new Set();
2093
- for (const [colIndex, corpusRowIndex] of results) {
2094
- const corpusRow = corpus[corpusRowIndex];
2095
- if (!corpusRow) continue;
2096
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2097
- if (visibleRowIndex === void 0) continue;
2098
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2099
- }
2100
- return keys;
2528
+ function getColumnFreezeStyle(offset, options) {
2529
+ if (!offset) return void 0;
2530
+ const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
2531
+ return {
2532
+ position: "sticky",
2533
+ ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
2534
+ zIndex: zBase + offset.stack
2535
+ };
2101
2536
  }
2102
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2103
- const [colIndex, corpusRowIndex] = item;
2104
- const corpusRow = corpus[corpusRowIndex];
2105
- if (!corpusRow) return null;
2106
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2107
- if (visibleRowIndex === void 0) return null;
2108
- return [colIndex, visibleRowIndex];
2537
+ function resolveHeaderFreezeOffset(column, freezeOffsets) {
2538
+ const direct = freezeOffsets.get(column.id);
2539
+ if (direct) return direct;
2540
+ const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
2541
+ if (leaves.length === 0) return void 0;
2542
+ const leafOffsets = [];
2543
+ for (const leaf of leaves) {
2544
+ const offset2 = freezeOffsets.get(leaf.id);
2545
+ if (!offset2) return void 0;
2546
+ leafOffsets.push(offset2);
2547
+ }
2548
+ const side = leafOffsets[0]?.side;
2549
+ if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
2550
+ return void 0;
2551
+ }
2552
+ const offset = Math.min(...leafOffsets.map((item) => item.offset));
2553
+ const leftmost = leafOffsets[0];
2554
+ const rightmost = leafOffsets[leafOffsets.length - 1];
2555
+ return {
2556
+ side,
2557
+ offset,
2558
+ edgeLeft: leftmost.edgeLeft,
2559
+ edgeRight: rightmost.edgeRight,
2560
+ isEdge: leftmost.edgeLeft || rightmost.edgeRight,
2561
+ stack: Math.max(...leafOffsets.map((item) => item.stack))
2562
+ };
2109
2563
  }
2110
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2111
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2564
+ function flattenHeaderLeaves(column) {
2565
+ if (!column.columns || column.columns.length === 0) return [column];
2566
+ return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2112
2567
  }
2113
2568
 
2114
2569
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
@@ -2116,16 +2571,35 @@ import {
2116
2571
  useCallback as useCallback3,
2117
2572
  useEffect as useEffect3,
2118
2573
  useId,
2119
- useMemo,
2574
+ useMemo as useMemo3,
2120
2575
  useRef as useRef3,
2121
2576
  useState as useState3
2122
2577
  } from "react";
2123
2578
  var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2579
+ var searchInstanceCount = 0;
2580
+ var lastPointerTarget = null;
2581
+ function trackPointerTarget(event) {
2582
+ lastPointerTarget = event.target;
2583
+ }
2584
+ function registerSearchInstance() {
2585
+ if (searchInstanceCount === 0) {
2586
+ document.addEventListener("pointerdown", trackPointerTarget, true);
2587
+ }
2588
+ searchInstanceCount += 1;
2589
+ return () => {
2590
+ searchInstanceCount -= 1;
2591
+ if (searchInstanceCount === 0) {
2592
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2593
+ lastPointerTarget = null;
2594
+ }
2595
+ };
2596
+ }
2124
2597
  function useInlineSearch({
2125
2598
  enabled = false,
2126
2599
  rowCount,
2127
2600
  columnCount,
2128
2601
  getCellValue,
2602
+ contentKey,
2129
2603
  initialStartRow = 0,
2130
2604
  showSearch: controlledShowSearch,
2131
2605
  searchValue: controlledSearchValue,
@@ -2334,6 +2808,7 @@ function useInlineSearch({
2334
2808
  }
2335
2809
  beginSearch(searchValue);
2336
2810
  }, [
2811
+ contentKey,
2337
2812
  beginSearch,
2338
2813
  cancelSearch,
2339
2814
  controlledSearchResults,
@@ -2354,6 +2829,9 @@ function useInlineSearch({
2354
2829
  if (!focusInside && active !== document.body) {
2355
2830
  return;
2356
2831
  }
2832
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2833
+ return;
2834
+ }
2357
2835
  }
2358
2836
  event.preventDefault();
2359
2837
  event.stopPropagation();
@@ -2367,14 +2845,18 @@ function useInlineSearch({
2367
2845
  }
2368
2846
  };
2369
2847
  window.addEventListener("keydown", handleKeyDown, true);
2370
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2848
+ const releaseInstance = registerSearchInstance();
2849
+ return () => {
2850
+ window.removeEventListener("keydown", handleKeyDown, true);
2851
+ releaseInstance();
2852
+ };
2371
2853
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2372
2854
  useEffect3(() => () => cancelSearch(), [cancelSearch]);
2373
- const searchMatchKeys = useMemo(
2855
+ const searchMatchKeys = useMemo3(
2374
2856
  () => buildSearchMatchKeys(searchResults),
2375
2857
  [searchResults]
2376
2858
  );
2377
- const activeMatch = useMemo(() => {
2859
+ const activeMatch = useMemo3(() => {
2378
2860
  if (!searchStatus || searchStatus.selectedIndex < 0) return null;
2379
2861
  return searchResults[searchStatus.selectedIndex] ?? null;
2380
2862
  }, [searchResults, searchStatus]);
@@ -2417,14 +2899,18 @@ function useInlineSearch({
2417
2899
  }
2418
2900
 
2419
2901
  // src/components/ui/table/features/row-expand/row-expand.ts
2420
- import { useEffect as useEffect4, useMemo as useMemo2, useRef as useRef4 } from "react";
2902
+ import { useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4 } from "react";
2421
2903
  function getFieldValue(row, key) {
2422
2904
  return row[key];
2423
2905
  }
2424
2906
  function canExpandRow(row) {
2425
2907
  const children = row.children;
2426
- const level = row.level;
2427
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
2908
+ return Array.isArray(children) && children.length > 0;
2909
+ }
2910
+ function toTreeToggleKey(value) {
2911
+ if (value === null || value === void 0) return null;
2912
+ const key = String(value);
2913
+ return key.length > 0 ? key : null;
2428
2914
  }
2429
2915
  function toggleExpandedRowId(rowId, previous) {
2430
2916
  const next = new Set(previous);
@@ -2445,7 +2931,8 @@ var useConvertTreeData = ({
2445
2931
  preventExpand = false,
2446
2932
  startIndex = 1,
2447
2933
  expandedRows,
2448
- onExpandedRowsChange
2934
+ onExpandedRowsChange,
2935
+ autoExpandOnLoad = true
2449
2936
  }) => {
2450
2937
  const onExpandedRowsChangeRef = useRef4(onExpandedRowsChange);
2451
2938
  const hasInitializedRef = useRef4(false);
@@ -2458,16 +2945,33 @@ var useConvertTreeData = ({
2458
2945
  return;
2459
2946
  }
2460
2947
  if (!enabled || hasInitializedRef.current) return;
2461
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2462
- onExpandedRowsChangeRef.current?.(new Set(ids));
2463
2948
  hasInitializedRef.current = true;
2464
- }, [enabled, data, toggleField]);
2465
- const processedData = useMemo2(() => {
2949
+ if (!autoExpandOnLoad) return;
2950
+ const ids = /* @__PURE__ */ new Set();
2951
+ const collect = (items) => {
2952
+ for (const item of items) {
2953
+ if (!item || typeof item !== "object") continue;
2954
+ const record = item;
2955
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
2956
+ if (key) ids.add(key);
2957
+ const nested = record[flattenField];
2958
+ if (Array.isArray(nested)) collect(nested);
2959
+ }
2960
+ };
2961
+ collect(data);
2962
+ onExpandedRowsChangeRef.current?.(ids);
2963
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
2964
+ const processedData = useMemo4(() => {
2466
2965
  if (!enabled || !data || data.length === 0) return [];
2467
2966
  const flattenedData = [];
2468
- const flattenItems = (items) => {
2469
- items.forEach((item) => {
2470
- const newItem = { ...item };
2967
+ const flattenItems = (items, parentPath) => {
2968
+ items.forEach((item, itemIndex) => {
2969
+ if (!item || typeof item !== "object") return;
2970
+ const source = {
2971
+ path: [...parentPath, itemIndex],
2972
+ childrenField: flattenField
2973
+ };
2974
+ const newItem = { ...item, [TREE_SOURCE]: source };
2471
2975
  const nested = newItem[flattenField];
2472
2976
  if (Array.isArray(nested)) {
2473
2977
  const children = nested.map(
@@ -2481,89 +2985,68 @@ var useConvertTreeData = ({
2481
2985
  child[childField] = newItem[toggleField];
2482
2986
  }
2483
2987
  });
2484
- flattenItems(children);
2988
+ flattenItems(children, source.path);
2485
2989
  } else {
2486
2990
  flattenedData.push(newItem);
2487
2991
  }
2488
2992
  });
2489
2993
  };
2490
- flattenItems(data);
2994
+ flattenItems(data, []);
2491
2995
  const dataWithLevels = flattenedData.map((item) => ({
2492
2996
  ...item,
2493
2997
  level: 0,
2494
2998
  children: [],
2495
2999
  processed: false
2496
3000
  }));
2497
- const findNearestPrecedingParent = (index, parentKey) => {
2498
- for (let i = index - 1; i >= 0; i -= 1) {
2499
- const candidate = dataWithLevels[i];
2500
- if (!candidate) continue;
2501
- if (getFieldValue(candidate, toggleField) === parentKey) {
2502
- return candidate;
2503
- }
2504
- }
2505
- return void 0;
2506
- };
2507
3001
  const rootItems = [];
3002
+ const latestByKey = /* @__PURE__ */ new Map();
2508
3003
  dataWithLevels.forEach((item) => {
2509
- if (!getFieldValue(item, childField)) {
2510
- rootItems.push(item);
2511
- item.processed = true;
2512
- }
2513
- });
2514
- dataWithLevels.forEach((item, index) => {
2515
3004
  const parentKey = getFieldValue(item, childField);
2516
- if (!parentKey || item.processed) return;
2517
- const parent = findNearestPrecedingParent(index, parentKey);
3005
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2518
3006
  if (parent) {
2519
3007
  item.level = parent.level + 1;
2520
3008
  parent.children.push(item);
2521
- item.processed = true;
2522
- return;
3009
+ } else {
3010
+ rootItems.push(item);
2523
3011
  }
2524
- rootItems.push(item);
2525
3012
  item.processed = true;
3013
+ latestByKey.set(getFieldValue(item, toggleField), item);
2526
3014
  });
2527
3015
  return rootItems;
2528
3016
  }, [enabled, data, toggleField, childField, flattenField]);
2529
- const flattenTree = useMemo2(() => {
3017
+ const flattenTree = useMemo4(() => {
2530
3018
  if (!enabled) return [];
2531
- const flatten = (nodes, result = [], level = 0) => {
3019
+ const flatten = (nodes, result, parentTreeNo) => {
2532
3020
  nodes.forEach((node, index) => {
2533
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
3021
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2534
3022
  const toggleValue = getFieldValue(node, toggleField);
2535
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3023
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2536
3024
  result.push({
2537
3025
  ...node,
2538
3026
  treeNo: currentIndex,
2539
3027
  uniqueId,
2540
3028
  processed: true
2541
3029
  });
2542
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
3030
+ const toggleKey = toTreeToggleKey(toggleValue);
3031
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
2543
3032
  if (shouldExpandChildren) {
2544
- flatten(node.children, result, index + startIndex);
3033
+ flatten(node.children, result, currentIndex);
2545
3034
  }
2546
3035
  });
2547
3036
  return result;
2548
3037
  };
2549
- const flattenedData = flatten(processedData, [], 0);
2550
- flattenedData.forEach((item, index) => {
3038
+ const flattenedData = flatten(processedData, [], null);
3039
+ const latestByKey = /* @__PURE__ */ new Map();
3040
+ flattenedData.forEach((item) => {
2551
3041
  const parentKey = getFieldValue(item, childField);
2552
3042
  if (!parentKey) {
2553
3043
  item.parentCount = 1;
2554
- return;
2555
- }
2556
- let parentItem;
2557
- for (let i = index - 1; i >= 0; i -= 1) {
2558
- const candidate = flattenedData[i];
2559
- if (!candidate) continue;
2560
- if (getFieldValue(candidate, toggleField) === parentKey) {
2561
- parentItem = candidate;
2562
- break;
2563
- }
3044
+ } else {
3045
+ const parentItem = latestByKey.get(parentKey);
3046
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3047
+ item.parentCount = parentAmount || 1;
2564
3048
  }
2565
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2566
- item.parentCount = parentAmount || 1;
3049
+ latestByKey.set(getFieldValue(item, toggleField), item);
2567
3050
  });
2568
3051
  return flattenedData;
2569
3052
  }, [
@@ -2576,22 +3059,11 @@ var useConvertTreeData = ({
2576
3059
  preventExpand,
2577
3060
  expandedRows
2578
3061
  ]);
2579
- const sortedData = useMemo2(() => {
3062
+ const sortedData = useMemo4(() => {
2580
3063
  if (!enabled) {
2581
3064
  return data ?? [];
2582
3065
  }
2583
- return [...flattenTree].sort((a, b) => {
2584
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2585
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2586
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2587
- const aVal = aParts[i] || 0;
2588
- const bVal = bParts[i] || 0;
2589
- if (aVal !== bVal) {
2590
- return aVal - bVal;
2591
- }
2592
- }
2593
- return 0;
2594
- });
3066
+ return flattenTree;
2595
3067
  }, [enabled, data, flattenTree]);
2596
3068
  return sortedData;
2597
3069
  };
@@ -2649,13 +3121,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2649
3121
  for (let index = 0; index < data.length; index++) {
2650
3122
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2651
3123
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2652
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3124
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2653
3125
  result.push({ rowSpan: 0, isFirstInGroup: false });
2654
3126
  continue;
2655
3127
  }
2656
3128
  let span = 1;
2657
3129
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2658
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3130
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2659
3131
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2660
3132
  span++;
2661
3133
  }
@@ -2748,6 +3220,9 @@ function collectRowSpanColumns(columns) {
2748
3220
  }
2749
3221
 
2750
3222
  // src/core/useGlideTable.ts
3223
+ function isProductionBuild() {
3224
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3225
+ }
2751
3226
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2752
3227
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2753
3228
  function useGlideTable(options) {
@@ -2769,18 +3244,24 @@ function useGlideTable(options) {
2769
3244
  selectOnRowClick = true,
2770
3245
  enableCellSelection = true,
2771
3246
  onDataChange,
2772
- onCellChange,
2773
- onBatchChange,
3247
+ onCellChange: onCellChangeProp,
3248
+ onBatchChange: onBatchChangeProp,
2774
3249
  cellRenderers,
2775
3250
  preserveRowSelection = false,
2776
- toggleField,
2777
- childField,
2778
- flattenField,
3251
+ toggleField: toggleFieldProp,
3252
+ idField,
3253
+ childField: childFieldProp,
3254
+ parentIdField,
3255
+ flattenField: flattenFieldProp,
3256
+ childrenField,
2779
3257
  qtyField,
3258
+ expandColumn,
2780
3259
  expandedRows: controlledExpandedRows,
2781
3260
  onExpandedRowsChange,
2782
3261
  preventExpand = false,
3262
+ autoExpandOnLoad = true,
2783
3263
  enableSubtreeCopy,
3264
+ escapeCopyFormulas = false,
2784
3265
  onCopyActionsReady,
2785
3266
  onRowsPaste,
2786
3267
  enableInsertPaste,
@@ -2801,9 +3282,28 @@ function useGlideTable(options) {
2801
3282
  onSearchValueChange,
2802
3283
  onSearchClose,
2803
3284
  searchResults,
2804
- onSearchResultsChanged
3285
+ onSearchResultsChanged,
3286
+ enableWasdNavigation = true
2805
3287
  } = options;
2806
- const labels = useMemo3(() => {
3288
+ const toggleField = toggleFieldProp ?? idField;
3289
+ const childField = childFieldProp ?? parentIdField;
3290
+ const flattenField = flattenFieldProp ?? childrenField;
3291
+ const onCellChange = useMemo5(() => {
3292
+ if (onCellChangeProp) return onCellChangeProp;
3293
+ if (!onBatchChangeProp) return void 0;
3294
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
3295
+ }, [onBatchChangeProp, onCellChangeProp]);
3296
+ const onBatchChange = useMemo5(() => {
3297
+ if (onBatchChangeProp) return onBatchChangeProp;
3298
+ if (!onCellChangeProp) return void 0;
3299
+ return (changes) => {
3300
+ for (const change of changes) {
3301
+ onCellChangeProp(change.rowId, change.columnId, change.value);
3302
+ }
3303
+ };
3304
+ }, [onBatchChangeProp, onCellChangeProp]);
3305
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
3306
+ const labels = useMemo5(() => {
2807
3307
  const resolved = resolveDataTableLabels(labelsProp);
2808
3308
  return {
2809
3309
  ...resolved,
@@ -2820,11 +3320,11 @@ function useGlideTable(options) {
2820
3320
  const [internalExpandedRows, setInternalExpandedRows] = useState4(
2821
3321
  () => /* @__PURE__ */ new Set()
2822
3322
  );
2823
- const [hoveredRowIndex, setHoveredRowIndex] = useState4(null);
3323
+ const [hoverStore] = useState4(createRowHoverStore);
2824
3324
  const scrollRef = useRef5(null);
2825
3325
  const rootRef = useRef5(null);
2826
3326
  const escapeDismissOwnerRef = useRef5(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
2827
- const cellRendererRegistry = useMemo3(
3327
+ const cellRendererRegistry = useMemo5(
2828
3328
  () => createCellRendererRegistry(cellRenderers),
2829
3329
  [cellRenderers]
2830
3330
  );
@@ -2843,7 +3343,7 @@ function useGlideTable(options) {
2843
3343
  );
2844
3344
  const columnSizing = controlledColumnSizing ?? internalColumnSizing;
2845
3345
  const columnOrder = controlledColumnOrder ?? internalColumnOrder;
2846
- const tableColumns = useMemo3(() => {
3346
+ const tableColumns = useMemo5(() => {
2847
3347
  if (!enableColumnReorder) return columns;
2848
3348
  return applyLeafColumnOrder(columns, columnOrder);
2849
3349
  }, [columnOrder, columns, enableColumnReorder]);
@@ -2877,8 +3377,10 @@ function useGlideTable(options) {
2877
3377
  qtyField,
2878
3378
  expandedRows,
2879
3379
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2880
- preventExpand
3380
+ preventExpand,
3381
+ autoExpandOnLoad
2881
3382
  });
3383
+ const sourceData = useMemo5(() => data ?? [], [data]);
2882
3384
  const table = useReactTable({
2883
3385
  data: tableData,
2884
3386
  columns: tableColumns,
@@ -2917,15 +3419,19 @@ function useGlideTable(options) {
2917
3419
  );
2918
3420
  },
2919
3421
  getCoreRowModel: getCoreRowModel(),
2920
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
3422
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
3423
+ // Tree rows: their path in the original data, which (unlike the
3424
+ // flattened index) survives expanding/collapsing rows above.
3425
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
3426
+ )
2921
3427
  });
2922
- const rowSpanColumnKeys = useMemo3(() => {
3428
+ const rowSpanColumnKeys = useMemo5(() => {
2923
3429
  if (!enableRowSpan) return [];
2924
3430
  return collectRowSpanColumns(columns);
2925
3431
  }, [enableRowSpan, columns]);
2926
3432
  const primaryRowSpanKey = rowSpanColumnKeys[0]?.rowSpanKey;
2927
3433
  const primaryRowSpanColumnId = rowSpanColumnKeys[0]?.columnId;
2928
- const columnRowSpanMap = useMemo3(
3434
+ const columnRowSpanMap = useMemo5(
2929
3435
  () => buildColumnRowSpanMap(tableData, rowSpanColumnKeys),
2930
3436
  [tableData, rowSpanColumnKeys]
2931
3437
  );
@@ -2934,7 +3440,21 @@ function useGlideTable(options) {
2934
3440
  const rows = table.getRowModel().rows;
2935
3441
  const columnCount = table.getAllLeafColumns().length || 1;
2936
3442
  const visibleLeafColumns = table.getVisibleLeafColumns();
2937
- const columnFreezeOffsets = useMemo3(() => {
3443
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
3444
+ const warnedBooleanColumnsRef = useRef5(/* @__PURE__ */ new Set());
3445
+ useEffect5(() => {
3446
+ if (!hasWriteCallback || isProductionBuild()) return;
3447
+ for (const column of visibleLeafColumns) {
3448
+ const meta = column.columnDef.meta;
3449
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
3450
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
3451
+ warnedBooleanColumnsRef.current.add(column.id);
3452
+ console.warn(
3453
+ `[react-glide-table] Column "${column.id}" (kind "boolean") has no \`editable\` prop, so its checkbox writes on click. Set editable={true} to keep that, or editable={false} for a read-only checkbox. A future major release will make boolean cells read-only unless editable is set, like other cells.`
3454
+ );
3455
+ }
3456
+ }, [hasWriteCallback, visibleLeafColumns]);
3457
+ const columnFreezeOffsets = useMemo5(() => {
2938
3458
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
2939
3459
  return buildColumnFreezeOffsets(
2940
3460
  visibleLeafColumns.map((column) => ({
@@ -2954,7 +3474,7 @@ function useGlideTable(options) {
2954
3474
  const totalSize = rowVirtualizer.getTotalSize();
2955
3475
  const paddingTop = virtualRows.length > 0 ? virtualRows[0]?.start ?? 0 : 0;
2956
3476
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0) : 0;
2957
- const selectedRowIndices = useMemo3(() => {
3477
+ const selectedRowIndices = useMemo5(() => {
2958
3478
  const indices = /* @__PURE__ */ new Set();
2959
3479
  for (const selectedRow of selectedRows) {
2960
3480
  indices.add(selectedRow.index);
@@ -2976,7 +3496,7 @@ function useGlideTable(options) {
2976
3496
  const cell = scrollElement.querySelector(
2977
3497
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
2978
3498
  );
2979
- if (cell instanceof HTMLElement) {
3499
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
2980
3500
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
2981
3501
  }
2982
3502
  };
@@ -2994,6 +3514,10 @@ function useGlideTable(options) {
2994
3514
  },
2995
3515
  [scrollCellIntoView]
2996
3516
  );
3517
+ const editKeyRef = useRef5(() => {
3518
+ });
3519
+ const clearKeyRef = useRef5(() => {
3520
+ });
2997
3521
  const {
2998
3522
  dragState,
2999
3523
  activeSelectionBounds,
@@ -3001,20 +3525,27 @@ function useGlideTable(options) {
3001
3525
  handleCellMouseEnter,
3002
3526
  handleFillHandleMouseDown,
3003
3527
  clearSelection: clearCellSelection,
3004
- copySelection
3528
+ copySelection,
3529
+ selectCell,
3530
+ focusSelection
3005
3531
  } = useCellSelection({
3006
- data: tableData,
3532
+ data: sourceData,
3007
3533
  rows,
3008
3534
  enabled: enableCellSelection,
3009
3535
  columnCount: visibleLeafColumns.length,
3536
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
3010
3537
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3538
+ escapeCopyFormulas,
3011
3539
  enableInsertPaste: enableInsertPaste ?? true,
3012
3540
  onDataChange,
3013
3541
  onBatchChange,
3014
3542
  onRowsPaste,
3015
3543
  onCellNavigate: handleCellNavigate,
3016
3544
  cellRendererRegistry,
3017
- rootRef
3545
+ rootRef,
3546
+ enableWasdNavigation,
3547
+ onEditKey: (position) => editKeyRef.current(position),
3548
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
3018
3549
  });
3019
3550
  const clearRowSelection = useCallback4(() => {
3020
3551
  if (rowSelectionMode === "none") return;
@@ -3035,22 +3566,79 @@ function useGlideTable(options) {
3035
3566
  const {
3036
3567
  editingCell,
3037
3568
  draftValue,
3569
+ draftInvalid,
3570
+ setDraftInvalid,
3038
3571
  setDraftValue,
3039
3572
  startEdit,
3040
3573
  commitEdit,
3041
3574
  cancelEdit
3042
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
3575
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
3576
+ editKeyRef.current = (position) => {
3577
+ startEdit(position.row, position.col);
3578
+ };
3579
+ clearKeyRef.current = (bounds) => {
3580
+ const changes = [];
3581
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
3582
+ const row = rows[rowIndex];
3583
+ if (!row) continue;
3584
+ const cells = row.getVisibleCells();
3585
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
3586
+ const cell = cells[colIndex];
3587
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
3588
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
3589
+ }
3590
+ }
3591
+ if (changes.length === 0) return;
3592
+ if (onBatchChange) {
3593
+ onBatchChange(changes);
3594
+ return;
3595
+ }
3596
+ if (!onDataChange) return;
3597
+ let next = sourceData;
3598
+ for (const change of changes) {
3599
+ const row = rows.find((item) => item.id === change.rowId);
3600
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
3601
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
3602
+ if (!row || !accessorKey) continue;
3603
+ next = applyCellChangesToData(next, [
3604
+ { original: row.original, index: row.index, accessorKey, value: null }
3605
+ ]);
3606
+ }
3607
+ if (next !== sourceData) onDataChange(next);
3608
+ };
3609
+ const commitEditAndMove = useCallback4(
3610
+ (raw, delta) => {
3611
+ const current = editingCell;
3612
+ if (!commitEdit(raw)) return false;
3613
+ if (current) {
3614
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
3615
+ }
3616
+ rootRef.current?.focus({ preventScroll: true });
3617
+ return true;
3618
+ },
3619
+ [commitEdit, editingCell, selectCell]
3620
+ );
3621
+ const cancelEditAndRefocus = useCallback4(() => {
3622
+ cancelEdit();
3623
+ rootRef.current?.focus({ preventScroll: true });
3624
+ }, [cancelEdit]);
3043
3625
  const commitRenderedCellValue = useCallback4(
3044
- (rowId, columnId, value) => commitCellValue({
3045
- data: tableData,
3046
- rows,
3047
- rowId,
3048
- columnId,
3049
- value,
3050
- onCellChange,
3051
- onDataChange
3052
- }),
3053
- [onCellChange, onDataChange, rows, tableData]
3626
+ (rowId, columnId, value) => {
3627
+ const columnDef = table.getColumn(columnId)?.columnDef;
3628
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
3629
+ return false;
3630
+ }
3631
+ return commitCellValue({
3632
+ data: sourceData,
3633
+ rows,
3634
+ rowId,
3635
+ columnId,
3636
+ value,
3637
+ onCellChange,
3638
+ onDataChange
3639
+ });
3640
+ },
3641
+ [onCellChange, onDataChange, rows, sourceData, table]
3054
3642
  );
3055
3643
  const getCellContext = useCallback4(
3056
3644
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3078,27 +3666,14 @@ function useGlideTable(options) {
3078
3666
  (row, index) => {
3079
3667
  if (getRowId) return getRowId(row, index);
3080
3668
  if (enableExpand) {
3081
- const record = row;
3082
- const idValue = record.id;
3083
- if (idValue != null && String(idValue).length > 0) {
3084
- return String(idValue);
3085
- }
3086
- const uniqueId = record.uniqueId;
3087
- if (uniqueId != null && String(uniqueId).length > 0) {
3088
- return String(uniqueId);
3089
- }
3090
- if (toggleField) {
3091
- const toggleValue = record[toggleField];
3092
- if (toggleValue != null && String(toggleValue).length > 0) {
3093
- return String(toggleValue);
3094
- }
3095
- }
3669
+ const treeKey = getTreeRowKey(row);
3670
+ if (treeKey) return treeKey;
3096
3671
  }
3097
3672
  return String(index);
3098
3673
  },
3099
- [enableExpand, getRowId, toggleField]
3674
+ [enableExpand, getRowId]
3100
3675
  );
3101
- const searchCorpus = useMemo3(() => {
3676
+ const searchCorpus = useMemo5(() => {
3102
3677
  if (!enableInlineSearch) return [];
3103
3678
  if (enableExpand && toggleField) {
3104
3679
  return buildTreeSearchCorpus(tableData, {
@@ -3116,35 +3691,66 @@ function useGlideTable(options) {
3116
3691
  ]);
3117
3692
  const searchCorpusRef = useRef5(searchCorpus);
3118
3693
  searchCorpusRef.current = searchCorpus;
3119
- const visibleRowIndexById = useMemo3(() => {
3694
+ const visibleRowIndexById = useMemo5(() => {
3120
3695
  const map = /* @__PURE__ */ new Map();
3121
3696
  for (const row of rows) {
3122
3697
  map.set(resolveSearchRowId(row.original, row.index), row.index);
3123
3698
  }
3124
3699
  return map;
3125
3700
  }, [resolveSearchRowId, rows]);
3126
- const getSearchCellValue = useCallback4(
3127
- (rowIndex, colIndex) => {
3128
- const corpusRow = searchCorpusRef.current[rowIndex];
3129
- const column = visibleLeafColumns[colIndex];
3130
- if (!corpusRow || !column) return void 0;
3701
+ const readSearchRawValue = useCallback4(
3702
+ (corpusRow, rowIndex, column) => {
3131
3703
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3132
3704
  if (visibleIndex !== void 0) {
3133
3705
  const visibleRow = rows[visibleIndex];
3134
3706
  if (visibleRow) {
3135
- return visibleRow.getValue(column.id);
3707
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3136
3708
  }
3137
3709
  }
3138
3710
  const columnDef = column.columnDef;
3139
3711
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3140
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3712
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3141
3713
  }
3142
3714
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3143
- return corpusRow.data[String(columnDef.accessorKey)];
3715
+ return {
3716
+ value: corpusRow.data[String(columnDef.accessorKey)],
3717
+ row: void 0
3718
+ };
3719
+ }
3720
+ return { value: corpusRow.data[column.id], row: void 0 };
3721
+ },
3722
+ [rows, visibleRowIndexById]
3723
+ );
3724
+ const getSearchCellValue = useCallback4(
3725
+ (rowIndex, colIndex) => {
3726
+ const corpusRow = searchCorpusRef.current[rowIndex];
3727
+ const column = visibleLeafColumns[colIndex];
3728
+ if (!corpusRow || !column) return void 0;
3729
+ if (isProtectedColumn(column.columnDef)) return void 0;
3730
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
3731
+ const meta = column.columnDef.meta;
3732
+ const searchValue2 = meta?.searchValue;
3733
+ if (!searchValue2 || searchValue2 === "value") return value;
3734
+ const ctx = {
3735
+ value,
3736
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
3737
+ index: row?.index ?? rowIndex,
3738
+ columnId: column.id,
3739
+ cellProps: meta?.cellProps,
3740
+ update: () => {
3741
+ }
3742
+ };
3743
+ try {
3744
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
3745
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
3746
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
3747
+ if (renderer) return reactNodeToText(renderer.render(ctx));
3748
+ } catch {
3749
+ return value;
3144
3750
  }
3145
- return corpusRow.data[column.id];
3751
+ return value;
3146
3752
  },
3147
- [rows, visibleLeafColumns, visibleRowIndexById]
3753
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3148
3754
  );
3149
3755
  const pendingSearchNavRef = useRef5(null);
3150
3756
  const focusSearchResult = useCallback4(
@@ -3195,11 +3801,19 @@ function useGlideTable(options) {
3195
3801
  focusSearchResult(pending.colIndex, visibleRowIndex);
3196
3802
  }, [focusSearchResult, rows, visibleRowIndexById]);
3197
3803
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
3804
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
3805
+ const searchContentKey = useMemo5(
3806
+ () => ({ data: sourceData, columns: searchColumnSignature }),
3807
+ [sourceData, searchColumnSignature]
3808
+ );
3198
3809
  const inlineSearch = useInlineSearch({
3199
3810
  enabled: enableInlineSearch,
3200
3811
  rowCount: searchCorpus.length,
3201
3812
  columnCount: visibleLeafColumns.length,
3202
3813
  getCellValue: getSearchCellValue,
3814
+ // Re-scan when the rows' content/order or the column order changes
3815
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
3816
+ contentKey: searchContentKey,
3203
3817
  initialStartRow: initialSearchStartRow,
3204
3818
  showSearch,
3205
3819
  searchValue,
@@ -3210,7 +3824,7 @@ function useGlideTable(options) {
3210
3824
  onNavigateToResult: navigateToCorpusSearchResult,
3211
3825
  rootRef
3212
3826
  });
3213
- const visibleSearchMatchKeys = useMemo3(() => {
3827
+ const visibleSearchMatchKeys = useMemo5(() => {
3214
3828
  if (!enableInlineSearch) return EMPTY_SEARCH_MATCH_KEYS;
3215
3829
  return mapSearchResultsToVisibleKeys(
3216
3830
  inlineSearch.searchResults,
@@ -3223,7 +3837,7 @@ function useGlideTable(options) {
3223
3837
  searchCorpus,
3224
3838
  visibleRowIndexById
3225
3839
  ]);
3226
- const visibleActiveMatch = useMemo3(() => {
3840
+ const visibleActiveMatch = useMemo5(() => {
3227
3841
  if (!enableInlineSearch || !inlineSearch.activeMatch) return null;
3228
3842
  return mapSearchResultToVisibleItem(
3229
3843
  inlineSearch.activeMatch,
@@ -3237,11 +3851,14 @@ function useGlideTable(options) {
3237
3851
  visibleRowIndexById
3238
3852
  ]);
3239
3853
  const clearHover = useCallback4(() => {
3240
- setHoveredRowIndex(null);
3241
- }, []);
3242
- const handleRowHover = useCallback4((rowIndex, _rowData) => {
3243
- setHoveredRowIndex(rowIndex);
3244
- }, []);
3854
+ hoverStore.setHoveredRowIndex(null);
3855
+ }, [hoverStore]);
3856
+ const handleRowHover = useCallback4(
3857
+ (rowIndex, _rowData) => {
3858
+ hoverStore.setHoveredRowIndex(rowIndex);
3859
+ },
3860
+ [hoverStore]
3861
+ );
3245
3862
  const handleToggleSelect = useCallback4(
3246
3863
  (row) => {
3247
3864
  if (!row.getCanSelect()) return;
@@ -3259,14 +3876,14 @@ function useGlideTable(options) {
3259
3876
  },
3260
3877
  [preventExpand, handleExpandedRowsChange, expandedRows]
3261
3878
  );
3262
- const rowContextValue = useMemo3(() => {
3879
+ const rowContextValue = useMemo5(() => {
3263
3880
  return {
3264
3881
  rowSpan: {
3265
3882
  enableRowSpan,
3266
3883
  primaryRowSpanKey,
3267
3884
  primaryRowSpanColumnId,
3268
3885
  columnRowSpanMap,
3269
- hoveredRowIndex,
3886
+ hoverStore,
3270
3887
  selectedRowIndices,
3271
3888
  onRowHover: handleRowHover
3272
3889
  },
@@ -3280,6 +3897,7 @@ function useGlideTable(options) {
3280
3897
  enableCellSelection,
3281
3898
  activeSelectionBounds,
3282
3899
  dragState,
3900
+ canFill,
3283
3901
  onCellMouseDown: handleCellMouseDownWithCommit,
3284
3902
  onCellMouseEnter: handleCellMouseEnter,
3285
3903
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3287,18 +3905,23 @@ function useGlideTable(options) {
3287
3905
  cellEdit: {
3288
3906
  editingCell,
3289
3907
  draftValue,
3908
+ draftInvalid,
3909
+ onDraftInvalidChange: setDraftInvalid,
3290
3910
  onDraftValueChange: setDraftValue,
3291
3911
  onStartEdit: startEdit,
3292
3912
  onCommitEdit: commitEdit,
3293
- onCancelEdit: cancelEdit
3913
+ onCommitEditAndMove: commitEditAndMove,
3914
+ onCancelEdit: cancelEditAndRefocus
3294
3915
  },
3295
3916
  cellRender: {
3296
3917
  registry: cellRendererRegistry,
3297
- commitValue: commitRenderedCellValue
3918
+ commitValue: commitRenderedCellValue,
3919
+ protectedLabel: labels.protectedCell
3298
3920
  },
3299
3921
  expand: {
3300
3922
  enableExpand,
3301
3923
  toggleField,
3924
+ expandColumn,
3302
3925
  expandedRows,
3303
3926
  preventExpand,
3304
3927
  onToggleExpand: handleToggleExpand,
@@ -3323,7 +3946,7 @@ function useGlideTable(options) {
3323
3946
  primaryRowSpanKey,
3324
3947
  primaryRowSpanColumnId,
3325
3948
  columnRowSpanMap,
3326
- hoveredRowIndex,
3949
+ hoverStore,
3327
3950
  selectedRowIndices,
3328
3951
  handleRowHover,
3329
3952
  rowSelectionMode,
@@ -3333,19 +3956,25 @@ function useGlideTable(options) {
3333
3956
  enableCellSelection,
3334
3957
  activeSelectionBounds,
3335
3958
  dragState,
3959
+ canFill,
3336
3960
  handleCellMouseDownWithCommit,
3337
3961
  handleCellMouseEnter,
3338
3962
  handleFillHandleMouseDown,
3339
3963
  editingCell,
3340
3964
  draftValue,
3965
+ draftInvalid,
3966
+ setDraftInvalid,
3341
3967
  setDraftValue,
3342
3968
  startEdit,
3343
3969
  commitEdit,
3344
- cancelEdit,
3970
+ commitEditAndMove,
3971
+ cancelEditAndRefocus,
3345
3972
  cellRendererRegistry,
3346
3973
  commitRenderedCellValue,
3974
+ labels.protectedCell,
3347
3975
  enableExpand,
3348
3976
  toggleField,
3977
+ expandColumn,
3349
3978
  expandedRows,
3350
3979
  preventExpand,
3351
3980
  handleToggleExpand,
@@ -3393,6 +4022,7 @@ function useGlideTable(options) {
3393
4022
  handleToggleSelect,
3394
4023
  clearHover,
3395
4024
  setColumnOrder,
4025
+ handleRootFocus: focusSelection,
3396
4026
  copySelection: stableCopySelection,
3397
4027
  inlineSearch: {
3398
4028
  showSearch: inlineSearch.showSearch,
@@ -3449,12 +4079,16 @@ function ResolvedTableCell({
3449
4079
  },
3450
4080
  [cellRender, columnId, row.id]
3451
4081
  );
4082
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
4083
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
4084
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
4085
+ }
3452
4086
  const ctx = {
3453
4087
  value,
3454
4088
  row,
3455
4089
  index: row.index,
3456
4090
  columnId,
3457
- cellProps: meta?.cellProps,
4091
+ cellProps,
3458
4092
  update
3459
4093
  };
3460
4094
  if (meta?.cellRender) {
@@ -3819,11 +4453,15 @@ function useColumnReorder(options) {
3819
4453
 
3820
4454
  // src/components/ui/table/components/DataTable/DataTable.tsx
3821
4455
  import { flexRender as flexRender2 } from "@tanstack/react-table";
3822
- import { useEffect as useEffect8, useMemo as useMemo4, useState as useState6 } from "react";
4456
+ import { useEffect as useEffect8, useLayoutEffect, useMemo as useMemo6, useState as useState6 } from "react";
3823
4457
 
3824
4458
  // src/components/ui/table/components/DataTable/DataTableRow.tsx
3825
4459
  import { flexRender } from "@tanstack/react-table";
3826
- import { useEffect as useEffect7, useRef as useRef7 } from "react";
4460
+ import {
4461
+ useEffect as useEffect7,
4462
+ useRef as useRef7,
4463
+ useSyncExternalStore
4464
+ } from "react";
3827
4465
 
3828
4466
  // src/components/ui/table/components/icons.tsx
3829
4467
  import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
@@ -3991,7 +4629,11 @@ function blurActiveElementOutside(container) {
3991
4629
  if (container instanceof Node && container.contains(active)) return;
3992
4630
  active.blur();
3993
4631
  }
3994
- function resolveExpandCellIndex(cells, toggleField) {
4632
+ function resolveExpandCellIndex(cells, toggleField, expandColumn) {
4633
+ if (expandColumn) {
4634
+ const explicitIndex = cells.findIndex((cell) => cell.column.id === expandColumn);
4635
+ if (explicitIndex >= 0) return explicitIndex;
4636
+ }
3995
4637
  if (!toggleField) return 0;
3996
4638
  const matchedIndex = cells.findIndex(
3997
4639
  (cell) => cell.column.id === toggleField
@@ -4034,7 +4676,7 @@ function DataTableRow({
4034
4676
  enableRowSpan,
4035
4677
  primaryRowSpanColumnId,
4036
4678
  columnRowSpanMap,
4037
- hoveredRowIndex,
4679
+ hoverStore,
4038
4680
  selectedRowIndices,
4039
4681
  onRowHover
4040
4682
  } = rowSpan;
@@ -4043,6 +4685,7 @@ function DataTableRow({
4043
4685
  enableCellSelection,
4044
4686
  activeSelectionBounds,
4045
4687
  dragState,
4688
+ canFill = true,
4046
4689
  onCellMouseDown,
4047
4690
  onCellMouseEnter,
4048
4691
  onFillHandleMouseDown
@@ -4050,9 +4693,12 @@ function DataTableRow({
4050
4693
  const {
4051
4694
  editingCell,
4052
4695
  draftValue,
4696
+ draftInvalid = false,
4697
+ onDraftInvalidChange,
4053
4698
  onDraftValueChange,
4054
4699
  onStartEdit,
4055
4700
  onCommitEdit,
4701
+ onCommitEditAndMove,
4056
4702
  onCancelEdit
4057
4703
  } = cellEdit;
4058
4704
  const renderCell = (tableCell) => flexRender(
@@ -4062,6 +4708,7 @@ function DataTableRow({
4062
4708
  const {
4063
4709
  enableExpand,
4064
4710
  toggleField,
4711
+ expandColumn,
4065
4712
  expandedRows,
4066
4713
  preventExpand,
4067
4714
  onToggleExpand,
@@ -4070,13 +4717,50 @@ function DataTableRow({
4070
4717
  } = expand;
4071
4718
  const rowIndex = row.index;
4072
4719
  const rowData = row.original;
4073
- const isRowHovered = hoveredRowIndex === rowIndex;
4074
4720
  const isRowSelected = row.getIsSelected();
4075
4721
  const { startRow: primaryGroupStart, rowSpan: primaryGroupSpan } = resolveRowSpanAt(
4076
4722
  primaryRowSpanColumnId ? columnRowSpanMap.get(primaryRowSpanColumnId) : void 0,
4077
4723
  rowIndex
4078
4724
  );
4079
- const isGroupHovered = enableRowSpan && hoveredRowIndex !== null && hoveredRowIndex >= primaryGroupStart && hoveredRowIndex <= primaryGroupStart + primaryGroupSpan - 1;
4725
+ const isRowHovered2 = useSyncExternalStore(
4726
+ hoverStore.subscribe,
4727
+ () => isRowHovered(hoverStore.getHoveredRowIndex(), rowIndex),
4728
+ () => false
4729
+ );
4730
+ const isGroupHovered = useSyncExternalStore(
4731
+ hoverStore.subscribe,
4732
+ () => isRowGroupHovered(
4733
+ hoverStore.getHoveredRowIndex(),
4734
+ enableRowSpan,
4735
+ primaryGroupStart,
4736
+ primaryGroupSpan
4737
+ ),
4738
+ () => false
4739
+ );
4740
+ const rowSpanColumnIds = enableRowSpan ? [...columnRowSpanMap.keys()].filter((id) => id !== primaryRowSpanColumnId) : [];
4741
+ const nestedRowSpanRanges = rowSpanColumnIds.map((columnId) => {
4742
+ const { startRow, rowSpan: span } = resolveRowSpanAt(
4743
+ columnRowSpanMap.get(columnId),
4744
+ rowIndex
4745
+ );
4746
+ return { columnId, startRow, span };
4747
+ });
4748
+ const nestedHoverSignature = useSyncExternalStore(
4749
+ hoverStore.subscribe,
4750
+ () => {
4751
+ const hovered = hoverStore.getHoveredRowIndex();
4752
+ return nestedRowSpanRanges.map(
4753
+ ({ startRow, span }) => isRowGroupHovered(hovered, true, startRow, span) ? "1" : "0"
4754
+ ).join("");
4755
+ },
4756
+ () => rowSpanColumnIds.map(() => "0").join("")
4757
+ );
4758
+ const nestedHoverByColumn = new Map(
4759
+ rowSpanColumnIds.map((columnId, index) => [
4760
+ columnId,
4761
+ nestedHoverSignature[index] === "1"
4762
+ ])
4763
+ );
4080
4764
  const visibleCells = row.getVisibleCells();
4081
4765
  const columnIdsByIndex = visibleCells.map((cell) => cell.column.id);
4082
4766
  row.getIsCellDragSelected = (columnId) => {
@@ -4122,12 +4806,13 @@ function DataTableRow({
4122
4806
  span
4123
4807
  );
4124
4808
  } : void 0;
4125
- const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField) : -1;
4809
+ const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField, expandColumn) : -1;
4126
4810
  const canExpand = enableExpand && !preventExpand && canExpandRow(rowData);
4127
4811
  const expandKey = toggleField && rowData[toggleField] !== null && rowData[toggleField] !== void 0 ? String(rowData[toggleField]) : null;
4128
4812
  const isExpanded = expandKey !== null && Boolean(expandedRows?.has(expandKey));
4129
4813
  const rowLevel = typeof rowData.level === "number" ? rowData.level : 0;
4130
4814
  const editInputRef = useRef7(null);
4815
+ const cellPressRef = useRef7(false);
4131
4816
  const isRowEditing = editingCell?.rowIndex === rowIndex;
4132
4817
  useEffect7(() => {
4133
4818
  if (!isRowEditing) return;
@@ -4140,23 +4825,29 @@ function DataTableRow({
4140
4825
  ref: measureElement,
4141
4826
  "data-index": virtualIndex,
4142
4827
  "data-selected": isRowSelected ? "" : void 0,
4143
- "data-hovered": isRowHovered || isGroupHovered ? "" : void 0,
4828
+ "data-hovered": isRowHovered2 || isGroupHovered ? "" : void 0,
4144
4829
  "data-expandable": enableExpand && canExpand ? "" : void 0,
4145
4830
  "data-expanded": isExpanded ? "" : void 0,
4831
+ "data-level": enableExpand ? rowLevel : void 0,
4146
4832
  className: cn(
4147
4833
  "DataTableRowJSX",
4148
4834
  !enableRowSpan && ROW_HOVER_CLASS,
4149
- enableRowSpan && isRowHovered && !isRowSelected && ROW_HOVERED_BG_CLASS,
4835
+ enableRowSpan && isRowHovered2 && !isRowSelected && ROW_HOVERED_BG_CLASS,
4150
4836
  isRowSelected && "is-selected",
4151
4837
  enableExpand && canExpand && "is-expandable",
4152
4838
  classNames?.row,
4153
4839
  getRowClassName?.(rowData, rowIndex)
4154
4840
  ),
4155
4841
  onMouseEnter: () => onRowHover(rowIndex, rowData),
4842
+ onMouseDownCapture: () => {
4843
+ cellPressRef.current = false;
4844
+ },
4156
4845
  onClick: () => {
4846
+ const startedCellSelection = cellPressRef.current;
4847
+ cellPressRef.current = false;
4157
4848
  if (isRowEditing) return;
4158
4849
  onRowClick?.(rowData, rowIndex);
4159
- if (rowSelectionMode !== "none" && selectOnRowClick) {
4850
+ if (rowSelectionMode !== "none" && selectOnRowClick && !startedCellSelection) {
4160
4851
  onToggleSelect();
4161
4852
  }
4162
4853
  },
@@ -4179,8 +4870,8 @@ function DataTableRow({
4179
4870
  }
4180
4871
  const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === cellIndex;
4181
4872
  const cellRowSpan = rowSpanInfo?.rowSpan ?? 1;
4182
- const isMergedCellHovered = hoveredRowIndex !== null && hoveredRowIndex >= rowIndex && hoveredRowIndex <= rowIndex + cellRowSpan - 1;
4183
- const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered;
4873
+ const isMergedCellHovered = columnId === primaryRowSpanColumnId ? isGroupHovered : nestedHoverByColumn.get(columnId) ?? false;
4874
+ const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered2;
4184
4875
  let isMergedCellSelected = false;
4185
4876
  if (isRowSpanColumn) {
4186
4877
  for (let r = rowIndex; r < rowIndex + cellRowSpan; r += 1) {
@@ -4202,7 +4893,7 @@ function DataTableRow({
4202
4893
  activeSelectionBounds,
4203
4894
  cellRowSpan
4204
4895
  );
4205
- const isBottomRightCell = !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4896
+ const isBottomRightCell = canFill && !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4206
4897
  const spanRowHeights = enableCellSelection && activeSelectionBounds && isCellDragSelected && cellRowSpan > 1 ? measureMergedSpanRowHeights(rowIndex, cellRowSpan) : void 0;
4207
4898
  const selectionEdgeStyle = getCellSelectionEdgeStyle(
4208
4899
  rowIndex,
@@ -4260,6 +4951,7 @@ function DataTableRow({
4260
4951
  if (isInteractiveMouseTarget(event.target)) return;
4261
4952
  event.preventDefault();
4262
4953
  blurActiveElementOutside(event.currentTarget);
4954
+ cellPressRef.current = true;
4263
4955
  onCellMouseDown(
4264
4956
  resolveCellRowIndex(event.clientY, event.currentTarget),
4265
4957
  cellIndex,
@@ -4313,6 +5005,8 @@ function DataTableRow({
4313
5005
  ref: editInputRef,
4314
5006
  type: editType === "number" ? "number" : "text",
4315
5007
  defaultValue: draftValue,
5008
+ "aria-invalid": draftInvalid ? true : void 0,
5009
+ "data-invalid": draftInvalid ? "" : void 0,
4316
5010
  className: cn(
4317
5011
  "cell-edit-input",
4318
5012
  CELL_ALIGN_CLASS[align],
@@ -4321,6 +5015,7 @@ function DataTableRow({
4321
5015
  ),
4322
5016
  onChange: (event) => {
4323
5017
  editInputProps?.onChange?.(event);
5018
+ onDraftInvalidChange?.(Boolean(event.target.validity?.badInput));
4324
5019
  onDraftValueChange(event.target.value);
4325
5020
  },
4326
5021
  onMouseDown: (event) => {
@@ -4334,9 +5029,22 @@ function DataTableRow({
4334
5029
  onKeyDown: (event) => {
4335
5030
  editInputProps?.onKeyDown?.(event);
4336
5031
  if (event.defaultPrevented) return;
4337
- if (event.key === "Enter") {
5032
+ if (event.nativeEvent.isComposing || event.keyCode === 229) {
5033
+ return;
5034
+ }
5035
+ if (event.key === "Enter" || event.key === "Tab") {
4338
5036
  event.preventDefault();
4339
- onCommitEdit(event.currentTarget.value);
5037
+ if (event.currentTarget.validity?.badInput) {
5038
+ onDraftInvalidChange?.(true);
5039
+ return;
5040
+ }
5041
+ const delta = event.key === "Enter" ? { row: event.shiftKey ? -1 : 1, col: 0 } : { row: 0, col: event.shiftKey ? -1 : 1 };
5042
+ if (onCommitEditAndMove) {
5043
+ onCommitEditAndMove(event.currentTarget.value, delta);
5044
+ } else {
5045
+ onCommitEdit(event.currentTarget.value);
5046
+ }
5047
+ return;
4340
5048
  }
4341
5049
  if (event.key === "Escape") {
4342
5050
  event.preventDefault();
@@ -4346,6 +5054,10 @@ function DataTableRow({
4346
5054
  onBlur: (event) => {
4347
5055
  editInputProps?.onBlur?.(event);
4348
5056
  if (event.defaultPrevented) return;
5057
+ if (event.currentTarget.validity?.badInput) {
5058
+ onDraftInvalidChange?.(true);
5059
+ return;
5060
+ }
4349
5061
  onCommitEdit(event.currentTarget.value);
4350
5062
  }
4351
5063
  }
@@ -4357,6 +5069,7 @@ function DataTableRow({
4357
5069
  "expand-cell-content",
4358
5070
  classNames?.expandCellContent
4359
5071
  ),
5072
+ style: { "--table-row-level": rowLevel },
4360
5073
  children: [
4361
5074
  rowLevel > 0 && /* @__PURE__ */ jsx4(
4362
5075
  "span",
@@ -4386,6 +5099,7 @@ function DataTableRow({
4386
5099
  {
4387
5100
  type: "button",
4388
5101
  "aria-label": isExpanded ? collapseRowLabel : expandRowLabel,
5102
+ "aria-expanded": isExpanded,
4389
5103
  className: cn(
4390
5104
  "expand-toggle-button",
4391
5105
  classNames?.expandToggle
@@ -4472,6 +5186,7 @@ function DataTableSearch({
4472
5186
  previousLabel,
4473
5187
  nextLabel,
4474
5188
  closeLabel,
5189
+ formatResult = formatSearchResultLabel,
4475
5190
  rowsTotal,
4476
5191
  classNames,
4477
5192
  onSearchValueChange,
@@ -4480,9 +5195,10 @@ function DataTableSearch({
4480
5195
  onPrevious
4481
5196
  }) {
4482
5197
  if (!showSearch) return null;
4483
- const resultString = searchStatus ? formatSearchResultLabel(searchStatus) : resultHint;
5198
+ const resultString = searchStatus ? formatResult(searchStatus) : resultHint;
4484
5199
  const progress = rowsTotal > 0 ? Math.floor((searchStatus?.rowsSearched ?? 0) / rowsTotal * 100) : 0;
4485
5200
  const handleKeyDown = (event) => {
5201
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
4486
5202
  if ((event.ctrlKey || event.metaKey) && event.code === "KeyF" || event.key === "Escape") {
4487
5203
  event.preventDefault();
4488
5204
  event.stopPropagation();
@@ -4606,6 +5322,7 @@ function DataTableToolbar({
4606
5322
  summary,
4607
5323
  selectedCount,
4608
5324
  selectionLabel,
5325
+ countLabel,
4609
5326
  toolbar,
4610
5327
  className,
4611
5328
  classNames
@@ -4619,7 +5336,7 @@ function DataTableToolbar({
4619
5336
  if (!hasLeftContent && !hasToolbar && !hasSelectionContent) return null;
4620
5337
  return /* @__PURE__ */ jsxs5("div", { className: cn("DataTableToolbarJSX", classNames?.toolbar, className), children: [
4621
5338
  /* @__PURE__ */ jsxs5("div", { className: cn("toolbar-left", classNames?.toolbarLeft), children: [
4622
- hasCount && /* @__PURE__ */ jsx6("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ jsxs5(Fragment, { children: [
5339
+ hasCount && /* @__PURE__ */ jsx6("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: countLabel ? countLabel(displayFiltered, totalCount) : displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ jsxs5(Fragment, { children: [
4623
5340
  /* @__PURE__ */ jsx6("span", { className: "toolbar-count-primary", children: displayFiltered }),
4624
5341
  /* @__PURE__ */ jsxs5("span", { className: "toolbar-count-placeholder", children: [
4625
5342
  " / ",
@@ -4746,7 +5463,8 @@ function DataTable({
4746
5463
  handleToggleSelect,
4747
5464
  clearHover,
4748
5465
  setColumnOrder,
4749
- inlineSearch
5466
+ inlineSearch,
5467
+ handleRootFocus
4750
5468
  } = useGlideTable(glideOptions);
4751
5469
  const ToolbarSlot = slots?.Toolbar ?? DataTableToolbar;
4752
5470
  const ScrollSlot = slots?.Scroll ?? DefaultScroll;
@@ -4780,7 +5498,7 @@ function DataTable({
4780
5498
  observer.observe(element);
4781
5499
  return () => observer.disconnect();
4782
5500
  }, [enableColumnResize, isPending, scrollRef, rows.length, leafColumnIds.join("|")]);
4783
- const layoutWidths = useMemo4(() => {
5501
+ const layoutWidths = useMemo6(() => {
4784
5502
  if (enableColumnResize) return void 0;
4785
5503
  const columns = table.getVisibleLeafColumns().map((column) => ({
4786
5504
  id: column.id,
@@ -4790,13 +5508,33 @@ function DataTable({
4790
5508
  }));
4791
5509
  return resolveColumnLayoutWidths(containerWidth, columns);
4792
5510
  }, [enableColumnResize, containerWidth, table, columnLayoutMetaSignature]);
4793
- const freezeOffsets = useMemo4(() => {
5511
+ const [measuredWidths, setMeasuredWidths] = useState6(
5512
+ () => /* @__PURE__ */ new Map()
5513
+ );
5514
+ useLayoutEffect(() => {
5515
+ if (!enableColumnFreeze || enableColumnResize) return;
5516
+ const element = scrollRef.current;
5517
+ if (!element) return;
5518
+ const next = /* @__PURE__ */ new Map();
5519
+ element.querySelectorAll("th[data-leaf-column-id]").forEach((th) => {
5520
+ const id = th.getAttribute("data-leaf-column-id");
5521
+ const width = th.getBoundingClientRect().width;
5522
+ if (id && width > 0) next.set(id, width);
5523
+ });
5524
+ setMeasuredWidths((previous) => {
5525
+ if (previous.size === next.size && [...next].every(([id, width]) => previous.get(id) === width)) {
5526
+ return previous;
5527
+ }
5528
+ return next;
5529
+ });
5530
+ });
5531
+ const freezeOffsets = useMemo6(() => {
4794
5532
  if (!enableColumnFreeze || enableColumnResize || !layoutWidths) {
4795
5533
  return rowContextValue.columnFreeze.offsets;
4796
5534
  }
4797
5535
  const columns = table.getVisibleLeafColumns().map((column) => ({
4798
5536
  id: column.id,
4799
- size: layoutWidths.get(column.id) ?? column.getSize(),
5537
+ size: measuredWidths.get(column.id) ?? layoutWidths.get(column.id) ?? column.getSize(),
4800
5538
  side: resolveColumnFreezeSide(column.columnDef.meta?.frozen)
4801
5539
  }));
4802
5540
  return buildColumnFreezeOffsets(columns);
@@ -4804,10 +5542,11 @@ function DataTable({
4804
5542
  enableColumnFreeze,
4805
5543
  enableColumnResize,
4806
5544
  layoutWidths,
5545
+ measuredWidths,
4807
5546
  rowContextValue.columnFreeze.offsets,
4808
5547
  table
4809
5548
  ]);
4810
- const contextValue = useMemo4(
5549
+ const contextValue = useMemo6(
4811
5550
  () => ({
4812
5551
  ...rowContextValue,
4813
5552
  classNames,
@@ -4836,6 +5575,10 @@ function DataTable({
4836
5575
  "div",
4837
5576
  {
4838
5577
  ref: rootRef,
5578
+ tabIndex: enableCellSelection ? 0 : void 0,
5579
+ onFocus: enableCellSelection ? (event) => {
5580
+ if (event.target === event.currentTarget) handleRootFocus();
5581
+ } : void 0,
4839
5582
  className: cn(
4840
5583
  "DataTableJSX",
4841
5584
  !enableCellSelection && "DataTableJSX--no-cell-selection",
@@ -4856,6 +5599,7 @@ function DataTable({
4856
5599
  summary,
4857
5600
  selectedCount,
4858
5601
  selectionLabel,
5602
+ countLabel: labels.count,
4859
5603
  toolbar,
4860
5604
  classNames
4861
5605
  }
@@ -4874,6 +5618,7 @@ function DataTable({
4874
5618
  previousLabel: labels.searchPrevious,
4875
5619
  nextLabel: labels.searchNext,
4876
5620
  closeLabel: labels.searchClose,
5621
+ formatResult: labels.searchResultCount,
4877
5622
  rowsTotal: inlineSearch.searchRowCount,
4878
5623
  classNames,
4879
5624
  onSearchValueChange: inlineSearch.setSearchValue,
@@ -4923,6 +5668,8 @@ function DataTable({
4923
5668
  (leafColumn) => isColumnReorderable(leafColumn.columnDef.meta)
4924
5669
  );
4925
5670
  const isDragging = draggingColumnId === header.column.id;
5671
+ const sortDirection = isPlaceholder ? void 0 : header.column.columnDef.meta?.sortDirection;
5672
+ const ariaSort = sortDirection === void 0 ? void 0 : sortDirection === "asc" ? "ascending" : sortDirection === "desc" ? "descending" : "none";
4926
5673
  const dropEdge = !isPlaceholder && dropTarget?.columnId === header.column.id ? dropTarget.edge : void 0;
4927
5674
  return /* @__PURE__ */ jsxs6(
4928
5675
  "th",
@@ -4938,7 +5685,8 @@ function DataTable({
4938
5685
  "data-resizing": header.column.getIsResizing() ? "" : void 0,
4939
5686
  "data-frozen": freezeOffset?.side,
4940
5687
  "data-freeze-edge": getColumnFreezeEdgeAttr(freezeOffset),
4941
- "aria-grabbed": isDragging ? true : void 0,
5688
+ "data-leaf-column-id": isLeafHeader ? header.column.id : void 0,
5689
+ "aria-sort": ariaSort,
4942
5690
  title: canDrag ? labels.reorderColumn : void 0,
4943
5691
  onPointerDown: enableColumnReorder ? (event) => onHeaderPointerDown(event, {
4944
5692
  columnId: header.column.id,
@@ -4965,7 +5713,31 @@ function DataTable({
4965
5713
  role: "separator",
4966
5714
  "aria-orientation": "vertical",
4967
5715
  "aria-label": labels.resizeColumn,
5716
+ "aria-valuenow": header.getSize(),
5717
+ tabIndex: 0,
4968
5718
  "data-table-disable-cell-selection": "",
5719
+ onKeyDown: (event) => {
5720
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {
5721
+ return;
5722
+ }
5723
+ event.preventDefault();
5724
+ event.stopPropagation();
5725
+ const step = event.shiftKey ? 50 : 10;
5726
+ const columnDef = header.column.columnDef;
5727
+ const min = columnDef.minSize ?? DATA_TABLE_COLUMN_MIN_SIZE;
5728
+ const max = columnDef.maxSize ?? DATA_TABLE_COLUMN_MAX_SIZE;
5729
+ const nextSize = Math.min(
5730
+ max,
5731
+ Math.max(
5732
+ min,
5733
+ header.getSize() + (event.key === "ArrowRight" ? step : -step)
5734
+ )
5735
+ );
5736
+ table.setColumnSizing((previous) => ({
5737
+ ...previous,
5738
+ [header.column.id]: nextSize
5739
+ }));
5740
+ },
4969
5741
  className: cn(
4970
5742
  "data-table-resize-handle",
4971
5743
  classNames?.resizeHandle
@@ -5073,16 +5845,21 @@ function DataTable({
5073
5845
  }
5074
5846
 
5075
5847
  // src/components/ui/table/components/Table/Table.tsx
5076
- import { useCallback as useCallback7, useMemo as useMemo5, useState as useState7 } from "react";
5848
+ import { useCallback as useCallback7, useMemo as useMemo7, useRef as useRef8, useState as useState7 } from "react";
5077
5849
 
5078
5850
  // src/components/ui/table/components/Table/buildColumnDef.tsx
5851
+ import { createContext as createContext2, use as use2 } from "react";
5079
5852
  import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
5853
+ var TableSortContext = createContext2(null);
5080
5854
  function SortableHeader({
5081
5855
  label,
5082
5856
  field,
5083
- sort,
5084
- onSort
5857
+ sort: sortProp,
5858
+ onSort: onSortProp
5085
5859
  }) {
5860
+ const context = use2(TableSortContext);
5861
+ const sort = context ? context.sort : sortProp;
5862
+ const onSort = context ? context.onSort : onSortProp;
5086
5863
  const isActive = sort?.field === field;
5087
5864
  const Icon = isActive ? sort.direction === "asc" ? ArrowUp : ArrowDown : ArrowUpDown;
5088
5865
  return /* @__PURE__ */ jsxs7(
@@ -5101,7 +5878,7 @@ function SortableHeader({
5101
5878
  }
5102
5879
  );
5103
5880
  }
5104
- function buildColumnDef(props, sort, onSort) {
5881
+ function buildColumnDef(props, sort, onSort, headerCache) {
5105
5882
  const {
5106
5883
  field,
5107
5884
  virtual = false,
@@ -5127,8 +5904,29 @@ function buildColumnDef(props, sort, onSort) {
5127
5904
  className,
5128
5905
  headerClassName,
5129
5906
  render,
5130
- copyValue
5907
+ copyValue,
5908
+ searchValue
5131
5909
  } = props;
5910
+ const createHeader = () => sortable ? () => /* @__PURE__ */ jsx8(
5911
+ SortableHeader,
5912
+ {
5913
+ label: children,
5914
+ field,
5915
+ sort,
5916
+ onSort
5917
+ }
5918
+ ) : (
5919
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
5920
+ () => children
5921
+ );
5922
+ const cached = headerCache?.get(field);
5923
+ let header;
5924
+ if (cached && cached.label === children && cached.sortable === sortable) {
5925
+ header = cached.render;
5926
+ } else {
5927
+ header = createHeader();
5928
+ headerCache?.set(field, { label: children, sortable, render: header });
5929
+ }
5132
5930
  return {
5133
5931
  id: field,
5134
5932
  ...!virtual ? { accessorKey: field } : {},
@@ -5136,18 +5934,7 @@ function buildColumnDef(props, sort, onSort) {
5136
5934
  ...minResizeWidth != null ? { minSize: minResizeWidth } : {},
5137
5935
  ...maxResizeWidth != null ? { maxSize: maxResizeWidth } : {},
5138
5936
  ...resizable === false ? { enableResizing: false } : {},
5139
- header: sortable ? () => /* @__PURE__ */ jsx8(
5140
- SortableHeader,
5141
- {
5142
- label: children,
5143
- field,
5144
- sort,
5145
- onSort
5146
- }
5147
- ) : (
5148
- // eslint-disable-next-line @typescript-eslint/promise-function-async
5149
- () => children
5150
- ),
5937
+ header,
5151
5938
  // eslint-disable-next-line @typescript-eslint/promise-function-async
5152
5939
  cell: (info) => /* @__PURE__ */ jsx8(ResolvedTableCell, { info }),
5153
5940
  meta: {
@@ -5162,6 +5949,8 @@ function buildColumnDef(props, sort, onSort) {
5162
5949
  cellProps,
5163
5950
  cellRender: render,
5164
5951
  copyValue,
5952
+ searchValue,
5953
+ sortDirection: sortable ? sort?.field === field ? sort.direction : false : void 0,
5165
5954
  frozen,
5166
5955
  reorderable,
5167
5956
  width,
@@ -5179,12 +5968,12 @@ function resolveGroupId(props, index) {
5179
5968
  }
5180
5969
  return `group:${index}`;
5181
5970
  }
5182
- function buildColumnDefsFromTree(nodes, sort, onSort) {
5971
+ function buildColumnDefsFromTree(nodes, sort, onSort, headerCache) {
5183
5972
  return nodes.map((node, index) => {
5184
5973
  if (node.type === "leaf") {
5185
- return buildColumnDef(node.props, sort, onSort);
5974
+ return buildColumnDef(node.props, sort, onSort, headerCache);
5186
5975
  }
5187
- const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort);
5976
+ const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort, headerCache);
5188
5977
  const { header, align, headerClassName } = node.props;
5189
5978
  return {
5190
5979
  id: resolveGroupId(node.props, index),
@@ -5320,13 +6109,22 @@ function TableColumnGroup(props) {
5320
6109
  TableColumnGroup.displayName = TABLE_COLUMN_GROUP_DISPLAY_NAME;
5321
6110
 
5322
6111
  // src/components/ui/table/components/Table/tableDataPipeline.ts
5323
- function sortTableData(data, sort) {
6112
+ function readField(row, field) {
6113
+ if (field in row || !field.includes(".")) return row[field];
6114
+ return field.split(".").reduce((current, key) => {
6115
+ if (current === null || current === void 0 || typeof current !== "object") {
6116
+ return void 0;
6117
+ }
6118
+ return current[key];
6119
+ }, row);
6120
+ }
6121
+ function sortTableData(data, sort, locale = "ko") {
5324
6122
  if (!sort) return data;
5325
6123
  const { field, direction } = sort;
5326
6124
  const multiplier = direction === "asc" ? 1 : -1;
5327
6125
  return [...data].sort((left, right) => {
5328
- const leftValue = left[field];
5329
- const rightValue = right[field];
6126
+ const leftValue = readField(left, field);
6127
+ const rightValue = readField(right, field);
5330
6128
  if ((leftValue === null || leftValue === void 0) && (rightValue === null || rightValue === void 0)) {
5331
6129
  return 0;
5332
6130
  }
@@ -5335,11 +6133,12 @@ function sortTableData(data, sort) {
5335
6133
  if (typeof leftValue === "number" && typeof rightValue === "number") {
5336
6134
  return (leftValue - rightValue) * multiplier;
5337
6135
  }
5338
- return String(leftValue).localeCompare(String(rightValue), "ko") * multiplier;
6136
+ return String(leftValue).localeCompare(String(rightValue), locale, { numeric: true }) * multiplier;
5339
6137
  });
5340
6138
  }
5341
6139
  function paginateTableData(data, page, pageSize) {
5342
- const safePage = Math.max(1, page);
6140
+ const lastPage = getTotalPages(data.length, pageSize);
6141
+ const safePage = Math.min(Math.max(1, page), lastPage);
5343
6142
  const start = (safePage - 1) * pageSize;
5344
6143
  return data.slice(start, start + pageSize);
5345
6144
  }
@@ -5347,6 +6146,36 @@ function getTotalPages(totalCount, pageSize) {
5347
6146
  if (pageSize <= 0) return 1;
5348
6147
  return Math.max(1, Math.ceil(totalCount / pageSize));
5349
6148
  }
6149
+ function buildTreeRootBlocks(data, fields, sort, locale) {
6150
+ const childrenByRow = /* @__PURE__ */ new Map();
6151
+ const roots = [];
6152
+ const latestById = /* @__PURE__ */ new Map();
6153
+ for (const row of data) {
6154
+ const parentKey = row[fields.parentIdField];
6155
+ const parent = parentKey !== null && parentKey !== void 0 && parentKey !== "" ? latestById.get(parentKey) : void 0;
6156
+ if (parent) {
6157
+ const siblings = childrenByRow.get(parent);
6158
+ if (siblings) siblings.push(row);
6159
+ else childrenByRow.set(parent, [row]);
6160
+ } else {
6161
+ roots.push(row);
6162
+ }
6163
+ latestById.set(row[fields.idField], row);
6164
+ }
6165
+ const appendSubtree = (row, out) => {
6166
+ out.push(row);
6167
+ const children = childrenByRow.get(row);
6168
+ if (!children) return;
6169
+ for (const child of sortTableData(children, sort, locale)) {
6170
+ appendSubtree(child, out);
6171
+ }
6172
+ };
6173
+ return sortTableData(roots, sort, locale).map((root) => {
6174
+ const block = [];
6175
+ appendSubtree(root, block);
6176
+ return block;
6177
+ });
6178
+ }
5350
6179
 
5351
6180
  // src/components/ui/table/components/Table/TableHeader.tsx
5352
6181
  function TableHeader(props) {
@@ -5362,7 +6191,9 @@ function TablePagination({
5362
6191
  pageSize = 10,
5363
6192
  totalCount = 0,
5364
6193
  onChange,
5365
- className
6194
+ className,
6195
+ previousLabel = "Previous page",
6196
+ nextLabel = "Next page"
5366
6197
  }) {
5367
6198
  const totalPages = getTotalPages(totalCount, pageSize);
5368
6199
  const safePage = Math.min(Math.max(1, page), totalPages);
@@ -5376,7 +6207,7 @@ function TablePagination({
5376
6207
  className: "pagination-button",
5377
6208
  disabled: !canGoPrev,
5378
6209
  onClick: () => onChange(safePage - 1),
5379
- "aria-label": "Previous page",
6210
+ "aria-label": previousLabel,
5380
6211
  children: /* @__PURE__ */ jsx9(ChevronLeft, { className: "pagination-button-icon" })
5381
6212
  }
5382
6213
  ),
@@ -5392,7 +6223,7 @@ function TablePagination({
5392
6223
  className: "pagination-button",
5393
6224
  disabled: !canGoNext,
5394
6225
  onClick: () => onChange(safePage + 1),
5395
- "aria-label": "Next page",
6226
+ "aria-label": nextLabel,
5396
6227
  children: /* @__PURE__ */ jsx9(ChevronRight, { className: "pagination-button-icon" })
5397
6228
  }
5398
6229
  )
@@ -5406,63 +6237,124 @@ function TableRoot({
5406
6237
  data,
5407
6238
  children,
5408
6239
  className,
6240
+ classNames,
5409
6241
  totalCount,
5410
6242
  filteredCount,
6243
+ onDataChange,
6244
+ getRowId,
6245
+ sort: controlledSort,
6246
+ defaultSort = null,
6247
+ onSortChange,
6248
+ sortLocale,
5411
6249
  ...dataTableProps
5412
6250
  }) {
5413
- const { header, pagination: paginationElement } = useMemo5(
6251
+ const { header, pagination: paginationElement } = useMemo7(
5414
6252
  () => parseTableChildren(children),
5415
6253
  [children]
5416
6254
  );
5417
- const [sort, setSort] = useState7(null);
5418
- const handleSort = useCallback7((field) => {
5419
- setSort((previous) => {
5420
- if (previous?.field !== field) {
5421
- return { field, direction: "asc" };
5422
- }
5423
- if (previous.direction === "asc") {
5424
- return { field, direction: "desc" };
6255
+ const [internalSort, setInternalSort] = useState7(defaultSort);
6256
+ const sort = controlledSort !== void 0 ? controlledSort : internalSort;
6257
+ const handleSort = useCallback7(
6258
+ (field) => {
6259
+ let next;
6260
+ if (sort?.field !== field) {
6261
+ next = { field, direction: "asc" };
6262
+ } else if (sort.direction === "asc") {
6263
+ next = { field, direction: "desc" };
6264
+ } else {
6265
+ next = null;
5425
6266
  }
5426
- return null;
5427
- });
5428
- }, []);
5429
- const columnTree = useMemo5(() => extractColumnTree(header), [header]);
5430
- const columns = useMemo5(
5431
- () => buildColumnDefsFromTree(columnTree, sort, handleSort),
6267
+ if (controlledSort === void 0) setInternalSort(next);
6268
+ onSortChange?.(next);
6269
+ },
6270
+ [controlledSort, onSortChange, sort]
6271
+ );
6272
+ const columnTree = useMemo7(() => extractColumnTree(header), [header]);
6273
+ const headerCacheRef = useRef8(/* @__PURE__ */ new Map());
6274
+ const columns = useMemo7(
6275
+ () => buildColumnDefsFromTree(columnTree, sort, handleSort, headerCacheRef.current),
5432
6276
  [columnTree, sort, handleSort]
5433
6277
  );
6278
+ const sortContextValue = useMemo7(() => ({ sort, onSort: handleSort }), [sort, handleSort]);
5434
6279
  const paginationProps = paginationElement?.props;
5435
6280
  const pageSize = paginationProps?.pageSize ?? 10;
5436
6281
  const page = paginationProps?.page ?? 1;
5437
6282
  const resolvedTotalCount = paginationProps?.totalCount ?? totalCount ?? data.length;
5438
- const tableData = useMemo5(() => {
5439
- const sortedData = sortTableData(data, sort);
5440
- if (!paginationProps) return sortedData;
6283
+ const isManualPagination = Boolean(paginationProps?.manual);
6284
+ const treeIdField = dataTableProps.toggleField ?? dataTableProps.idField;
6285
+ const isTree = Boolean(treeIdField);
6286
+ const treeParentIdField = dataTableProps.childField ?? dataTableProps.parentIdField ?? DEFAULT_TREE_PARENT_ID_FIELD;
6287
+ const treeBlocks = useMemo7(() => {
6288
+ if (!isTree || !treeIdField) return null;
6289
+ if (!sort && (!paginationProps || isManualPagination)) return null;
6290
+ return buildTreeRootBlocks(
6291
+ data,
6292
+ { idField: treeIdField, parentIdField: treeParentIdField },
6293
+ sort,
6294
+ sortLocale
6295
+ );
6296
+ }, [data, isManualPagination, isTree, paginationProps, sort, sortLocale, treeIdField, treeParentIdField]);
6297
+ const pageTotalCount = paginationProps?.totalCount ?? totalCount ?? (treeBlocks ? treeBlocks.length : data.length);
6298
+ const tableData = useMemo7(() => {
6299
+ if (treeBlocks) {
6300
+ const blocks = !paginationProps || isManualPagination ? treeBlocks : paginateTableData(treeBlocks, page, pageSize);
6301
+ return blocks.flat();
6302
+ }
6303
+ const sortedData = sortTableData(data, sort, sortLocale);
6304
+ if (!paginationProps || isManualPagination) return sortedData;
5441
6305
  return paginateTableData(sortedData, page, pageSize);
5442
- }, [data, sort, paginationProps, page, pageSize]);
6306
+ }, [treeBlocks, data, sort, sortLocale, paginationProps, isManualPagination, page, pageSize]);
6307
+ const originalIndexByRow = useMemo7(() => {
6308
+ const map = /* @__PURE__ */ new Map();
6309
+ data.forEach((row, index) => map.set(row, index));
6310
+ return map;
6311
+ }, [data]);
6312
+ const resolvedGetRowId = useMemo7(() => {
6313
+ if (getRowId) return getRowId;
6314
+ if (isTree) return void 0;
6315
+ return (row, index) => String(originalIndexByRow.get(row) ?? index);
6316
+ }, [isTree, getRowId, originalIndexByRow]);
6317
+ const handleDataChange = useMemo7(() => {
6318
+ if (!onDataChange) return void 0;
6319
+ return (next) => {
6320
+ const merged = data.slice();
6321
+ tableData.forEach((row, index) => {
6322
+ const nextRow = next[index];
6323
+ if (nextRow === void 0 || nextRow === row) return;
6324
+ const originalIndex = originalIndexByRow.get(row);
6325
+ if (originalIndex !== void 0) merged[originalIndex] = nextRow;
6326
+ });
6327
+ onDataChange(merged);
6328
+ };
6329
+ }, [data, onDataChange, originalIndexByRow, tableData]);
5443
6330
  if (countLeafColumns(columnTree) === 0) {
5444
6331
  console.warn("[Table] Declare at least one Table.Column inside Table.Header.");
5445
6332
  }
5446
- return /* @__PURE__ */ jsxs9("div", { className: "TableJSX", children: [
5447
- /* @__PURE__ */ jsx10(
6333
+ return /* @__PURE__ */ jsxs9("div", { className: cn("TableJSX", classNames?.tableRoot), children: [
6334
+ /* @__PURE__ */ jsx10(TableSortContext, { value: sortContextValue, children: /* @__PURE__ */ jsx10(
5448
6335
  DataTable,
5449
6336
  {
5450
6337
  ...dataTableProps,
6338
+ classNames,
6339
+ getRowId: resolvedGetRowId,
6340
+ onDataChange: handleDataChange,
5451
6341
  data: tableData,
5452
6342
  columns,
5453
6343
  totalCount: paginationProps ? resolvedTotalCount : totalCount,
5454
6344
  filteredCount: filteredCount ?? data.length,
5455
6345
  className: cn(className, paginationProps && "DataTableJSX--with-pagination")
5456
6346
  }
5457
- ),
6347
+ ) }),
5458
6348
  paginationProps && /* @__PURE__ */ jsx10(
5459
6349
  TablePagination,
5460
6350
  {
5461
6351
  page,
5462
6352
  pageSize,
5463
- totalCount: resolvedTotalCount,
6353
+ totalCount: pageTotalCount,
5464
6354
  onChange: paginationProps.onChange,
5465
- className: paginationProps.className
6355
+ className: cn(classNames?.pagination, paginationProps.className),
6356
+ previousLabel: paginationProps.previousLabel ?? dataTableProps.labels?.paginationPrevious,
6357
+ nextLabel: paginationProps.nextLabel ?? dataTableProps.labels?.paginationNext
5466
6358
  }
5467
6359
  )
5468
6360
  ] });
@@ -5535,6 +6427,7 @@ export {
5535
6427
  createSearchRegex,
5536
6428
  createTable,
5537
6429
  escapeSearchRegex,
6430
+ escapeSpreadsheetFormula,
5538
6431
  flattenSubtreeRows,
5539
6432
  formatCellValue,
5540
6433
  formatDefaultCellValue,