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/core.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";
@@ -51,7 +212,62 @@ var DATA_TABLE_COLUMN_MAX_SIZE = 800;
51
212
  var DATA_TABLE_COLUMN_REORDER_THRESHOLD = 4;
52
213
 
53
214
  // src/components/ui/table/features/cell-edit/useCellEdit.ts
54
- import { useCallback, useEffect, useRef, useState } from "react";
215
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
216
+
217
+ // src/components/ui/table/features/data-patch/dataPatch.ts
218
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
219
+ function getTreeSource(row) {
220
+ if (!row || typeof row !== "object") return void 0;
221
+ return row[TREE_SOURCE];
222
+ }
223
+ function getTreeRowKey(row) {
224
+ const source = getTreeSource(row);
225
+ if (!source) return void 0;
226
+ return `tree:${source.path.join(".")}`;
227
+ }
228
+ function setValueAtAccessor(record, accessorKey, value) {
229
+ if (!accessorKey.includes(".") || accessorKey in record) {
230
+ return { ...record, [accessorKey]: value };
231
+ }
232
+ const [head, ...rest] = accessorKey.split(".");
233
+ const current = record[head];
234
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
235
+ return {
236
+ ...record,
237
+ [head]: setValueAtAccessor(child, rest.join("."), value)
238
+ };
239
+ }
240
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
241
+ const [head, ...rest] = path;
242
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
243
+ const node = nodes[head];
244
+ if (!node || typeof node !== "object") return null;
245
+ const record = node;
246
+ let nextNode;
247
+ if (rest.length === 0) {
248
+ nextNode = setValueAtAccessor(record, accessorKey, value);
249
+ } else {
250
+ const children = record[childrenField];
251
+ if (!Array.isArray(children)) return null;
252
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
253
+ if (!nextChildren) return null;
254
+ nextNode = { ...record, [childrenField]: nextChildren };
255
+ }
256
+ const next = nodes.slice();
257
+ next[head] = nextNode;
258
+ return next;
259
+ }
260
+ function applyCellChangesToData(data, changes) {
261
+ let next = data;
262
+ for (const change of changes) {
263
+ const source = getTreeSource(change.original);
264
+ const path = source ? source.path : [change.index];
265
+ const childrenField = source?.childrenField ?? "";
266
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
267
+ if (patched) next = patched;
268
+ }
269
+ return next === data ? data.slice() : next;
270
+ }
55
271
 
56
272
  // src/components/ui/table/features/cell-edit/cellEdit.ts
57
273
  function getColumnAccessorKey(columnDef) {
@@ -60,7 +276,11 @@ function getColumnAccessorKey(columnDef) {
60
276
  }
61
277
  return columnDef.id;
62
278
  }
279
+ function isProtectedColumn(columnDef) {
280
+ return columnDef.meta?.kind === "protected";
281
+ }
63
282
  function isColumnEditable(columnDef) {
283
+ if (isProtectedColumn(columnDef)) return false;
64
284
  return Boolean(columnDef.meta?.editable);
65
285
  }
66
286
  function getColumnEditType(columnDef) {
@@ -93,10 +313,11 @@ function applyCellEdit(data, rows, rowIndex, colIndex, raw) {
93
313
  if (!accessorKey) return null;
94
314
  const parsed = parseCellEditValue(raw, getColumnEditType(columnDef));
95
315
  if (!parsed.ok) return null;
96
- const newData = data.map((row) => ({ ...row }));
97
- if (!newData[rowIndex]) return null;
98
- newData[rowIndex][accessorKey] = parsed.value;
99
- return newData;
316
+ const row = rows[rowIndex];
317
+ if (!row) return null;
318
+ return applyCellChangesToData(data, [
319
+ { original: row.original, index: row.index, accessorKey, value: parsed.value }
320
+ ]);
100
321
  }
101
322
 
102
323
  // src/components/ui/table/features/cell-render/commitCellValue.ts
@@ -120,12 +341,12 @@ function commitCellValue({
120
341
  if (!cell) return false;
121
342
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
122
343
  if (!accessorKey) return false;
123
- const dataIndex = row.index;
124
- if (dataIndex < 0 || dataIndex >= data.length) return false;
125
- const next = data.map((item) => ({ ...item }));
126
- const target = next[dataIndex];
127
- if (!target) return false;
128
- target[accessorKey] = value;
344
+ const next = applyCellChangesToData(data, [
345
+ { original: row.original, index: row.index, accessorKey, value }
346
+ ]);
347
+ if (next === data || next.every((item, index) => item === data[index])) {
348
+ return false;
349
+ }
129
350
  onDataChange?.(next);
130
351
  return true;
131
352
  }
@@ -137,19 +358,36 @@ function useCellEdit({
137
358
  onDataChange,
138
359
  onCellChange
139
360
  }) {
140
- const [editingCell, setEditingCell] = useState(null);
361
+ const [editingKey, setEditingKey] = useState(null);
141
362
  const [draftValue, setDraftValue] = useState("");
142
363
  const draftValueRef = useRef(draftValue);
143
- const editingCellRef = useRef(editingCell);
364
+ const [draftInvalid, setDraftInvalidState] = useState(false);
365
+ const draftInvalidRef = useRef(false);
366
+ const setDraftInvalid = useCallback((invalid) => {
367
+ draftInvalidRef.current = invalid;
368
+ setDraftInvalidState(invalid);
369
+ }, []);
144
370
  useEffect(() => {
145
371
  draftValueRef.current = draftValue;
146
372
  }, [draftValue]);
373
+ const editingCell = useMemo(
374
+ () => resolveEditingCell(rows, editingKey),
375
+ [rows, editingKey]
376
+ );
377
+ const editingCellRef = useRef(editingCell);
378
+ editingCellRef.current = editingCell;
147
379
  useEffect(() => {
148
- editingCellRef.current = editingCell;
149
- }, [editingCell]);
380
+ if (editingKey && !editingCell) {
381
+ setEditingKey(null);
382
+ setDraftValue("");
383
+ }
384
+ }, [editingCell, editingKey]);
150
385
  const cancelEdit = useCallback(() => {
151
- setEditingCell(null);
386
+ editingCellRef.current = null;
387
+ setEditingKey(null);
152
388
  setDraftValue("");
389
+ draftInvalidRef.current = false;
390
+ setDraftInvalidState(false);
153
391
  }, []);
154
392
  const commitEdit = useCallback(
155
393
  (raw) => {
@@ -169,6 +407,7 @@ function useCellEdit({
169
407
  cancelEdit();
170
408
  return true;
171
409
  }
410
+ if (draftInvalidRef.current) return false;
172
411
  const value = raw ?? draftValueRef.current;
173
412
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
174
413
  if (!parsed.ok) return false;
@@ -189,13 +428,15 @@ function useCellEdit({
189
428
  );
190
429
  const startEdit = useCallback(
191
430
  (rowIndex, colIndex) => {
192
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
193
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
431
+ const row = rows[rowIndex];
432
+ const cell = row?.getVisibleCells()[colIndex];
433
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
434
+ if (!isTextEditableValue(cell.getValue())) return;
194
435
  const current = editingCellRef.current;
195
436
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
196
437
  return;
197
438
  }
198
- setEditingCell({ rowIndex, colIndex });
439
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
199
440
  setDraftValue(getCellEditDraftValue(cell.getValue()));
200
441
  },
201
442
  [commitEdit, rows]
@@ -203,12 +444,55 @@ function useCellEdit({
203
444
  return {
204
445
  editingCell,
205
446
  draftValue,
447
+ draftInvalid,
448
+ setDraftInvalid,
206
449
  setDraftValue,
207
450
  startEdit,
208
451
  commitEdit,
209
452
  cancelEdit
210
453
  };
211
454
  }
455
+ function resolveEditingCell(rows, key) {
456
+ if (!key) return null;
457
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
458
+ if (rowIndex < 0) return null;
459
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
460
+ if (colIndex < 0) return null;
461
+ return { rowIndex, colIndex };
462
+ }
463
+ function isTextEditableValue(value) {
464
+ return value === null || value === void 0 || typeof value !== "object";
465
+ }
466
+
467
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
468
+ function formatObjectValue(value) {
469
+ const text = value.text ?? value.label ?? value.name ?? value.title;
470
+ if (text != null && text !== "") {
471
+ return formatCellValue(text);
472
+ }
473
+ try {
474
+ return JSON.stringify(value);
475
+ } catch {
476
+ return "";
477
+ }
478
+ }
479
+ function formatCellValue(value) {
480
+ if (value === null || value === void 0) return "";
481
+ if (value instanceof Date) {
482
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
483
+ }
484
+ if (Array.isArray(value)) {
485
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
486
+ }
487
+ if (typeof value === "object") {
488
+ return formatObjectValue(value);
489
+ }
490
+ if (typeof value === "string") return value;
491
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
492
+ return String(value);
493
+ }
494
+ return "";
495
+ }
212
496
 
213
497
  // src/components/ui/table/features/cell-render/builtins.tsx
214
498
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -232,8 +516,9 @@ function asDrilldownItems(value) {
232
516
  const record = item;
233
517
  const text = asString(record.text ?? record.label ?? "");
234
518
  if (!text) return [];
235
- const img = record.img ?? record.image;
236
- return [{ text, ...typeof img === "string" ? { img } : {} }];
519
+ const rawImg = record.img ?? record.image;
520
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
521
+ return [{ text, ...img ? { img } : {} }];
237
522
  }
238
523
  return [{ text: asString(item) }];
239
524
  });
@@ -294,6 +579,22 @@ function sanitizeUriHref(raw) {
294
579
  return href;
295
580
  }
296
581
  }
582
+ function sanitizeImageSrc(raw) {
583
+ const src = raw.trim();
584
+ if (!src) return null;
585
+ try {
586
+ const parsed = new URL(src);
587
+ const protocol = parsed.protocol.toLowerCase();
588
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
589
+ return src;
590
+ }
591
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
592
+ return null;
593
+ } catch {
594
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
595
+ return src;
596
+ }
597
+ }
297
598
  function UriCell({ value }) {
298
599
  const raw = asString(value);
299
600
  if (!raw) return null;
@@ -315,7 +616,10 @@ function UriCell({ value }) {
315
616
  );
316
617
  }
317
618
  function ImageCell({ value }) {
318
- const urls = asStringList(value);
619
+ const urls = asStringList(value).flatMap((url) => {
620
+ const src = sanitizeImageSrc(url);
621
+ return src ? [src] : [];
622
+ });
319
623
  if (urls.length === 0) return null;
320
624
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ jsx(
321
625
  "img",
@@ -368,8 +672,33 @@ function DrilldownCell({ value }) {
368
672
  function LoadingCell() {
369
673
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-loading", "aria-busy": "true" });
370
674
  }
371
- function ProtectedCell() {
372
- return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
675
+ function ProtectedCell({ cellProps }) {
676
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
677
+ return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
678
+ }
679
+ function RowSelectCell({ row, cellProps }) {
680
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
681
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
682
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
683
+ return /* @__PURE__ */ jsx(
684
+ "input",
685
+ {
686
+ type: "checkbox",
687
+ className: "data-table-cell-row-select",
688
+ checked,
689
+ disabled: !canSelect,
690
+ "aria-label": label,
691
+ onChange: () => {
692
+ if (canSelect) row.toggleSelected();
693
+ },
694
+ onClick: (event) => {
695
+ event.stopPropagation();
696
+ },
697
+ onMouseDown: (event) => {
698
+ event.stopPropagation();
699
+ }
700
+ }
701
+ );
373
702
  }
374
703
  function RowIdCell({ value }) {
375
704
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -385,7 +714,8 @@ var BUILTIN_RENDER_MAP = {
385
714
  drilldown: DrilldownCell,
386
715
  loading: LoadingCell,
387
716
  protected: ProtectedCell,
388
- "row-id": RowIdCell
717
+ "row-id": RowIdCell,
718
+ "row-select": RowSelectCell
389
719
  };
390
720
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
391
721
  kind,
@@ -419,496 +749,170 @@ function formatDefaultCellValue(value) {
419
749
  return String(value);
420
750
  }
421
751
  if (typeof value === "bigint") return value.toString();
422
- return String(value);
752
+ return formatCellValue(value);
423
753
  }
424
754
 
425
- // src/components/ui/table/features/cell-render/withCellUpdate.ts
426
- function withCellUpdate(context, commitValue) {
427
- return {
428
- ...context,
429
- update: (next) => {
430
- commitValue(context.row.id, context.column.id, next);
431
- }
432
- };
433
- }
755
+ // src/components/ui/table/features/cell-selection/copyData.ts
756
+ import { isValidElement } from "react";
434
757
 
435
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
436
- import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
758
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
759
+ var lastSubtreeCopy = null;
760
+ function normalize(text) {
761
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
762
+ }
763
+ function rememberSubtreeCopy(text) {
764
+ lastSubtreeCopy = normalize(text);
765
+ }
766
+ function isOwnSubtreeCopy(text) {
767
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
768
+ }
437
769
 
438
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
439
- var activeOwner = null;
440
- var clearByOwner = /* @__PURE__ */ new Map();
441
- function createCellSelectionOwner() {
442
- return /* @__PURE__ */ Symbol("cell-selection-owner");
770
+ // src/components/ui/table/features/cell-selection/copyData.ts
771
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
772
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
773
+ function escapeSpreadsheetFormula(text) {
774
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
775
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
776
+ return `'${text}`;
443
777
  }
444
- function registerCellSelectionOwner(owner, clearSelection) {
445
- clearByOwner.set(owner, clearSelection);
446
- return () => {
447
- clearByOwner.delete(owner);
448
- if (activeOwner === owner) {
449
- activeOwner = null;
450
- }
451
- };
778
+ function isReactNodeIterable(node) {
779
+ return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
452
780
  }
453
- function claimCellSelectionOwner(owner) {
454
- if (activeOwner === owner) return;
455
- activeOwner = owner;
456
- for (const [id, clearSelection] of clearByOwner) {
457
- if (id !== owner) {
458
- clearSelection();
459
- }
781
+ function getElementTypeName(type) {
782
+ if (typeof type === "string") return type;
783
+ if (typeof type === "function") {
784
+ const fn = type;
785
+ return fn.displayName || fn.name || "";
460
786
  }
461
- }
462
- function isActiveCellSelectionOwner(owner) {
463
- return activeOwner === owner;
464
- }
465
- function releaseCellSelectionOwner(owner) {
466
- if (activeOwner === owner) {
467
- activeOwner = null;
787
+ if (typeof type === "object" && type !== null) {
788
+ const component = type;
789
+ return component.displayName || component.render?.displayName || component.render?.name || "";
468
790
  }
791
+ return "";
469
792
  }
470
-
471
- // src/components/ui/table/features/cell-selection/cellSelection.ts
472
- var INITIAL_DRAG_STATE = {
473
- isSelecting: false,
474
- isFillDragging: false,
475
- start: null,
476
- end: null,
477
- fillAnchor: null,
478
- fillEnd: null
479
- };
480
- function getCellSelectionBounds(start, end) {
481
- if (!start || !end) return null;
482
- return {
483
- startRow: Math.min(start.row, end.row),
484
- endRow: Math.max(start.row, end.row),
485
- startCol: Math.min(start.col, end.col),
486
- endCol: Math.max(start.col, end.col)
487
- };
793
+ function isButtonReactElement(node) {
794
+ const typeName = getElementTypeName(node.type);
795
+ if (typeName === "button" || /button/i.test(typeName)) return true;
796
+ const props = node.props;
797
+ if (props.role === "button") return true;
798
+ if (typeName === "input" && props.type === "button") return true;
799
+ return false;
488
800
  }
489
- function getCellNavigationDelta(key) {
490
- switch (key) {
491
- case "ArrowUp":
492
- case "w":
493
- case "W":
494
- return { row: -1, col: 0 };
495
- case "ArrowDown":
496
- case "s":
497
- case "S":
498
- return { row: 1, col: 0 };
499
- case "ArrowLeft":
500
- case "a":
501
- case "A":
502
- return { row: 0, col: -1 };
503
- case "ArrowRight":
504
- case "d":
505
- case "D":
506
- return { row: 0, col: 1 };
507
- default:
508
- return null;
509
- }
801
+ function isImageReactElement(node) {
802
+ const typeName = getElementTypeName(node.type);
803
+ return typeName === "img" || typeName === "image" || /image/i.test(typeName);
510
804
  }
511
- function clampCellPosition(position, rowCount, columnCount) {
512
- const maxRow = Math.max(rowCount - 1, 0);
513
- const maxCol = Math.max(columnCount - 1, 0);
514
- return {
515
- row: Math.min(Math.max(position.row, 0), maxRow),
516
- col: Math.min(Math.max(position.col, 0), maxCol)
517
- };
805
+ var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
806
+ function isLikelyUrl(value) {
807
+ const trimmed = value.trim();
808
+ if (!trimmed) return false;
809
+ if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
810
+ if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
811
+ return false;
518
812
  }
519
- function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
520
- if (rowSpan <= 1) return void 0;
521
- const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
522
- if (!tbody) return void 0;
523
- const rows = tbody.querySelectorAll(":scope > tr");
524
- if (rows.length < rowIndex + rowSpan) return void 0;
525
- const heights = [];
526
- for (let i = 0; i < rowSpan; i++) {
527
- const row = rows[rowIndex + i];
528
- const height = row?.getBoundingClientRect().height ?? 0;
529
- if (height <= 0) return void 0;
530
- heights.push(height);
813
+ function pickUrlFromUnknown(value) {
814
+ if (typeof value === "string") {
815
+ return isLikelyUrl(value) ? value.trim() : "";
531
816
  }
532
- return heights;
533
- }
534
- function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
535
- if (rowSpan <= 1) return rowIndex;
536
- const rect = cellElement.getBoundingClientRect();
537
- const relativeY = clientY - rect.top;
538
- const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
539
- if (heights && heights.length === rowSpan) {
540
- let accrued = 0;
541
- for (let i = 0; i < rowSpan; i++) {
542
- accrued += heights[i];
543
- if (relativeY < accrued) {
544
- return rowIndex + i;
817
+ if (Array.isArray(value)) {
818
+ return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
819
+ }
820
+ if (value && typeof value === "object") {
821
+ const record = value;
822
+ for (const key of IMAGE_URL_PROP_KEYS) {
823
+ const candidate = record[key];
824
+ if (typeof candidate === "string" && candidate.trim()) {
825
+ return candidate.trim();
545
826
  }
546
827
  }
547
- return rowIndex + rowSpan - 1;
548
828
  }
549
- const rowHeight = rect.height / rowSpan;
550
- const offset = Math.min(
551
- Math.max(Math.floor(relativeY / rowHeight), 0),
552
- rowSpan - 1
553
- );
554
- return rowIndex + offset;
829
+ return "";
555
830
  }
556
- function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
557
- if (!bounds) return false;
558
- const cellEndRow = rowIndex + rowSpan - 1;
559
- return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
831
+ function imageElementText(node) {
832
+ const props = node.props;
833
+ for (const key of IMAGE_URL_PROP_KEYS) {
834
+ const candidate = props[key];
835
+ if (typeof candidate === "string" && candidate.trim()) {
836
+ return candidate.trim();
837
+ }
838
+ }
839
+ return "";
560
840
  }
561
- function getActiveSelectionBounds(dragState, selectionBounds) {
562
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
563
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
841
+ function reactNodeContainsImage(node) {
842
+ if (isValidElement(node)) {
843
+ if (isImageReactElement(node)) return true;
844
+ return reactNodeContainsImage(node.props.children);
564
845
  }
565
- return selectionBounds;
846
+ if (isReactNodeIterable(node)) {
847
+ for (const child of node) {
848
+ if (reactNodeContainsImage(child)) return true;
849
+ }
850
+ }
851
+ return false;
566
852
  }
567
- var SELECTION_EDGE_WIDTH_PX = 2;
568
- var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
569
- var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
570
- function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
571
- const clampedFrom = Math.max(fromRow, rowIndex);
572
- const clampedTo = Math.min(toRowExclusive, rowIndex + span);
573
- if (clampedTo <= clampedFrom) {
574
- return { offsetRatio: 0, lengthRatio: 0 };
853
+ function readImgUrl(img) {
854
+ const attr = img.getAttribute("src")?.trim() ?? "";
855
+ if (attr) return attr;
856
+ if (img instanceof HTMLImageElement) {
857
+ const current = img.currentSrc?.trim() ?? "";
858
+ if (current && current !== img.baseURI) return current;
575
859
  }
576
- if (!rowHeights || rowHeights.length !== span) {
577
- return {
578
- offsetRatio: (clampedFrom - rowIndex) / span,
579
- lengthRatio: (clampedTo - clampedFrom) / span
580
- };
860
+ return "";
861
+ }
862
+ function readDomImageUrls(rowIndex, colIndex, root) {
863
+ const scope = root ?? (typeof document === "undefined" ? null : document);
864
+ if (!scope) return "";
865
+ const cells = scope.querySelectorAll(
866
+ `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
867
+ );
868
+ for (const cell of cells) {
869
+ const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
870
+ const url = readImgUrl(img);
871
+ return url ? [url] : [];
872
+ });
873
+ if (urls.length > 0) return urls.join(", ");
581
874
  }
582
- const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
583
- let offsetPx = 0;
584
- for (let i = 0; i < clampedFrom - rowIndex; i++) {
585
- offsetPx += rowHeights[i] ?? 0;
875
+ return "";
876
+ }
877
+ function reactNodeToText(node) {
878
+ if (node == null || typeof node === "boolean") return "";
879
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
880
+ return String(node);
586
881
  }
587
- let lengthPx = 0;
588
- for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
589
- lengthPx += rowHeights[i] ?? 0;
882
+ if (isReactNodeIterable(node)) {
883
+ let text = "";
884
+ for (const child of node) {
885
+ text += reactNodeToText(child);
886
+ }
887
+ return text;
888
+ }
889
+ if (isValidElement(node)) {
890
+ if (isButtonReactElement(node)) return "";
891
+ const props = node.props;
892
+ const childText = reactNodeToText(props.children);
893
+ if (childText) return childText;
894
+ const fromImage = imageElementText(node);
895
+ if (fromImage) return fromImage;
896
+ if (isImageReactElement(node)) return "";
897
+ if (typeof props.alt === "string" && props.alt) return props.alt;
898
+ if (typeof props.title === "string" && props.title) return props.title;
899
+ return "";
590
900
  }
901
+ return "";
902
+ }
903
+ function quoteTsvCell(text) {
904
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
905
+ return `"${text.replace(/"/g, '""')}"`;
906
+ }
907
+ function sanitizeClipboardCell(text) {
908
+ return text.replace(/\s+/g, " ").trim();
909
+ }
910
+ function createCopyRenderRow(rowData, index) {
591
911
  return {
592
- offsetRatio: offsetPx / total,
593
- lengthRatio: lengthPx / total,
594
- offsetPx,
595
- lengthPx
596
- };
597
- }
598
- function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
599
- const cellEndRow = rowIndex + rowSpan - 1;
600
- const span = cellEndRow - rowIndex + 1;
601
- if (span <= 1) return [];
602
- const edges = [];
603
- const isNeighborSelected = (row, neighborCol) => {
604
- if (isVisuallySelectedAt) {
605
- return isVisuallySelectedAt(row, neighborCol);
606
- }
607
- return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
608
- };
609
- const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
610
- let runStart = null;
611
- for (let row = fromRow; row < toRowExclusive; row++) {
612
- if (!isNeighborSelected(row, neighborCol)) {
613
- if (runStart === null) runStart = row;
614
- continue;
615
- }
616
- if (runStart !== null) {
617
- const ratios = rowRangeToHeightRatios(
618
- rowIndex,
619
- span,
620
- runStart,
621
- row,
622
- rowHeights
623
- );
624
- if (ratios.lengthRatio > 0) {
625
- edges.push({ side, ...ratios });
626
- }
627
- runStart = null;
628
- }
629
- }
630
- if (runStart !== null) {
631
- const ratios = rowRangeToHeightRatios(
632
- rowIndex,
633
- span,
634
- runStart,
635
- toRowExclusive,
636
- rowHeights
637
- );
638
- if (ratios.lengthRatio > 0) {
639
- edges.push({ side, ...ratios });
640
- }
641
- }
642
- };
643
- const collectSide = (side, neighborCol) => {
644
- if (bounds.startRow > rowIndex) {
645
- pushUnselectedRuns(
646
- side,
647
- neighborCol,
648
- rowIndex,
649
- Math.min(bounds.startRow, cellEndRow + 1)
650
- );
651
- }
652
- if (bounds.endRow < cellEndRow) {
653
- pushUnselectedRuns(
654
- side,
655
- neighborCol,
656
- Math.max(bounds.endRow + 1, rowIndex),
657
- cellEndRow + 1
658
- );
659
- }
660
- };
661
- if (colIndex < bounds.endCol) {
662
- collectSide("right", colIndex + 1);
663
- }
664
- if (colIndex > bounds.startCol) {
665
- collectSide("left", colIndex - 1);
666
- }
667
- return edges;
668
- }
669
- function buildPartialEdgeGradient(edge) {
670
- const usePx = edge.offsetPx != null && edge.lengthPx != null;
671
- const startPct = edge.offsetRatio * 100;
672
- const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
673
- const startPx = edge.offsetPx ?? 0;
674
- const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
675
- const overlapPx = SELECTION_EDGE_WIDTH_PX;
676
- const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
677
- const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
678
- const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
679
- const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
680
- const xPos = edge.side === "left" ? "0" : "100%";
681
- const layers = [
682
- {
683
- image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
684
- size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
685
- position: `${xPos} 0`
686
- }
687
- ];
688
- if (isTopProtrusion || isBottomProtrusion) {
689
- 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)`;
690
- layers.push({
691
- image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
692
- size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
693
- position: `${xPos} ${capTop}`
694
- });
695
- }
696
- return layers;
697
- }
698
- function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
699
- if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
700
- return void 0;
701
- const cellEndRow = rowIndex + rowSpan - 1;
702
- const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
703
- const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
704
- const isLeftEdge = colIndex === bounds.startCol;
705
- const isRightEdge = colIndex === bounds.endCol;
706
- const selectionContinuesBelow = cellEndRow < bounds.endRow;
707
- const stepEdges = getMergedCellStepEdges(
708
- rowIndex,
709
- colIndex,
710
- bounds,
711
- rowSpan,
712
- isVisuallySelectedAt,
713
- rowHeights
714
- );
715
- const shadows = [];
716
- const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
717
- if (hasFullPerimeter) {
718
- shadows.push(
719
- `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
720
- );
721
- } else {
722
- if (isTopEdge) {
723
- shadows.push(
724
- `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
725
- );
726
- }
727
- if (isBottomEdge) {
728
- shadows.push(
729
- `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
730
- );
731
- }
732
- if (isLeftEdge) {
733
- shadows.push(
734
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
735
- );
736
- }
737
- if (isRightEdge) {
738
- shadows.push(
739
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
740
- );
741
- }
742
- }
743
- const gradients = [];
744
- const sizes = [];
745
- const positions = [];
746
- for (const edge of stepEdges) {
747
- for (const partial of buildPartialEdgeGradient(edge)) {
748
- gradients.push(partial.image);
749
- sizes.push(partial.size);
750
- positions.push(partial.position);
751
- }
752
- }
753
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
754
- return void 0;
755
- }
756
- const style = {};
757
- if (shadows.length > 0) {
758
- style["--selection-edge-shadows"] = shadows.join(", ");
759
- }
760
- if (gradients.length > 0) {
761
- style["--selection-edge-gradients"] = gradients.join(", ");
762
- style["--selection-edge-sizes"] = sizes.join(", ");
763
- style["--selection-edge-positions"] = positions.join(", ");
764
- }
765
- if (selectionContinuesBelow) {
766
- style.borderBottomColor = "var(--color-brand-surface)";
767
- }
768
- return style;
769
- }
770
- function hasCellSelectionEdges(style) {
771
- return Boolean(
772
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
773
- );
774
- }
775
-
776
- // src/components/ui/table/features/cell-selection/copyData.ts
777
- import { isValidElement } from "react";
778
- function isReactNodeIterable(node) {
779
- return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
780
- }
781
- function getElementTypeName(type) {
782
- if (typeof type === "string") return type;
783
- if (typeof type === "function") {
784
- const fn = type;
785
- return fn.displayName || fn.name || "";
786
- }
787
- if (typeof type === "object" && type !== null) {
788
- const component = type;
789
- return component.displayName || component.render?.displayName || component.render?.name || "";
790
- }
791
- return "";
792
- }
793
- function isButtonReactElement(node) {
794
- const typeName = getElementTypeName(node.type);
795
- if (typeName === "button" || /button/i.test(typeName)) return true;
796
- const props = node.props;
797
- if (props.role === "button") return true;
798
- if (typeName === "input" && props.type === "button") return true;
799
- return false;
800
- }
801
- function isImageReactElement(node) {
802
- const typeName = getElementTypeName(node.type);
803
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
804
- }
805
- var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
806
- function isLikelyUrl(value) {
807
- const trimmed = value.trim();
808
- if (!trimmed) return false;
809
- if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
810
- if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
811
- return false;
812
- }
813
- function pickUrlFromUnknown(value) {
814
- if (typeof value === "string") {
815
- return isLikelyUrl(value) ? value.trim() : "";
816
- }
817
- if (Array.isArray(value)) {
818
- return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
819
- }
820
- if (value && typeof value === "object") {
821
- const record = value;
822
- for (const key of IMAGE_URL_PROP_KEYS) {
823
- const candidate = record[key];
824
- if (typeof candidate === "string" && candidate.trim()) {
825
- return candidate.trim();
826
- }
827
- }
828
- }
829
- return "";
830
- }
831
- function imageElementText(node) {
832
- const props = node.props;
833
- for (const key of IMAGE_URL_PROP_KEYS) {
834
- const candidate = props[key];
835
- if (typeof candidate === "string" && candidate.trim()) {
836
- return candidate.trim();
837
- }
838
- }
839
- return "";
840
- }
841
- function reactNodeContainsImage(node) {
842
- if (isValidElement(node)) {
843
- if (isImageReactElement(node)) return true;
844
- return reactNodeContainsImage(node.props.children);
845
- }
846
- if (isReactNodeIterable(node)) {
847
- for (const child of node) {
848
- if (reactNodeContainsImage(child)) return true;
849
- }
850
- }
851
- return false;
852
- }
853
- function readImgUrl(img) {
854
- const attr = img.getAttribute("src")?.trim() ?? "";
855
- if (attr) return attr;
856
- if (img instanceof HTMLImageElement) {
857
- const current = img.currentSrc?.trim() ?? "";
858
- if (current && current !== img.baseURI) return current;
859
- }
860
- return "";
861
- }
862
- function readDomImageUrls(rowIndex, colIndex, root) {
863
- const scope = root ?? (typeof document === "undefined" ? null : document);
864
- if (!scope) return "";
865
- const cells = scope.querySelectorAll(
866
- `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
867
- );
868
- for (const cell of cells) {
869
- const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
870
- const url = readImgUrl(img);
871
- return url ? [url] : [];
872
- });
873
- if (urls.length > 0) return urls.join(", ");
874
- }
875
- return "";
876
- }
877
- function reactNodeToText(node) {
878
- if (node == null || typeof node === "boolean") return "";
879
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
880
- return String(node);
881
- }
882
- if (isReactNodeIterable(node)) {
883
- let text = "";
884
- for (const child of node) {
885
- text += reactNodeToText(child);
886
- }
887
- return text;
888
- }
889
- if (isValidElement(node)) {
890
- if (isButtonReactElement(node)) return "";
891
- const props = node.props;
892
- const childText = reactNodeToText(props.children);
893
- if (childText) return childText;
894
- const fromImage = imageElementText(node);
895
- if (fromImage) return fromImage;
896
- if (isImageReactElement(node)) return "";
897
- if (typeof props.alt === "string" && props.alt) return props.alt;
898
- if (typeof props.title === "string" && props.title) return props.title;
899
- return "";
900
- }
901
- return "";
902
- }
903
- function sanitizeClipboardCell(text) {
904
- return text.replace(/\s+/g, " ").trim();
905
- }
906
- function createCopyRenderRow(rowData, index) {
907
- return {
908
- id: getOriginalRowId(rowData) || String(index),
909
- index,
910
- original: rowData,
911
- getIsCellDragSelected: () => false
912
+ id: getOriginalRowId(rowData) || String(index),
913
+ index,
914
+ original: rowData,
915
+ getIsCellDragSelected: () => false
912
916
  };
913
917
  }
914
918
  function buildVisibleRowLookup(visibleRows) {
@@ -975,204 +979,550 @@ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIn
975
979
  return formatCellValue(value);
976
980
  }
977
981
  }
978
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
979
- try {
980
- const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
981
- if (renderer) {
982
- const node = renderer.render(ctx);
983
- const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
984
- if (rendered) return rendered;
982
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
983
+ try {
984
+ const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
985
+ if (renderer) {
986
+ const node = renderer.render(ctx);
987
+ const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
988
+ if (rendered) return rendered;
989
+ }
990
+ } catch {
991
+ return formatCellValue(value);
992
+ }
993
+ }
994
+ return formatCellValue(value);
995
+ }
996
+ function getNestedValue(row, path) {
997
+ if (!path.includes(".")) return row[path];
998
+ return path.split(".").reduce((current, key) => {
999
+ if (current === null || current === void 0 || typeof current !== "object") {
1000
+ return void 0;
1001
+ }
1002
+ return current[key];
1003
+ }, row);
1004
+ }
1005
+ function readRowColumnValue(rowData, columnDef) {
1006
+ if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1007
+ return columnDef.accessorFn(rowData, 0);
1008
+ }
1009
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1010
+ return getNestedValue(rowData, String(columnDef.accessorKey));
1011
+ }
1012
+ return void 0;
1013
+ }
1014
+ function flattenSubtreeRows(row) {
1015
+ const children = row.children;
1016
+ if (!Array.isArray(children) || children.length === 0) return [];
1017
+ const result = [];
1018
+ const walk = (nodes) => {
1019
+ for (const node of nodes) {
1020
+ result.push(node);
1021
+ const nested = node.children;
1022
+ if (Array.isArray(nested) && nested.length > 0) {
1023
+ walk(nested);
1024
+ }
1025
+ }
1026
+ };
1027
+ walk(children);
1028
+ return result;
1029
+ }
1030
+ function hasSubtree(row) {
1031
+ const children = row.children;
1032
+ return Array.isArray(children) && children.length > 0;
1033
+ }
1034
+ function getOriginalRowId(original) {
1035
+ return String(original.id ?? original.uniqueId ?? "");
1036
+ }
1037
+ function getRowDepth(original) {
1038
+ return typeof original.level === "number" ? original.level : 0;
1039
+ }
1040
+ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1041
+ const { startRow, endRow } = bounds;
1042
+ const result = [];
1043
+ if (mode !== "subtree") {
1044
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1045
+ const row = visibleRows[rowIndex];
1046
+ if (row) result.push({ row: row.original, depth: 0 });
1047
+ }
1048
+ return result;
1049
+ }
1050
+ const included = /* @__PURE__ */ new Set();
1051
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
1052
+ const appendSubtree = (node, depth) => {
1053
+ const children = node.children;
1054
+ if (!Array.isArray(children) || children.length === 0) return;
1055
+ for (const child of children) {
1056
+ const key = keyOf(child);
1057
+ if (!included.has(key)) {
1058
+ result.push({ row: child, depth });
1059
+ included.add(key);
1060
+ }
1061
+ appendSubtree(child, depth + 1);
1062
+ }
1063
+ };
1064
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1065
+ const row = visibleRows[rowIndex];
1066
+ if (!row) continue;
1067
+ const key = keyOf(row.original);
1068
+ if (included.has(key)) continue;
1069
+ const depth = getRowDepth(row.original);
1070
+ result.push({ row: row.original, depth });
1071
+ included.add(key);
1072
+ if (!hasSubtree(row.original)) continue;
1073
+ appendSubtree(row.original, depth + 1);
1074
+ }
1075
+ return result;
1076
+ }
1077
+ function collectCopyRows(visibleRows, bounds, mode = "visible") {
1078
+ return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1079
+ }
1080
+ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1081
+ if (copyRows.length === 0) return "";
1082
+ const { startCol, endCol } = bounds;
1083
+ const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1084
+ if (columnCells.length === 0) return "";
1085
+ const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1086
+ const minDepth = Math.min(...resolvedDepths);
1087
+ const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1088
+ const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1089
+ const meta = templateCell.column.columnDef.meta;
1090
+ if (meta?.copyValue === "omit") return [];
1091
+ return [{ templateCell, colOffset }];
1092
+ });
1093
+ return copyRows.map((rowData, index) => {
1094
+ const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1095
+ const visibleRow = visibleRowByOriginal.get(rowData);
1096
+ const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1097
+ const line = copyableColumns.map(({ templateCell, colOffset }) => {
1098
+ const sourceCell = matchingCells?.[colOffset];
1099
+ const column = sourceCell?.column ?? templateCell.column;
1100
+ const text = formatCopyCellText(
1101
+ rowData,
1102
+ column.columnDef,
1103
+ resolveCopyColumnId(sourceCell ?? templateCell),
1104
+ visibleRow,
1105
+ visibleRow?.index ?? index,
1106
+ sourceCell,
1107
+ visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1108
+ options
1109
+ );
1110
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
1111
+ return quoteTsvCell(escaped);
1112
+ }).join(" ");
1113
+ return `${" ".repeat(relativeDepth)}${line}`;
1114
+ }).join("\n");
1115
+ }
1116
+ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1117
+ const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1118
+ return serializeCopyRowsToTSV(
1119
+ entries.map((entry) => entry.row),
1120
+ visibleRows,
1121
+ bounds,
1122
+ entries.map((entry) => entry.depth),
1123
+ options
1124
+ );
1125
+ }
1126
+ function writeTextWithExecCommand(text) {
1127
+ if (typeof document === "undefined") return false;
1128
+ const textarea = document.createElement("textarea");
1129
+ textarea.value = text;
1130
+ textarea.setAttribute("readonly", "");
1131
+ textarea.style.position = "fixed";
1132
+ textarea.style.top = "0";
1133
+ textarea.style.left = "0";
1134
+ textarea.style.opacity = "0";
1135
+ textarea.style.pointerEvents = "none";
1136
+ document.body.appendChild(textarea);
1137
+ const previouslyFocused = document.activeElement;
1138
+ try {
1139
+ textarea.focus();
1140
+ textarea.select();
1141
+ return document.execCommand("copy");
1142
+ } catch {
1143
+ return false;
1144
+ } finally {
1145
+ document.body.removeChild(textarea);
1146
+ previouslyFocused?.focus?.();
1147
+ }
1148
+ }
1149
+ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1150
+ const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1151
+ if (!text) return false;
1152
+ if (mode === "subtree") rememberSubtreeCopy(text);
1153
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1154
+ return writeTextWithExecCommand(text);
1155
+ }
1156
+ try {
1157
+ await navigator.clipboard.writeText(text);
1158
+ return true;
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ }
1163
+
1164
+ // src/components/ui/table/features/cell-render/withCellUpdate.ts
1165
+ function withCellUpdate(context, commitValue) {
1166
+ return {
1167
+ ...context,
1168
+ update: (next) => {
1169
+ commitValue(context.row.id, context.column.id, next);
1170
+ }
1171
+ };
1172
+ }
1173
+
1174
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
1175
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
1176
+
1177
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
1178
+ var activeOwner = null;
1179
+ var clearByOwner = /* @__PURE__ */ new Map();
1180
+ function createCellSelectionOwner() {
1181
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
1182
+ }
1183
+ function registerCellSelectionOwner(owner, clearSelection) {
1184
+ clearByOwner.set(owner, clearSelection);
1185
+ return () => {
1186
+ clearByOwner.delete(owner);
1187
+ if (activeOwner === owner) {
1188
+ activeOwner = null;
1189
+ }
1190
+ };
1191
+ }
1192
+ function claimCellSelectionOwner(owner) {
1193
+ if (activeOwner === owner) return;
1194
+ activeOwner = owner;
1195
+ for (const [id, clearSelection] of clearByOwner) {
1196
+ if (id !== owner) {
1197
+ clearSelection();
1198
+ }
1199
+ }
1200
+ }
1201
+ function isActiveCellSelectionOwner(owner) {
1202
+ return activeOwner === owner;
1203
+ }
1204
+ function releaseCellSelectionOwner(owner) {
1205
+ if (activeOwner === owner) {
1206
+ activeOwner = null;
1207
+ }
1208
+ }
1209
+
1210
+ // src/components/ui/table/features/cell-selection/cellSelection.ts
1211
+ var INITIAL_DRAG_STATE = {
1212
+ isSelecting: false,
1213
+ isFillDragging: false,
1214
+ start: null,
1215
+ end: null,
1216
+ fillAnchor: null,
1217
+ fillEnd: null
1218
+ };
1219
+ function getCellSelectionBounds(start, end) {
1220
+ if (!start || !end) return null;
1221
+ return {
1222
+ startRow: Math.min(start.row, end.row),
1223
+ endRow: Math.max(start.row, end.row),
1224
+ startCol: Math.min(start.col, end.col),
1225
+ endCol: Math.max(start.col, end.col)
1226
+ };
1227
+ }
1228
+ function getCellNavigationDelta(key) {
1229
+ switch (key) {
1230
+ case "ArrowUp":
1231
+ case "w":
1232
+ case "W":
1233
+ return { row: -1, col: 0 };
1234
+ case "ArrowDown":
1235
+ case "s":
1236
+ case "S":
1237
+ return { row: 1, col: 0 };
1238
+ case "ArrowLeft":
1239
+ case "a":
1240
+ case "A":
1241
+ return { row: 0, col: -1 };
1242
+ case "ArrowRight":
1243
+ case "d":
1244
+ case "D":
1245
+ return { row: 0, col: 1 };
1246
+ default:
1247
+ return null;
1248
+ }
1249
+ }
1250
+ function clampCellPosition(position, rowCount, columnCount) {
1251
+ const maxRow = Math.max(rowCount - 1, 0);
1252
+ const maxCol = Math.max(columnCount - 1, 0);
1253
+ return {
1254
+ row: Math.min(Math.max(position.row, 0), maxRow),
1255
+ col: Math.min(Math.max(position.col, 0), maxCol)
1256
+ };
1257
+ }
1258
+ function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
1259
+ if (rowSpan <= 1) return void 0;
1260
+ const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
1261
+ if (!tbody) return void 0;
1262
+ const rows = tbody.querySelectorAll(":scope > tr");
1263
+ if (rows.length < rowIndex + rowSpan) return void 0;
1264
+ const heights = [];
1265
+ for (let i = 0; i < rowSpan; i++) {
1266
+ const row = rows[rowIndex + i];
1267
+ const height = row?.getBoundingClientRect().height ?? 0;
1268
+ if (height <= 0) return void 0;
1269
+ heights.push(height);
1270
+ }
1271
+ return heights;
1272
+ }
1273
+ function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
1274
+ if (rowSpan <= 1) return rowIndex;
1275
+ const rect = cellElement.getBoundingClientRect();
1276
+ const relativeY = clientY - rect.top;
1277
+ const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
1278
+ if (heights && heights.length === rowSpan) {
1279
+ let accrued = 0;
1280
+ for (let i = 0; i < rowSpan; i++) {
1281
+ accrued += heights[i];
1282
+ if (relativeY < accrued) {
1283
+ return rowIndex + i;
985
1284
  }
986
- } catch {
987
- return formatCellValue(value);
988
1285
  }
1286
+ return rowIndex + rowSpan - 1;
989
1287
  }
990
- return formatCellValue(value);
1288
+ const rowHeight = rect.height / rowSpan;
1289
+ const offset = Math.min(
1290
+ Math.max(Math.floor(relativeY / rowHeight), 0),
1291
+ rowSpan - 1
1292
+ );
1293
+ return rowIndex + offset;
991
1294
  }
992
- function formatPrimitive(value) {
993
- if (value === null || value === void 0) return "";
994
- if (typeof value === "string") return value;
995
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
996
- return String(value);
997
- }
998
- return "";
1295
+ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
1296
+ if (!bounds) return false;
1297
+ const cellEndRow = rowIndex + rowSpan - 1;
1298
+ return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
999
1299
  }
1000
- function formatObjectValue(value) {
1001
- const text = value.text ?? value.label ?? value.name ?? value.title;
1002
- if (text != null && text !== "") {
1003
- return formatCellValue(text);
1300
+ function resolveFillBounds(source, pointer) {
1301
+ const below = pointer.row - source.endRow;
1302
+ const above = source.startRow - pointer.row;
1303
+ const right = pointer.col - source.endCol;
1304
+ const left = source.startCol - pointer.col;
1305
+ const vertical = Math.max(below, above, 0);
1306
+ const horizontal = Math.max(right, left, 0);
1307
+ if (vertical === 0 && horizontal === 0) return { ...source };
1308
+ if (vertical >= horizontal) {
1309
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
1004
1310
  }
1005
- try {
1006
- return JSON.stringify(value);
1007
- } catch {
1008
- return "";
1311
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1312
+ }
1313
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1314
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1315
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1009
1316
  }
1317
+ return selectionBounds;
1010
1318
  }
1011
- function formatCellValue(value) {
1012
- if (value === null || value === void 0) return "";
1013
- if (Array.isArray(value)) {
1014
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
1319
+ var SELECTION_EDGE_WIDTH_PX = 2;
1320
+ var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
1321
+ var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
1322
+ function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
1323
+ const clampedFrom = Math.max(fromRow, rowIndex);
1324
+ const clampedTo = Math.min(toRowExclusive, rowIndex + span);
1325
+ if (clampedTo <= clampedFrom) {
1326
+ return { offsetRatio: 0, lengthRatio: 0 };
1015
1327
  }
1016
- if (typeof value === "object") {
1017
- return formatObjectValue(value);
1328
+ if (!rowHeights || rowHeights.length !== span) {
1329
+ return {
1330
+ offsetRatio: (clampedFrom - rowIndex) / span,
1331
+ lengthRatio: (clampedTo - clampedFrom) / span
1332
+ };
1018
1333
  }
1019
- return formatPrimitive(value);
1020
- }
1021
- function getNestedValue(row, path) {
1022
- if (!path.includes(".")) return row[path];
1023
- return path.split(".").reduce((current, key) => {
1024
- if (current === null || current === void 0 || typeof current !== "object") {
1025
- return void 0;
1026
- }
1027
- return current[key];
1028
- }, row);
1029
- }
1030
- function readRowColumnValue(rowData, columnDef) {
1031
- if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1032
- return columnDef.accessorFn(rowData, 0);
1334
+ const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
1335
+ let offsetPx = 0;
1336
+ for (let i = 0; i < clampedFrom - rowIndex; i++) {
1337
+ offsetPx += rowHeights[i] ?? 0;
1033
1338
  }
1034
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1035
- return getNestedValue(rowData, String(columnDef.accessorKey));
1339
+ let lengthPx = 0;
1340
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1341
+ lengthPx += rowHeights[i] ?? 0;
1036
1342
  }
1037
- return void 0;
1343
+ return {
1344
+ offsetRatio: offsetPx / total,
1345
+ lengthRatio: lengthPx / total,
1346
+ offsetPx,
1347
+ lengthPx
1348
+ };
1038
1349
  }
1039
- function flattenSubtreeRows(row) {
1040
- const children = row.children;
1041
- if (!Array.isArray(children) || children.length === 0) return [];
1042
- const result = [];
1043
- const walk = (nodes) => {
1044
- for (const node of nodes) {
1045
- result.push(node);
1046
- const nested = node.children;
1047
- if (Array.isArray(nested) && nested.length > 0) {
1048
- walk(nested);
1049
- }
1350
+ function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
1351
+ const cellEndRow = rowIndex + rowSpan - 1;
1352
+ const span = cellEndRow - rowIndex + 1;
1353
+ if (span <= 1) return [];
1354
+ const edges = [];
1355
+ const isNeighborSelected = (row, neighborCol) => {
1356
+ if (isVisuallySelectedAt) {
1357
+ return isVisuallySelectedAt(row, neighborCol);
1050
1358
  }
1359
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
1051
1360
  };
1052
- walk(children);
1053
- return result;
1054
- }
1055
- function hasSubtree(row) {
1056
- const children = row.children;
1057
- return Array.isArray(children) && children.length > 0;
1058
- }
1059
- function getOriginalRowId(original) {
1060
- return String(original.id ?? original.uniqueId ?? "");
1061
- }
1062
- function getRowDepth(original) {
1063
- return typeof original.level === "number" ? original.level : 0;
1064
- }
1065
- function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1066
- const { startRow, endRow } = bounds;
1067
- const result = [];
1068
- const includedOriginalIds = /* @__PURE__ */ new Set();
1069
- const appendSubtree = (node, depth) => {
1070
- const children = node.children;
1071
- if (!Array.isArray(children) || children.length === 0) return;
1072
- for (const child of children) {
1073
- const childId = getOriginalRowId(child);
1074
- if (!(childId && includedOriginalIds.has(childId))) {
1075
- result.push({ row: child, depth });
1076
- if (childId) includedOriginalIds.add(childId);
1361
+ const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
1362
+ let runStart = null;
1363
+ for (let row = fromRow; row < toRowExclusive; row++) {
1364
+ if (!isNeighborSelected(row, neighborCol)) {
1365
+ if (runStart === null) runStart = row;
1366
+ continue;
1367
+ }
1368
+ if (runStart !== null) {
1369
+ const ratios = rowRangeToHeightRatios(
1370
+ rowIndex,
1371
+ span,
1372
+ runStart,
1373
+ row,
1374
+ rowHeights
1375
+ );
1376
+ if (ratios.lengthRatio > 0) {
1377
+ edges.push({ side, ...ratios });
1378
+ }
1379
+ runStart = null;
1380
+ }
1381
+ }
1382
+ if (runStart !== null) {
1383
+ const ratios = rowRangeToHeightRatios(
1384
+ rowIndex,
1385
+ span,
1386
+ runStart,
1387
+ toRowExclusive,
1388
+ rowHeights
1389
+ );
1390
+ if (ratios.lengthRatio > 0) {
1391
+ edges.push({ side, ...ratios });
1077
1392
  }
1078
- appendSubtree(child, depth + 1);
1079
1393
  }
1080
1394
  };
1081
- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1082
- const row = visibleRows[rowIndex];
1083
- if (!row) continue;
1084
- const originalId = getOriginalRowId(row.original);
1085
- if (originalId && includedOriginalIds.has(originalId)) continue;
1086
- const depth = getRowDepth(row.original);
1087
- result.push({ row: row.original, depth });
1088
- if (originalId) includedOriginalIds.add(originalId);
1089
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
1090
- appendSubtree(row.original, depth + 1);
1091
- }
1092
- return result;
1093
- }
1094
- function collectCopyRows(visibleRows, bounds, mode = "visible") {
1095
- return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1096
- }
1097
- function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1098
- if (copyRows.length === 0) return "";
1099
- const { startCol, endCol } = bounds;
1100
- const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1101
- if (columnCells.length === 0) return "";
1102
- const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1103
- const minDepth = Math.min(...resolvedDepths);
1104
- const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1105
- const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1106
- const meta = templateCell.column.columnDef.meta;
1107
- if (meta?.copyValue === "omit") return [];
1108
- return [{ templateCell, colOffset }];
1109
- });
1110
- return copyRows.map((rowData, index) => {
1111
- const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1112
- const visibleRow = visibleRowByOriginal.get(rowData);
1113
- const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1114
- const line = copyableColumns.map(({ templateCell, colOffset }) => {
1115
- const sourceCell = matchingCells?.[colOffset];
1116
- const column = sourceCell?.column ?? templateCell.column;
1117
- return formatCopyCellText(
1118
- rowData,
1119
- column.columnDef,
1120
- resolveCopyColumnId(sourceCell ?? templateCell),
1121
- visibleRow,
1122
- visibleRow?.index ?? index,
1123
- sourceCell,
1124
- visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1125
- options
1395
+ const collectSide = (side, neighborCol) => {
1396
+ if (bounds.startRow > rowIndex) {
1397
+ pushUnselectedRuns(
1398
+ side,
1399
+ neighborCol,
1400
+ rowIndex,
1401
+ Math.min(bounds.startRow, cellEndRow + 1)
1126
1402
  );
1127
- }).join(" ");
1128
- return `${" ".repeat(relativeDepth)}${line}`;
1129
- }).join("\n");
1403
+ }
1404
+ if (bounds.endRow < cellEndRow) {
1405
+ pushUnselectedRuns(
1406
+ side,
1407
+ neighborCol,
1408
+ Math.max(bounds.endRow + 1, rowIndex),
1409
+ cellEndRow + 1
1410
+ );
1411
+ }
1412
+ };
1413
+ if (colIndex < bounds.endCol) {
1414
+ collectSide("right", colIndex + 1);
1415
+ }
1416
+ if (colIndex > bounds.startCol) {
1417
+ collectSide("left", colIndex - 1);
1418
+ }
1419
+ return edges;
1130
1420
  }
1131
- function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1132
- const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1133
- return serializeCopyRowsToTSV(
1134
- entries.map((entry) => entry.row),
1135
- visibleRows,
1421
+ function buildPartialEdgeGradient(edge) {
1422
+ const usePx = edge.offsetPx != null && edge.lengthPx != null;
1423
+ const startPct = edge.offsetRatio * 100;
1424
+ const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
1425
+ const startPx = edge.offsetPx ?? 0;
1426
+ const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
1427
+ const overlapPx = SELECTION_EDGE_WIDTH_PX;
1428
+ const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
1429
+ const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
1430
+ const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
1431
+ const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
1432
+ const xPos = edge.side === "left" ? "0" : "100%";
1433
+ const layers = [
1434
+ {
1435
+ image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
1436
+ size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
1437
+ position: `${xPos} 0`
1438
+ }
1439
+ ];
1440
+ if (isTopProtrusion || isBottomProtrusion) {
1441
+ 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)`;
1442
+ layers.push({
1443
+ image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
1444
+ size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
1445
+ position: `${xPos} ${capTop}`
1446
+ });
1447
+ }
1448
+ return layers;
1449
+ }
1450
+ function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
1451
+ if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
1452
+ return void 0;
1453
+ const cellEndRow = rowIndex + rowSpan - 1;
1454
+ const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
1455
+ const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
1456
+ const isLeftEdge = colIndex === bounds.startCol;
1457
+ const isRightEdge = colIndex === bounds.endCol;
1458
+ const selectionContinuesBelow = cellEndRow < bounds.endRow;
1459
+ const stepEdges = getMergedCellStepEdges(
1460
+ rowIndex,
1461
+ colIndex,
1136
1462
  bounds,
1137
- entries.map((entry) => entry.depth),
1138
- options
1463
+ rowSpan,
1464
+ isVisuallySelectedAt,
1465
+ rowHeights
1139
1466
  );
1140
- }
1141
- function writeTextWithExecCommand(text) {
1142
- if (typeof document === "undefined") return false;
1143
- const textarea = document.createElement("textarea");
1144
- textarea.value = text;
1145
- textarea.setAttribute("readonly", "");
1146
- textarea.style.position = "fixed";
1147
- textarea.style.top = "0";
1148
- textarea.style.left = "0";
1149
- textarea.style.opacity = "0";
1150
- textarea.style.pointerEvents = "none";
1151
- document.body.appendChild(textarea);
1152
- const previouslyFocused = document.activeElement;
1153
- try {
1154
- textarea.focus();
1155
- textarea.select();
1156
- return document.execCommand("copy");
1157
- } catch {
1158
- return false;
1159
- } finally {
1160
- document.body.removeChild(textarea);
1161
- previouslyFocused?.focus?.();
1467
+ const shadows = [];
1468
+ const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
1469
+ if (hasFullPerimeter) {
1470
+ shadows.push(
1471
+ `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
1472
+ );
1473
+ } else {
1474
+ if (isTopEdge) {
1475
+ shadows.push(
1476
+ `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1477
+ );
1478
+ }
1479
+ if (isBottomEdge) {
1480
+ shadows.push(
1481
+ `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1482
+ );
1483
+ }
1484
+ if (isLeftEdge) {
1485
+ shadows.push(
1486
+ `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1487
+ );
1488
+ }
1489
+ if (isRightEdge) {
1490
+ shadows.push(
1491
+ `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1492
+ );
1493
+ }
1162
1494
  }
1163
- }
1164
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1165
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1166
- if (!text) return false;
1167
- if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1168
- return writeTextWithExecCommand(text);
1495
+ const gradients = [];
1496
+ const sizes = [];
1497
+ const positions = [];
1498
+ for (const edge of stepEdges) {
1499
+ for (const partial of buildPartialEdgeGradient(edge)) {
1500
+ gradients.push(partial.image);
1501
+ sizes.push(partial.size);
1502
+ positions.push(partial.position);
1503
+ }
1169
1504
  }
1170
- try {
1171
- await navigator.clipboard.writeText(text);
1172
- return true;
1173
- } catch {
1174
- return false;
1505
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1506
+ return void 0;
1175
1507
  }
1508
+ const style = {};
1509
+ if (shadows.length > 0) {
1510
+ style["--selection-edge-shadows"] = shadows.join(", ");
1511
+ }
1512
+ if (gradients.length > 0) {
1513
+ style["--selection-edge-gradients"] = gradients.join(", ");
1514
+ style["--selection-edge-sizes"] = sizes.join(", ");
1515
+ style["--selection-edge-positions"] = positions.join(", ");
1516
+ }
1517
+ if (selectionContinuesBelow) {
1518
+ style.borderBottomColor = "var(--color-brand-surface)";
1519
+ }
1520
+ return style;
1521
+ }
1522
+ function hasCellSelectionEdges(style) {
1523
+ return Boolean(
1524
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1525
+ );
1176
1526
  }
1177
1527
 
1178
1528
  // src/components/ui/table/features/cell-selection/fillData.ts
@@ -1197,6 +1547,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1197
1547
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1198
1548
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1199
1549
  if (!targetRow || !targetCell || !sourceCell) continue;
1550
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1551
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1200
1552
  const accessorKey = getColumnAccessorKey2(
1201
1553
  targetCell.column.columnDef
1202
1554
  );
@@ -1218,13 +1570,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1218
1570
  );
1219
1571
  }
1220
1572
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1221
- const newData = data.map((row) => ({ ...row }));
1222
1573
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1223
- for (const target of targets) {
1224
- if (!newData[target.rowIndex]) continue;
1225
- newData[target.rowIndex][target.accessorKey] = target.value;
1226
- }
1227
- return newData;
1574
+ return applyCellChangesToData(
1575
+ data,
1576
+ targets.flatMap((target) => {
1577
+ const row = rows[target.rowIndex];
1578
+ if (!row) return [];
1579
+ return [
1580
+ {
1581
+ original: row.original,
1582
+ index: row.index,
1583
+ accessorKey: target.accessorKey,
1584
+ value: target.value
1585
+ }
1586
+ ];
1587
+ })
1588
+ );
1228
1589
  }
1229
1590
  function hasFillExtension(sourceBounds, fillBounds) {
1230
1591
  if (!sourceBounds) return false;
@@ -1245,17 +1606,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1245
1606
  if (firstDepth !== 0) return false;
1246
1607
  return leadingEmptyCounts.some((depth) => depth > 0);
1247
1608
  }
1609
+ function splitTSV(text) {
1610
+ const rows = [];
1611
+ let row = [];
1612
+ let index = 0;
1613
+ while (index <= text.length) {
1614
+ let cell = "";
1615
+ if (text[index] === '"') {
1616
+ index += 1;
1617
+ while (index < text.length) {
1618
+ const char = text[index];
1619
+ if (char === '"') {
1620
+ if (text[index + 1] === '"') {
1621
+ cell += '"';
1622
+ index += 2;
1623
+ continue;
1624
+ }
1625
+ index += 1;
1626
+ break;
1627
+ }
1628
+ cell += char;
1629
+ index += 1;
1630
+ }
1631
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1632
+ cell += text[index];
1633
+ index += 1;
1634
+ }
1635
+ } else {
1636
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1637
+ cell += text[index];
1638
+ index += 1;
1639
+ }
1640
+ }
1641
+ row.push(cell);
1642
+ if (index >= text.length) {
1643
+ rows.push(row);
1644
+ break;
1645
+ }
1646
+ if (text[index] === "\n") {
1647
+ rows.push(row);
1648
+ row = [];
1649
+ }
1650
+ index += 1;
1651
+ }
1652
+ return rows;
1653
+ }
1248
1654
  function parseClipboardTSV(text) {
1249
1655
  return parseClipboardTSVWithDepths(text).values;
1250
1656
  }
1251
- function parseClipboardTSVWithDepths(text) {
1657
+ function parseClipboardTSVWithDepths(text, options) {
1252
1658
  if (!text) return { values: [], depths: [] };
1253
1659
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1254
1660
  const withoutTrailing = normalized.replace(/\n+$/, "");
1255
1661
  if (!withoutTrailing) return { values: [], depths: [] };
1256
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1662
+ const rows = splitTSV(withoutTrailing);
1257
1663
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1258
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1664
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1259
1665
  const values = [];
1260
1666
  const depths = [];
1261
1667
  for (let index = 0; index < rows.length; index += 1) {
@@ -1282,8 +1688,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1282
1688
  }
1283
1689
  return columnIds;
1284
1690
  }
1285
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1286
- const { values, depths } = parseClipboardTSVWithDepths(text);
1691
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1692
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1287
1693
  if (values.length === 0) return null;
1288
1694
  const width = Math.max(...values.map((row) => row.length), 0);
1289
1695
  if (width === 0) return null;
@@ -1316,6 +1722,19 @@ function isEditablePasteTarget(target) {
1316
1722
  }
1317
1723
 
1318
1724
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
1725
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
1726
+ function isInteractiveFocus() {
1727
+ const active = document.activeElement;
1728
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
1729
+ }
1730
+ function hasPageTextSelectionOutside(root) {
1731
+ if (typeof window.getSelection !== "function") return false;
1732
+ const selection = window.getSelection();
1733
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
1734
+ if (!selection.toString()) return false;
1735
+ const anchor = selection.anchorNode;
1736
+ return !(root && anchor && root.contains(anchor));
1737
+ }
1319
1738
  function isFocusOutsideRoot(rootRef) {
1320
1739
  const root = rootRef?.current;
1321
1740
  if (!root) return false;
@@ -1328,29 +1747,50 @@ function useCellSelection({
1328
1747
  rows,
1329
1748
  enabled = true,
1330
1749
  columnCount = 0,
1750
+ columnSignature,
1331
1751
  enableSubtreeCopy = false,
1752
+ escapeCopyFormulas = false,
1332
1753
  enableInsertPaste = true,
1333
1754
  onDataChange,
1334
1755
  onBatchChange,
1335
1756
  onRowsPaste,
1336
1757
  onCellNavigate,
1337
1758
  cellRendererRegistry,
1338
- rootRef
1759
+ rootRef,
1760
+ enableWasdNavigation = true,
1761
+ onEditKey,
1762
+ onClearKey
1339
1763
  }) {
1340
1764
  const ownerRef = useRef2(createCellSelectionOwner());
1341
1765
  const [dragState, setDragState] = useState2(INITIAL_DRAG_STATE);
1342
1766
  const pendingPasteModeRef = useRef2(null);
1343
1767
  const dragStateRef = useRef2(dragState);
1344
1768
  const onCellNavigateRef = useRef2(onCellNavigate);
1769
+ const onEditKeyRef = useRef2(onEditKey);
1770
+ const onClearKeyRef = useRef2(onClearKey);
1345
1771
  dragStateRef.current = dragState;
1346
1772
  onCellNavigateRef.current = onCellNavigate;
1347
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1348
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
1773
+ onEditKeyRef.current = onEditKey;
1774
+ onClearKeyRef.current = onClearKey;
1775
+ const updateDragState = useCallback2((update) => {
1776
+ const prev = dragStateRef.current;
1777
+ const next = update(prev);
1778
+ if (next === prev) return;
1779
+ dragStateRef.current = next;
1780
+ setDragState(next);
1781
+ }, []);
1782
+ const activeSelectionBounds = useMemo2(() => {
1783
+ if (!enabled) return null;
1784
+ return getActiveSelectionBounds(
1785
+ dragState,
1786
+ getCellSelectionBounds(dragState.start, dragState.end)
1787
+ );
1788
+ }, [dragState, enabled]);
1349
1789
  const handleCellMouseDown = useCallback2(
1350
1790
  (rowIndex, colIndex, options) => {
1351
1791
  if (!enabled) return;
1352
1792
  claimCellSelectionOwner(ownerRef.current);
1353
- setDragState((prev) => {
1793
+ updateDragState((prev) => {
1354
1794
  if (options?.shiftKey && prev.start) {
1355
1795
  return {
1356
1796
  ...prev,
@@ -1371,28 +1811,30 @@ function useCellSelection({
1371
1811
  };
1372
1812
  });
1373
1813
  },
1374
- [enabled]
1814
+ [enabled, updateDragState]
1375
1815
  );
1376
1816
  const handleCellMouseEnter = useCallback2(
1377
1817
  (rowIndex, colIndex) => {
1378
1818
  if (!enabled) return;
1379
- setDragState((prev) => {
1819
+ updateDragState((prev) => {
1380
1820
  if (prev.isSelecting) {
1821
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1381
1822
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1382
1823
  }
1383
1824
  if (prev.isFillDragging) {
1825
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1384
1826
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1385
1827
  }
1386
1828
  return prev;
1387
1829
  });
1388
1830
  },
1389
- [enabled]
1831
+ [enabled, updateDragState]
1390
1832
  );
1391
1833
  const handleFillHandleMouseDown = useCallback2(
1392
1834
  (rowIndex, colIndex) => {
1393
1835
  if (!enabled) return;
1394
1836
  claimCellSelectionOwner(ownerRef.current);
1395
- setDragState((prev) => {
1837
+ updateDragState((prev) => {
1396
1838
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1397
1839
  if (!bounds) return prev;
1398
1840
  return {
@@ -1404,7 +1846,7 @@ function useCellSelection({
1404
1846
  };
1405
1847
  });
1406
1848
  },
1407
- [enabled]
1849
+ [enabled, updateDragState]
1408
1850
  );
1409
1851
  const clearSelection = useCallback2(() => {
1410
1852
  const prev = dragStateRef.current;
@@ -1423,6 +1865,130 @@ function useCellSelection({
1423
1865
  useEffect2(() => {
1424
1866
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1425
1867
  }, [clearSelection]);
1868
+ const previousColumnSignatureRef = useRef2(columnSignature);
1869
+ useEffect2(() => {
1870
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
1871
+ previousColumnSignatureRef.current = columnSignature;
1872
+ const prev = dragStateRef.current;
1873
+ if (!prev.start || !prev.end) return;
1874
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1875
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
1876
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
1877
+ if (columnsChanged || outOfRange) {
1878
+ clearSelection();
1879
+ }
1880
+ }, [clearSelection, columnCount, columnSignature, rows]);
1881
+ useEffect2(() => {
1882
+ if (!enabled) return;
1883
+ const handlePointerDown = (event) => {
1884
+ const root = rootRef?.current;
1885
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
1886
+ if (event.target instanceof Node && root.contains(event.target)) return;
1887
+ releaseCellSelectionOwner(ownerRef.current);
1888
+ };
1889
+ document.addEventListener("pointerdown", handlePointerDown, true);
1890
+ document.addEventListener("mousedown", handlePointerDown, true);
1891
+ return () => {
1892
+ document.removeEventListener("pointerdown", handlePointerDown, true);
1893
+ document.removeEventListener("mousedown", handlePointerDown, true);
1894
+ };
1895
+ }, [enabled, rootRef]);
1896
+ const getColumnCount = useCallback2(
1897
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
1898
+ [columnCount, rows]
1899
+ );
1900
+ const selectCell = useCallback2(
1901
+ (row, col) => {
1902
+ if (!enabled) return;
1903
+ const resolvedColumnCount = getColumnCount();
1904
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
1905
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
1906
+ claimCellSelectionOwner(ownerRef.current);
1907
+ const nextState = {
1908
+ isSelecting: false,
1909
+ isFillDragging: false,
1910
+ start: position,
1911
+ end: position,
1912
+ fillAnchor: null,
1913
+ fillEnd: null
1914
+ };
1915
+ dragStateRef.current = nextState;
1916
+ setDragState(nextState);
1917
+ onCellNavigateRef.current?.(position);
1918
+ },
1919
+ [enabled, getColumnCount, rows.length]
1920
+ );
1921
+ const focusSelection = useCallback2(() => {
1922
+ if (!enabled) return;
1923
+ const prev = dragStateRef.current;
1924
+ if (prev.start && prev.end) {
1925
+ claimCellSelectionOwner(ownerRef.current);
1926
+ return;
1927
+ }
1928
+ selectCell(0, 0);
1929
+ }, [enabled, selectCell]);
1930
+ useEffect2(() => {
1931
+ if (!enabled) return;
1932
+ const handleKeyDown = (e) => {
1933
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1934
+ if (e.altKey) return;
1935
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
1936
+ return;
1937
+ }
1938
+ if (isFocusOutsideRoot(rootRef)) return;
1939
+ const prev = dragStateRef.current;
1940
+ if (!prev.start || !prev.end) return;
1941
+ if (prev.isSelecting || prev.isFillDragging) return;
1942
+ const rowCount = rows.length;
1943
+ const resolvedColumnCount = getColumnCount();
1944
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
1945
+ const withModifier = e.ctrlKey || e.metaKey;
1946
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
1947
+ e.preventDefault();
1948
+ claimCellSelectionOwner(ownerRef.current);
1949
+ const nextState = {
1950
+ isSelecting: false,
1951
+ isFillDragging: false,
1952
+ start: { row: 0, col: 0 },
1953
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
1954
+ fillAnchor: null,
1955
+ fillEnd: null
1956
+ };
1957
+ dragStateRef.current = nextState;
1958
+ setDragState(nextState);
1959
+ return;
1960
+ }
1961
+ if (e.key === "Home" || e.key === "End") {
1962
+ e.preventDefault();
1963
+ const toEnd = e.key === "End";
1964
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
1965
+ if (e.shiftKey) {
1966
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
1967
+ dragStateRef.current = nextState;
1968
+ setDragState(nextState);
1969
+ onCellNavigateRef.current?.(target);
1970
+ } else {
1971
+ selectCell(target.row, target.col);
1972
+ }
1973
+ return;
1974
+ }
1975
+ if (withModifier || isInteractiveFocus()) return;
1976
+ if (e.key === "Enter" || e.key === "F2") {
1977
+ if (!onEditKeyRef.current) return;
1978
+ e.preventDefault();
1979
+ onEditKeyRef.current(prev.end);
1980
+ return;
1981
+ }
1982
+ if (e.key === "Delete" || e.key === "Backspace") {
1983
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1984
+ if (!bounds || !onClearKeyRef.current) return;
1985
+ e.preventDefault();
1986
+ onClearKeyRef.current(bounds);
1987
+ }
1988
+ };
1989
+ window.addEventListener("keydown", handleKeyDown);
1990
+ return () => window.removeEventListener("keydown", handleKeyDown);
1991
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
1426
1992
  useEffect2(() => {
1427
1993
  if (!enabled) return;
1428
1994
  const handleKeyDown = (e) => {
@@ -1432,6 +1998,7 @@ function useCellSelection({
1432
1998
  return;
1433
1999
  }
1434
2000
  if (isFocusOutsideRoot(rootRef)) return;
2001
+ if (!enableWasdNavigation && e.key.length === 1) return;
1435
2002
  const delta = getCellNavigationDelta(e.key);
1436
2003
  if (!delta) return;
1437
2004
  const prev = dragStateRef.current;
@@ -1471,14 +2038,15 @@ function useCellSelection({
1471
2038
  };
1472
2039
  window.addEventListener("keydown", handleKeyDown);
1473
2040
  return () => window.removeEventListener("keydown", handleKeyDown);
1474
- }, [columnCount, enabled, rows]);
2041
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1475
2042
  const copySelection = useCallback2(
1476
2043
  async (options) => {
1477
2044
  if (!enabled || !activeSelectionBounds) return false;
1478
2045
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1479
2046
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1480
2047
  registry: cellRendererRegistry,
1481
- root: rootRef?.current
2048
+ root: rootRef?.current,
2049
+ escapeFormulas: escapeCopyFormulas
1482
2050
  });
1483
2051
  },
1484
2052
  [
@@ -1486,6 +2054,7 @@ function useCellSelection({
1486
2054
  cellRendererRegistry,
1487
2055
  enableSubtreeCopy,
1488
2056
  enabled,
2057
+ escapeCopyFormulas,
1489
2058
  rootRef,
1490
2059
  rows
1491
2060
  ]
@@ -1503,6 +2072,7 @@ function useCellSelection({
1503
2072
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1504
2073
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1505
2074
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2075
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1506
2076
  e.preventDefault();
1507
2077
  void copySelection({ includeDescendants: isSubtreeShortcut });
1508
2078
  };
@@ -1518,9 +2088,17 @@ function useCellSelection({
1518
2088
  activeSelectionBounds.startCol,
1519
2089
  text,
1520
2090
  mode,
1521
- activeSelectionBounds.endRow
2091
+ activeSelectionBounds.endRow,
2092
+ // Leading blank cells are tree depth only in this table's own subtree
2093
+ // copy; from a spreadsheet they are real (empty) cells.
2094
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
1522
2095
  );
1523
2096
  if (!payload) return false;
2097
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
2098
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
2099
+ const cell = cells.find((item) => item.column.id === columnId);
2100
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
2101
+ });
1524
2102
  onRowsPaste(payload);
1525
2103
  return true;
1526
2104
  },
@@ -1551,7 +2129,10 @@ function useCellSelection({
1551
2129
  void (async () => {
1552
2130
  try {
1553
2131
  const text = await navigator.clipboard.readText();
1554
- if (pasteHandledRef.current) return;
2132
+ if (pasteHandledRef.current) {
2133
+ pasteHandledRef.current = false;
2134
+ return;
2135
+ }
1555
2136
  if (pendingPasteModeRef.current !== mode) return;
1556
2137
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1557
2138
  if (!text) return;
@@ -1576,6 +2157,7 @@ function useCellSelection({
1576
2157
  }
1577
2158
  const mode = pendingPasteModeRef.current ?? "overwrite";
1578
2159
  if (pasteHandledRef.current) {
2160
+ pasteHandledRef.current = false;
1579
2161
  e.preventDefault();
1580
2162
  return;
1581
2163
  }
@@ -1602,39 +2184,41 @@ function useCellSelection({
1602
2184
  useEffect2(() => {
1603
2185
  if (!enabled) return;
1604
2186
  const handleMouseUp = () => {
1605
- setDragState((prev) => {
1606
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1607
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1608
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1609
- if (newBounds) {
1610
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1611
- if (onBatchChange) {
1612
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1613
- if (changes.length > 0) {
1614
- onBatchChange(changes);
1615
- }
1616
- } else if (onDataChange) {
1617
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
2187
+ const prev = dragStateRef.current;
2188
+ let next = prev;
2189
+ if (prev.isFillDragging && prev.fillEnd) {
2190
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
2191
+ if (sourceBounds) {
2192
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
2193
+ if (hasFillExtension(sourceBounds, newBounds)) {
2194
+ if (onBatchChange) {
2195
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
2196
+ if (changes.length > 0) {
2197
+ onBatchChange(changes);
1618
2198
  }
2199
+ } else if (onDataChange) {
2200
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1619
2201
  }
1620
- return {
1621
- isSelecting: false,
1622
- isFillDragging: false,
1623
- start: { row: newBounds.startRow, col: newBounds.startCol },
1624
- end: { row: newBounds.endRow, col: newBounds.endCol },
1625
- fillAnchor: null,
1626
- fillEnd: null
1627
- };
1628
2202
  }
2203
+ next = {
2204
+ isSelecting: false,
2205
+ isFillDragging: false,
2206
+ start: { row: newBounds.startRow, col: newBounds.startCol },
2207
+ end: { row: newBounds.endRow, col: newBounds.endCol },
2208
+ fillAnchor: null,
2209
+ fillEnd: null
2210
+ };
2211
+ } else {
2212
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1629
2213
  }
1630
- if (prev.isSelecting) {
1631
- return { ...prev, isSelecting: false };
1632
- }
1633
- if (prev.isFillDragging) {
1634
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1635
- }
1636
- return prev;
1637
- });
2214
+ } else if (prev.isSelecting) {
2215
+ next = { ...prev, isSelecting: false };
2216
+ } else if (prev.isFillDragging) {
2217
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
2218
+ }
2219
+ if (next === prev) return;
2220
+ dragStateRef.current = next;
2221
+ setDragState(next);
1638
2222
  };
1639
2223
  window.addEventListener("mouseup", handleMouseUp);
1640
2224
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1646,7 +2230,27 @@ function useCellSelection({
1646
2230
  handleCellMouseEnter,
1647
2231
  handleFillHandleMouseDown,
1648
2232
  clearSelection,
1649
- copySelection
2233
+ copySelection,
2234
+ selectCell,
2235
+ focusSelection
2236
+ };
2237
+ }
2238
+
2239
+ // src/components/ui/table/features/row-hover/rowHover.ts
2240
+ function createRowHoverStore() {
2241
+ let hoveredRowIndex = null;
2242
+ const listeners = /* @__PURE__ */ new Set();
2243
+ return {
2244
+ getHoveredRowIndex: () => hoveredRowIndex,
2245
+ setHoveredRowIndex: (nextRowIndex) => {
2246
+ if (nextRowIndex === hoveredRowIndex) return;
2247
+ hoveredRowIndex = nextRowIndex;
2248
+ listeners.forEach((listener) => listener());
2249
+ },
2250
+ subscribe: (listener) => {
2251
+ listeners.add(listener);
2252
+ return () => listeners.delete(listener);
2253
+ }
1650
2254
  };
1651
2255
  }
1652
2256
 
@@ -1940,177 +2544,40 @@ function flattenHeaderLeaves(column) {
1940
2544
  return column.columns.flatMap((child) => flattenHeaderLeaves(child));
1941
2545
  }
1942
2546
 
1943
- // src/components/ui/table/features/inline-search/inlineSearch.ts
1944
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
1945
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
1946
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
1947
- function escapeSearchRegex(value) {
1948
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
1949
- }
1950
- function createSearchRegex(query) {
1951
- const trimmed = query.trim();
1952
- if (!trimmed) return null;
1953
- return new RegExp(escapeSearchRegex(trimmed), "i");
1954
- }
1955
- function cellValueToSearchText(value) {
1956
- if (value == null) return void 0;
1957
- if (typeof value === "string") return value;
1958
- if (typeof value === "number" || typeof value === "boolean") {
1959
- return String(value);
1960
- }
1961
- if (Array.isArray(value)) {
1962
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
1963
- }
1964
- if (typeof value === "object") {
1965
- try {
1966
- return JSON.stringify(value);
1967
- } catch {
1968
- return String(value);
1969
- }
1970
- }
1971
- return String(value);
1972
- }
1973
- function formatSearchResultLabel(status) {
1974
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
1975
- if (status.selectedIndex >= 0 && status.results > 0) {
1976
- return `${status.selectedIndex + 1} of ${countLabel}`;
1977
- }
1978
- return countLabel;
1979
- }
1980
- function nextSearchIndex(selectedIndex, results) {
1981
- if (results <= 0) return -1;
1982
- if (selectedIndex < 0) return 0;
1983
- return (selectedIndex + 1) % results;
1984
- }
1985
- function previousSearchIndex(selectedIndex, results) {
1986
- if (results <= 0) return -1;
1987
- if (selectedIndex < 0) return results - 1;
1988
- let next = (selectedIndex - 1) % results;
1989
- if (next < 0) next += results;
1990
- return next;
1991
- }
1992
- function buildSearchMatchKey(colIndex, rowIndex) {
1993
- return `${colIndex}:${rowIndex}`;
1994
- }
1995
- function buildSearchMatchKeys(results) {
1996
- const keys = /* @__PURE__ */ new Set();
1997
- for (const [colIndex, rowIndex] of results) {
1998
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
1999
- }
2000
- return keys;
2001
- }
2002
- function collectSearchMatchesInRange(options) {
2003
- const {
2004
- query,
2005
- startRow,
2006
- rowCount,
2007
- columnCount,
2008
- getCellValue,
2009
- maxResults = INLINE_SEARCH_MAX_RESULTS
2010
- } = options;
2011
- const regex = createSearchRegex(query);
2012
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
2013
- const matches = [];
2014
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2015
- const rowIndex = startRow + rowOffset;
2016
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2017
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2018
- if (text !== void 0 && regex.test(text)) {
2019
- matches.push([colIndex, rowIndex]);
2020
- if (matches.length >= maxResults) {
2021
- return matches;
2022
- }
2023
- }
2024
- }
2025
- }
2026
- return matches;
2027
- }
2028
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2029
- const rounded = Math.max(elapsedMs, 1);
2030
- const scalar = targetMs / rounded;
2031
- return Math.max(1, Math.ceil(currentStride * scalar));
2032
- }
2033
- function buildFlatSearchCorpus(rows, getRowId) {
2034
- return rows.map((data, index) => ({
2035
- id: getRowId(data, index),
2036
- data,
2037
- ancestorToggleKeys: []
2038
- }));
2039
- }
2040
- function buildTreeSearchCorpus(visibleRows, options) {
2041
- const { toggleField, getRowId } = options;
2042
- const corpus = [];
2043
- const seen = /* @__PURE__ */ new Set();
2044
- const walk = (node, ancestorToggleKeys) => {
2045
- const id = getRowId(node, corpus.length);
2046
- if (seen.has(id)) return;
2047
- seen.add(id);
2048
- corpus.push({
2049
- id,
2050
- data: node,
2051
- ancestorToggleKeys
2052
- });
2053
- const children = node.children;
2054
- if (!Array.isArray(children) || children.length === 0) return;
2055
- const toggleValue = node[toggleField];
2056
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2057
- for (const child of children) {
2058
- if (child && typeof child === "object") {
2059
- walk(child, childAncestors);
2060
- }
2061
- }
2062
- };
2063
- for (const row of visibleRows) {
2064
- const level = row.level;
2065
- if (level === 0 || level === void 0) {
2066
- walk(row, []);
2067
- }
2068
- }
2069
- for (const row of visibleRows) {
2070
- const id = getRowId(row, corpus.length);
2071
- if (seen.has(id)) continue;
2072
- walk(row, []);
2073
- }
2074
- return corpus;
2075
- }
2076
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2077
- const keys = /* @__PURE__ */ new Set();
2078
- for (const [colIndex, corpusRowIndex] of results) {
2079
- const corpusRow = corpus[corpusRowIndex];
2080
- if (!corpusRow) continue;
2081
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2082
- if (visibleRowIndex === void 0) continue;
2083
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2084
- }
2085
- return keys;
2086
- }
2087
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2088
- const [colIndex, corpusRowIndex] = item;
2089
- const corpusRow = corpus[corpusRowIndex];
2090
- if (!corpusRow) return null;
2091
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2092
- if (visibleRowIndex === void 0) return null;
2093
- return [colIndex, visibleRowIndex];
2094
- }
2095
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2096
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2097
- }
2098
-
2099
2547
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
2100
2548
  import {
2101
2549
  useCallback as useCallback3,
2102
2550
  useEffect as useEffect3,
2103
2551
  useId,
2104
- useMemo,
2552
+ useMemo as useMemo3,
2105
2553
  useRef as useRef3,
2106
2554
  useState as useState3
2107
2555
  } from "react";
2108
2556
  var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2557
+ var searchInstanceCount = 0;
2558
+ var lastPointerTarget = null;
2559
+ function trackPointerTarget(event) {
2560
+ lastPointerTarget = event.target;
2561
+ }
2562
+ function registerSearchInstance() {
2563
+ if (searchInstanceCount === 0) {
2564
+ document.addEventListener("pointerdown", trackPointerTarget, true);
2565
+ }
2566
+ searchInstanceCount += 1;
2567
+ return () => {
2568
+ searchInstanceCount -= 1;
2569
+ if (searchInstanceCount === 0) {
2570
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2571
+ lastPointerTarget = null;
2572
+ }
2573
+ };
2574
+ }
2109
2575
  function useInlineSearch({
2110
2576
  enabled = false,
2111
2577
  rowCount,
2112
2578
  columnCount,
2113
2579
  getCellValue,
2580
+ contentKey,
2114
2581
  initialStartRow = 0,
2115
2582
  showSearch: controlledShowSearch,
2116
2583
  searchValue: controlledSearchValue,
@@ -2319,6 +2786,7 @@ function useInlineSearch({
2319
2786
  }
2320
2787
  beginSearch(searchValue);
2321
2788
  }, [
2789
+ contentKey,
2322
2790
  beginSearch,
2323
2791
  cancelSearch,
2324
2792
  controlledSearchResults,
@@ -2339,6 +2807,9 @@ function useInlineSearch({
2339
2807
  if (!focusInside && active !== document.body) {
2340
2808
  return;
2341
2809
  }
2810
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2811
+ return;
2812
+ }
2342
2813
  }
2343
2814
  event.preventDefault();
2344
2815
  event.stopPropagation();
@@ -2352,14 +2823,18 @@ function useInlineSearch({
2352
2823
  }
2353
2824
  };
2354
2825
  window.addEventListener("keydown", handleKeyDown, true);
2355
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2826
+ const releaseInstance = registerSearchInstance();
2827
+ return () => {
2828
+ window.removeEventListener("keydown", handleKeyDown, true);
2829
+ releaseInstance();
2830
+ };
2356
2831
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2357
2832
  useEffect3(() => () => cancelSearch(), [cancelSearch]);
2358
- const searchMatchKeys = useMemo(
2833
+ const searchMatchKeys = useMemo3(
2359
2834
  () => buildSearchMatchKeys(searchResults),
2360
2835
  [searchResults]
2361
2836
  );
2362
- const activeMatch = useMemo(() => {
2837
+ const activeMatch = useMemo3(() => {
2363
2838
  if (!searchStatus || searchStatus.selectedIndex < 0) return null;
2364
2839
  return searchResults[searchStatus.selectedIndex] ?? null;
2365
2840
  }, [searchResults, searchStatus]);
@@ -2402,14 +2877,18 @@ function useInlineSearch({
2402
2877
  }
2403
2878
 
2404
2879
  // src/components/ui/table/features/row-expand/row-expand.ts
2405
- import { useEffect as useEffect4, useMemo as useMemo2, useRef as useRef4 } from "react";
2880
+ import { useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4 } from "react";
2406
2881
  function getFieldValue(row, key) {
2407
2882
  return row[key];
2408
2883
  }
2409
2884
  function canExpandRow(row) {
2410
2885
  const children = row.children;
2411
- const level = row.level;
2412
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
2886
+ return Array.isArray(children) && children.length > 0;
2887
+ }
2888
+ function toTreeToggleKey(value) {
2889
+ if (value === null || value === void 0) return null;
2890
+ const key = String(value);
2891
+ return key.length > 0 ? key : null;
2413
2892
  }
2414
2893
  function toggleExpandedRowId(rowId, previous) {
2415
2894
  const next = new Set(previous);
@@ -2430,7 +2909,8 @@ var useConvertTreeData = ({
2430
2909
  preventExpand = false,
2431
2910
  startIndex = 1,
2432
2911
  expandedRows,
2433
- onExpandedRowsChange
2912
+ onExpandedRowsChange,
2913
+ autoExpandOnLoad = true
2434
2914
  }) => {
2435
2915
  const onExpandedRowsChangeRef = useRef4(onExpandedRowsChange);
2436
2916
  const hasInitializedRef = useRef4(false);
@@ -2443,16 +2923,33 @@ var useConvertTreeData = ({
2443
2923
  return;
2444
2924
  }
2445
2925
  if (!enabled || hasInitializedRef.current) return;
2446
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2447
- onExpandedRowsChangeRef.current?.(new Set(ids));
2448
2926
  hasInitializedRef.current = true;
2449
- }, [enabled, data, toggleField]);
2450
- const processedData = useMemo2(() => {
2927
+ if (!autoExpandOnLoad) return;
2928
+ const ids = /* @__PURE__ */ new Set();
2929
+ const collect = (items) => {
2930
+ for (const item of items) {
2931
+ if (!item || typeof item !== "object") continue;
2932
+ const record = item;
2933
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
2934
+ if (key) ids.add(key);
2935
+ const nested = record[flattenField];
2936
+ if (Array.isArray(nested)) collect(nested);
2937
+ }
2938
+ };
2939
+ collect(data);
2940
+ onExpandedRowsChangeRef.current?.(ids);
2941
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
2942
+ const processedData = useMemo4(() => {
2451
2943
  if (!enabled || !data || data.length === 0) return [];
2452
2944
  const flattenedData = [];
2453
- const flattenItems = (items) => {
2454
- items.forEach((item) => {
2455
- const newItem = { ...item };
2945
+ const flattenItems = (items, parentPath) => {
2946
+ items.forEach((item, itemIndex) => {
2947
+ if (!item || typeof item !== "object") return;
2948
+ const source = {
2949
+ path: [...parentPath, itemIndex],
2950
+ childrenField: flattenField
2951
+ };
2952
+ const newItem = { ...item, [TREE_SOURCE]: source };
2456
2953
  const nested = newItem[flattenField];
2457
2954
  if (Array.isArray(nested)) {
2458
2955
  const children = nested.map(
@@ -2466,89 +2963,68 @@ var useConvertTreeData = ({
2466
2963
  child[childField] = newItem[toggleField];
2467
2964
  }
2468
2965
  });
2469
- flattenItems(children);
2966
+ flattenItems(children, source.path);
2470
2967
  } else {
2471
2968
  flattenedData.push(newItem);
2472
2969
  }
2473
2970
  });
2474
2971
  };
2475
- flattenItems(data);
2972
+ flattenItems(data, []);
2476
2973
  const dataWithLevels = flattenedData.map((item) => ({
2477
2974
  ...item,
2478
2975
  level: 0,
2479
2976
  children: [],
2480
2977
  processed: false
2481
2978
  }));
2482
- const findNearestPrecedingParent = (index, parentKey) => {
2483
- for (let i = index - 1; i >= 0; i -= 1) {
2484
- const candidate = dataWithLevels[i];
2485
- if (!candidate) continue;
2486
- if (getFieldValue(candidate, toggleField) === parentKey) {
2487
- return candidate;
2488
- }
2489
- }
2490
- return void 0;
2491
- };
2492
2979
  const rootItems = [];
2980
+ const latestByKey = /* @__PURE__ */ new Map();
2493
2981
  dataWithLevels.forEach((item) => {
2494
- if (!getFieldValue(item, childField)) {
2495
- rootItems.push(item);
2496
- item.processed = true;
2497
- }
2498
- });
2499
- dataWithLevels.forEach((item, index) => {
2500
2982
  const parentKey = getFieldValue(item, childField);
2501
- if (!parentKey || item.processed) return;
2502
- const parent = findNearestPrecedingParent(index, parentKey);
2983
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2503
2984
  if (parent) {
2504
2985
  item.level = parent.level + 1;
2505
2986
  parent.children.push(item);
2506
- item.processed = true;
2507
- return;
2987
+ } else {
2988
+ rootItems.push(item);
2508
2989
  }
2509
- rootItems.push(item);
2510
2990
  item.processed = true;
2991
+ latestByKey.set(getFieldValue(item, toggleField), item);
2511
2992
  });
2512
2993
  return rootItems;
2513
2994
  }, [enabled, data, toggleField, childField, flattenField]);
2514
- const flattenTree = useMemo2(() => {
2995
+ const flattenTree = useMemo4(() => {
2515
2996
  if (!enabled) return [];
2516
- const flatten = (nodes, result = [], level = 0) => {
2997
+ const flatten = (nodes, result, parentTreeNo) => {
2517
2998
  nodes.forEach((node, index) => {
2518
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
2999
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2519
3000
  const toggleValue = getFieldValue(node, toggleField);
2520
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3001
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2521
3002
  result.push({
2522
3003
  ...node,
2523
3004
  treeNo: currentIndex,
2524
3005
  uniqueId,
2525
3006
  processed: true
2526
3007
  });
2527
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
3008
+ const toggleKey = toTreeToggleKey(toggleValue);
3009
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
2528
3010
  if (shouldExpandChildren) {
2529
- flatten(node.children, result, index + startIndex);
3011
+ flatten(node.children, result, currentIndex);
2530
3012
  }
2531
3013
  });
2532
3014
  return result;
2533
3015
  };
2534
- const flattenedData = flatten(processedData, [], 0);
2535
- flattenedData.forEach((item, index) => {
3016
+ const flattenedData = flatten(processedData, [], null);
3017
+ const latestByKey = /* @__PURE__ */ new Map();
3018
+ flattenedData.forEach((item) => {
2536
3019
  const parentKey = getFieldValue(item, childField);
2537
3020
  if (!parentKey) {
2538
3021
  item.parentCount = 1;
2539
- return;
2540
- }
2541
- let parentItem;
2542
- for (let i = index - 1; i >= 0; i -= 1) {
2543
- const candidate = flattenedData[i];
2544
- if (!candidate) continue;
2545
- if (getFieldValue(candidate, toggleField) === parentKey) {
2546
- parentItem = candidate;
2547
- break;
2548
- }
3022
+ } else {
3023
+ const parentItem = latestByKey.get(parentKey);
3024
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3025
+ item.parentCount = parentAmount || 1;
2549
3026
  }
2550
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2551
- item.parentCount = parentAmount || 1;
3027
+ latestByKey.set(getFieldValue(item, toggleField), item);
2552
3028
  });
2553
3029
  return flattenedData;
2554
3030
  }, [
@@ -2561,22 +3037,11 @@ var useConvertTreeData = ({
2561
3037
  preventExpand,
2562
3038
  expandedRows
2563
3039
  ]);
2564
- const sortedData = useMemo2(() => {
3040
+ const sortedData = useMemo4(() => {
2565
3041
  if (!enabled) {
2566
3042
  return data ?? [];
2567
3043
  }
2568
- return [...flattenTree].sort((a, b) => {
2569
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2570
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2571
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2572
- const aVal = aParts[i] || 0;
2573
- const bVal = bParts[i] || 0;
2574
- if (aVal !== bVal) {
2575
- return aVal - bVal;
2576
- }
2577
- }
2578
- return 0;
2579
- });
3044
+ return flattenTree;
2580
3045
  }, [enabled, data, flattenTree]);
2581
3046
  return sortedData;
2582
3047
  };
@@ -2634,13 +3099,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2634
3099
  for (let index = 0; index < data.length; index++) {
2635
3100
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2636
3101
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2637
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3102
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2638
3103
  result.push({ rowSpan: 0, isFirstInGroup: false });
2639
3104
  continue;
2640
3105
  }
2641
3106
  let span = 1;
2642
3107
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2643
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3108
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2644
3109
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2645
3110
  span++;
2646
3111
  }
@@ -2733,6 +3198,9 @@ function collectRowSpanColumns(columns) {
2733
3198
  }
2734
3199
 
2735
3200
  // src/core/useGlideTable.ts
3201
+ function isProductionBuild() {
3202
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3203
+ }
2736
3204
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2737
3205
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2738
3206
  function useGlideTable(options) {
@@ -2754,18 +3222,24 @@ function useGlideTable(options) {
2754
3222
  selectOnRowClick = true,
2755
3223
  enableCellSelection = true,
2756
3224
  onDataChange,
2757
- onCellChange,
2758
- onBatchChange,
3225
+ onCellChange: onCellChangeProp,
3226
+ onBatchChange: onBatchChangeProp,
2759
3227
  cellRenderers,
2760
3228
  preserveRowSelection = false,
2761
- toggleField,
2762
- childField,
2763
- flattenField,
3229
+ toggleField: toggleFieldProp,
3230
+ idField,
3231
+ childField: childFieldProp,
3232
+ parentIdField,
3233
+ flattenField: flattenFieldProp,
3234
+ childrenField,
2764
3235
  qtyField,
3236
+ expandColumn,
2765
3237
  expandedRows: controlledExpandedRows,
2766
3238
  onExpandedRowsChange,
2767
3239
  preventExpand = false,
3240
+ autoExpandOnLoad = true,
2768
3241
  enableSubtreeCopy,
3242
+ escapeCopyFormulas = false,
2769
3243
  onCopyActionsReady,
2770
3244
  onRowsPaste,
2771
3245
  enableInsertPaste,
@@ -2786,9 +3260,28 @@ function useGlideTable(options) {
2786
3260
  onSearchValueChange,
2787
3261
  onSearchClose,
2788
3262
  searchResults,
2789
- onSearchResultsChanged
3263
+ onSearchResultsChanged,
3264
+ enableWasdNavigation = true
2790
3265
  } = options;
2791
- const labels = useMemo3(() => {
3266
+ const toggleField = toggleFieldProp ?? idField;
3267
+ const childField = childFieldProp ?? parentIdField;
3268
+ const flattenField = flattenFieldProp ?? childrenField;
3269
+ const onCellChange = useMemo5(() => {
3270
+ if (onCellChangeProp) return onCellChangeProp;
3271
+ if (!onBatchChangeProp) return void 0;
3272
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
3273
+ }, [onBatchChangeProp, onCellChangeProp]);
3274
+ const onBatchChange = useMemo5(() => {
3275
+ if (onBatchChangeProp) return onBatchChangeProp;
3276
+ if (!onCellChangeProp) return void 0;
3277
+ return (changes) => {
3278
+ for (const change of changes) {
3279
+ onCellChangeProp(change.rowId, change.columnId, change.value);
3280
+ }
3281
+ };
3282
+ }, [onBatchChangeProp, onCellChangeProp]);
3283
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
3284
+ const labels = useMemo5(() => {
2792
3285
  const resolved = resolveDataTableLabels(labelsProp);
2793
3286
  return {
2794
3287
  ...resolved,
@@ -2805,11 +3298,11 @@ function useGlideTable(options) {
2805
3298
  const [internalExpandedRows, setInternalExpandedRows] = useState4(
2806
3299
  () => /* @__PURE__ */ new Set()
2807
3300
  );
2808
- const [hoveredRowIndex, setHoveredRowIndex] = useState4(null);
3301
+ const [hoverStore] = useState4(createRowHoverStore);
2809
3302
  const scrollRef = useRef5(null);
2810
3303
  const rootRef = useRef5(null);
2811
3304
  const escapeDismissOwnerRef = useRef5(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
2812
- const cellRendererRegistry = useMemo3(
3305
+ const cellRendererRegistry = useMemo5(
2813
3306
  () => createCellRendererRegistry(cellRenderers),
2814
3307
  [cellRenderers]
2815
3308
  );
@@ -2828,7 +3321,7 @@ function useGlideTable(options) {
2828
3321
  );
2829
3322
  const columnSizing = controlledColumnSizing ?? internalColumnSizing;
2830
3323
  const columnOrder = controlledColumnOrder ?? internalColumnOrder;
2831
- const tableColumns = useMemo3(() => {
3324
+ const tableColumns = useMemo5(() => {
2832
3325
  if (!enableColumnReorder) return columns;
2833
3326
  return applyLeafColumnOrder(columns, columnOrder);
2834
3327
  }, [columnOrder, columns, enableColumnReorder]);
@@ -2862,8 +3355,10 @@ function useGlideTable(options) {
2862
3355
  qtyField,
2863
3356
  expandedRows,
2864
3357
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2865
- preventExpand
3358
+ preventExpand,
3359
+ autoExpandOnLoad
2866
3360
  });
3361
+ const sourceData = useMemo5(() => data ?? [], [data]);
2867
3362
  const table = useReactTable({
2868
3363
  data: tableData,
2869
3364
  columns: tableColumns,
@@ -2902,15 +3397,19 @@ function useGlideTable(options) {
2902
3397
  );
2903
3398
  },
2904
3399
  getCoreRowModel: getCoreRowModel(),
2905
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
3400
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
3401
+ // Tree rows: their path in the original data, which (unlike the
3402
+ // flattened index) survives expanding/collapsing rows above.
3403
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
3404
+ )
2906
3405
  });
2907
- const rowSpanColumnKeys = useMemo3(() => {
3406
+ const rowSpanColumnKeys = useMemo5(() => {
2908
3407
  if (!enableRowSpan) return [];
2909
3408
  return collectRowSpanColumns(columns);
2910
3409
  }, [enableRowSpan, columns]);
2911
3410
  const primaryRowSpanKey = rowSpanColumnKeys[0]?.rowSpanKey;
2912
3411
  const primaryRowSpanColumnId = rowSpanColumnKeys[0]?.columnId;
2913
- const columnRowSpanMap = useMemo3(
3412
+ const columnRowSpanMap = useMemo5(
2914
3413
  () => buildColumnRowSpanMap(tableData, rowSpanColumnKeys),
2915
3414
  [tableData, rowSpanColumnKeys]
2916
3415
  );
@@ -2919,7 +3418,21 @@ function useGlideTable(options) {
2919
3418
  const rows = table.getRowModel().rows;
2920
3419
  const columnCount = table.getAllLeafColumns().length || 1;
2921
3420
  const visibleLeafColumns = table.getVisibleLeafColumns();
2922
- const columnFreezeOffsets = useMemo3(() => {
3421
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
3422
+ const warnedBooleanColumnsRef = useRef5(/* @__PURE__ */ new Set());
3423
+ useEffect5(() => {
3424
+ if (!hasWriteCallback || isProductionBuild()) return;
3425
+ for (const column of visibleLeafColumns) {
3426
+ const meta = column.columnDef.meta;
3427
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
3428
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
3429
+ warnedBooleanColumnsRef.current.add(column.id);
3430
+ console.warn(
3431
+ `[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.`
3432
+ );
3433
+ }
3434
+ }, [hasWriteCallback, visibleLeafColumns]);
3435
+ const columnFreezeOffsets = useMemo5(() => {
2923
3436
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
2924
3437
  return buildColumnFreezeOffsets(
2925
3438
  visibleLeafColumns.map((column) => ({
@@ -2939,7 +3452,7 @@ function useGlideTable(options) {
2939
3452
  const totalSize = rowVirtualizer.getTotalSize();
2940
3453
  const paddingTop = virtualRows.length > 0 ? virtualRows[0]?.start ?? 0 : 0;
2941
3454
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0) : 0;
2942
- const selectedRowIndices = useMemo3(() => {
3455
+ const selectedRowIndices = useMemo5(() => {
2943
3456
  const indices = /* @__PURE__ */ new Set();
2944
3457
  for (const selectedRow of selectedRows) {
2945
3458
  indices.add(selectedRow.index);
@@ -2961,7 +3474,7 @@ function useGlideTable(options) {
2961
3474
  const cell = scrollElement.querySelector(
2962
3475
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
2963
3476
  );
2964
- if (cell instanceof HTMLElement) {
3477
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
2965
3478
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
2966
3479
  }
2967
3480
  };
@@ -2979,6 +3492,10 @@ function useGlideTable(options) {
2979
3492
  },
2980
3493
  [scrollCellIntoView]
2981
3494
  );
3495
+ const editKeyRef = useRef5(() => {
3496
+ });
3497
+ const clearKeyRef = useRef5(() => {
3498
+ });
2982
3499
  const {
2983
3500
  dragState,
2984
3501
  activeSelectionBounds,
@@ -2986,20 +3503,27 @@ function useGlideTable(options) {
2986
3503
  handleCellMouseEnter,
2987
3504
  handleFillHandleMouseDown,
2988
3505
  clearSelection: clearCellSelection,
2989
- copySelection
3506
+ copySelection,
3507
+ selectCell,
3508
+ focusSelection
2990
3509
  } = useCellSelection({
2991
- data: tableData,
3510
+ data: sourceData,
2992
3511
  rows,
2993
3512
  enabled: enableCellSelection,
2994
3513
  columnCount: visibleLeafColumns.length,
3514
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
2995
3515
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3516
+ escapeCopyFormulas,
2996
3517
  enableInsertPaste: enableInsertPaste ?? true,
2997
3518
  onDataChange,
2998
3519
  onBatchChange,
2999
3520
  onRowsPaste,
3000
3521
  onCellNavigate: handleCellNavigate,
3001
3522
  cellRendererRegistry,
3002
- rootRef
3523
+ rootRef,
3524
+ enableWasdNavigation,
3525
+ onEditKey: (position) => editKeyRef.current(position),
3526
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
3003
3527
  });
3004
3528
  const clearRowSelection = useCallback4(() => {
3005
3529
  if (rowSelectionMode === "none") return;
@@ -3020,22 +3544,79 @@ function useGlideTable(options) {
3020
3544
  const {
3021
3545
  editingCell,
3022
3546
  draftValue,
3547
+ draftInvalid,
3548
+ setDraftInvalid,
3023
3549
  setDraftValue,
3024
3550
  startEdit,
3025
3551
  commitEdit,
3026
3552
  cancelEdit
3027
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
3553
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
3554
+ editKeyRef.current = (position) => {
3555
+ startEdit(position.row, position.col);
3556
+ };
3557
+ clearKeyRef.current = (bounds) => {
3558
+ const changes = [];
3559
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
3560
+ const row = rows[rowIndex];
3561
+ if (!row) continue;
3562
+ const cells = row.getVisibleCells();
3563
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
3564
+ const cell = cells[colIndex];
3565
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
3566
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
3567
+ }
3568
+ }
3569
+ if (changes.length === 0) return;
3570
+ if (onBatchChange) {
3571
+ onBatchChange(changes);
3572
+ return;
3573
+ }
3574
+ if (!onDataChange) return;
3575
+ let next = sourceData;
3576
+ for (const change of changes) {
3577
+ const row = rows.find((item) => item.id === change.rowId);
3578
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
3579
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
3580
+ if (!row || !accessorKey) continue;
3581
+ next = applyCellChangesToData(next, [
3582
+ { original: row.original, index: row.index, accessorKey, value: null }
3583
+ ]);
3584
+ }
3585
+ if (next !== sourceData) onDataChange(next);
3586
+ };
3587
+ const commitEditAndMove = useCallback4(
3588
+ (raw, delta) => {
3589
+ const current = editingCell;
3590
+ if (!commitEdit(raw)) return false;
3591
+ if (current) {
3592
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
3593
+ }
3594
+ rootRef.current?.focus({ preventScroll: true });
3595
+ return true;
3596
+ },
3597
+ [commitEdit, editingCell, selectCell]
3598
+ );
3599
+ const cancelEditAndRefocus = useCallback4(() => {
3600
+ cancelEdit();
3601
+ rootRef.current?.focus({ preventScroll: true });
3602
+ }, [cancelEdit]);
3028
3603
  const commitRenderedCellValue = useCallback4(
3029
- (rowId, columnId, value) => commitCellValue({
3030
- data: tableData,
3031
- rows,
3032
- rowId,
3033
- columnId,
3034
- value,
3035
- onCellChange,
3036
- onDataChange
3037
- }),
3038
- [onCellChange, onDataChange, rows, tableData]
3604
+ (rowId, columnId, value) => {
3605
+ const columnDef = table.getColumn(columnId)?.columnDef;
3606
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
3607
+ return false;
3608
+ }
3609
+ return commitCellValue({
3610
+ data: sourceData,
3611
+ rows,
3612
+ rowId,
3613
+ columnId,
3614
+ value,
3615
+ onCellChange,
3616
+ onDataChange
3617
+ });
3618
+ },
3619
+ [onCellChange, onDataChange, rows, sourceData, table]
3039
3620
  );
3040
3621
  const getCellContext = useCallback4(
3041
3622
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3063,27 +3644,14 @@ function useGlideTable(options) {
3063
3644
  (row, index) => {
3064
3645
  if (getRowId) return getRowId(row, index);
3065
3646
  if (enableExpand) {
3066
- const record = row;
3067
- const idValue = record.id;
3068
- if (idValue != null && String(idValue).length > 0) {
3069
- return String(idValue);
3070
- }
3071
- const uniqueId = record.uniqueId;
3072
- if (uniqueId != null && String(uniqueId).length > 0) {
3073
- return String(uniqueId);
3074
- }
3075
- if (toggleField) {
3076
- const toggleValue = record[toggleField];
3077
- if (toggleValue != null && String(toggleValue).length > 0) {
3078
- return String(toggleValue);
3079
- }
3080
- }
3647
+ const treeKey = getTreeRowKey(row);
3648
+ if (treeKey) return treeKey;
3081
3649
  }
3082
3650
  return String(index);
3083
3651
  },
3084
- [enableExpand, getRowId, toggleField]
3652
+ [enableExpand, getRowId]
3085
3653
  );
3086
- const searchCorpus = useMemo3(() => {
3654
+ const searchCorpus = useMemo5(() => {
3087
3655
  if (!enableInlineSearch) return [];
3088
3656
  if (enableExpand && toggleField) {
3089
3657
  return buildTreeSearchCorpus(tableData, {
@@ -3101,35 +3669,66 @@ function useGlideTable(options) {
3101
3669
  ]);
3102
3670
  const searchCorpusRef = useRef5(searchCorpus);
3103
3671
  searchCorpusRef.current = searchCorpus;
3104
- const visibleRowIndexById = useMemo3(() => {
3672
+ const visibleRowIndexById = useMemo5(() => {
3105
3673
  const map = /* @__PURE__ */ new Map();
3106
3674
  for (const row of rows) {
3107
3675
  map.set(resolveSearchRowId(row.original, row.index), row.index);
3108
3676
  }
3109
3677
  return map;
3110
3678
  }, [resolveSearchRowId, rows]);
3111
- const getSearchCellValue = useCallback4(
3112
- (rowIndex, colIndex) => {
3113
- const corpusRow = searchCorpusRef.current[rowIndex];
3114
- const column = visibleLeafColumns[colIndex];
3115
- if (!corpusRow || !column) return void 0;
3679
+ const readSearchRawValue = useCallback4(
3680
+ (corpusRow, rowIndex, column) => {
3116
3681
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3117
3682
  if (visibleIndex !== void 0) {
3118
3683
  const visibleRow = rows[visibleIndex];
3119
3684
  if (visibleRow) {
3120
- return visibleRow.getValue(column.id);
3685
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3121
3686
  }
3122
3687
  }
3123
3688
  const columnDef = column.columnDef;
3124
3689
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3125
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3690
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3126
3691
  }
3127
3692
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3128
- return corpusRow.data[String(columnDef.accessorKey)];
3693
+ return {
3694
+ value: corpusRow.data[String(columnDef.accessorKey)],
3695
+ row: void 0
3696
+ };
3697
+ }
3698
+ return { value: corpusRow.data[column.id], row: void 0 };
3699
+ },
3700
+ [rows, visibleRowIndexById]
3701
+ );
3702
+ const getSearchCellValue = useCallback4(
3703
+ (rowIndex, colIndex) => {
3704
+ const corpusRow = searchCorpusRef.current[rowIndex];
3705
+ const column = visibleLeafColumns[colIndex];
3706
+ if (!corpusRow || !column) return void 0;
3707
+ if (isProtectedColumn(column.columnDef)) return void 0;
3708
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
3709
+ const meta = column.columnDef.meta;
3710
+ const searchValue2 = meta?.searchValue;
3711
+ if (!searchValue2 || searchValue2 === "value") return value;
3712
+ const ctx = {
3713
+ value,
3714
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
3715
+ index: row?.index ?? rowIndex,
3716
+ columnId: column.id,
3717
+ cellProps: meta?.cellProps,
3718
+ update: () => {
3719
+ }
3720
+ };
3721
+ try {
3722
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
3723
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
3724
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
3725
+ if (renderer) return reactNodeToText(renderer.render(ctx));
3726
+ } catch {
3727
+ return value;
3129
3728
  }
3130
- return corpusRow.data[column.id];
3729
+ return value;
3131
3730
  },
3132
- [rows, visibleLeafColumns, visibleRowIndexById]
3731
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3133
3732
  );
3134
3733
  const pendingSearchNavRef = useRef5(null);
3135
3734
  const focusSearchResult = useCallback4(
@@ -3180,11 +3779,19 @@ function useGlideTable(options) {
3180
3779
  focusSearchResult(pending.colIndex, visibleRowIndex);
3181
3780
  }, [focusSearchResult, rows, visibleRowIndexById]);
3182
3781
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
3782
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
3783
+ const searchContentKey = useMemo5(
3784
+ () => ({ data: sourceData, columns: searchColumnSignature }),
3785
+ [sourceData, searchColumnSignature]
3786
+ );
3183
3787
  const inlineSearch = useInlineSearch({
3184
3788
  enabled: enableInlineSearch,
3185
3789
  rowCount: searchCorpus.length,
3186
3790
  columnCount: visibleLeafColumns.length,
3187
3791
  getCellValue: getSearchCellValue,
3792
+ // Re-scan when the rows' content/order or the column order changes
3793
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
3794
+ contentKey: searchContentKey,
3188
3795
  initialStartRow: initialSearchStartRow,
3189
3796
  showSearch,
3190
3797
  searchValue,
@@ -3195,7 +3802,7 @@ function useGlideTable(options) {
3195
3802
  onNavigateToResult: navigateToCorpusSearchResult,
3196
3803
  rootRef
3197
3804
  });
3198
- const visibleSearchMatchKeys = useMemo3(() => {
3805
+ const visibleSearchMatchKeys = useMemo5(() => {
3199
3806
  if (!enableInlineSearch) return EMPTY_SEARCH_MATCH_KEYS;
3200
3807
  return mapSearchResultsToVisibleKeys(
3201
3808
  inlineSearch.searchResults,
@@ -3208,7 +3815,7 @@ function useGlideTable(options) {
3208
3815
  searchCorpus,
3209
3816
  visibleRowIndexById
3210
3817
  ]);
3211
- const visibleActiveMatch = useMemo3(() => {
3818
+ const visibleActiveMatch = useMemo5(() => {
3212
3819
  if (!enableInlineSearch || !inlineSearch.activeMatch) return null;
3213
3820
  return mapSearchResultToVisibleItem(
3214
3821
  inlineSearch.activeMatch,
@@ -3222,11 +3829,14 @@ function useGlideTable(options) {
3222
3829
  visibleRowIndexById
3223
3830
  ]);
3224
3831
  const clearHover = useCallback4(() => {
3225
- setHoveredRowIndex(null);
3226
- }, []);
3227
- const handleRowHover = useCallback4((rowIndex, _rowData) => {
3228
- setHoveredRowIndex(rowIndex);
3229
- }, []);
3832
+ hoverStore.setHoveredRowIndex(null);
3833
+ }, [hoverStore]);
3834
+ const handleRowHover = useCallback4(
3835
+ (rowIndex, _rowData) => {
3836
+ hoverStore.setHoveredRowIndex(rowIndex);
3837
+ },
3838
+ [hoverStore]
3839
+ );
3230
3840
  const handleToggleSelect = useCallback4(
3231
3841
  (row) => {
3232
3842
  if (!row.getCanSelect()) return;
@@ -3244,14 +3854,14 @@ function useGlideTable(options) {
3244
3854
  },
3245
3855
  [preventExpand, handleExpandedRowsChange, expandedRows]
3246
3856
  );
3247
- const rowContextValue = useMemo3(() => {
3857
+ const rowContextValue = useMemo5(() => {
3248
3858
  return {
3249
3859
  rowSpan: {
3250
3860
  enableRowSpan,
3251
3861
  primaryRowSpanKey,
3252
3862
  primaryRowSpanColumnId,
3253
3863
  columnRowSpanMap,
3254
- hoveredRowIndex,
3864
+ hoverStore,
3255
3865
  selectedRowIndices,
3256
3866
  onRowHover: handleRowHover
3257
3867
  },
@@ -3265,6 +3875,7 @@ function useGlideTable(options) {
3265
3875
  enableCellSelection,
3266
3876
  activeSelectionBounds,
3267
3877
  dragState,
3878
+ canFill,
3268
3879
  onCellMouseDown: handleCellMouseDownWithCommit,
3269
3880
  onCellMouseEnter: handleCellMouseEnter,
3270
3881
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3272,18 +3883,23 @@ function useGlideTable(options) {
3272
3883
  cellEdit: {
3273
3884
  editingCell,
3274
3885
  draftValue,
3886
+ draftInvalid,
3887
+ onDraftInvalidChange: setDraftInvalid,
3275
3888
  onDraftValueChange: setDraftValue,
3276
3889
  onStartEdit: startEdit,
3277
3890
  onCommitEdit: commitEdit,
3278
- onCancelEdit: cancelEdit
3891
+ onCommitEditAndMove: commitEditAndMove,
3892
+ onCancelEdit: cancelEditAndRefocus
3279
3893
  },
3280
3894
  cellRender: {
3281
3895
  registry: cellRendererRegistry,
3282
- commitValue: commitRenderedCellValue
3896
+ commitValue: commitRenderedCellValue,
3897
+ protectedLabel: labels.protectedCell
3283
3898
  },
3284
3899
  expand: {
3285
3900
  enableExpand,
3286
3901
  toggleField,
3902
+ expandColumn,
3287
3903
  expandedRows,
3288
3904
  preventExpand,
3289
3905
  onToggleExpand: handleToggleExpand,
@@ -3308,7 +3924,7 @@ function useGlideTable(options) {
3308
3924
  primaryRowSpanKey,
3309
3925
  primaryRowSpanColumnId,
3310
3926
  columnRowSpanMap,
3311
- hoveredRowIndex,
3927
+ hoverStore,
3312
3928
  selectedRowIndices,
3313
3929
  handleRowHover,
3314
3930
  rowSelectionMode,
@@ -3318,19 +3934,25 @@ function useGlideTable(options) {
3318
3934
  enableCellSelection,
3319
3935
  activeSelectionBounds,
3320
3936
  dragState,
3937
+ canFill,
3321
3938
  handleCellMouseDownWithCommit,
3322
3939
  handleCellMouseEnter,
3323
3940
  handleFillHandleMouseDown,
3324
3941
  editingCell,
3325
3942
  draftValue,
3943
+ draftInvalid,
3944
+ setDraftInvalid,
3326
3945
  setDraftValue,
3327
3946
  startEdit,
3328
3947
  commitEdit,
3329
- cancelEdit,
3948
+ commitEditAndMove,
3949
+ cancelEditAndRefocus,
3330
3950
  cellRendererRegistry,
3331
3951
  commitRenderedCellValue,
3952
+ labels.protectedCell,
3332
3953
  enableExpand,
3333
3954
  toggleField,
3955
+ expandColumn,
3334
3956
  expandedRows,
3335
3957
  preventExpand,
3336
3958
  handleToggleExpand,
@@ -3378,6 +4000,7 @@ function useGlideTable(options) {
3378
4000
  handleToggleSelect,
3379
4001
  clearHover,
3380
4002
  setColumnOrder,
4003
+ handleRootFocus: focusSelection,
3381
4004
  copySelection: stableCopySelection,
3382
4005
  inlineSearch: {
3383
4006
  showSearch: inlineSearch.showSearch,
@@ -3428,12 +4051,16 @@ function ResolvedTableCell({
3428
4051
  },
3429
4052
  [cellRender, columnId, row.id]
3430
4053
  );
4054
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
4055
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
4056
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
4057
+ }
3431
4058
  const ctx = {
3432
4059
  value,
3433
4060
  row,
3434
4061
  index: row.index,
3435
4062
  columnId,
3436
- cellProps: meta?.cellProps,
4063
+ cellProps,
3437
4064
  update
3438
4065
  };
3439
4066
  if (meta?.cellRender) {
@@ -3829,6 +4456,7 @@ export {
3829
4456
  createCellRendererRegistry,
3830
4457
  createSearchRegex,
3831
4458
  escapeSearchRegex,
4459
+ escapeSpreadsheetFormula,
3832
4460
  flattenSubtreeRows,
3833
4461
  formatCellValue,
3834
4462
  formatDefaultCellValue,