react-glide-table 2.3.4 → 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,735 +749,781 @@ 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
912
+ id: getOriginalRowId(rowData) || String(index),
913
+ index,
914
+ original: rowData,
915
+ getIsCellDragSelected: () => false
596
916
  };
597
917
  }
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);
918
+ function buildVisibleRowLookup(visibleRows) {
919
+ const lookup = /* @__PURE__ */ new Map();
920
+ for (const row of visibleRows) {
921
+ lookup.set(row.original, row);
663
922
  }
664
- if (colIndex > bounds.startCol) {
665
- collectSide("left", colIndex - 1);
923
+ return lookup;
924
+ }
925
+ function resolveCopyColumnId(cell) {
926
+ if (cell.column.id) return cell.column.id;
927
+ const columnDef = cell.column.columnDef;
928
+ if (columnDef.id) return columnDef.id;
929
+ if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
930
+ return String(columnDef.accessorKey);
666
931
  }
667
- return edges;
932
+ return "";
668
933
  }
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
- });
934
+ function isPrimitiveCopyValue(value) {
935
+ return value == null || typeof value !== "object";
936
+ }
937
+ function extractRenderedCopyText(node, value, cellPosition, root) {
938
+ const rendered = sanitizeClipboardCell(reactNodeToText(node));
939
+ if (reactNodeContainsImage(node)) {
940
+ const fromDom = cellPosition != null ? sanitizeClipboardCell(
941
+ readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
942
+ ) : "";
943
+ if (fromDom) return fromDom;
944
+ if (rendered && isLikelyUrl(rendered)) return rendered;
945
+ return sanitizeClipboardCell(pickUrlFromUnknown(value));
695
946
  }
696
- return layers;
947
+ return rendered;
697
948
  }
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
- );
949
+ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
950
+ const meta = columnDef.meta;
951
+ const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
952
+ const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
953
+ const ctx = {
954
+ value,
955
+ row,
956
+ index: row.index,
957
+ columnId,
958
+ cellProps: meta?.cellProps,
959
+ update: () => {
731
960
  }
732
- if (isLeftEdge) {
733
- shadows.push(
734
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
735
- );
961
+ };
962
+ const copyValue = meta?.copyValue;
963
+ if (typeof copyValue === "function") {
964
+ try {
965
+ return sanitizeClipboardCell(copyValue(ctx));
966
+ } catch {
967
+ return formatCellValue(value);
736
968
  }
737
- if (isRightEdge) {
738
- shadows.push(
739
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
740
- );
969
+ }
970
+ if (copyValue === "value") {
971
+ return formatCellValue(value);
972
+ }
973
+ const cellRender = meta?.cellRender;
974
+ if (typeof cellRender === "function") {
975
+ try {
976
+ const node = cellRender(ctx);
977
+ return extractRenderedCopyText(node, value, cellPosition, options?.root);
978
+ } catch {
979
+ return formatCellValue(value);
741
980
  }
742
981
  }
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);
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);
751
992
  }
752
993
  }
753
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
754
- return void 0;
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);
755
1008
  }
756
- const style = {};
757
- if (shadows.length > 0) {
758
- style["--selection-edge-shadows"] = shadows.join(", ");
1009
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1010
+ return getNestedValue(rowData, String(columnDef.accessorKey));
759
1011
  }
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(", ");
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;
764
1049
  }
765
- if (selectionContinuesBelow) {
766
- style.borderBottomColor = "var(--color-brand-surface)";
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);
767
1074
  }
768
- return style;
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");
769
1115
  }
770
- function hasCellSelectionEdges(style) {
771
- return Boolean(
772
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
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
773
1124
  );
774
1125
  }
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;
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
+ }
780
1148
  }
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 || "";
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);
786
1155
  }
787
- if (typeof type === "object" && type !== null) {
788
- const component = type;
789
- return component.displayName || component.render?.displayName || component.render?.name || "";
1156
+ try {
1157
+ await navigator.clipboard.writeText(text);
1158
+ return true;
1159
+ } catch {
1160
+ return false;
790
1161
  }
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
1162
  }
801
- function isImageReactElement(node) {
802
- const typeName = getElementTypeName(node.type);
803
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
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
+ };
804
1172
  }
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;
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");
812
1182
  }
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
- }
1183
+ function registerCellSelectionOwner(owner, clearSelection) {
1184
+ clearByOwner.set(owner, clearSelection);
1185
+ return () => {
1186
+ clearByOwner.delete(owner);
1187
+ if (activeOwner === owner) {
1188
+ activeOwner = null;
827
1189
  }
828
- }
829
- return "";
1190
+ };
830
1191
  }
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();
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();
837
1198
  }
838
1199
  }
839
- return "";
840
1200
  }
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;
1201
+ function isActiveCellSelectionOwner(owner) {
1202
+ return activeOwner === owner;
852
1203
  }
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;
1204
+ function releaseCellSelectionOwner(owner) {
1205
+ if (activeOwner === owner) {
1206
+ activeOwner = null;
859
1207
  }
860
- return "";
861
1208
  }
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 "";
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
+ };
876
1227
  }
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 "";
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;
900
1248
  }
901
- return "";
902
1249
  }
903
- function sanitizeClipboardCell(text) {
904
- return text.replace(/\s+/g, " ").trim();
905
- }
906
- function createCopyRenderRow(rowData, index) {
1250
+ function clampCellPosition(position, rowCount, columnCount) {
1251
+ const maxRow = Math.max(rowCount - 1, 0);
1252
+ const maxCol = Math.max(columnCount - 1, 0);
907
1253
  return {
908
- id: getOriginalRowId(rowData) || String(index),
909
- index,
910
- original: rowData,
911
- getIsCellDragSelected: () => false
1254
+ row: Math.min(Math.max(position.row, 0), maxRow),
1255
+ col: Math.min(Math.max(position.col, 0), maxCol)
912
1256
  };
913
1257
  }
914
- function buildVisibleRowLookup(visibleRows) {
915
- const lookup = /* @__PURE__ */ new Map();
916
- for (const row of visibleRows) {
917
- lookup.set(row.original, row);
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;
1284
+ }
1285
+ }
1286
+ return rowIndex + rowSpan - 1;
918
1287
  }
919
- return lookup;
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;
920
1294
  }
921
- function resolveCopyColumnId(cell) {
922
- if (cell.column.id) return cell.column.id;
923
- const columnDef = cell.column.columnDef;
924
- if (columnDef.id) return columnDef.id;
925
- if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
926
- return String(columnDef.accessorKey);
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;
1299
+ }
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 };
927
1310
  }
928
- return "";
1311
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
929
1312
  }
930
- function isPrimitiveCopyValue(value) {
931
- return value == null || typeof value !== "object";
1313
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1314
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1315
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1316
+ }
1317
+ return selectionBounds;
932
1318
  }
933
- function extractRenderedCopyText(node, value, cellPosition, root) {
934
- const rendered = sanitizeClipboardCell(reactNodeToText(node));
935
- if (reactNodeContainsImage(node)) {
936
- const fromDom = cellPosition != null ? sanitizeClipboardCell(
937
- readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
938
- ) : "";
939
- if (fromDom) return fromDom;
940
- if (rendered && isLikelyUrl(rendered)) return rendered;
941
- return sanitizeClipboardCell(pickUrlFromUnknown(value));
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 };
942
1327
  }
943
- return rendered;
1328
+ if (!rowHeights || rowHeights.length !== span) {
1329
+ return {
1330
+ offsetRatio: (clampedFrom - rowIndex) / span,
1331
+ lengthRatio: (clampedTo - clampedFrom) / span
1332
+ };
1333
+ }
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;
1338
+ }
1339
+ let lengthPx = 0;
1340
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1341
+ lengthPx += rowHeights[i] ?? 0;
1342
+ }
1343
+ return {
1344
+ offsetRatio: offsetPx / total,
1345
+ lengthRatio: lengthPx / total,
1346
+ offsetPx,
1347
+ lengthPx
1348
+ };
944
1349
  }
945
- function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
946
- const meta = columnDef.meta;
947
- const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
948
- const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
949
- const ctx = {
950
- value,
951
- row,
952
- index: row.index,
953
- columnId,
954
- cellProps: meta?.cellProps,
955
- update: () => {
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);
956
1358
  }
1359
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
957
1360
  };
958
- const copyValue = meta?.copyValue;
959
- if (typeof copyValue === "function") {
960
- try {
961
- return sanitizeClipboardCell(copyValue(ctx));
962
- } catch {
963
- return formatCellValue(value);
964
- }
965
- }
966
- if (copyValue === "value") {
967
- return formatCellValue(value);
968
- }
969
- const cellRender = meta?.cellRender;
970
- if (typeof cellRender === "function") {
971
- try {
972
- const node = cellRender(ctx);
973
- return extractRenderedCopyText(node, value, cellPosition, options?.root);
974
- } catch {
975
- return formatCellValue(value);
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
+ }
976
1381
  }
977
- }
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;
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 });
985
1392
  }
986
- } catch {
987
- return formatCellValue(value);
988
1393
  }
1394
+ };
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)
1402
+ );
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);
989
1415
  }
990
- return formatCellValue(value);
991
- }
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);
1416
+ if (colIndex > bounds.startCol) {
1417
+ collectSide("left", colIndex - 1);
997
1418
  }
998
- return "";
1419
+ return edges;
999
1420
  }
1000
- function formatObjectValue(value) {
1001
- const text = value.text ?? value.label ?? value.name ?? value.title;
1002
- if (text != null && text !== "") {
1003
- return formatCellValue(text);
1004
- }
1005
- try {
1006
- return JSON.stringify(value);
1007
- } catch {
1008
- return "";
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
+ });
1009
1447
  }
1448
+ return layers;
1010
1449
  }
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(", ");
1015
- }
1016
- if (typeof value === "object") {
1017
- return formatObjectValue(value);
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,
1462
+ bounds,
1463
+ rowSpan,
1464
+ isVisuallySelectedAt,
1465
+ rowHeights
1466
+ );
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
+ }
1018
1494
  }
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;
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);
1026
1503
  }
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);
1033
1504
  }
1034
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1035
- return getNestedValue(rowData, String(columnDef.accessorKey));
1505
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1506
+ return void 0;
1036
1507
  }
1037
- return void 0;
1038
- }
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
- }
1050
- }
1051
- };
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);
1077
- }
1078
- appendSubtree(child, depth + 1);
1079
- }
1080
- };
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);
1508
+ const style = {};
1509
+ if (shadows.length > 0) {
1510
+ style["--selection-edge-shadows"] = shadows.join(", ");
1091
1511
  }
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
1126
- );
1127
- }).join(" ");
1128
- return `${" ".repeat(relativeDepth)}${line}`;
1129
- }).join("\n");
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;
1130
1521
  }
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,
1136
- bounds,
1137
- entries.map((entry) => entry.depth),
1138
- options
1522
+ function hasCellSelectionEdges(style) {
1523
+ return Boolean(
1524
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1139
1525
  );
1140
1526
  }
1141
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1142
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1143
- if (!text) return false;
1144
- try {
1145
- await navigator.clipboard.writeText(text);
1146
- } catch {
1147
- return false;
1148
- }
1149
- return true;
1150
- }
1151
1527
 
1152
1528
  // src/components/ui/table/features/cell-selection/fillData.ts
1153
1529
  function getColumnAccessorKey2(columnDef) {
@@ -1171,6 +1547,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1171
1547
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1172
1548
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1173
1549
  if (!targetRow || !targetCell || !sourceCell) continue;
1550
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1551
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1174
1552
  const accessorKey = getColumnAccessorKey2(
1175
1553
  targetCell.column.columnDef
1176
1554
  );
@@ -1192,13 +1570,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1192
1570
  );
1193
1571
  }
1194
1572
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1195
- const newData = data.map((row) => ({ ...row }));
1196
1573
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1197
- for (const target of targets) {
1198
- if (!newData[target.rowIndex]) continue;
1199
- newData[target.rowIndex][target.accessorKey] = target.value;
1200
- }
1201
- 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
+ );
1202
1589
  }
1203
1590
  function hasFillExtension(sourceBounds, fillBounds) {
1204
1591
  if (!sourceBounds) return false;
@@ -1219,17 +1606,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1219
1606
  if (firstDepth !== 0) return false;
1220
1607
  return leadingEmptyCounts.some((depth) => depth > 0);
1221
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
+ }
1222
1654
  function parseClipboardTSV(text) {
1223
1655
  return parseClipboardTSVWithDepths(text).values;
1224
1656
  }
1225
- function parseClipboardTSVWithDepths(text) {
1657
+ function parseClipboardTSVWithDepths(text, options) {
1226
1658
  if (!text) return { values: [], depths: [] };
1227
1659
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1228
1660
  const withoutTrailing = normalized.replace(/\n+$/, "");
1229
1661
  if (!withoutTrailing) return { values: [], depths: [] };
1230
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1662
+ const rows = splitTSV(withoutTrailing);
1231
1663
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1232
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1664
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1233
1665
  const values = [];
1234
1666
  const depths = [];
1235
1667
  for (let index = 0; index < rows.length; index += 1) {
@@ -1256,8 +1688,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1256
1688
  }
1257
1689
  return columnIds;
1258
1690
  }
1259
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1260
- const { values, depths } = parseClipboardTSVWithDepths(text);
1691
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1692
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1261
1693
  if (values.length === 0) return null;
1262
1694
  const width = Math.max(...values.map((row) => row.length), 0);
1263
1695
  if (width === 0) return null;
@@ -1290,6 +1722,19 @@ function isEditablePasteTarget(target) {
1290
1722
  }
1291
1723
 
1292
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
+ }
1293
1738
  function isFocusOutsideRoot(rootRef) {
1294
1739
  const root = rootRef?.current;
1295
1740
  if (!root) return false;
@@ -1302,29 +1747,50 @@ function useCellSelection({
1302
1747
  rows,
1303
1748
  enabled = true,
1304
1749
  columnCount = 0,
1750
+ columnSignature,
1305
1751
  enableSubtreeCopy = false,
1752
+ escapeCopyFormulas = false,
1306
1753
  enableInsertPaste = true,
1307
1754
  onDataChange,
1308
1755
  onBatchChange,
1309
1756
  onRowsPaste,
1310
1757
  onCellNavigate,
1311
1758
  cellRendererRegistry,
1312
- rootRef
1759
+ rootRef,
1760
+ enableWasdNavigation = true,
1761
+ onEditKey,
1762
+ onClearKey
1313
1763
  }) {
1314
1764
  const ownerRef = useRef2(createCellSelectionOwner());
1315
1765
  const [dragState, setDragState] = useState2(INITIAL_DRAG_STATE);
1316
1766
  const pendingPasteModeRef = useRef2(null);
1317
1767
  const dragStateRef = useRef2(dragState);
1318
1768
  const onCellNavigateRef = useRef2(onCellNavigate);
1769
+ const onEditKeyRef = useRef2(onEditKey);
1770
+ const onClearKeyRef = useRef2(onClearKey);
1319
1771
  dragStateRef.current = dragState;
1320
1772
  onCellNavigateRef.current = onCellNavigate;
1321
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1322
- 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]);
1323
1789
  const handleCellMouseDown = useCallback2(
1324
1790
  (rowIndex, colIndex, options) => {
1325
1791
  if (!enabled) return;
1326
1792
  claimCellSelectionOwner(ownerRef.current);
1327
- setDragState((prev) => {
1793
+ updateDragState((prev) => {
1328
1794
  if (options?.shiftKey && prev.start) {
1329
1795
  return {
1330
1796
  ...prev,
@@ -1345,28 +1811,30 @@ function useCellSelection({
1345
1811
  };
1346
1812
  });
1347
1813
  },
1348
- [enabled]
1814
+ [enabled, updateDragState]
1349
1815
  );
1350
1816
  const handleCellMouseEnter = useCallback2(
1351
1817
  (rowIndex, colIndex) => {
1352
1818
  if (!enabled) return;
1353
- setDragState((prev) => {
1819
+ updateDragState((prev) => {
1354
1820
  if (prev.isSelecting) {
1821
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1355
1822
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1356
1823
  }
1357
1824
  if (prev.isFillDragging) {
1825
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1358
1826
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1359
1827
  }
1360
1828
  return prev;
1361
1829
  });
1362
1830
  },
1363
- [enabled]
1831
+ [enabled, updateDragState]
1364
1832
  );
1365
1833
  const handleFillHandleMouseDown = useCallback2(
1366
1834
  (rowIndex, colIndex) => {
1367
1835
  if (!enabled) return;
1368
1836
  claimCellSelectionOwner(ownerRef.current);
1369
- setDragState((prev) => {
1837
+ updateDragState((prev) => {
1370
1838
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1371
1839
  if (!bounds) return prev;
1372
1840
  return {
@@ -1378,7 +1846,7 @@ function useCellSelection({
1378
1846
  };
1379
1847
  });
1380
1848
  },
1381
- [enabled]
1849
+ [enabled, updateDragState]
1382
1850
  );
1383
1851
  const clearSelection = useCallback2(() => {
1384
1852
  const prev = dragStateRef.current;
@@ -1397,6 +1865,130 @@ function useCellSelection({
1397
1865
  useEffect2(() => {
1398
1866
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1399
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]);
1400
1992
  useEffect2(() => {
1401
1993
  if (!enabled) return;
1402
1994
  const handleKeyDown = (e) => {
@@ -1406,6 +1998,7 @@ function useCellSelection({
1406
1998
  return;
1407
1999
  }
1408
2000
  if (isFocusOutsideRoot(rootRef)) return;
2001
+ if (!enableWasdNavigation && e.key.length === 1) return;
1409
2002
  const delta = getCellNavigationDelta(e.key);
1410
2003
  if (!delta) return;
1411
2004
  const prev = dragStateRef.current;
@@ -1445,14 +2038,15 @@ function useCellSelection({
1445
2038
  };
1446
2039
  window.addEventListener("keydown", handleKeyDown);
1447
2040
  return () => window.removeEventListener("keydown", handleKeyDown);
1448
- }, [columnCount, enabled, rows]);
2041
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1449
2042
  const copySelection = useCallback2(
1450
2043
  async (options) => {
1451
2044
  if (!enabled || !activeSelectionBounds) return false;
1452
2045
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1453
2046
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1454
2047
  registry: cellRendererRegistry,
1455
- root: rootRef?.current
2048
+ root: rootRef?.current,
2049
+ escapeFormulas: escapeCopyFormulas
1456
2050
  });
1457
2051
  },
1458
2052
  [
@@ -1460,6 +2054,7 @@ function useCellSelection({
1460
2054
  cellRendererRegistry,
1461
2055
  enableSubtreeCopy,
1462
2056
  enabled,
2057
+ escapeCopyFormulas,
1463
2058
  rootRef,
1464
2059
  rows
1465
2060
  ]
@@ -1477,6 +2072,7 @@ function useCellSelection({
1477
2072
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1478
2073
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1479
2074
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2075
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1480
2076
  e.preventDefault();
1481
2077
  void copySelection({ includeDescendants: isSubtreeShortcut });
1482
2078
  };
@@ -1492,9 +2088,17 @@ function useCellSelection({
1492
2088
  activeSelectionBounds.startCol,
1493
2089
  text,
1494
2090
  mode,
1495
- 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" }
1496
2095
  );
1497
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
+ });
1498
2102
  onRowsPaste(payload);
1499
2103
  return true;
1500
2104
  },
@@ -1525,7 +2129,10 @@ function useCellSelection({
1525
2129
  void (async () => {
1526
2130
  try {
1527
2131
  const text = await navigator.clipboard.readText();
1528
- if (pasteHandledRef.current) return;
2132
+ if (pasteHandledRef.current) {
2133
+ pasteHandledRef.current = false;
2134
+ return;
2135
+ }
1529
2136
  if (pendingPasteModeRef.current !== mode) return;
1530
2137
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1531
2138
  if (!text) return;
@@ -1550,6 +2157,7 @@ function useCellSelection({
1550
2157
  }
1551
2158
  const mode = pendingPasteModeRef.current ?? "overwrite";
1552
2159
  if (pasteHandledRef.current) {
2160
+ pasteHandledRef.current = false;
1553
2161
  e.preventDefault();
1554
2162
  return;
1555
2163
  }
@@ -1576,39 +2184,41 @@ function useCellSelection({
1576
2184
  useEffect2(() => {
1577
2185
  if (!enabled) return;
1578
2186
  const handleMouseUp = () => {
1579
- setDragState((prev) => {
1580
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1581
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1582
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1583
- if (newBounds) {
1584
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1585
- if (onBatchChange) {
1586
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1587
- if (changes.length > 0) {
1588
- onBatchChange(changes);
1589
- }
1590
- } else if (onDataChange) {
1591
- 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);
1592
2198
  }
2199
+ } else if (onDataChange) {
2200
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1593
2201
  }
1594
- return {
1595
- isSelecting: false,
1596
- isFillDragging: false,
1597
- start: { row: newBounds.startRow, col: newBounds.startCol },
1598
- end: { row: newBounds.endRow, col: newBounds.endCol },
1599
- fillAnchor: null,
1600
- fillEnd: null
1601
- };
1602
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 };
1603
2213
  }
1604
- if (prev.isSelecting) {
1605
- return { ...prev, isSelecting: false };
1606
- }
1607
- if (prev.isFillDragging) {
1608
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1609
- }
1610
- return prev;
1611
- });
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);
1612
2222
  };
1613
2223
  window.addEventListener("mouseup", handleMouseUp);
1614
2224
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1620,7 +2230,27 @@ function useCellSelection({
1620
2230
  handleCellMouseEnter,
1621
2231
  handleFillHandleMouseDown,
1622
2232
  clearSelection,
1623
- 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
+ }
1624
2254
  };
1625
2255
  }
1626
2256
 
@@ -1655,8 +2285,12 @@ function handleEscape(event) {
1655
2285
  if (isOverlayDismissIgnoreTarget(event.target) || isOverlayDismissIgnoreTarget(document.activeElement)) {
1656
2286
  return;
1657
2287
  }
1658
- for (const clearAllSelections of clearAllByOwner.values()) {
1659
- clearAllSelections();
2288
+ for (const clearAllSelections of [...clearAllByOwner.values()]) {
2289
+ try {
2290
+ clearAllSelections();
2291
+ } catch (error) {
2292
+ console.error("[react-glide-table] escape-dismiss callback failed", error);
2293
+ }
1660
2294
  }
1661
2295
  }
1662
2296
  function registerEscapeDismiss(owner, clearAllSelections) {
@@ -1910,177 +2544,40 @@ function flattenHeaderLeaves(column) {
1910
2544
  return column.columns.flatMap((child) => flattenHeaderLeaves(child));
1911
2545
  }
1912
2546
 
1913
- // src/components/ui/table/features/inline-search/inlineSearch.ts
1914
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
1915
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
1916
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
1917
- function escapeSearchRegex(value) {
1918
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
1919
- }
1920
- function createSearchRegex(query) {
1921
- const trimmed = query.trim();
1922
- if (!trimmed) return null;
1923
- return new RegExp(escapeSearchRegex(trimmed), "i");
1924
- }
1925
- function cellValueToSearchText(value) {
1926
- if (value == null) return void 0;
1927
- if (typeof value === "string") return value;
1928
- if (typeof value === "number" || typeof value === "boolean") {
1929
- return String(value);
1930
- }
1931
- if (Array.isArray(value)) {
1932
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
1933
- }
1934
- if (typeof value === "object") {
1935
- try {
1936
- return JSON.stringify(value);
1937
- } catch {
1938
- return String(value);
1939
- }
1940
- }
1941
- return String(value);
1942
- }
1943
- function formatSearchResultLabel(status) {
1944
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
1945
- if (status.selectedIndex >= 0 && status.results > 0) {
1946
- return `${status.selectedIndex + 1} of ${countLabel}`;
1947
- }
1948
- return countLabel;
1949
- }
1950
- function nextSearchIndex(selectedIndex, results) {
1951
- if (results <= 0) return -1;
1952
- if (selectedIndex < 0) return 0;
1953
- return (selectedIndex + 1) % results;
1954
- }
1955
- function previousSearchIndex(selectedIndex, results) {
1956
- if (results <= 0) return -1;
1957
- if (selectedIndex < 0) return results - 1;
1958
- let next = (selectedIndex - 1) % results;
1959
- if (next < 0) next += results;
1960
- return next;
1961
- }
1962
- function buildSearchMatchKey(colIndex, rowIndex) {
1963
- return `${colIndex}:${rowIndex}`;
1964
- }
1965
- function buildSearchMatchKeys(results) {
1966
- const keys = /* @__PURE__ */ new Set();
1967
- for (const [colIndex, rowIndex] of results) {
1968
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
1969
- }
1970
- return keys;
1971
- }
1972
- function collectSearchMatchesInRange(options) {
1973
- const {
1974
- query,
1975
- startRow,
1976
- rowCount,
1977
- columnCount,
1978
- getCellValue,
1979
- maxResults = INLINE_SEARCH_MAX_RESULTS
1980
- } = options;
1981
- const regex = createSearchRegex(query);
1982
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
1983
- const matches = [];
1984
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
1985
- const rowIndex = startRow + rowOffset;
1986
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
1987
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
1988
- if (text !== void 0 && regex.test(text)) {
1989
- matches.push([colIndex, rowIndex]);
1990
- if (matches.length >= maxResults) {
1991
- return matches;
1992
- }
1993
- }
1994
- }
1995
- }
1996
- return matches;
1997
- }
1998
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
1999
- const rounded = Math.max(elapsedMs, 1);
2000
- const scalar = targetMs / rounded;
2001
- return Math.max(1, Math.ceil(currentStride * scalar));
2002
- }
2003
- function buildFlatSearchCorpus(rows, getRowId) {
2004
- return rows.map((data, index) => ({
2005
- id: getRowId(data, index),
2006
- data,
2007
- ancestorToggleKeys: []
2008
- }));
2009
- }
2010
- function buildTreeSearchCorpus(visibleRows, options) {
2011
- const { toggleField, getRowId } = options;
2012
- const corpus = [];
2013
- const seen = /* @__PURE__ */ new Set();
2014
- const walk = (node, ancestorToggleKeys) => {
2015
- const id = getRowId(node, corpus.length);
2016
- if (seen.has(id)) return;
2017
- seen.add(id);
2018
- corpus.push({
2019
- id,
2020
- data: node,
2021
- ancestorToggleKeys
2022
- });
2023
- const children = node.children;
2024
- if (!Array.isArray(children) || children.length === 0) return;
2025
- const toggleValue = node[toggleField];
2026
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2027
- for (const child of children) {
2028
- if (child && typeof child === "object") {
2029
- walk(child, childAncestors);
2030
- }
2031
- }
2032
- };
2033
- for (const row of visibleRows) {
2034
- const level = row.level;
2035
- if (level === 0 || level === void 0) {
2036
- walk(row, []);
2037
- }
2038
- }
2039
- for (const row of visibleRows) {
2040
- const id = getRowId(row, corpus.length);
2041
- if (seen.has(id)) continue;
2042
- walk(row, []);
2043
- }
2044
- return corpus;
2045
- }
2046
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2047
- const keys = /* @__PURE__ */ new Set();
2048
- for (const [colIndex, corpusRowIndex] of results) {
2049
- const corpusRow = corpus[corpusRowIndex];
2050
- if (!corpusRow) continue;
2051
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2052
- if (visibleRowIndex === void 0) continue;
2053
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2054
- }
2055
- return keys;
2056
- }
2057
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2058
- const [colIndex, corpusRowIndex] = item;
2059
- const corpusRow = corpus[corpusRowIndex];
2060
- if (!corpusRow) return null;
2061
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2062
- if (visibleRowIndex === void 0) return null;
2063
- return [colIndex, visibleRowIndex];
2064
- }
2065
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2066
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2067
- }
2068
-
2069
2547
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
2070
2548
  import {
2071
2549
  useCallback as useCallback3,
2072
2550
  useEffect as useEffect3,
2073
2551
  useId,
2074
- useMemo,
2552
+ useMemo as useMemo3,
2075
2553
  useRef as useRef3,
2076
2554
  useState as useState3
2077
2555
  } from "react";
2078
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
+ }
2079
2575
  function useInlineSearch({
2080
2576
  enabled = false,
2081
2577
  rowCount,
2082
2578
  columnCount,
2083
2579
  getCellValue,
2580
+ contentKey,
2084
2581
  initialStartRow = 0,
2085
2582
  showSearch: controlledShowSearch,
2086
2583
  searchValue: controlledSearchValue,
@@ -2289,6 +2786,7 @@ function useInlineSearch({
2289
2786
  }
2290
2787
  beginSearch(searchValue);
2291
2788
  }, [
2789
+ contentKey,
2292
2790
  beginSearch,
2293
2791
  cancelSearch,
2294
2792
  controlledSearchResults,
@@ -2309,6 +2807,9 @@ function useInlineSearch({
2309
2807
  if (!focusInside && active !== document.body) {
2310
2808
  return;
2311
2809
  }
2810
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2811
+ return;
2812
+ }
2312
2813
  }
2313
2814
  event.preventDefault();
2314
2815
  event.stopPropagation();
@@ -2322,14 +2823,18 @@ function useInlineSearch({
2322
2823
  }
2323
2824
  };
2324
2825
  window.addEventListener("keydown", handleKeyDown, true);
2325
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2826
+ const releaseInstance = registerSearchInstance();
2827
+ return () => {
2828
+ window.removeEventListener("keydown", handleKeyDown, true);
2829
+ releaseInstance();
2830
+ };
2326
2831
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2327
2832
  useEffect3(() => () => cancelSearch(), [cancelSearch]);
2328
- const searchMatchKeys = useMemo(
2833
+ const searchMatchKeys = useMemo3(
2329
2834
  () => buildSearchMatchKeys(searchResults),
2330
2835
  [searchResults]
2331
2836
  );
2332
- const activeMatch = useMemo(() => {
2837
+ const activeMatch = useMemo3(() => {
2333
2838
  if (!searchStatus || searchStatus.selectedIndex < 0) return null;
2334
2839
  return searchResults[searchStatus.selectedIndex] ?? null;
2335
2840
  }, [searchResults, searchStatus]);
@@ -2372,14 +2877,18 @@ function useInlineSearch({
2372
2877
  }
2373
2878
 
2374
2879
  // src/components/ui/table/features/row-expand/row-expand.ts
2375
- 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";
2376
2881
  function getFieldValue(row, key) {
2377
2882
  return row[key];
2378
2883
  }
2379
2884
  function canExpandRow(row) {
2380
2885
  const children = row.children;
2381
- const level = row.level;
2382
- 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;
2383
2892
  }
2384
2893
  function toggleExpandedRowId(rowId, previous) {
2385
2894
  const next = new Set(previous);
@@ -2400,7 +2909,8 @@ var useConvertTreeData = ({
2400
2909
  preventExpand = false,
2401
2910
  startIndex = 1,
2402
2911
  expandedRows,
2403
- onExpandedRowsChange
2912
+ onExpandedRowsChange,
2913
+ autoExpandOnLoad = true
2404
2914
  }) => {
2405
2915
  const onExpandedRowsChangeRef = useRef4(onExpandedRowsChange);
2406
2916
  const hasInitializedRef = useRef4(false);
@@ -2413,16 +2923,33 @@ var useConvertTreeData = ({
2413
2923
  return;
2414
2924
  }
2415
2925
  if (!enabled || hasInitializedRef.current) return;
2416
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2417
- onExpandedRowsChangeRef.current?.(new Set(ids));
2418
2926
  hasInitializedRef.current = true;
2419
- }, [enabled, data, toggleField]);
2420
- 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(() => {
2421
2943
  if (!enabled || !data || data.length === 0) return [];
2422
2944
  const flattenedData = [];
2423
- const flattenItems = (items) => {
2424
- items.forEach((item) => {
2425
- 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 };
2426
2953
  const nested = newItem[flattenField];
2427
2954
  if (Array.isArray(nested)) {
2428
2955
  const children = nested.map(
@@ -2436,89 +2963,68 @@ var useConvertTreeData = ({
2436
2963
  child[childField] = newItem[toggleField];
2437
2964
  }
2438
2965
  });
2439
- flattenItems(children);
2966
+ flattenItems(children, source.path);
2440
2967
  } else {
2441
2968
  flattenedData.push(newItem);
2442
2969
  }
2443
2970
  });
2444
2971
  };
2445
- flattenItems(data);
2972
+ flattenItems(data, []);
2446
2973
  const dataWithLevels = flattenedData.map((item) => ({
2447
2974
  ...item,
2448
2975
  level: 0,
2449
2976
  children: [],
2450
2977
  processed: false
2451
2978
  }));
2452
- const findNearestPrecedingParent = (index, parentKey) => {
2453
- for (let i = index - 1; i >= 0; i -= 1) {
2454
- const candidate = dataWithLevels[i];
2455
- if (!candidate) continue;
2456
- if (getFieldValue(candidate, toggleField) === parentKey) {
2457
- return candidate;
2458
- }
2459
- }
2460
- return void 0;
2461
- };
2462
2979
  const rootItems = [];
2980
+ const latestByKey = /* @__PURE__ */ new Map();
2463
2981
  dataWithLevels.forEach((item) => {
2464
- if (!getFieldValue(item, childField)) {
2465
- rootItems.push(item);
2466
- item.processed = true;
2467
- }
2468
- });
2469
- dataWithLevels.forEach((item, index) => {
2470
2982
  const parentKey = getFieldValue(item, childField);
2471
- if (!parentKey || item.processed) return;
2472
- const parent = findNearestPrecedingParent(index, parentKey);
2983
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2473
2984
  if (parent) {
2474
2985
  item.level = parent.level + 1;
2475
2986
  parent.children.push(item);
2476
- item.processed = true;
2477
- return;
2987
+ } else {
2988
+ rootItems.push(item);
2478
2989
  }
2479
- rootItems.push(item);
2480
2990
  item.processed = true;
2991
+ latestByKey.set(getFieldValue(item, toggleField), item);
2481
2992
  });
2482
2993
  return rootItems;
2483
2994
  }, [enabled, data, toggleField, childField, flattenField]);
2484
- const flattenTree = useMemo2(() => {
2995
+ const flattenTree = useMemo4(() => {
2485
2996
  if (!enabled) return [];
2486
- const flatten = (nodes, result = [], level = 0) => {
2997
+ const flatten = (nodes, result, parentTreeNo) => {
2487
2998
  nodes.forEach((node, index) => {
2488
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
2999
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2489
3000
  const toggleValue = getFieldValue(node, toggleField);
2490
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3001
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2491
3002
  result.push({
2492
3003
  ...node,
2493
3004
  treeNo: currentIndex,
2494
3005
  uniqueId,
2495
3006
  processed: true
2496
3007
  });
2497
- 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)));
2498
3010
  if (shouldExpandChildren) {
2499
- flatten(node.children, result, index + startIndex);
3011
+ flatten(node.children, result, currentIndex);
2500
3012
  }
2501
3013
  });
2502
3014
  return result;
2503
3015
  };
2504
- const flattenedData = flatten(processedData, [], 0);
2505
- flattenedData.forEach((item, index) => {
3016
+ const flattenedData = flatten(processedData, [], null);
3017
+ const latestByKey = /* @__PURE__ */ new Map();
3018
+ flattenedData.forEach((item) => {
2506
3019
  const parentKey = getFieldValue(item, childField);
2507
3020
  if (!parentKey) {
2508
3021
  item.parentCount = 1;
2509
- return;
2510
- }
2511
- let parentItem;
2512
- for (let i = index - 1; i >= 0; i -= 1) {
2513
- const candidate = flattenedData[i];
2514
- if (!candidate) continue;
2515
- if (getFieldValue(candidate, toggleField) === parentKey) {
2516
- parentItem = candidate;
2517
- break;
2518
- }
3022
+ } else {
3023
+ const parentItem = latestByKey.get(parentKey);
3024
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3025
+ item.parentCount = parentAmount || 1;
2519
3026
  }
2520
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2521
- item.parentCount = parentAmount || 1;
3027
+ latestByKey.set(getFieldValue(item, toggleField), item);
2522
3028
  });
2523
3029
  return flattenedData;
2524
3030
  }, [
@@ -2531,22 +3037,11 @@ var useConvertTreeData = ({
2531
3037
  preventExpand,
2532
3038
  expandedRows
2533
3039
  ]);
2534
- const sortedData = useMemo2(() => {
3040
+ const sortedData = useMemo4(() => {
2535
3041
  if (!enabled) {
2536
3042
  return data ?? [];
2537
3043
  }
2538
- return [...flattenTree].sort((a, b) => {
2539
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2540
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2541
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2542
- const aVal = aParts[i] || 0;
2543
- const bVal = bParts[i] || 0;
2544
- if (aVal !== bVal) {
2545
- return aVal - bVal;
2546
- }
2547
- }
2548
- return 0;
2549
- });
3044
+ return flattenTree;
2550
3045
  }, [enabled, data, flattenTree]);
2551
3046
  return sortedData;
2552
3047
  };
@@ -2604,13 +3099,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2604
3099
  for (let index = 0; index < data.length; index++) {
2605
3100
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2606
3101
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2607
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3102
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2608
3103
  result.push({ rowSpan: 0, isFirstInGroup: false });
2609
3104
  continue;
2610
3105
  }
2611
3106
  let span = 1;
2612
3107
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2613
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3108
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2614
3109
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2615
3110
  span++;
2616
3111
  }
@@ -2703,6 +3198,9 @@ function collectRowSpanColumns(columns) {
2703
3198
  }
2704
3199
 
2705
3200
  // src/core/useGlideTable.ts
3201
+ function isProductionBuild() {
3202
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3203
+ }
2706
3204
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2707
3205
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2708
3206
  function useGlideTable(options) {
@@ -2724,18 +3222,24 @@ function useGlideTable(options) {
2724
3222
  selectOnRowClick = true,
2725
3223
  enableCellSelection = true,
2726
3224
  onDataChange,
2727
- onCellChange,
2728
- onBatchChange,
3225
+ onCellChange: onCellChangeProp,
3226
+ onBatchChange: onBatchChangeProp,
2729
3227
  cellRenderers,
2730
3228
  preserveRowSelection = false,
2731
- toggleField,
2732
- childField,
2733
- flattenField,
3229
+ toggleField: toggleFieldProp,
3230
+ idField,
3231
+ childField: childFieldProp,
3232
+ parentIdField,
3233
+ flattenField: flattenFieldProp,
3234
+ childrenField,
2734
3235
  qtyField,
3236
+ expandColumn,
2735
3237
  expandedRows: controlledExpandedRows,
2736
3238
  onExpandedRowsChange,
2737
3239
  preventExpand = false,
3240
+ autoExpandOnLoad = true,
2738
3241
  enableSubtreeCopy,
3242
+ escapeCopyFormulas = false,
2739
3243
  onCopyActionsReady,
2740
3244
  onRowsPaste,
2741
3245
  enableInsertPaste,
@@ -2756,9 +3260,28 @@ function useGlideTable(options) {
2756
3260
  onSearchValueChange,
2757
3261
  onSearchClose,
2758
3262
  searchResults,
2759
- onSearchResultsChanged
3263
+ onSearchResultsChanged,
3264
+ enableWasdNavigation = true
2760
3265
  } = options;
2761
- 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(() => {
2762
3285
  const resolved = resolveDataTableLabels(labelsProp);
2763
3286
  return {
2764
3287
  ...resolved,
@@ -2775,11 +3298,11 @@ function useGlideTable(options) {
2775
3298
  const [internalExpandedRows, setInternalExpandedRows] = useState4(
2776
3299
  () => /* @__PURE__ */ new Set()
2777
3300
  );
2778
- const [hoveredRowIndex, setHoveredRowIndex] = useState4(null);
3301
+ const [hoverStore] = useState4(createRowHoverStore);
2779
3302
  const scrollRef = useRef5(null);
2780
3303
  const rootRef = useRef5(null);
2781
3304
  const escapeDismissOwnerRef = useRef5(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
2782
- const cellRendererRegistry = useMemo3(
3305
+ const cellRendererRegistry = useMemo5(
2783
3306
  () => createCellRendererRegistry(cellRenderers),
2784
3307
  [cellRenderers]
2785
3308
  );
@@ -2798,7 +3321,7 @@ function useGlideTable(options) {
2798
3321
  );
2799
3322
  const columnSizing = controlledColumnSizing ?? internalColumnSizing;
2800
3323
  const columnOrder = controlledColumnOrder ?? internalColumnOrder;
2801
- const tableColumns = useMemo3(() => {
3324
+ const tableColumns = useMemo5(() => {
2802
3325
  if (!enableColumnReorder) return columns;
2803
3326
  return applyLeafColumnOrder(columns, columnOrder);
2804
3327
  }, [columnOrder, columns, enableColumnReorder]);
@@ -2832,8 +3355,10 @@ function useGlideTable(options) {
2832
3355
  qtyField,
2833
3356
  expandedRows,
2834
3357
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2835
- preventExpand
3358
+ preventExpand,
3359
+ autoExpandOnLoad
2836
3360
  });
3361
+ const sourceData = useMemo5(() => data ?? [], [data]);
2837
3362
  const table = useReactTable({
2838
3363
  data: tableData,
2839
3364
  columns: tableColumns,
@@ -2872,15 +3397,19 @@ function useGlideTable(options) {
2872
3397
  );
2873
3398
  },
2874
3399
  getCoreRowModel: getCoreRowModel(),
2875
- 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
+ )
2876
3405
  });
2877
- const rowSpanColumnKeys = useMemo3(() => {
3406
+ const rowSpanColumnKeys = useMemo5(() => {
2878
3407
  if (!enableRowSpan) return [];
2879
3408
  return collectRowSpanColumns(columns);
2880
3409
  }, [enableRowSpan, columns]);
2881
3410
  const primaryRowSpanKey = rowSpanColumnKeys[0]?.rowSpanKey;
2882
3411
  const primaryRowSpanColumnId = rowSpanColumnKeys[0]?.columnId;
2883
- const columnRowSpanMap = useMemo3(
3412
+ const columnRowSpanMap = useMemo5(
2884
3413
  () => buildColumnRowSpanMap(tableData, rowSpanColumnKeys),
2885
3414
  [tableData, rowSpanColumnKeys]
2886
3415
  );
@@ -2889,7 +3418,21 @@ function useGlideTable(options) {
2889
3418
  const rows = table.getRowModel().rows;
2890
3419
  const columnCount = table.getAllLeafColumns().length || 1;
2891
3420
  const visibleLeafColumns = table.getVisibleLeafColumns();
2892
- 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(() => {
2893
3436
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
2894
3437
  return buildColumnFreezeOffsets(
2895
3438
  visibleLeafColumns.map((column) => ({
@@ -2909,7 +3452,7 @@ function useGlideTable(options) {
2909
3452
  const totalSize = rowVirtualizer.getTotalSize();
2910
3453
  const paddingTop = virtualRows.length > 0 ? virtualRows[0]?.start ?? 0 : 0;
2911
3454
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0) : 0;
2912
- const selectedRowIndices = useMemo3(() => {
3455
+ const selectedRowIndices = useMemo5(() => {
2913
3456
  const indices = /* @__PURE__ */ new Set();
2914
3457
  for (const selectedRow of selectedRows) {
2915
3458
  indices.add(selectedRow.index);
@@ -2931,7 +3474,7 @@ function useGlideTable(options) {
2931
3474
  const cell = scrollElement.querySelector(
2932
3475
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
2933
3476
  );
2934
- if (cell instanceof HTMLElement) {
3477
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
2935
3478
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
2936
3479
  }
2937
3480
  };
@@ -2949,6 +3492,10 @@ function useGlideTable(options) {
2949
3492
  },
2950
3493
  [scrollCellIntoView]
2951
3494
  );
3495
+ const editKeyRef = useRef5(() => {
3496
+ });
3497
+ const clearKeyRef = useRef5(() => {
3498
+ });
2952
3499
  const {
2953
3500
  dragState,
2954
3501
  activeSelectionBounds,
@@ -2956,20 +3503,27 @@ function useGlideTable(options) {
2956
3503
  handleCellMouseEnter,
2957
3504
  handleFillHandleMouseDown,
2958
3505
  clearSelection: clearCellSelection,
2959
- copySelection
3506
+ copySelection,
3507
+ selectCell,
3508
+ focusSelection
2960
3509
  } = useCellSelection({
2961
- data: tableData,
3510
+ data: sourceData,
2962
3511
  rows,
2963
3512
  enabled: enableCellSelection,
2964
3513
  columnCount: visibleLeafColumns.length,
3514
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
2965
3515
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3516
+ escapeCopyFormulas,
2966
3517
  enableInsertPaste: enableInsertPaste ?? true,
2967
3518
  onDataChange,
2968
3519
  onBatchChange,
2969
3520
  onRowsPaste,
2970
3521
  onCellNavigate: handleCellNavigate,
2971
3522
  cellRendererRegistry,
2972
- rootRef
3523
+ rootRef,
3524
+ enableWasdNavigation,
3525
+ onEditKey: (position) => editKeyRef.current(position),
3526
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
2973
3527
  });
2974
3528
  const clearRowSelection = useCallback4(() => {
2975
3529
  if (rowSelectionMode === "none") return;
@@ -2990,22 +3544,79 @@ function useGlideTable(options) {
2990
3544
  const {
2991
3545
  editingCell,
2992
3546
  draftValue,
3547
+ draftInvalid,
3548
+ setDraftInvalid,
2993
3549
  setDraftValue,
2994
3550
  startEdit,
2995
3551
  commitEdit,
2996
3552
  cancelEdit
2997
- } = 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]);
2998
3603
  const commitRenderedCellValue = useCallback4(
2999
- (rowId, columnId, value) => commitCellValue({
3000
- data: tableData,
3001
- rows,
3002
- rowId,
3003
- columnId,
3004
- value,
3005
- onCellChange,
3006
- onDataChange
3007
- }),
3008
- [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]
3009
3620
  );
3010
3621
  const getCellContext = useCallback4(
3011
3622
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3033,27 +3644,14 @@ function useGlideTable(options) {
3033
3644
  (row, index) => {
3034
3645
  if (getRowId) return getRowId(row, index);
3035
3646
  if (enableExpand) {
3036
- const record = row;
3037
- const idValue = record.id;
3038
- if (idValue != null && String(idValue).length > 0) {
3039
- return String(idValue);
3040
- }
3041
- const uniqueId = record.uniqueId;
3042
- if (uniqueId != null && String(uniqueId).length > 0) {
3043
- return String(uniqueId);
3044
- }
3045
- if (toggleField) {
3046
- const toggleValue = record[toggleField];
3047
- if (toggleValue != null && String(toggleValue).length > 0) {
3048
- return String(toggleValue);
3049
- }
3050
- }
3647
+ const treeKey = getTreeRowKey(row);
3648
+ if (treeKey) return treeKey;
3051
3649
  }
3052
3650
  return String(index);
3053
3651
  },
3054
- [enableExpand, getRowId, toggleField]
3652
+ [enableExpand, getRowId]
3055
3653
  );
3056
- const searchCorpus = useMemo3(() => {
3654
+ const searchCorpus = useMemo5(() => {
3057
3655
  if (!enableInlineSearch) return [];
3058
3656
  if (enableExpand && toggleField) {
3059
3657
  return buildTreeSearchCorpus(tableData, {
@@ -3071,35 +3669,66 @@ function useGlideTable(options) {
3071
3669
  ]);
3072
3670
  const searchCorpusRef = useRef5(searchCorpus);
3073
3671
  searchCorpusRef.current = searchCorpus;
3074
- const visibleRowIndexById = useMemo3(() => {
3672
+ const visibleRowIndexById = useMemo5(() => {
3075
3673
  const map = /* @__PURE__ */ new Map();
3076
3674
  for (const row of rows) {
3077
3675
  map.set(resolveSearchRowId(row.original, row.index), row.index);
3078
3676
  }
3079
3677
  return map;
3080
3678
  }, [resolveSearchRowId, rows]);
3081
- const getSearchCellValue = useCallback4(
3082
- (rowIndex, colIndex) => {
3083
- const corpusRow = searchCorpusRef.current[rowIndex];
3084
- const column = visibleLeafColumns[colIndex];
3085
- if (!corpusRow || !column) return void 0;
3679
+ const readSearchRawValue = useCallback4(
3680
+ (corpusRow, rowIndex, column) => {
3086
3681
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3087
3682
  if (visibleIndex !== void 0) {
3088
3683
  const visibleRow = rows[visibleIndex];
3089
3684
  if (visibleRow) {
3090
- return visibleRow.getValue(column.id);
3685
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3091
3686
  }
3092
3687
  }
3093
3688
  const columnDef = column.columnDef;
3094
3689
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3095
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3690
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3096
3691
  }
3097
3692
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3098
- 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;
3099
3728
  }
3100
- return corpusRow.data[column.id];
3729
+ return value;
3101
3730
  },
3102
- [rows, visibleLeafColumns, visibleRowIndexById]
3731
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3103
3732
  );
3104
3733
  const pendingSearchNavRef = useRef5(null);
3105
3734
  const focusSearchResult = useCallback4(
@@ -3150,11 +3779,19 @@ function useGlideTable(options) {
3150
3779
  focusSearchResult(pending.colIndex, visibleRowIndex);
3151
3780
  }, [focusSearchResult, rows, visibleRowIndexById]);
3152
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
+ );
3153
3787
  const inlineSearch = useInlineSearch({
3154
3788
  enabled: enableInlineSearch,
3155
3789
  rowCount: searchCorpus.length,
3156
3790
  columnCount: visibleLeafColumns.length,
3157
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,
3158
3795
  initialStartRow: initialSearchStartRow,
3159
3796
  showSearch,
3160
3797
  searchValue,
@@ -3165,7 +3802,7 @@ function useGlideTable(options) {
3165
3802
  onNavigateToResult: navigateToCorpusSearchResult,
3166
3803
  rootRef
3167
3804
  });
3168
- const visibleSearchMatchKeys = useMemo3(() => {
3805
+ const visibleSearchMatchKeys = useMemo5(() => {
3169
3806
  if (!enableInlineSearch) return EMPTY_SEARCH_MATCH_KEYS;
3170
3807
  return mapSearchResultsToVisibleKeys(
3171
3808
  inlineSearch.searchResults,
@@ -3178,7 +3815,7 @@ function useGlideTable(options) {
3178
3815
  searchCorpus,
3179
3816
  visibleRowIndexById
3180
3817
  ]);
3181
- const visibleActiveMatch = useMemo3(() => {
3818
+ const visibleActiveMatch = useMemo5(() => {
3182
3819
  if (!enableInlineSearch || !inlineSearch.activeMatch) return null;
3183
3820
  return mapSearchResultToVisibleItem(
3184
3821
  inlineSearch.activeMatch,
@@ -3192,11 +3829,14 @@ function useGlideTable(options) {
3192
3829
  visibleRowIndexById
3193
3830
  ]);
3194
3831
  const clearHover = useCallback4(() => {
3195
- setHoveredRowIndex(null);
3196
- }, []);
3197
- const handleRowHover = useCallback4((rowIndex, _rowData) => {
3198
- setHoveredRowIndex(rowIndex);
3199
- }, []);
3832
+ hoverStore.setHoveredRowIndex(null);
3833
+ }, [hoverStore]);
3834
+ const handleRowHover = useCallback4(
3835
+ (rowIndex, _rowData) => {
3836
+ hoverStore.setHoveredRowIndex(rowIndex);
3837
+ },
3838
+ [hoverStore]
3839
+ );
3200
3840
  const handleToggleSelect = useCallback4(
3201
3841
  (row) => {
3202
3842
  if (!row.getCanSelect()) return;
@@ -3214,14 +3854,14 @@ function useGlideTable(options) {
3214
3854
  },
3215
3855
  [preventExpand, handleExpandedRowsChange, expandedRows]
3216
3856
  );
3217
- const rowContextValue = useMemo3(() => {
3857
+ const rowContextValue = useMemo5(() => {
3218
3858
  return {
3219
3859
  rowSpan: {
3220
3860
  enableRowSpan,
3221
3861
  primaryRowSpanKey,
3222
3862
  primaryRowSpanColumnId,
3223
3863
  columnRowSpanMap,
3224
- hoveredRowIndex,
3864
+ hoverStore,
3225
3865
  selectedRowIndices,
3226
3866
  onRowHover: handleRowHover
3227
3867
  },
@@ -3235,6 +3875,7 @@ function useGlideTable(options) {
3235
3875
  enableCellSelection,
3236
3876
  activeSelectionBounds,
3237
3877
  dragState,
3878
+ canFill,
3238
3879
  onCellMouseDown: handleCellMouseDownWithCommit,
3239
3880
  onCellMouseEnter: handleCellMouseEnter,
3240
3881
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3242,18 +3883,23 @@ function useGlideTable(options) {
3242
3883
  cellEdit: {
3243
3884
  editingCell,
3244
3885
  draftValue,
3886
+ draftInvalid,
3887
+ onDraftInvalidChange: setDraftInvalid,
3245
3888
  onDraftValueChange: setDraftValue,
3246
3889
  onStartEdit: startEdit,
3247
3890
  onCommitEdit: commitEdit,
3248
- onCancelEdit: cancelEdit
3891
+ onCommitEditAndMove: commitEditAndMove,
3892
+ onCancelEdit: cancelEditAndRefocus
3249
3893
  },
3250
3894
  cellRender: {
3251
3895
  registry: cellRendererRegistry,
3252
- commitValue: commitRenderedCellValue
3896
+ commitValue: commitRenderedCellValue,
3897
+ protectedLabel: labels.protectedCell
3253
3898
  },
3254
3899
  expand: {
3255
3900
  enableExpand,
3256
3901
  toggleField,
3902
+ expandColumn,
3257
3903
  expandedRows,
3258
3904
  preventExpand,
3259
3905
  onToggleExpand: handleToggleExpand,
@@ -3278,7 +3924,7 @@ function useGlideTable(options) {
3278
3924
  primaryRowSpanKey,
3279
3925
  primaryRowSpanColumnId,
3280
3926
  columnRowSpanMap,
3281
- hoveredRowIndex,
3927
+ hoverStore,
3282
3928
  selectedRowIndices,
3283
3929
  handleRowHover,
3284
3930
  rowSelectionMode,
@@ -3288,19 +3934,25 @@ function useGlideTable(options) {
3288
3934
  enableCellSelection,
3289
3935
  activeSelectionBounds,
3290
3936
  dragState,
3937
+ canFill,
3291
3938
  handleCellMouseDownWithCommit,
3292
3939
  handleCellMouseEnter,
3293
3940
  handleFillHandleMouseDown,
3294
3941
  editingCell,
3295
3942
  draftValue,
3943
+ draftInvalid,
3944
+ setDraftInvalid,
3296
3945
  setDraftValue,
3297
3946
  startEdit,
3298
3947
  commitEdit,
3299
- cancelEdit,
3948
+ commitEditAndMove,
3949
+ cancelEditAndRefocus,
3300
3950
  cellRendererRegistry,
3301
3951
  commitRenderedCellValue,
3952
+ labels.protectedCell,
3302
3953
  enableExpand,
3303
3954
  toggleField,
3955
+ expandColumn,
3304
3956
  expandedRows,
3305
3957
  preventExpand,
3306
3958
  handleToggleExpand,
@@ -3348,6 +4000,7 @@ function useGlideTable(options) {
3348
4000
  handleToggleSelect,
3349
4001
  clearHover,
3350
4002
  setColumnOrder,
4003
+ handleRootFocus: focusSelection,
3351
4004
  copySelection: stableCopySelection,
3352
4005
  inlineSearch: {
3353
4006
  showSearch: inlineSearch.showSearch,
@@ -3398,12 +4051,16 @@ function ResolvedTableCell({
3398
4051
  },
3399
4052
  [cellRender, columnId, row.id]
3400
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
+ }
3401
4058
  const ctx = {
3402
4059
  value,
3403
4060
  row,
3404
4061
  index: row.index,
3405
4062
  columnId,
3406
- cellProps: meta?.cellProps,
4063
+ cellProps,
3407
4064
  update
3408
4065
  };
3409
4066
  if (meta?.cellRender) {
@@ -3799,6 +4456,7 @@ export {
3799
4456
  createCellRendererRegistry,
3800
4457
  createSearchRegex,
3801
4458
  escapeSearchRegex,
4459
+ escapeSpreadsheetFormula,
3802
4460
  flattenSubtreeRows,
3803
4461
  formatCellValue,
3804
4462
  formatDefaultCellValue,