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/index.js CHANGED
@@ -1,3 +1,160 @@
1
+ // src/components/ui/table/features/inline-search/inlineSearch.ts
2
+ var INLINE_SEARCH_MAX_RESULTS = 1e3;
3
+ var INLINE_SEARCH_TARGET_TICK_MS = 10;
4
+ var INLINE_SEARCH_INITIAL_STRIDE = 10;
5
+ function escapeSearchRegex(value) {
6
+ return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
7
+ }
8
+ function createSearchRegex(query) {
9
+ const trimmed = query.trim();
10
+ if (!trimmed) return null;
11
+ return new RegExp(escapeSearchRegex(trimmed), "i");
12
+ }
13
+ function cellValueToSearchText(value) {
14
+ if (value == null) return void 0;
15
+ if (typeof value === "string") return value;
16
+ if (typeof value === "number" || typeof value === "boolean") {
17
+ return String(value);
18
+ }
19
+ if (Array.isArray(value)) {
20
+ return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
21
+ }
22
+ if (typeof value === "object") {
23
+ try {
24
+ return JSON.stringify(value);
25
+ } catch {
26
+ return String(value);
27
+ }
28
+ }
29
+ return String(value);
30
+ }
31
+ function formatSearchResultLabel(status) {
32
+ const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
33
+ if (status.selectedIndex >= 0 && status.results > 0) {
34
+ return `${status.selectedIndex + 1} of ${countLabel}`;
35
+ }
36
+ return countLabel;
37
+ }
38
+ function nextSearchIndex(selectedIndex, results) {
39
+ if (results <= 0) return -1;
40
+ if (selectedIndex < 0) return 0;
41
+ return (selectedIndex + 1) % results;
42
+ }
43
+ function previousSearchIndex(selectedIndex, results) {
44
+ if (results <= 0) return -1;
45
+ if (selectedIndex < 0) return results - 1;
46
+ let next = (selectedIndex - 1) % results;
47
+ if (next < 0) next += results;
48
+ return next;
49
+ }
50
+ function buildSearchMatchKey(colIndex, rowIndex) {
51
+ return `${colIndex}:${rowIndex}`;
52
+ }
53
+ function buildSearchMatchKeys(results) {
54
+ const keys = /* @__PURE__ */ new Set();
55
+ for (const [colIndex, rowIndex] of results) {
56
+ keys.add(buildSearchMatchKey(colIndex, rowIndex));
57
+ }
58
+ return keys;
59
+ }
60
+ function collectSearchMatchesInRange(options) {
61
+ const {
62
+ query,
63
+ startRow,
64
+ rowCount,
65
+ columnCount,
66
+ getCellValue,
67
+ maxResults = INLINE_SEARCH_MAX_RESULTS
68
+ } = options;
69
+ const regex = createSearchRegex(query);
70
+ if (!regex || rowCount <= 0 || columnCount <= 0) return [];
71
+ const matches = [];
72
+ for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
73
+ const rowIndex = startRow + rowOffset;
74
+ for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
75
+ const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
76
+ if (text !== void 0 && regex.test(text)) {
77
+ matches.push([colIndex, rowIndex]);
78
+ if (matches.length >= maxResults) {
79
+ return matches;
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return matches;
85
+ }
86
+ function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
87
+ const rounded = Math.max(elapsedMs, 1);
88
+ const scalar = targetMs / rounded;
89
+ return Math.max(1, Math.ceil(currentStride * scalar));
90
+ }
91
+ function buildFlatSearchCorpus(rows, getRowId) {
92
+ return rows.map((data, index) => ({
93
+ id: getRowId(data, index),
94
+ data,
95
+ ancestorToggleKeys: []
96
+ }));
97
+ }
98
+ function buildTreeSearchCorpus(visibleRows, options) {
99
+ const { toggleField, getRowId } = options;
100
+ const corpus = [];
101
+ const seen = /* @__PURE__ */ new Set();
102
+ const walk = (node, ancestorToggleKeys) => {
103
+ const id = getRowId(node, corpus.length);
104
+ if (seen.has(id)) return;
105
+ seen.add(id);
106
+ corpus.push({
107
+ id,
108
+ data: node,
109
+ ancestorToggleKeys
110
+ });
111
+ const children = node.children;
112
+ if (!Array.isArray(children) || children.length === 0) return;
113
+ const toggleValue = node[toggleField];
114
+ const toggleKey = toggleValue === null || toggleValue === void 0 ? "" : String(toggleValue);
115
+ const childAncestors = toggleKey.length > 0 ? [...ancestorToggleKeys, toggleKey] : ancestorToggleKeys;
116
+ for (const child of children) {
117
+ if (child && typeof child === "object") {
118
+ walk(child, childAncestors);
119
+ }
120
+ }
121
+ };
122
+ for (const row of visibleRows) {
123
+ const level = row.level;
124
+ if (level === 0 || level === void 0) {
125
+ walk(row, []);
126
+ }
127
+ }
128
+ for (const row of visibleRows) {
129
+ const id = getRowId(row, corpus.length);
130
+ if (seen.has(id)) continue;
131
+ walk(row, []);
132
+ }
133
+ return corpus;
134
+ }
135
+ function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
136
+ const keys = /* @__PURE__ */ new Set();
137
+ for (const [colIndex, corpusRowIndex] of results) {
138
+ const corpusRow = corpus[corpusRowIndex];
139
+ if (!corpusRow) continue;
140
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
141
+ if (visibleRowIndex === void 0) continue;
142
+ keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
143
+ }
144
+ return keys;
145
+ }
146
+ function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
147
+ const [colIndex, corpusRowIndex] = item;
148
+ const corpusRow = corpus[corpusRowIndex];
149
+ if (!corpusRow) return null;
150
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
151
+ if (visibleRowIndex === void 0) return null;
152
+ return [colIndex, visibleRowIndex];
153
+ }
154
+ function collectAncestorKeysToExpand(corpusRow, expandedRows) {
155
+ return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
156
+ }
157
+
1
158
  // src/core/labels.ts
2
159
  var DEFAULT_DATA_TABLE_LABELS = {
3
160
  empty: "No data",
@@ -11,7 +168,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
11
168
  searchResultHint: "Type to search",
12
169
  searchPrevious: "Previous result",
13
170
  searchNext: "Next result",
14
- searchClose: "Close search"
171
+ searchClose: "Close search",
172
+ searchResultCount: formatSearchResultLabel,
173
+ protectedCell: "protected",
174
+ paginationPrevious: "Previous page",
175
+ paginationNext: "Next page"
15
176
  };
16
177
  function resolveDataTableLabels(partial) {
17
178
  return {
@@ -37,7 +198,7 @@ import {
37
198
  import {
38
199
  useCallback as useCallback4,
39
200
  useEffect as useEffect5,
40
- useMemo as useMemo3,
201
+ useMemo as useMemo5,
41
202
  useRef as useRef5,
42
203
  useState as useState4
43
204
  } from "react";
@@ -60,7 +221,62 @@ var DATA_TABLE_COLUMN_MAX_SIZE = 800;
60
221
  var DATA_TABLE_COLUMN_REORDER_THRESHOLD = 4;
61
222
 
62
223
  // src/components/ui/table/features/cell-edit/useCellEdit.ts
63
- import { useCallback, useEffect, useRef, useState } from "react";
224
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
225
+
226
+ // src/components/ui/table/features/data-patch/dataPatch.ts
227
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
228
+ function getTreeSource(row) {
229
+ if (!row || typeof row !== "object") return void 0;
230
+ return row[TREE_SOURCE];
231
+ }
232
+ function getTreeRowKey(row) {
233
+ const source = getTreeSource(row);
234
+ if (!source) return void 0;
235
+ return `tree:${source.path.join(".")}`;
236
+ }
237
+ function setValueAtAccessor(record, accessorKey, value) {
238
+ if (!accessorKey.includes(".") || accessorKey in record) {
239
+ return { ...record, [accessorKey]: value };
240
+ }
241
+ const [head, ...rest] = accessorKey.split(".");
242
+ const current = record[head];
243
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
244
+ return {
245
+ ...record,
246
+ [head]: setValueAtAccessor(child, rest.join("."), value)
247
+ };
248
+ }
249
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
250
+ const [head, ...rest] = path;
251
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
252
+ const node = nodes[head];
253
+ if (!node || typeof node !== "object") return null;
254
+ const record = node;
255
+ let nextNode;
256
+ if (rest.length === 0) {
257
+ nextNode = setValueAtAccessor(record, accessorKey, value);
258
+ } else {
259
+ const children = record[childrenField];
260
+ if (!Array.isArray(children)) return null;
261
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
262
+ if (!nextChildren) return null;
263
+ nextNode = { ...record, [childrenField]: nextChildren };
264
+ }
265
+ const next = nodes.slice();
266
+ next[head] = nextNode;
267
+ return next;
268
+ }
269
+ function applyCellChangesToData(data, changes) {
270
+ let next = data;
271
+ for (const change of changes) {
272
+ const source = getTreeSource(change.original);
273
+ const path = source ? source.path : [change.index];
274
+ const childrenField = source?.childrenField ?? "";
275
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
276
+ if (patched) next = patched;
277
+ }
278
+ return next === data ? data.slice() : next;
279
+ }
64
280
 
65
281
  // src/components/ui/table/features/cell-edit/cellEdit.ts
66
282
  function getColumnAccessorKey(columnDef) {
@@ -69,7 +285,11 @@ function getColumnAccessorKey(columnDef) {
69
285
  }
70
286
  return columnDef.id;
71
287
  }
288
+ function isProtectedColumn(columnDef) {
289
+ return columnDef.meta?.kind === "protected";
290
+ }
72
291
  function isColumnEditable(columnDef) {
292
+ if (isProtectedColumn(columnDef)) return false;
73
293
  return Boolean(columnDef.meta?.editable);
74
294
  }
75
295
  function getColumnEditType(columnDef) {
@@ -102,10 +322,11 @@ function applyCellEdit(data, rows, rowIndex, colIndex, raw) {
102
322
  if (!accessorKey) return null;
103
323
  const parsed = parseCellEditValue(raw, getColumnEditType(columnDef));
104
324
  if (!parsed.ok) return null;
105
- const newData = data.map((row) => ({ ...row }));
106
- if (!newData[rowIndex]) return null;
107
- newData[rowIndex][accessorKey] = parsed.value;
108
- return newData;
325
+ const row = rows[rowIndex];
326
+ if (!row) return null;
327
+ return applyCellChangesToData(data, [
328
+ { original: row.original, index: row.index, accessorKey, value: parsed.value }
329
+ ]);
109
330
  }
110
331
 
111
332
  // src/components/ui/table/features/cell-render/commitCellValue.ts
@@ -129,12 +350,12 @@ function commitCellValue({
129
350
  if (!cell) return false;
130
351
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
131
352
  if (!accessorKey) return false;
132
- const dataIndex = row.index;
133
- if (dataIndex < 0 || dataIndex >= data.length) return false;
134
- const next = data.map((item) => ({ ...item }));
135
- const target = next[dataIndex];
136
- if (!target) return false;
137
- target[accessorKey] = value;
353
+ const next = applyCellChangesToData(data, [
354
+ { original: row.original, index: row.index, accessorKey, value }
355
+ ]);
356
+ if (next === data || next.every((item, index) => item === data[index])) {
357
+ return false;
358
+ }
138
359
  onDataChange?.(next);
139
360
  return true;
140
361
  }
@@ -146,19 +367,36 @@ function useCellEdit({
146
367
  onDataChange,
147
368
  onCellChange
148
369
  }) {
149
- const [editingCell, setEditingCell] = useState(null);
370
+ const [editingKey, setEditingKey] = useState(null);
150
371
  const [draftValue, setDraftValue] = useState("");
151
372
  const draftValueRef = useRef(draftValue);
152
- const editingCellRef = useRef(editingCell);
373
+ const [draftInvalid, setDraftInvalidState] = useState(false);
374
+ const draftInvalidRef = useRef(false);
375
+ const setDraftInvalid = useCallback((invalid) => {
376
+ draftInvalidRef.current = invalid;
377
+ setDraftInvalidState(invalid);
378
+ }, []);
153
379
  useEffect(() => {
154
380
  draftValueRef.current = draftValue;
155
381
  }, [draftValue]);
382
+ const editingCell = useMemo(
383
+ () => resolveEditingCell(rows, editingKey),
384
+ [rows, editingKey]
385
+ );
386
+ const editingCellRef = useRef(editingCell);
387
+ editingCellRef.current = editingCell;
156
388
  useEffect(() => {
157
- editingCellRef.current = editingCell;
158
- }, [editingCell]);
389
+ if (editingKey && !editingCell) {
390
+ setEditingKey(null);
391
+ setDraftValue("");
392
+ }
393
+ }, [editingCell, editingKey]);
159
394
  const cancelEdit = useCallback(() => {
160
- setEditingCell(null);
395
+ editingCellRef.current = null;
396
+ setEditingKey(null);
161
397
  setDraftValue("");
398
+ draftInvalidRef.current = false;
399
+ setDraftInvalidState(false);
162
400
  }, []);
163
401
  const commitEdit = useCallback(
164
402
  (raw) => {
@@ -178,6 +416,7 @@ function useCellEdit({
178
416
  cancelEdit();
179
417
  return true;
180
418
  }
419
+ if (draftInvalidRef.current) return false;
181
420
  const value = raw ?? draftValueRef.current;
182
421
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
183
422
  if (!parsed.ok) return false;
@@ -198,13 +437,15 @@ function useCellEdit({
198
437
  );
199
438
  const startEdit = useCallback(
200
439
  (rowIndex, colIndex) => {
201
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
202
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
440
+ const row = rows[rowIndex];
441
+ const cell = row?.getVisibleCells()[colIndex];
442
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
443
+ if (!isTextEditableValue(cell.getValue())) return;
203
444
  const current = editingCellRef.current;
204
445
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
205
446
  return;
206
447
  }
207
- setEditingCell({ rowIndex, colIndex });
448
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
208
449
  setDraftValue(getCellEditDraftValue(cell.getValue()));
209
450
  },
210
451
  [commitEdit, rows]
@@ -212,12 +453,55 @@ function useCellEdit({
212
453
  return {
213
454
  editingCell,
214
455
  draftValue,
456
+ draftInvalid,
457
+ setDraftInvalid,
215
458
  setDraftValue,
216
459
  startEdit,
217
460
  commitEdit,
218
461
  cancelEdit
219
462
  };
220
463
  }
464
+ function resolveEditingCell(rows, key) {
465
+ if (!key) return null;
466
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
467
+ if (rowIndex < 0) return null;
468
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
469
+ if (colIndex < 0) return null;
470
+ return { rowIndex, colIndex };
471
+ }
472
+ function isTextEditableValue(value) {
473
+ return value === null || value === void 0 || typeof value !== "object";
474
+ }
475
+
476
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
477
+ function formatObjectValue(value) {
478
+ const text = value.text ?? value.label ?? value.name ?? value.title;
479
+ if (text != null && text !== "") {
480
+ return formatCellValue(text);
481
+ }
482
+ try {
483
+ return JSON.stringify(value);
484
+ } catch {
485
+ return "";
486
+ }
487
+ }
488
+ function formatCellValue(value) {
489
+ if (value === null || value === void 0) return "";
490
+ if (value instanceof Date) {
491
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
492
+ }
493
+ if (Array.isArray(value)) {
494
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
495
+ }
496
+ if (typeof value === "object") {
497
+ return formatObjectValue(value);
498
+ }
499
+ if (typeof value === "string") return value;
500
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
501
+ return String(value);
502
+ }
503
+ return "";
504
+ }
221
505
 
222
506
  // src/components/ui/table/features/cell-render/builtins.tsx
223
507
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -241,8 +525,9 @@ function asDrilldownItems(value) {
241
525
  const record = item;
242
526
  const text = asString(record.text ?? record.label ?? "");
243
527
  if (!text) return [];
244
- const img = record.img ?? record.image;
245
- return [{ text, ...typeof img === "string" ? { img } : {} }];
528
+ const rawImg = record.img ?? record.image;
529
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
530
+ return [{ text, ...img ? { img } : {} }];
246
531
  }
247
532
  return [{ text: asString(item) }];
248
533
  });
@@ -303,6 +588,22 @@ function sanitizeUriHref(raw) {
303
588
  return href;
304
589
  }
305
590
  }
591
+ function sanitizeImageSrc(raw) {
592
+ const src = raw.trim();
593
+ if (!src) return null;
594
+ try {
595
+ const parsed = new URL(src);
596
+ const protocol = parsed.protocol.toLowerCase();
597
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
598
+ return src;
599
+ }
600
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
601
+ return null;
602
+ } catch {
603
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
604
+ return src;
605
+ }
606
+ }
306
607
  function UriCell({ value }) {
307
608
  const raw = asString(value);
308
609
  if (!raw) return null;
@@ -324,7 +625,10 @@ function UriCell({ value }) {
324
625
  );
325
626
  }
326
627
  function ImageCell({ value }) {
327
- const urls = asStringList(value);
628
+ const urls = asStringList(value).flatMap((url) => {
629
+ const src = sanitizeImageSrc(url);
630
+ return src ? [src] : [];
631
+ });
328
632
  if (urls.length === 0) return null;
329
633
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ jsx(
330
634
  "img",
@@ -377,8 +681,33 @@ function DrilldownCell({ value }) {
377
681
  function LoadingCell() {
378
682
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-loading", "aria-busy": "true" });
379
683
  }
380
- function ProtectedCell() {
381
- return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
684
+ function ProtectedCell({ cellProps }) {
685
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
686
+ return /* @__PURE__ */ jsx("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
687
+ }
688
+ function RowSelectCell({ row, cellProps }) {
689
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
690
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
691
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
692
+ return /* @__PURE__ */ jsx(
693
+ "input",
694
+ {
695
+ type: "checkbox",
696
+ className: "data-table-cell-row-select",
697
+ checked,
698
+ disabled: !canSelect,
699
+ "aria-label": label,
700
+ onChange: () => {
701
+ if (canSelect) row.toggleSelected();
702
+ },
703
+ onClick: (event) => {
704
+ event.stopPropagation();
705
+ },
706
+ onMouseDown: (event) => {
707
+ event.stopPropagation();
708
+ }
709
+ }
710
+ );
382
711
  }
383
712
  function RowIdCell({ value }) {
384
713
  return /* @__PURE__ */ jsx("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -394,7 +723,8 @@ var BUILTIN_RENDER_MAP = {
394
723
  drilldown: DrilldownCell,
395
724
  loading: LoadingCell,
396
725
  protected: ProtectedCell,
397
- "row-id": RowIdCell
726
+ "row-id": RowIdCell,
727
+ "row-select": RowSelectCell
398
728
  };
399
729
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
400
730
  kind,
@@ -428,38 +758,447 @@ function formatDefaultCellValue(value) {
428
758
  return String(value);
429
759
  }
430
760
  if (typeof value === "bigint") return value.toString();
431
- return String(value);
432
- }
433
-
434
- // src/components/ui/table/features/cell-render/withCellUpdate.ts
435
- function withCellUpdate(context, commitValue) {
436
- return {
437
- ...context,
438
- update: (next) => {
439
- commitValue(context.row.id, context.column.id, next);
440
- }
441
- };
761
+ return formatCellValue(value);
442
762
  }
443
763
 
444
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
445
- import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
764
+ // src/components/ui/table/features/cell-selection/copyData.ts
765
+ import { isValidElement } from "react";
446
766
 
447
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
448
- var activeOwner = null;
449
- var clearByOwner = /* @__PURE__ */ new Map();
450
- function createCellSelectionOwner() {
451
- return /* @__PURE__ */ Symbol("cell-selection-owner");
767
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
768
+ var lastSubtreeCopy = null;
769
+ function normalize(text) {
770
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
452
771
  }
453
- function registerCellSelectionOwner(owner, clearSelection) {
454
- clearByOwner.set(owner, clearSelection);
455
- return () => {
456
- clearByOwner.delete(owner);
457
- if (activeOwner === owner) {
458
- activeOwner = null;
459
- }
460
- };
772
+ function rememberSubtreeCopy(text) {
773
+ lastSubtreeCopy = normalize(text);
461
774
  }
462
- function claimCellSelectionOwner(owner) {
775
+ function isOwnSubtreeCopy(text) {
776
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
777
+ }
778
+
779
+ // src/components/ui/table/features/cell-selection/copyData.ts
780
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
781
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
782
+ function escapeSpreadsheetFormula(text) {
783
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
784
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
785
+ return `'${text}`;
786
+ }
787
+ function isReactNodeIterable(node) {
788
+ return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
789
+ }
790
+ function getElementTypeName(type) {
791
+ if (typeof type === "string") return type;
792
+ if (typeof type === "function") {
793
+ const fn = type;
794
+ return fn.displayName || fn.name || "";
795
+ }
796
+ if (typeof type === "object" && type !== null) {
797
+ const component = type;
798
+ return component.displayName || component.render?.displayName || component.render?.name || "";
799
+ }
800
+ return "";
801
+ }
802
+ function isButtonReactElement(node) {
803
+ const typeName = getElementTypeName(node.type);
804
+ if (typeName === "button" || /button/i.test(typeName)) return true;
805
+ const props = node.props;
806
+ if (props.role === "button") return true;
807
+ if (typeName === "input" && props.type === "button") return true;
808
+ return false;
809
+ }
810
+ function isImageReactElement(node) {
811
+ const typeName = getElementTypeName(node.type);
812
+ return typeName === "img" || typeName === "image" || /image/i.test(typeName);
813
+ }
814
+ var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
815
+ function isLikelyUrl(value) {
816
+ const trimmed = value.trim();
817
+ if (!trimmed) return false;
818
+ if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
819
+ if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
820
+ return false;
821
+ }
822
+ function pickUrlFromUnknown(value) {
823
+ if (typeof value === "string") {
824
+ return isLikelyUrl(value) ? value.trim() : "";
825
+ }
826
+ if (Array.isArray(value)) {
827
+ return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
828
+ }
829
+ if (value && typeof value === "object") {
830
+ const record = value;
831
+ for (const key of IMAGE_URL_PROP_KEYS) {
832
+ const candidate = record[key];
833
+ if (typeof candidate === "string" && candidate.trim()) {
834
+ return candidate.trim();
835
+ }
836
+ }
837
+ }
838
+ return "";
839
+ }
840
+ function imageElementText(node) {
841
+ const props = node.props;
842
+ for (const key of IMAGE_URL_PROP_KEYS) {
843
+ const candidate = props[key];
844
+ if (typeof candidate === "string" && candidate.trim()) {
845
+ return candidate.trim();
846
+ }
847
+ }
848
+ return "";
849
+ }
850
+ function reactNodeContainsImage(node) {
851
+ if (isValidElement(node)) {
852
+ if (isImageReactElement(node)) return true;
853
+ return reactNodeContainsImage(node.props.children);
854
+ }
855
+ if (isReactNodeIterable(node)) {
856
+ for (const child of node) {
857
+ if (reactNodeContainsImage(child)) return true;
858
+ }
859
+ }
860
+ return false;
861
+ }
862
+ function readImgUrl(img) {
863
+ const attr = img.getAttribute("src")?.trim() ?? "";
864
+ if (attr) return attr;
865
+ if (img instanceof HTMLImageElement) {
866
+ const current = img.currentSrc?.trim() ?? "";
867
+ if (current && current !== img.baseURI) return current;
868
+ }
869
+ return "";
870
+ }
871
+ function readDomImageUrls(rowIndex, colIndex, root) {
872
+ const scope = root ?? (typeof document === "undefined" ? null : document);
873
+ if (!scope) return "";
874
+ const cells = scope.querySelectorAll(
875
+ `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
876
+ );
877
+ for (const cell of cells) {
878
+ const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
879
+ const url = readImgUrl(img);
880
+ return url ? [url] : [];
881
+ });
882
+ if (urls.length > 0) return urls.join(", ");
883
+ }
884
+ return "";
885
+ }
886
+ function reactNodeToText(node) {
887
+ if (node == null || typeof node === "boolean") return "";
888
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
889
+ return String(node);
890
+ }
891
+ if (isReactNodeIterable(node)) {
892
+ let text = "";
893
+ for (const child of node) {
894
+ text += reactNodeToText(child);
895
+ }
896
+ return text;
897
+ }
898
+ if (isValidElement(node)) {
899
+ if (isButtonReactElement(node)) return "";
900
+ const props = node.props;
901
+ const childText = reactNodeToText(props.children);
902
+ if (childText) return childText;
903
+ const fromImage = imageElementText(node);
904
+ if (fromImage) return fromImage;
905
+ if (isImageReactElement(node)) return "";
906
+ if (typeof props.alt === "string" && props.alt) return props.alt;
907
+ if (typeof props.title === "string" && props.title) return props.title;
908
+ return "";
909
+ }
910
+ return "";
911
+ }
912
+ function quoteTsvCell(text) {
913
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
914
+ return `"${text.replace(/"/g, '""')}"`;
915
+ }
916
+ function sanitizeClipboardCell(text) {
917
+ return text.replace(/\s+/g, " ").trim();
918
+ }
919
+ function createCopyRenderRow(rowData, index) {
920
+ return {
921
+ id: getOriginalRowId(rowData) || String(index),
922
+ index,
923
+ original: rowData,
924
+ getIsCellDragSelected: () => false
925
+ };
926
+ }
927
+ function buildVisibleRowLookup(visibleRows) {
928
+ const lookup = /* @__PURE__ */ new Map();
929
+ for (const row of visibleRows) {
930
+ lookup.set(row.original, row);
931
+ }
932
+ return lookup;
933
+ }
934
+ function resolveCopyColumnId(cell) {
935
+ if (cell.column.id) return cell.column.id;
936
+ const columnDef = cell.column.columnDef;
937
+ if (columnDef.id) return columnDef.id;
938
+ if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
939
+ return String(columnDef.accessorKey);
940
+ }
941
+ return "";
942
+ }
943
+ function isPrimitiveCopyValue(value) {
944
+ return value == null || typeof value !== "object";
945
+ }
946
+ function extractRenderedCopyText(node, value, cellPosition, root) {
947
+ const rendered = sanitizeClipboardCell(reactNodeToText(node));
948
+ if (reactNodeContainsImage(node)) {
949
+ const fromDom = cellPosition != null ? sanitizeClipboardCell(
950
+ readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
951
+ ) : "";
952
+ if (fromDom) return fromDom;
953
+ if (rendered && isLikelyUrl(rendered)) return rendered;
954
+ return sanitizeClipboardCell(pickUrlFromUnknown(value));
955
+ }
956
+ return rendered;
957
+ }
958
+ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
959
+ const meta = columnDef.meta;
960
+ const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
961
+ const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
962
+ const ctx = {
963
+ value,
964
+ row,
965
+ index: row.index,
966
+ columnId,
967
+ cellProps: meta?.cellProps,
968
+ update: () => {
969
+ }
970
+ };
971
+ const copyValue = meta?.copyValue;
972
+ if (typeof copyValue === "function") {
973
+ try {
974
+ return sanitizeClipboardCell(copyValue(ctx));
975
+ } catch {
976
+ return formatCellValue(value);
977
+ }
978
+ }
979
+ if (copyValue === "value") {
980
+ return formatCellValue(value);
981
+ }
982
+ const cellRender = meta?.cellRender;
983
+ if (typeof cellRender === "function") {
984
+ try {
985
+ const node = cellRender(ctx);
986
+ return extractRenderedCopyText(node, value, cellPosition, options?.root);
987
+ } catch {
988
+ return formatCellValue(value);
989
+ }
990
+ }
991
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
992
+ try {
993
+ const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
994
+ if (renderer) {
995
+ const node = renderer.render(ctx);
996
+ const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
997
+ if (rendered) return rendered;
998
+ }
999
+ } catch {
1000
+ return formatCellValue(value);
1001
+ }
1002
+ }
1003
+ return formatCellValue(value);
1004
+ }
1005
+ function getNestedValue(row, path) {
1006
+ if (!path.includes(".")) return row[path];
1007
+ return path.split(".").reduce((current, key) => {
1008
+ if (current === null || current === void 0 || typeof current !== "object") {
1009
+ return void 0;
1010
+ }
1011
+ return current[key];
1012
+ }, row);
1013
+ }
1014
+ function readRowColumnValue(rowData, columnDef) {
1015
+ if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1016
+ return columnDef.accessorFn(rowData, 0);
1017
+ }
1018
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1019
+ return getNestedValue(rowData, String(columnDef.accessorKey));
1020
+ }
1021
+ return void 0;
1022
+ }
1023
+ function flattenSubtreeRows(row) {
1024
+ const children = row.children;
1025
+ if (!Array.isArray(children) || children.length === 0) return [];
1026
+ const result = [];
1027
+ const walk = (nodes) => {
1028
+ for (const node of nodes) {
1029
+ result.push(node);
1030
+ const nested = node.children;
1031
+ if (Array.isArray(nested) && nested.length > 0) {
1032
+ walk(nested);
1033
+ }
1034
+ }
1035
+ };
1036
+ walk(children);
1037
+ return result;
1038
+ }
1039
+ function hasSubtree(row) {
1040
+ const children = row.children;
1041
+ return Array.isArray(children) && children.length > 0;
1042
+ }
1043
+ function getOriginalRowId(original) {
1044
+ return String(original.id ?? original.uniqueId ?? "");
1045
+ }
1046
+ function getRowDepth(original) {
1047
+ return typeof original.level === "number" ? original.level : 0;
1048
+ }
1049
+ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1050
+ const { startRow, endRow } = bounds;
1051
+ const result = [];
1052
+ if (mode !== "subtree") {
1053
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1054
+ const row = visibleRows[rowIndex];
1055
+ if (row) result.push({ row: row.original, depth: 0 });
1056
+ }
1057
+ return result;
1058
+ }
1059
+ const included = /* @__PURE__ */ new Set();
1060
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
1061
+ const appendSubtree = (node, depth) => {
1062
+ const children = node.children;
1063
+ if (!Array.isArray(children) || children.length === 0) return;
1064
+ for (const child of children) {
1065
+ const key = keyOf(child);
1066
+ if (!included.has(key)) {
1067
+ result.push({ row: child, depth });
1068
+ included.add(key);
1069
+ }
1070
+ appendSubtree(child, depth + 1);
1071
+ }
1072
+ };
1073
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1074
+ const row = visibleRows[rowIndex];
1075
+ if (!row) continue;
1076
+ const key = keyOf(row.original);
1077
+ if (included.has(key)) continue;
1078
+ const depth = getRowDepth(row.original);
1079
+ result.push({ row: row.original, depth });
1080
+ included.add(key);
1081
+ if (!hasSubtree(row.original)) continue;
1082
+ appendSubtree(row.original, depth + 1);
1083
+ }
1084
+ return result;
1085
+ }
1086
+ function collectCopyRows(visibleRows, bounds, mode = "visible") {
1087
+ return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1088
+ }
1089
+ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1090
+ if (copyRows.length === 0) return "";
1091
+ const { startCol, endCol } = bounds;
1092
+ const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1093
+ if (columnCells.length === 0) return "";
1094
+ const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1095
+ const minDepth = Math.min(...resolvedDepths);
1096
+ const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1097
+ const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1098
+ const meta = templateCell.column.columnDef.meta;
1099
+ if (meta?.copyValue === "omit") return [];
1100
+ return [{ templateCell, colOffset }];
1101
+ });
1102
+ return copyRows.map((rowData, index) => {
1103
+ const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1104
+ const visibleRow = visibleRowByOriginal.get(rowData);
1105
+ const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1106
+ const line = copyableColumns.map(({ templateCell, colOffset }) => {
1107
+ const sourceCell = matchingCells?.[colOffset];
1108
+ const column = sourceCell?.column ?? templateCell.column;
1109
+ const text = formatCopyCellText(
1110
+ rowData,
1111
+ column.columnDef,
1112
+ resolveCopyColumnId(sourceCell ?? templateCell),
1113
+ visibleRow,
1114
+ visibleRow?.index ?? index,
1115
+ sourceCell,
1116
+ visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1117
+ options
1118
+ );
1119
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
1120
+ return quoteTsvCell(escaped);
1121
+ }).join(" ");
1122
+ return `${" ".repeat(relativeDepth)}${line}`;
1123
+ }).join("\n");
1124
+ }
1125
+ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1126
+ const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1127
+ return serializeCopyRowsToTSV(
1128
+ entries.map((entry) => entry.row),
1129
+ visibleRows,
1130
+ bounds,
1131
+ entries.map((entry) => entry.depth),
1132
+ options
1133
+ );
1134
+ }
1135
+ function writeTextWithExecCommand(text) {
1136
+ if (typeof document === "undefined") return false;
1137
+ const textarea = document.createElement("textarea");
1138
+ textarea.value = text;
1139
+ textarea.setAttribute("readonly", "");
1140
+ textarea.style.position = "fixed";
1141
+ textarea.style.top = "0";
1142
+ textarea.style.left = "0";
1143
+ textarea.style.opacity = "0";
1144
+ textarea.style.pointerEvents = "none";
1145
+ document.body.appendChild(textarea);
1146
+ const previouslyFocused = document.activeElement;
1147
+ try {
1148
+ textarea.focus();
1149
+ textarea.select();
1150
+ return document.execCommand("copy");
1151
+ } catch {
1152
+ return false;
1153
+ } finally {
1154
+ document.body.removeChild(textarea);
1155
+ previouslyFocused?.focus?.();
1156
+ }
1157
+ }
1158
+ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1159
+ const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1160
+ if (!text) return false;
1161
+ if (mode === "subtree") rememberSubtreeCopy(text);
1162
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1163
+ return writeTextWithExecCommand(text);
1164
+ }
1165
+ try {
1166
+ await navigator.clipboard.writeText(text);
1167
+ return true;
1168
+ } catch {
1169
+ return false;
1170
+ }
1171
+ }
1172
+
1173
+ // src/components/ui/table/features/cell-render/withCellUpdate.ts
1174
+ function withCellUpdate(context, commitValue) {
1175
+ return {
1176
+ ...context,
1177
+ update: (next) => {
1178
+ commitValue(context.row.id, context.column.id, next);
1179
+ }
1180
+ };
1181
+ }
1182
+
1183
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
1184
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
1185
+
1186
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
1187
+ var activeOwner = null;
1188
+ var clearByOwner = /* @__PURE__ */ new Map();
1189
+ function createCellSelectionOwner() {
1190
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
1191
+ }
1192
+ function registerCellSelectionOwner(owner, clearSelection) {
1193
+ clearByOwner.set(owner, clearSelection);
1194
+ return () => {
1195
+ clearByOwner.delete(owner);
1196
+ if (activeOwner === owner) {
1197
+ activeOwner = null;
1198
+ }
1199
+ };
1200
+ }
1201
+ function claimCellSelectionOwner(owner) {
463
1202
  if (activeOwner === owner) return;
464
1203
  activeOwner = owner;
465
1204
  for (const [id, clearSelection] of clearByOwner) {
@@ -567,9 +1306,22 @@ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
567
1306
  const cellEndRow = rowIndex + rowSpan - 1;
568
1307
  return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
569
1308
  }
1309
+ function resolveFillBounds(source, pointer) {
1310
+ const below = pointer.row - source.endRow;
1311
+ const above = source.startRow - pointer.row;
1312
+ const right = pointer.col - source.endCol;
1313
+ const left = source.startCol - pointer.col;
1314
+ const vertical = Math.max(below, above, 0);
1315
+ const horizontal = Math.max(right, left, 0);
1316
+ if (vertical === 0 && horizontal === 0) return { ...source };
1317
+ if (vertical >= horizontal) {
1318
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
1319
+ }
1320
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1321
+ }
570
1322
  function getActiveSelectionBounds(dragState, selectionBounds) {
571
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
572
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
1323
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1324
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
573
1325
  }
574
1326
  return selectionBounds;
575
1327
  }
@@ -739,424 +1491,48 @@ function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVi
739
1491
  );
740
1492
  }
741
1493
  if (isLeftEdge) {
742
- shadows.push(
743
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
744
- );
745
- }
746
- if (isRightEdge) {
747
- shadows.push(
748
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
749
- );
750
- }
751
- }
752
- const gradients = [];
753
- const sizes = [];
754
- const positions = [];
755
- for (const edge of stepEdges) {
756
- for (const partial of buildPartialEdgeGradient(edge)) {
757
- gradients.push(partial.image);
758
- sizes.push(partial.size);
759
- positions.push(partial.position);
760
- }
761
- }
762
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
763
- return void 0;
764
- }
765
- const style = {};
766
- if (shadows.length > 0) {
767
- style["--selection-edge-shadows"] = shadows.join(", ");
768
- }
769
- if (gradients.length > 0) {
770
- style["--selection-edge-gradients"] = gradients.join(", ");
771
- style["--selection-edge-sizes"] = sizes.join(", ");
772
- style["--selection-edge-positions"] = positions.join(", ");
773
- }
774
- if (selectionContinuesBelow) {
775
- style.borderBottomColor = "var(--color-brand-surface)";
776
- }
777
- return style;
778
- }
779
- function hasCellSelectionEdges(style) {
780
- return Boolean(
781
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
782
- );
783
- }
784
-
785
- // src/components/ui/table/features/cell-selection/copyData.ts
786
- import { isValidElement } from "react";
787
- function isReactNodeIterable(node) {
788
- return typeof node === "object" && node !== null && !isValidElement(node) && Symbol.iterator in node;
789
- }
790
- function getElementTypeName(type) {
791
- if (typeof type === "string") return type;
792
- if (typeof type === "function") {
793
- const fn = type;
794
- return fn.displayName || fn.name || "";
795
- }
796
- if (typeof type === "object" && type !== null) {
797
- const component = type;
798
- return component.displayName || component.render?.displayName || component.render?.name || "";
799
- }
800
- return "";
801
- }
802
- function isButtonReactElement(node) {
803
- const typeName = getElementTypeName(node.type);
804
- if (typeName === "button" || /button/i.test(typeName)) return true;
805
- const props = node.props;
806
- if (props.role === "button") return true;
807
- if (typeName === "input" && props.type === "button") return true;
808
- return false;
809
- }
810
- function isImageReactElement(node) {
811
- const typeName = getElementTypeName(node.type);
812
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
813
- }
814
- var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
815
- function isLikelyUrl(value) {
816
- const trimmed = value.trim();
817
- if (!trimmed) return false;
818
- if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
819
- if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
820
- return false;
821
- }
822
- function pickUrlFromUnknown(value) {
823
- if (typeof value === "string") {
824
- return isLikelyUrl(value) ? value.trim() : "";
825
- }
826
- if (Array.isArray(value)) {
827
- return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
828
- }
829
- if (value && typeof value === "object") {
830
- const record = value;
831
- for (const key of IMAGE_URL_PROP_KEYS) {
832
- const candidate = record[key];
833
- if (typeof candidate === "string" && candidate.trim()) {
834
- return candidate.trim();
835
- }
836
- }
837
- }
838
- return "";
839
- }
840
- function imageElementText(node) {
841
- const props = node.props;
842
- for (const key of IMAGE_URL_PROP_KEYS) {
843
- const candidate = props[key];
844
- if (typeof candidate === "string" && candidate.trim()) {
845
- return candidate.trim();
846
- }
847
- }
848
- return "";
849
- }
850
- function reactNodeContainsImage(node) {
851
- if (isValidElement(node)) {
852
- if (isImageReactElement(node)) return true;
853
- return reactNodeContainsImage(node.props.children);
854
- }
855
- if (isReactNodeIterable(node)) {
856
- for (const child of node) {
857
- if (reactNodeContainsImage(child)) return true;
858
- }
859
- }
860
- return false;
861
- }
862
- function readImgUrl(img) {
863
- const attr = img.getAttribute("src")?.trim() ?? "";
864
- if (attr) return attr;
865
- if (img instanceof HTMLImageElement) {
866
- const current = img.currentSrc?.trim() ?? "";
867
- if (current && current !== img.baseURI) return current;
868
- }
869
- return "";
870
- }
871
- function readDomImageUrls(rowIndex, colIndex, root) {
872
- const scope = root ?? (typeof document === "undefined" ? null : document);
873
- if (!scope) return "";
874
- const cells = scope.querySelectorAll(
875
- `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
876
- );
877
- for (const cell of cells) {
878
- const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
879
- const url = readImgUrl(img);
880
- return url ? [url] : [];
881
- });
882
- if (urls.length > 0) return urls.join(", ");
883
- }
884
- return "";
885
- }
886
- function reactNodeToText(node) {
887
- if (node == null || typeof node === "boolean") return "";
888
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
889
- return String(node);
890
- }
891
- if (isReactNodeIterable(node)) {
892
- let text = "";
893
- for (const child of node) {
894
- text += reactNodeToText(child);
895
- }
896
- return text;
897
- }
898
- if (isValidElement(node)) {
899
- if (isButtonReactElement(node)) return "";
900
- const props = node.props;
901
- const childText = reactNodeToText(props.children);
902
- if (childText) return childText;
903
- const fromImage = imageElementText(node);
904
- if (fromImage) return fromImage;
905
- if (isImageReactElement(node)) return "";
906
- if (typeof props.alt === "string" && props.alt) return props.alt;
907
- if (typeof props.title === "string" && props.title) return props.title;
908
- return "";
909
- }
910
- return "";
911
- }
912
- function sanitizeClipboardCell(text) {
913
- return text.replace(/\s+/g, " ").trim();
914
- }
915
- function createCopyRenderRow(rowData, index) {
916
- return {
917
- id: getOriginalRowId(rowData) || String(index),
918
- index,
919
- original: rowData,
920
- getIsCellDragSelected: () => false
921
- };
922
- }
923
- function buildVisibleRowLookup(visibleRows) {
924
- const lookup = /* @__PURE__ */ new Map();
925
- for (const row of visibleRows) {
926
- lookup.set(row.original, row);
927
- }
928
- return lookup;
929
- }
930
- function resolveCopyColumnId(cell) {
931
- if (cell.column.id) return cell.column.id;
932
- const columnDef = cell.column.columnDef;
933
- if (columnDef.id) return columnDef.id;
934
- if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
935
- return String(columnDef.accessorKey);
936
- }
937
- return "";
938
- }
939
- function isPrimitiveCopyValue(value) {
940
- return value == null || typeof value !== "object";
941
- }
942
- function extractRenderedCopyText(node, value, cellPosition, root) {
943
- const rendered = sanitizeClipboardCell(reactNodeToText(node));
944
- if (reactNodeContainsImage(node)) {
945
- const fromDom = cellPosition != null ? sanitizeClipboardCell(
946
- readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
947
- ) : "";
948
- if (fromDom) return fromDom;
949
- if (rendered && isLikelyUrl(rendered)) return rendered;
950
- return sanitizeClipboardCell(pickUrlFromUnknown(value));
951
- }
952
- return rendered;
953
- }
954
- function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
955
- const meta = columnDef.meta;
956
- const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
957
- const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
958
- const ctx = {
959
- value,
960
- row,
961
- index: row.index,
962
- columnId,
963
- cellProps: meta?.cellProps,
964
- update: () => {
965
- }
966
- };
967
- const copyValue = meta?.copyValue;
968
- if (typeof copyValue === "function") {
969
- try {
970
- return sanitizeClipboardCell(copyValue(ctx));
971
- } catch {
972
- return formatCellValue(value);
1494
+ shadows.push(
1495
+ `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1496
+ );
973
1497
  }
974
- }
975
- if (copyValue === "value") {
976
- return formatCellValue(value);
977
- }
978
- const cellRender = meta?.cellRender;
979
- if (typeof cellRender === "function") {
980
- try {
981
- const node = cellRender(ctx);
982
- return extractRenderedCopyText(node, value, cellPosition, options?.root);
983
- } catch {
984
- return formatCellValue(value);
1498
+ if (isRightEdge) {
1499
+ shadows.push(
1500
+ `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1501
+ );
985
1502
  }
986
1503
  }
987
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
988
- try {
989
- const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
990
- if (renderer) {
991
- const node = renderer.render(ctx);
992
- const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
993
- if (rendered) return rendered;
994
- }
995
- } catch {
996
- return formatCellValue(value);
1504
+ const gradients = [];
1505
+ const sizes = [];
1506
+ const positions = [];
1507
+ for (const edge of stepEdges) {
1508
+ for (const partial of buildPartialEdgeGradient(edge)) {
1509
+ gradients.push(partial.image);
1510
+ sizes.push(partial.size);
1511
+ positions.push(partial.position);
997
1512
  }
998
1513
  }
999
- return formatCellValue(value);
1000
- }
1001
- function formatPrimitive(value) {
1002
- if (value === null || value === void 0) return "";
1003
- if (typeof value === "string") return value;
1004
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1005
- return String(value);
1006
- }
1007
- return "";
1008
- }
1009
- function formatObjectValue(value) {
1010
- const text = value.text ?? value.label ?? value.name ?? value.title;
1011
- if (text != null && text !== "") {
1012
- return formatCellValue(text);
1013
- }
1014
- try {
1015
- return JSON.stringify(value);
1016
- } catch {
1017
- return "";
1018
- }
1019
- }
1020
- function formatCellValue(value) {
1021
- if (value === null || value === void 0) return "";
1022
- if (Array.isArray(value)) {
1023
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
1024
- }
1025
- if (typeof value === "object") {
1026
- return formatObjectValue(value);
1514
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1515
+ return void 0;
1027
1516
  }
1028
- return formatPrimitive(value);
1029
- }
1030
- function getNestedValue(row, path) {
1031
- if (!path.includes(".")) return row[path];
1032
- return path.split(".").reduce((current, key) => {
1033
- if (current === null || current === void 0 || typeof current !== "object") {
1034
- return void 0;
1035
- }
1036
- return current[key];
1037
- }, row);
1038
- }
1039
- function readRowColumnValue(rowData, columnDef) {
1040
- if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1041
- return columnDef.accessorFn(rowData, 0);
1517
+ const style = {};
1518
+ if (shadows.length > 0) {
1519
+ style["--selection-edge-shadows"] = shadows.join(", ");
1042
1520
  }
1043
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1044
- return getNestedValue(rowData, String(columnDef.accessorKey));
1521
+ if (gradients.length > 0) {
1522
+ style["--selection-edge-gradients"] = gradients.join(", ");
1523
+ style["--selection-edge-sizes"] = sizes.join(", ");
1524
+ style["--selection-edge-positions"] = positions.join(", ");
1045
1525
  }
1046
- return void 0;
1047
- }
1048
- function flattenSubtreeRows(row) {
1049
- const children = row.children;
1050
- if (!Array.isArray(children) || children.length === 0) return [];
1051
- const result = [];
1052
- const walk = (nodes) => {
1053
- for (const node of nodes) {
1054
- result.push(node);
1055
- const nested = node.children;
1056
- if (Array.isArray(nested) && nested.length > 0) {
1057
- walk(nested);
1058
- }
1059
- }
1060
- };
1061
- walk(children);
1062
- return result;
1063
- }
1064
- function hasSubtree(row) {
1065
- const children = row.children;
1066
- return Array.isArray(children) && children.length > 0;
1067
- }
1068
- function getOriginalRowId(original) {
1069
- return String(original.id ?? original.uniqueId ?? "");
1070
- }
1071
- function getRowDepth(original) {
1072
- return typeof original.level === "number" ? original.level : 0;
1073
- }
1074
- function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1075
- const { startRow, endRow } = bounds;
1076
- const result = [];
1077
- const includedOriginalIds = /* @__PURE__ */ new Set();
1078
- const appendSubtree = (node, depth) => {
1079
- const children = node.children;
1080
- if (!Array.isArray(children) || children.length === 0) return;
1081
- for (const child of children) {
1082
- const childId = getOriginalRowId(child);
1083
- if (!(childId && includedOriginalIds.has(childId))) {
1084
- result.push({ row: child, depth });
1085
- if (childId) includedOriginalIds.add(childId);
1086
- }
1087
- appendSubtree(child, depth + 1);
1088
- }
1089
- };
1090
- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1091
- const row = visibleRows[rowIndex];
1092
- if (!row) continue;
1093
- const originalId = getOriginalRowId(row.original);
1094
- if (originalId && includedOriginalIds.has(originalId)) continue;
1095
- const depth = getRowDepth(row.original);
1096
- result.push({ row: row.original, depth });
1097
- if (originalId) includedOriginalIds.add(originalId);
1098
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
1099
- appendSubtree(row.original, depth + 1);
1526
+ if (selectionContinuesBelow) {
1527
+ style.borderBottomColor = "var(--color-brand-surface)";
1100
1528
  }
1101
- return result;
1102
- }
1103
- function collectCopyRows(visibleRows, bounds, mode = "visible") {
1104
- return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1105
- }
1106
- function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1107
- if (copyRows.length === 0) return "";
1108
- const { startCol, endCol } = bounds;
1109
- const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1110
- if (columnCells.length === 0) return "";
1111
- const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1112
- const minDepth = Math.min(...resolvedDepths);
1113
- const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1114
- const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1115
- const meta = templateCell.column.columnDef.meta;
1116
- if (meta?.copyValue === "omit") return [];
1117
- return [{ templateCell, colOffset }];
1118
- });
1119
- return copyRows.map((rowData, index) => {
1120
- const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1121
- const visibleRow = visibleRowByOriginal.get(rowData);
1122
- const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1123
- const line = copyableColumns.map(({ templateCell, colOffset }) => {
1124
- const sourceCell = matchingCells?.[colOffset];
1125
- const column = sourceCell?.column ?? templateCell.column;
1126
- return formatCopyCellText(
1127
- rowData,
1128
- column.columnDef,
1129
- resolveCopyColumnId(sourceCell ?? templateCell),
1130
- visibleRow,
1131
- visibleRow?.index ?? index,
1132
- sourceCell,
1133
- visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1134
- options
1135
- );
1136
- }).join(" ");
1137
- return `${" ".repeat(relativeDepth)}${line}`;
1138
- }).join("\n");
1529
+ return style;
1139
1530
  }
1140
- function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1141
- const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1142
- return serializeCopyRowsToTSV(
1143
- entries.map((entry) => entry.row),
1144
- visibleRows,
1145
- bounds,
1146
- entries.map((entry) => entry.depth),
1147
- options
1531
+ function hasCellSelectionEdges(style) {
1532
+ return Boolean(
1533
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1148
1534
  );
1149
1535
  }
1150
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1151
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1152
- if (!text) return false;
1153
- try {
1154
- await navigator.clipboard.writeText(text);
1155
- } catch {
1156
- return false;
1157
- }
1158
- return true;
1159
- }
1160
1536
 
1161
1537
  // src/components/ui/table/features/cell-selection/fillData.ts
1162
1538
  function getColumnAccessorKey2(columnDef) {
@@ -1180,6 +1556,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1180
1556
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1181
1557
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1182
1558
  if (!targetRow || !targetCell || !sourceCell) continue;
1559
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1560
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1183
1561
  const accessorKey = getColumnAccessorKey2(
1184
1562
  targetCell.column.columnDef
1185
1563
  );
@@ -1201,13 +1579,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1201
1579
  );
1202
1580
  }
1203
1581
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1204
- const newData = data.map((row) => ({ ...row }));
1205
1582
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1206
- for (const target of targets) {
1207
- if (!newData[target.rowIndex]) continue;
1208
- newData[target.rowIndex][target.accessorKey] = target.value;
1209
- }
1210
- return newData;
1583
+ return applyCellChangesToData(
1584
+ data,
1585
+ targets.flatMap((target) => {
1586
+ const row = rows[target.rowIndex];
1587
+ if (!row) return [];
1588
+ return [
1589
+ {
1590
+ original: row.original,
1591
+ index: row.index,
1592
+ accessorKey: target.accessorKey,
1593
+ value: target.value
1594
+ }
1595
+ ];
1596
+ })
1597
+ );
1211
1598
  }
1212
1599
  function hasFillExtension(sourceBounds, fillBounds) {
1213
1600
  if (!sourceBounds) return false;
@@ -1228,17 +1615,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1228
1615
  if (firstDepth !== 0) return false;
1229
1616
  return leadingEmptyCounts.some((depth) => depth > 0);
1230
1617
  }
1618
+ function splitTSV(text) {
1619
+ const rows = [];
1620
+ let row = [];
1621
+ let index = 0;
1622
+ while (index <= text.length) {
1623
+ let cell = "";
1624
+ if (text[index] === '"') {
1625
+ index += 1;
1626
+ while (index < text.length) {
1627
+ const char = text[index];
1628
+ if (char === '"') {
1629
+ if (text[index + 1] === '"') {
1630
+ cell += '"';
1631
+ index += 2;
1632
+ continue;
1633
+ }
1634
+ index += 1;
1635
+ break;
1636
+ }
1637
+ cell += char;
1638
+ index += 1;
1639
+ }
1640
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1641
+ cell += text[index];
1642
+ index += 1;
1643
+ }
1644
+ } else {
1645
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1646
+ cell += text[index];
1647
+ index += 1;
1648
+ }
1649
+ }
1650
+ row.push(cell);
1651
+ if (index >= text.length) {
1652
+ rows.push(row);
1653
+ break;
1654
+ }
1655
+ if (text[index] === "\n") {
1656
+ rows.push(row);
1657
+ row = [];
1658
+ }
1659
+ index += 1;
1660
+ }
1661
+ return rows;
1662
+ }
1231
1663
  function parseClipboardTSV(text) {
1232
1664
  return parseClipboardTSVWithDepths(text).values;
1233
1665
  }
1234
- function parseClipboardTSVWithDepths(text) {
1666
+ function parseClipboardTSVWithDepths(text, options) {
1235
1667
  if (!text) return { values: [], depths: [] };
1236
1668
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1237
1669
  const withoutTrailing = normalized.replace(/\n+$/, "");
1238
1670
  if (!withoutTrailing) return { values: [], depths: [] };
1239
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1671
+ const rows = splitTSV(withoutTrailing);
1240
1672
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1241
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1673
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1242
1674
  const values = [];
1243
1675
  const depths = [];
1244
1676
  for (let index = 0; index < rows.length; index += 1) {
@@ -1265,8 +1697,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1265
1697
  }
1266
1698
  return columnIds;
1267
1699
  }
1268
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1269
- const { values, depths } = parseClipboardTSVWithDepths(text);
1700
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1701
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1270
1702
  if (values.length === 0) return null;
1271
1703
  const width = Math.max(...values.map((row) => row.length), 0);
1272
1704
  if (width === 0) return null;
@@ -1299,6 +1731,19 @@ function isEditablePasteTarget(target) {
1299
1731
  }
1300
1732
 
1301
1733
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
1734
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
1735
+ function isInteractiveFocus() {
1736
+ const active = document.activeElement;
1737
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
1738
+ }
1739
+ function hasPageTextSelectionOutside(root) {
1740
+ if (typeof window.getSelection !== "function") return false;
1741
+ const selection = window.getSelection();
1742
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
1743
+ if (!selection.toString()) return false;
1744
+ const anchor = selection.anchorNode;
1745
+ return !(root && anchor && root.contains(anchor));
1746
+ }
1302
1747
  function isFocusOutsideRoot(rootRef) {
1303
1748
  const root = rootRef?.current;
1304
1749
  if (!root) return false;
@@ -1311,29 +1756,50 @@ function useCellSelection({
1311
1756
  rows,
1312
1757
  enabled = true,
1313
1758
  columnCount = 0,
1759
+ columnSignature,
1314
1760
  enableSubtreeCopy = false,
1761
+ escapeCopyFormulas = false,
1315
1762
  enableInsertPaste = true,
1316
1763
  onDataChange,
1317
1764
  onBatchChange,
1318
1765
  onRowsPaste,
1319
1766
  onCellNavigate,
1320
1767
  cellRendererRegistry,
1321
- rootRef
1768
+ rootRef,
1769
+ enableWasdNavigation = true,
1770
+ onEditKey,
1771
+ onClearKey
1322
1772
  }) {
1323
1773
  const ownerRef = useRef2(createCellSelectionOwner());
1324
1774
  const [dragState, setDragState] = useState2(INITIAL_DRAG_STATE);
1325
1775
  const pendingPasteModeRef = useRef2(null);
1326
1776
  const dragStateRef = useRef2(dragState);
1327
1777
  const onCellNavigateRef = useRef2(onCellNavigate);
1778
+ const onEditKeyRef = useRef2(onEditKey);
1779
+ const onClearKeyRef = useRef2(onClearKey);
1328
1780
  dragStateRef.current = dragState;
1329
1781
  onCellNavigateRef.current = onCellNavigate;
1330
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1331
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
1782
+ onEditKeyRef.current = onEditKey;
1783
+ onClearKeyRef.current = onClearKey;
1784
+ const updateDragState = useCallback2((update) => {
1785
+ const prev = dragStateRef.current;
1786
+ const next = update(prev);
1787
+ if (next === prev) return;
1788
+ dragStateRef.current = next;
1789
+ setDragState(next);
1790
+ }, []);
1791
+ const activeSelectionBounds = useMemo2(() => {
1792
+ if (!enabled) return null;
1793
+ return getActiveSelectionBounds(
1794
+ dragState,
1795
+ getCellSelectionBounds(dragState.start, dragState.end)
1796
+ );
1797
+ }, [dragState, enabled]);
1332
1798
  const handleCellMouseDown = useCallback2(
1333
1799
  (rowIndex, colIndex, options) => {
1334
1800
  if (!enabled) return;
1335
1801
  claimCellSelectionOwner(ownerRef.current);
1336
- setDragState((prev) => {
1802
+ updateDragState((prev) => {
1337
1803
  if (options?.shiftKey && prev.start) {
1338
1804
  return {
1339
1805
  ...prev,
@@ -1354,28 +1820,30 @@ function useCellSelection({
1354
1820
  };
1355
1821
  });
1356
1822
  },
1357
- [enabled]
1823
+ [enabled, updateDragState]
1358
1824
  );
1359
1825
  const handleCellMouseEnter = useCallback2(
1360
1826
  (rowIndex, colIndex) => {
1361
1827
  if (!enabled) return;
1362
- setDragState((prev) => {
1828
+ updateDragState((prev) => {
1363
1829
  if (prev.isSelecting) {
1830
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1364
1831
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1365
1832
  }
1366
1833
  if (prev.isFillDragging) {
1834
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1367
1835
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1368
1836
  }
1369
1837
  return prev;
1370
1838
  });
1371
1839
  },
1372
- [enabled]
1840
+ [enabled, updateDragState]
1373
1841
  );
1374
1842
  const handleFillHandleMouseDown = useCallback2(
1375
1843
  (rowIndex, colIndex) => {
1376
1844
  if (!enabled) return;
1377
1845
  claimCellSelectionOwner(ownerRef.current);
1378
- setDragState((prev) => {
1846
+ updateDragState((prev) => {
1379
1847
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1380
1848
  if (!bounds) return prev;
1381
1849
  return {
@@ -1387,7 +1855,7 @@ function useCellSelection({
1387
1855
  };
1388
1856
  });
1389
1857
  },
1390
- [enabled]
1858
+ [enabled, updateDragState]
1391
1859
  );
1392
1860
  const clearSelection = useCallback2(() => {
1393
1861
  const prev = dragStateRef.current;
@@ -1406,6 +1874,130 @@ function useCellSelection({
1406
1874
  useEffect2(() => {
1407
1875
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1408
1876
  }, [clearSelection]);
1877
+ const previousColumnSignatureRef = useRef2(columnSignature);
1878
+ useEffect2(() => {
1879
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
1880
+ previousColumnSignatureRef.current = columnSignature;
1881
+ const prev = dragStateRef.current;
1882
+ if (!prev.start || !prev.end) return;
1883
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1884
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
1885
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
1886
+ if (columnsChanged || outOfRange) {
1887
+ clearSelection();
1888
+ }
1889
+ }, [clearSelection, columnCount, columnSignature, rows]);
1890
+ useEffect2(() => {
1891
+ if (!enabled) return;
1892
+ const handlePointerDown = (event) => {
1893
+ const root = rootRef?.current;
1894
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
1895
+ if (event.target instanceof Node && root.contains(event.target)) return;
1896
+ releaseCellSelectionOwner(ownerRef.current);
1897
+ };
1898
+ document.addEventListener("pointerdown", handlePointerDown, true);
1899
+ document.addEventListener("mousedown", handlePointerDown, true);
1900
+ return () => {
1901
+ document.removeEventListener("pointerdown", handlePointerDown, true);
1902
+ document.removeEventListener("mousedown", handlePointerDown, true);
1903
+ };
1904
+ }, [enabled, rootRef]);
1905
+ const getColumnCount = useCallback2(
1906
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
1907
+ [columnCount, rows]
1908
+ );
1909
+ const selectCell = useCallback2(
1910
+ (row, col) => {
1911
+ if (!enabled) return;
1912
+ const resolvedColumnCount = getColumnCount();
1913
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
1914
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
1915
+ claimCellSelectionOwner(ownerRef.current);
1916
+ const nextState = {
1917
+ isSelecting: false,
1918
+ isFillDragging: false,
1919
+ start: position,
1920
+ end: position,
1921
+ fillAnchor: null,
1922
+ fillEnd: null
1923
+ };
1924
+ dragStateRef.current = nextState;
1925
+ setDragState(nextState);
1926
+ onCellNavigateRef.current?.(position);
1927
+ },
1928
+ [enabled, getColumnCount, rows.length]
1929
+ );
1930
+ const focusSelection = useCallback2(() => {
1931
+ if (!enabled) return;
1932
+ const prev = dragStateRef.current;
1933
+ if (prev.start && prev.end) {
1934
+ claimCellSelectionOwner(ownerRef.current);
1935
+ return;
1936
+ }
1937
+ selectCell(0, 0);
1938
+ }, [enabled, selectCell]);
1939
+ useEffect2(() => {
1940
+ if (!enabled) return;
1941
+ const handleKeyDown = (e) => {
1942
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1943
+ if (e.altKey) return;
1944
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
1945
+ return;
1946
+ }
1947
+ if (isFocusOutsideRoot(rootRef)) return;
1948
+ const prev = dragStateRef.current;
1949
+ if (!prev.start || !prev.end) return;
1950
+ if (prev.isSelecting || prev.isFillDragging) return;
1951
+ const rowCount = rows.length;
1952
+ const resolvedColumnCount = getColumnCount();
1953
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
1954
+ const withModifier = e.ctrlKey || e.metaKey;
1955
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
1956
+ e.preventDefault();
1957
+ claimCellSelectionOwner(ownerRef.current);
1958
+ const nextState = {
1959
+ isSelecting: false,
1960
+ isFillDragging: false,
1961
+ start: { row: 0, col: 0 },
1962
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
1963
+ fillAnchor: null,
1964
+ fillEnd: null
1965
+ };
1966
+ dragStateRef.current = nextState;
1967
+ setDragState(nextState);
1968
+ return;
1969
+ }
1970
+ if (e.key === "Home" || e.key === "End") {
1971
+ e.preventDefault();
1972
+ const toEnd = e.key === "End";
1973
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
1974
+ if (e.shiftKey) {
1975
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
1976
+ dragStateRef.current = nextState;
1977
+ setDragState(nextState);
1978
+ onCellNavigateRef.current?.(target);
1979
+ } else {
1980
+ selectCell(target.row, target.col);
1981
+ }
1982
+ return;
1983
+ }
1984
+ if (withModifier || isInteractiveFocus()) return;
1985
+ if (e.key === "Enter" || e.key === "F2") {
1986
+ if (!onEditKeyRef.current) return;
1987
+ e.preventDefault();
1988
+ onEditKeyRef.current(prev.end);
1989
+ return;
1990
+ }
1991
+ if (e.key === "Delete" || e.key === "Backspace") {
1992
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1993
+ if (!bounds || !onClearKeyRef.current) return;
1994
+ e.preventDefault();
1995
+ onClearKeyRef.current(bounds);
1996
+ }
1997
+ };
1998
+ window.addEventListener("keydown", handleKeyDown);
1999
+ return () => window.removeEventListener("keydown", handleKeyDown);
2000
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
1409
2001
  useEffect2(() => {
1410
2002
  if (!enabled) return;
1411
2003
  const handleKeyDown = (e) => {
@@ -1415,6 +2007,7 @@ function useCellSelection({
1415
2007
  return;
1416
2008
  }
1417
2009
  if (isFocusOutsideRoot(rootRef)) return;
2010
+ if (!enableWasdNavigation && e.key.length === 1) return;
1418
2011
  const delta = getCellNavigationDelta(e.key);
1419
2012
  if (!delta) return;
1420
2013
  const prev = dragStateRef.current;
@@ -1454,14 +2047,15 @@ function useCellSelection({
1454
2047
  };
1455
2048
  window.addEventListener("keydown", handleKeyDown);
1456
2049
  return () => window.removeEventListener("keydown", handleKeyDown);
1457
- }, [columnCount, enabled, rows]);
2050
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1458
2051
  const copySelection = useCallback2(
1459
2052
  async (options) => {
1460
2053
  if (!enabled || !activeSelectionBounds) return false;
1461
2054
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1462
2055
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1463
2056
  registry: cellRendererRegistry,
1464
- root: rootRef?.current
2057
+ root: rootRef?.current,
2058
+ escapeFormulas: escapeCopyFormulas
1465
2059
  });
1466
2060
  },
1467
2061
  [
@@ -1469,6 +2063,7 @@ function useCellSelection({
1469
2063
  cellRendererRegistry,
1470
2064
  enableSubtreeCopy,
1471
2065
  enabled,
2066
+ escapeCopyFormulas,
1472
2067
  rootRef,
1473
2068
  rows
1474
2069
  ]
@@ -1486,6 +2081,7 @@ function useCellSelection({
1486
2081
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1487
2082
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1488
2083
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2084
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1489
2085
  e.preventDefault();
1490
2086
  void copySelection({ includeDescendants: isSubtreeShortcut });
1491
2087
  };
@@ -1501,9 +2097,17 @@ function useCellSelection({
1501
2097
  activeSelectionBounds.startCol,
1502
2098
  text,
1503
2099
  mode,
1504
- activeSelectionBounds.endRow
2100
+ activeSelectionBounds.endRow,
2101
+ // Leading blank cells are tree depth only in this table's own subtree
2102
+ // copy; from a spreadsheet they are real (empty) cells.
2103
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
1505
2104
  );
1506
2105
  if (!payload) return false;
2106
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
2107
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
2108
+ const cell = cells.find((item) => item.column.id === columnId);
2109
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
2110
+ });
1507
2111
  onRowsPaste(payload);
1508
2112
  return true;
1509
2113
  },
@@ -1534,7 +2138,10 @@ function useCellSelection({
1534
2138
  void (async () => {
1535
2139
  try {
1536
2140
  const text = await navigator.clipboard.readText();
1537
- if (pasteHandledRef.current) return;
2141
+ if (pasteHandledRef.current) {
2142
+ pasteHandledRef.current = false;
2143
+ return;
2144
+ }
1538
2145
  if (pendingPasteModeRef.current !== mode) return;
1539
2146
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1540
2147
  if (!text) return;
@@ -1559,6 +2166,7 @@ function useCellSelection({
1559
2166
  }
1560
2167
  const mode = pendingPasteModeRef.current ?? "overwrite";
1561
2168
  if (pasteHandledRef.current) {
2169
+ pasteHandledRef.current = false;
1562
2170
  e.preventDefault();
1563
2171
  return;
1564
2172
  }
@@ -1585,39 +2193,41 @@ function useCellSelection({
1585
2193
  useEffect2(() => {
1586
2194
  if (!enabled) return;
1587
2195
  const handleMouseUp = () => {
1588
- setDragState((prev) => {
1589
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1590
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1591
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1592
- if (newBounds) {
1593
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1594
- if (onBatchChange) {
1595
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1596
- if (changes.length > 0) {
1597
- onBatchChange(changes);
1598
- }
1599
- } else if (onDataChange) {
1600
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
2196
+ const prev = dragStateRef.current;
2197
+ let next = prev;
2198
+ if (prev.isFillDragging && prev.fillEnd) {
2199
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
2200
+ if (sourceBounds) {
2201
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
2202
+ if (hasFillExtension(sourceBounds, newBounds)) {
2203
+ if (onBatchChange) {
2204
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
2205
+ if (changes.length > 0) {
2206
+ onBatchChange(changes);
1601
2207
  }
2208
+ } else if (onDataChange) {
2209
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1602
2210
  }
1603
- return {
1604
- isSelecting: false,
1605
- isFillDragging: false,
1606
- start: { row: newBounds.startRow, col: newBounds.startCol },
1607
- end: { row: newBounds.endRow, col: newBounds.endCol },
1608
- fillAnchor: null,
1609
- fillEnd: null
1610
- };
1611
2211
  }
2212
+ next = {
2213
+ isSelecting: false,
2214
+ isFillDragging: false,
2215
+ start: { row: newBounds.startRow, col: newBounds.startCol },
2216
+ end: { row: newBounds.endRow, col: newBounds.endCol },
2217
+ fillAnchor: null,
2218
+ fillEnd: null
2219
+ };
2220
+ } else {
2221
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1612
2222
  }
1613
- if (prev.isSelecting) {
1614
- return { ...prev, isSelecting: false };
1615
- }
1616
- if (prev.isFillDragging) {
1617
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1618
- }
1619
- return prev;
1620
- });
2223
+ } else if (prev.isSelecting) {
2224
+ next = { ...prev, isSelecting: false };
2225
+ } else if (prev.isFillDragging) {
2226
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
2227
+ }
2228
+ if (next === prev) return;
2229
+ dragStateRef.current = next;
2230
+ setDragState(next);
1621
2231
  };
1622
2232
  window.addEventListener("mouseup", handleMouseUp);
1623
2233
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1629,9 +2239,36 @@ function useCellSelection({
1629
2239
  handleCellMouseEnter,
1630
2240
  handleFillHandleMouseDown,
1631
2241
  clearSelection,
1632
- copySelection
2242
+ copySelection,
2243
+ selectCell,
2244
+ focusSelection
2245
+ };
2246
+ }
2247
+
2248
+ // src/components/ui/table/features/row-hover/rowHover.ts
2249
+ function createRowHoverStore() {
2250
+ let hoveredRowIndex = null;
2251
+ const listeners = /* @__PURE__ */ new Set();
2252
+ return {
2253
+ getHoveredRowIndex: () => hoveredRowIndex,
2254
+ setHoveredRowIndex: (nextRowIndex) => {
2255
+ if (nextRowIndex === hoveredRowIndex) return;
2256
+ hoveredRowIndex = nextRowIndex;
2257
+ listeners.forEach((listener) => listener());
2258
+ },
2259
+ subscribe: (listener) => {
2260
+ listeners.add(listener);
2261
+ return () => listeners.delete(listener);
2262
+ }
1633
2263
  };
1634
2264
  }
2265
+ function isRowHovered(hoveredRowIndex, rowIndex) {
2266
+ return hoveredRowIndex === rowIndex;
2267
+ }
2268
+ function isRowGroupHovered(hoveredRowIndex, enableRowSpan, groupStart, groupSpan) {
2269
+ if (!enableRowSpan || hoveredRowIndex === null) return false;
2270
+ return hoveredRowIndex >= groupStart && hoveredRowIndex <= groupStart + groupSpan - 1;
2271
+ }
1635
2272
 
1636
2273
  // src/components/ui/table/features/selection-dismiss/isOutsideDismissTarget.ts
1637
2274
  var OVERLAY_DISMISS_IGNORE_SELECTOR = [
@@ -1664,8 +2301,12 @@ function handleEscape(event) {
1664
2301
  if (isOverlayDismissIgnoreTarget(event.target) || isOverlayDismissIgnoreTarget(document.activeElement)) {
1665
2302
  return;
1666
2303
  }
1667
- for (const clearAllSelections of clearAllByOwner.values()) {
1668
- clearAllSelections();
2304
+ for (const clearAllSelections of [...clearAllByOwner.values()]) {
2305
+ try {
2306
+ clearAllSelections();
2307
+ } catch (error) {
2308
+ console.error("[react-glide-table] escape-dismiss callback failed", error);
2309
+ }
1669
2310
  }
1670
2311
  }
1671
2312
  function registerEscapeDismiss(owner, clearAllSelections) {
@@ -1854,231 +2495,75 @@ function buildColumnFreezeOffsets(columns) {
1854
2495
  for (let index = columns.length - 1; index >= 0; index -= 1) {
1855
2496
  const column = columns[index];
1856
2497
  if (!column || column.side !== "right") continue;
1857
- rightIds.push(column.id);
1858
- result.set(column.id, {
1859
- side: "right",
1860
- offset: rightOffset,
1861
- isEdge: false,
1862
- edgeLeft: false,
1863
- edgeRight: false,
1864
- stack: 0
1865
- });
1866
- rightOffset += column.size;
1867
- }
1868
- rightIds.forEach((id, index) => {
1869
- const entry = result.get(id);
1870
- if (!entry) return;
1871
- entry.stack = rightIds.length - index;
1872
- });
1873
- columns.forEach((column, index) => {
1874
- if (!column.side) return;
1875
- const entry = result.get(column.id);
1876
- if (!entry) return;
1877
- const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
1878
- const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
1879
- entry.edgeLeft = prevSide !== column.side;
1880
- entry.edgeRight = nextSide !== column.side;
1881
- if (index === 0) entry.edgeLeft = false;
1882
- if (index === columns.length - 1) entry.edgeRight = false;
1883
- entry.isEdge = entry.edgeLeft || entry.edgeRight;
1884
- });
1885
- return result;
1886
- }
1887
- function getColumnFreezeStyle(offset, options) {
1888
- if (!offset) return void 0;
1889
- const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
1890
- return {
1891
- position: "sticky",
1892
- ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
1893
- zIndex: zBase + offset.stack
1894
- };
1895
- }
1896
- function resolveHeaderFreezeOffset(column, freezeOffsets) {
1897
- const direct = freezeOffsets.get(column.id);
1898
- if (direct) return direct;
1899
- const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
1900
- if (leaves.length === 0) return void 0;
1901
- const leafOffsets = [];
1902
- for (const leaf of leaves) {
1903
- const offset2 = freezeOffsets.get(leaf.id);
1904
- if (!offset2) return void 0;
1905
- leafOffsets.push(offset2);
1906
- }
1907
- const side = leafOffsets[0]?.side;
1908
- if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
1909
- return void 0;
1910
- }
1911
- const offset = Math.min(...leafOffsets.map((item) => item.offset));
1912
- const leftmost = leafOffsets[0];
1913
- const rightmost = leafOffsets[leafOffsets.length - 1];
1914
- return {
1915
- side,
1916
- offset,
1917
- edgeLeft: leftmost.edgeLeft,
1918
- edgeRight: rightmost.edgeRight,
1919
- isEdge: leftmost.edgeLeft || rightmost.edgeRight,
1920
- stack: Math.max(...leafOffsets.map((item) => item.stack))
1921
- };
1922
- }
1923
- function flattenHeaderLeaves(column) {
1924
- if (!column.columns || column.columns.length === 0) return [column];
1925
- return column.columns.flatMap((child) => flattenHeaderLeaves(child));
1926
- }
1927
-
1928
- // src/components/ui/table/features/inline-search/inlineSearch.ts
1929
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
1930
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
1931
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
1932
- function escapeSearchRegex(value) {
1933
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
1934
- }
1935
- function createSearchRegex(query) {
1936
- const trimmed = query.trim();
1937
- if (!trimmed) return null;
1938
- return new RegExp(escapeSearchRegex(trimmed), "i");
1939
- }
1940
- function cellValueToSearchText(value) {
1941
- if (value == null) return void 0;
1942
- if (typeof value === "string") return value;
1943
- if (typeof value === "number" || typeof value === "boolean") {
1944
- return String(value);
1945
- }
1946
- if (Array.isArray(value)) {
1947
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
1948
- }
1949
- if (typeof value === "object") {
1950
- try {
1951
- return JSON.stringify(value);
1952
- } catch {
1953
- return String(value);
1954
- }
1955
- }
1956
- return String(value);
1957
- }
1958
- function formatSearchResultLabel(status) {
1959
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
1960
- if (status.selectedIndex >= 0 && status.results > 0) {
1961
- return `${status.selectedIndex + 1} of ${countLabel}`;
1962
- }
1963
- return countLabel;
1964
- }
1965
- function nextSearchIndex(selectedIndex, results) {
1966
- if (results <= 0) return -1;
1967
- if (selectedIndex < 0) return 0;
1968
- return (selectedIndex + 1) % results;
1969
- }
1970
- function previousSearchIndex(selectedIndex, results) {
1971
- if (results <= 0) return -1;
1972
- if (selectedIndex < 0) return results - 1;
1973
- let next = (selectedIndex - 1) % results;
1974
- if (next < 0) next += results;
1975
- return next;
1976
- }
1977
- function buildSearchMatchKey(colIndex, rowIndex) {
1978
- return `${colIndex}:${rowIndex}`;
1979
- }
1980
- function buildSearchMatchKeys(results) {
1981
- const keys = /* @__PURE__ */ new Set();
1982
- for (const [colIndex, rowIndex] of results) {
1983
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
1984
- }
1985
- return keys;
1986
- }
1987
- function collectSearchMatchesInRange(options) {
1988
- const {
1989
- query,
1990
- startRow,
1991
- rowCount,
1992
- columnCount,
1993
- getCellValue,
1994
- maxResults = INLINE_SEARCH_MAX_RESULTS
1995
- } = options;
1996
- const regex = createSearchRegex(query);
1997
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
1998
- const matches = [];
1999
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2000
- const rowIndex = startRow + rowOffset;
2001
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2002
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2003
- if (text !== void 0 && regex.test(text)) {
2004
- matches.push([colIndex, rowIndex]);
2005
- if (matches.length >= maxResults) {
2006
- return matches;
2007
- }
2008
- }
2009
- }
2010
- }
2011
- return matches;
2012
- }
2013
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2014
- const rounded = Math.max(elapsedMs, 1);
2015
- const scalar = targetMs / rounded;
2016
- return Math.max(1, Math.ceil(currentStride * scalar));
2017
- }
2018
- function buildFlatSearchCorpus(rows, getRowId) {
2019
- return rows.map((data, index) => ({
2020
- id: getRowId(data, index),
2021
- data,
2022
- ancestorToggleKeys: []
2023
- }));
2024
- }
2025
- function buildTreeSearchCorpus(visibleRows, options) {
2026
- const { toggleField, getRowId } = options;
2027
- const corpus = [];
2028
- const seen = /* @__PURE__ */ new Set();
2029
- const walk = (node, ancestorToggleKeys) => {
2030
- const id = getRowId(node, corpus.length);
2031
- if (seen.has(id)) return;
2032
- seen.add(id);
2033
- corpus.push({
2034
- id,
2035
- data: node,
2036
- ancestorToggleKeys
2037
- });
2038
- const children = node.children;
2039
- if (!Array.isArray(children) || children.length === 0) return;
2040
- const toggleValue = node[toggleField];
2041
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2042
- for (const child of children) {
2043
- if (child && typeof child === "object") {
2044
- walk(child, childAncestors);
2045
- }
2046
- }
2047
- };
2048
- for (const row of visibleRows) {
2049
- const level = row.level;
2050
- if (level === 0 || level === void 0) {
2051
- walk(row, []);
2052
- }
2053
- }
2054
- for (const row of visibleRows) {
2055
- const id = getRowId(row, corpus.length);
2056
- if (seen.has(id)) continue;
2057
- walk(row, []);
2498
+ rightIds.push(column.id);
2499
+ result.set(column.id, {
2500
+ side: "right",
2501
+ offset: rightOffset,
2502
+ isEdge: false,
2503
+ edgeLeft: false,
2504
+ edgeRight: false,
2505
+ stack: 0
2506
+ });
2507
+ rightOffset += column.size;
2058
2508
  }
2059
- return corpus;
2509
+ rightIds.forEach((id, index) => {
2510
+ const entry = result.get(id);
2511
+ if (!entry) return;
2512
+ entry.stack = rightIds.length - index;
2513
+ });
2514
+ columns.forEach((column, index) => {
2515
+ if (!column.side) return;
2516
+ const entry = result.get(column.id);
2517
+ if (!entry) return;
2518
+ const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
2519
+ const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
2520
+ entry.edgeLeft = prevSide !== column.side;
2521
+ entry.edgeRight = nextSide !== column.side;
2522
+ if (index === 0) entry.edgeLeft = false;
2523
+ if (index === columns.length - 1) entry.edgeRight = false;
2524
+ entry.isEdge = entry.edgeLeft || entry.edgeRight;
2525
+ });
2526
+ return result;
2060
2527
  }
2061
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2062
- const keys = /* @__PURE__ */ new Set();
2063
- for (const [colIndex, corpusRowIndex] of results) {
2064
- const corpusRow = corpus[corpusRowIndex];
2065
- if (!corpusRow) continue;
2066
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2067
- if (visibleRowIndex === void 0) continue;
2068
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2069
- }
2070
- return keys;
2528
+ function getColumnFreezeStyle(offset, options) {
2529
+ if (!offset) return void 0;
2530
+ const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
2531
+ return {
2532
+ position: "sticky",
2533
+ ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
2534
+ zIndex: zBase + offset.stack
2535
+ };
2071
2536
  }
2072
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2073
- const [colIndex, corpusRowIndex] = item;
2074
- const corpusRow = corpus[corpusRowIndex];
2075
- if (!corpusRow) return null;
2076
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2077
- if (visibleRowIndex === void 0) return null;
2078
- return [colIndex, visibleRowIndex];
2537
+ function resolveHeaderFreezeOffset(column, freezeOffsets) {
2538
+ const direct = freezeOffsets.get(column.id);
2539
+ if (direct) return direct;
2540
+ const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
2541
+ if (leaves.length === 0) return void 0;
2542
+ const leafOffsets = [];
2543
+ for (const leaf of leaves) {
2544
+ const offset2 = freezeOffsets.get(leaf.id);
2545
+ if (!offset2) return void 0;
2546
+ leafOffsets.push(offset2);
2547
+ }
2548
+ const side = leafOffsets[0]?.side;
2549
+ if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
2550
+ return void 0;
2551
+ }
2552
+ const offset = Math.min(...leafOffsets.map((item) => item.offset));
2553
+ const leftmost = leafOffsets[0];
2554
+ const rightmost = leafOffsets[leafOffsets.length - 1];
2555
+ return {
2556
+ side,
2557
+ offset,
2558
+ edgeLeft: leftmost.edgeLeft,
2559
+ edgeRight: rightmost.edgeRight,
2560
+ isEdge: leftmost.edgeLeft || rightmost.edgeRight,
2561
+ stack: Math.max(...leafOffsets.map((item) => item.stack))
2562
+ };
2079
2563
  }
2080
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2081
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2564
+ function flattenHeaderLeaves(column) {
2565
+ if (!column.columns || column.columns.length === 0) return [column];
2566
+ return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2082
2567
  }
2083
2568
 
2084
2569
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
@@ -2086,16 +2571,35 @@ import {
2086
2571
  useCallback as useCallback3,
2087
2572
  useEffect as useEffect3,
2088
2573
  useId,
2089
- useMemo,
2574
+ useMemo as useMemo3,
2090
2575
  useRef as useRef3,
2091
2576
  useState as useState3
2092
2577
  } from "react";
2093
2578
  var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2579
+ var searchInstanceCount = 0;
2580
+ var lastPointerTarget = null;
2581
+ function trackPointerTarget(event) {
2582
+ lastPointerTarget = event.target;
2583
+ }
2584
+ function registerSearchInstance() {
2585
+ if (searchInstanceCount === 0) {
2586
+ document.addEventListener("pointerdown", trackPointerTarget, true);
2587
+ }
2588
+ searchInstanceCount += 1;
2589
+ return () => {
2590
+ searchInstanceCount -= 1;
2591
+ if (searchInstanceCount === 0) {
2592
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2593
+ lastPointerTarget = null;
2594
+ }
2595
+ };
2596
+ }
2094
2597
  function useInlineSearch({
2095
2598
  enabled = false,
2096
2599
  rowCount,
2097
2600
  columnCount,
2098
2601
  getCellValue,
2602
+ contentKey,
2099
2603
  initialStartRow = 0,
2100
2604
  showSearch: controlledShowSearch,
2101
2605
  searchValue: controlledSearchValue,
@@ -2304,6 +2808,7 @@ function useInlineSearch({
2304
2808
  }
2305
2809
  beginSearch(searchValue);
2306
2810
  }, [
2811
+ contentKey,
2307
2812
  beginSearch,
2308
2813
  cancelSearch,
2309
2814
  controlledSearchResults,
@@ -2324,6 +2829,9 @@ function useInlineSearch({
2324
2829
  if (!focusInside && active !== document.body) {
2325
2830
  return;
2326
2831
  }
2832
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2833
+ return;
2834
+ }
2327
2835
  }
2328
2836
  event.preventDefault();
2329
2837
  event.stopPropagation();
@@ -2337,14 +2845,18 @@ function useInlineSearch({
2337
2845
  }
2338
2846
  };
2339
2847
  window.addEventListener("keydown", handleKeyDown, true);
2340
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2848
+ const releaseInstance = registerSearchInstance();
2849
+ return () => {
2850
+ window.removeEventListener("keydown", handleKeyDown, true);
2851
+ releaseInstance();
2852
+ };
2341
2853
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2342
2854
  useEffect3(() => () => cancelSearch(), [cancelSearch]);
2343
- const searchMatchKeys = useMemo(
2855
+ const searchMatchKeys = useMemo3(
2344
2856
  () => buildSearchMatchKeys(searchResults),
2345
2857
  [searchResults]
2346
2858
  );
2347
- const activeMatch = useMemo(() => {
2859
+ const activeMatch = useMemo3(() => {
2348
2860
  if (!searchStatus || searchStatus.selectedIndex < 0) return null;
2349
2861
  return searchResults[searchStatus.selectedIndex] ?? null;
2350
2862
  }, [searchResults, searchStatus]);
@@ -2387,14 +2899,18 @@ function useInlineSearch({
2387
2899
  }
2388
2900
 
2389
2901
  // src/components/ui/table/features/row-expand/row-expand.ts
2390
- import { useEffect as useEffect4, useMemo as useMemo2, useRef as useRef4 } from "react";
2902
+ import { useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4 } from "react";
2391
2903
  function getFieldValue(row, key) {
2392
2904
  return row[key];
2393
2905
  }
2394
2906
  function canExpandRow(row) {
2395
2907
  const children = row.children;
2396
- const level = row.level;
2397
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
2908
+ return Array.isArray(children) && children.length > 0;
2909
+ }
2910
+ function toTreeToggleKey(value) {
2911
+ if (value === null || value === void 0) return null;
2912
+ const key = String(value);
2913
+ return key.length > 0 ? key : null;
2398
2914
  }
2399
2915
  function toggleExpandedRowId(rowId, previous) {
2400
2916
  const next = new Set(previous);
@@ -2415,7 +2931,8 @@ var useConvertTreeData = ({
2415
2931
  preventExpand = false,
2416
2932
  startIndex = 1,
2417
2933
  expandedRows,
2418
- onExpandedRowsChange
2934
+ onExpandedRowsChange,
2935
+ autoExpandOnLoad = true
2419
2936
  }) => {
2420
2937
  const onExpandedRowsChangeRef = useRef4(onExpandedRowsChange);
2421
2938
  const hasInitializedRef = useRef4(false);
@@ -2428,16 +2945,33 @@ var useConvertTreeData = ({
2428
2945
  return;
2429
2946
  }
2430
2947
  if (!enabled || hasInitializedRef.current) return;
2431
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2432
- onExpandedRowsChangeRef.current?.(new Set(ids));
2433
2948
  hasInitializedRef.current = true;
2434
- }, [enabled, data, toggleField]);
2435
- const processedData = useMemo2(() => {
2949
+ if (!autoExpandOnLoad) return;
2950
+ const ids = /* @__PURE__ */ new Set();
2951
+ const collect = (items) => {
2952
+ for (const item of items) {
2953
+ if (!item || typeof item !== "object") continue;
2954
+ const record = item;
2955
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
2956
+ if (key) ids.add(key);
2957
+ const nested = record[flattenField];
2958
+ if (Array.isArray(nested)) collect(nested);
2959
+ }
2960
+ };
2961
+ collect(data);
2962
+ onExpandedRowsChangeRef.current?.(ids);
2963
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
2964
+ const processedData = useMemo4(() => {
2436
2965
  if (!enabled || !data || data.length === 0) return [];
2437
2966
  const flattenedData = [];
2438
- const flattenItems = (items) => {
2439
- items.forEach((item) => {
2440
- const newItem = { ...item };
2967
+ const flattenItems = (items, parentPath) => {
2968
+ items.forEach((item, itemIndex) => {
2969
+ if (!item || typeof item !== "object") return;
2970
+ const source = {
2971
+ path: [...parentPath, itemIndex],
2972
+ childrenField: flattenField
2973
+ };
2974
+ const newItem = { ...item, [TREE_SOURCE]: source };
2441
2975
  const nested = newItem[flattenField];
2442
2976
  if (Array.isArray(nested)) {
2443
2977
  const children = nested.map(
@@ -2451,89 +2985,68 @@ var useConvertTreeData = ({
2451
2985
  child[childField] = newItem[toggleField];
2452
2986
  }
2453
2987
  });
2454
- flattenItems(children);
2988
+ flattenItems(children, source.path);
2455
2989
  } else {
2456
2990
  flattenedData.push(newItem);
2457
2991
  }
2458
2992
  });
2459
2993
  };
2460
- flattenItems(data);
2994
+ flattenItems(data, []);
2461
2995
  const dataWithLevels = flattenedData.map((item) => ({
2462
2996
  ...item,
2463
2997
  level: 0,
2464
2998
  children: [],
2465
2999
  processed: false
2466
3000
  }));
2467
- const findNearestPrecedingParent = (index, parentKey) => {
2468
- for (let i = index - 1; i >= 0; i -= 1) {
2469
- const candidate = dataWithLevels[i];
2470
- if (!candidate) continue;
2471
- if (getFieldValue(candidate, toggleField) === parentKey) {
2472
- return candidate;
2473
- }
2474
- }
2475
- return void 0;
2476
- };
2477
3001
  const rootItems = [];
3002
+ const latestByKey = /* @__PURE__ */ new Map();
2478
3003
  dataWithLevels.forEach((item) => {
2479
- if (!getFieldValue(item, childField)) {
2480
- rootItems.push(item);
2481
- item.processed = true;
2482
- }
2483
- });
2484
- dataWithLevels.forEach((item, index) => {
2485
3004
  const parentKey = getFieldValue(item, childField);
2486
- if (!parentKey || item.processed) return;
2487
- const parent = findNearestPrecedingParent(index, parentKey);
3005
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2488
3006
  if (parent) {
2489
3007
  item.level = parent.level + 1;
2490
3008
  parent.children.push(item);
2491
- item.processed = true;
2492
- return;
3009
+ } else {
3010
+ rootItems.push(item);
2493
3011
  }
2494
- rootItems.push(item);
2495
3012
  item.processed = true;
3013
+ latestByKey.set(getFieldValue(item, toggleField), item);
2496
3014
  });
2497
3015
  return rootItems;
2498
3016
  }, [enabled, data, toggleField, childField, flattenField]);
2499
- const flattenTree = useMemo2(() => {
3017
+ const flattenTree = useMemo4(() => {
2500
3018
  if (!enabled) return [];
2501
- const flatten = (nodes, result = [], level = 0) => {
3019
+ const flatten = (nodes, result, parentTreeNo) => {
2502
3020
  nodes.forEach((node, index) => {
2503
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
3021
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2504
3022
  const toggleValue = getFieldValue(node, toggleField);
2505
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3023
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2506
3024
  result.push({
2507
3025
  ...node,
2508
3026
  treeNo: currentIndex,
2509
3027
  uniqueId,
2510
3028
  processed: true
2511
3029
  });
2512
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
3030
+ const toggleKey = toTreeToggleKey(toggleValue);
3031
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
2513
3032
  if (shouldExpandChildren) {
2514
- flatten(node.children, result, index + startIndex);
3033
+ flatten(node.children, result, currentIndex);
2515
3034
  }
2516
3035
  });
2517
3036
  return result;
2518
3037
  };
2519
- const flattenedData = flatten(processedData, [], 0);
2520
- flattenedData.forEach((item, index) => {
3038
+ const flattenedData = flatten(processedData, [], null);
3039
+ const latestByKey = /* @__PURE__ */ new Map();
3040
+ flattenedData.forEach((item) => {
2521
3041
  const parentKey = getFieldValue(item, childField);
2522
3042
  if (!parentKey) {
2523
3043
  item.parentCount = 1;
2524
- return;
2525
- }
2526
- let parentItem;
2527
- for (let i = index - 1; i >= 0; i -= 1) {
2528
- const candidate = flattenedData[i];
2529
- if (!candidate) continue;
2530
- if (getFieldValue(candidate, toggleField) === parentKey) {
2531
- parentItem = candidate;
2532
- break;
2533
- }
3044
+ } else {
3045
+ const parentItem = latestByKey.get(parentKey);
3046
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3047
+ item.parentCount = parentAmount || 1;
2534
3048
  }
2535
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2536
- item.parentCount = parentAmount || 1;
3049
+ latestByKey.set(getFieldValue(item, toggleField), item);
2537
3050
  });
2538
3051
  return flattenedData;
2539
3052
  }, [
@@ -2546,22 +3059,11 @@ var useConvertTreeData = ({
2546
3059
  preventExpand,
2547
3060
  expandedRows
2548
3061
  ]);
2549
- const sortedData = useMemo2(() => {
3062
+ const sortedData = useMemo4(() => {
2550
3063
  if (!enabled) {
2551
3064
  return data ?? [];
2552
3065
  }
2553
- return [...flattenTree].sort((a, b) => {
2554
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2555
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2556
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2557
- const aVal = aParts[i] || 0;
2558
- const bVal = bParts[i] || 0;
2559
- if (aVal !== bVal) {
2560
- return aVal - bVal;
2561
- }
2562
- }
2563
- return 0;
2564
- });
3066
+ return flattenTree;
2565
3067
  }, [enabled, data, flattenTree]);
2566
3068
  return sortedData;
2567
3069
  };
@@ -2619,13 +3121,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2619
3121
  for (let index = 0; index < data.length; index++) {
2620
3122
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2621
3123
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2622
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3124
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2623
3125
  result.push({ rowSpan: 0, isFirstInGroup: false });
2624
3126
  continue;
2625
3127
  }
2626
3128
  let span = 1;
2627
3129
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2628
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3130
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2629
3131
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2630
3132
  span++;
2631
3133
  }
@@ -2718,6 +3220,9 @@ function collectRowSpanColumns(columns) {
2718
3220
  }
2719
3221
 
2720
3222
  // src/core/useGlideTable.ts
3223
+ function isProductionBuild() {
3224
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3225
+ }
2721
3226
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2722
3227
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2723
3228
  function useGlideTable(options) {
@@ -2739,18 +3244,24 @@ function useGlideTable(options) {
2739
3244
  selectOnRowClick = true,
2740
3245
  enableCellSelection = true,
2741
3246
  onDataChange,
2742
- onCellChange,
2743
- onBatchChange,
3247
+ onCellChange: onCellChangeProp,
3248
+ onBatchChange: onBatchChangeProp,
2744
3249
  cellRenderers,
2745
3250
  preserveRowSelection = false,
2746
- toggleField,
2747
- childField,
2748
- flattenField,
3251
+ toggleField: toggleFieldProp,
3252
+ idField,
3253
+ childField: childFieldProp,
3254
+ parentIdField,
3255
+ flattenField: flattenFieldProp,
3256
+ childrenField,
2749
3257
  qtyField,
3258
+ expandColumn,
2750
3259
  expandedRows: controlledExpandedRows,
2751
3260
  onExpandedRowsChange,
2752
3261
  preventExpand = false,
3262
+ autoExpandOnLoad = true,
2753
3263
  enableSubtreeCopy,
3264
+ escapeCopyFormulas = false,
2754
3265
  onCopyActionsReady,
2755
3266
  onRowsPaste,
2756
3267
  enableInsertPaste,
@@ -2771,9 +3282,28 @@ function useGlideTable(options) {
2771
3282
  onSearchValueChange,
2772
3283
  onSearchClose,
2773
3284
  searchResults,
2774
- onSearchResultsChanged
3285
+ onSearchResultsChanged,
3286
+ enableWasdNavigation = true
2775
3287
  } = options;
2776
- const labels = useMemo3(() => {
3288
+ const toggleField = toggleFieldProp ?? idField;
3289
+ const childField = childFieldProp ?? parentIdField;
3290
+ const flattenField = flattenFieldProp ?? childrenField;
3291
+ const onCellChange = useMemo5(() => {
3292
+ if (onCellChangeProp) return onCellChangeProp;
3293
+ if (!onBatchChangeProp) return void 0;
3294
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
3295
+ }, [onBatchChangeProp, onCellChangeProp]);
3296
+ const onBatchChange = useMemo5(() => {
3297
+ if (onBatchChangeProp) return onBatchChangeProp;
3298
+ if (!onCellChangeProp) return void 0;
3299
+ return (changes) => {
3300
+ for (const change of changes) {
3301
+ onCellChangeProp(change.rowId, change.columnId, change.value);
3302
+ }
3303
+ };
3304
+ }, [onBatchChangeProp, onCellChangeProp]);
3305
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
3306
+ const labels = useMemo5(() => {
2777
3307
  const resolved = resolveDataTableLabels(labelsProp);
2778
3308
  return {
2779
3309
  ...resolved,
@@ -2790,11 +3320,11 @@ function useGlideTable(options) {
2790
3320
  const [internalExpandedRows, setInternalExpandedRows] = useState4(
2791
3321
  () => /* @__PURE__ */ new Set()
2792
3322
  );
2793
- const [hoveredRowIndex, setHoveredRowIndex] = useState4(null);
3323
+ const [hoverStore] = useState4(createRowHoverStore);
2794
3324
  const scrollRef = useRef5(null);
2795
3325
  const rootRef = useRef5(null);
2796
3326
  const escapeDismissOwnerRef = useRef5(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
2797
- const cellRendererRegistry = useMemo3(
3327
+ const cellRendererRegistry = useMemo5(
2798
3328
  () => createCellRendererRegistry(cellRenderers),
2799
3329
  [cellRenderers]
2800
3330
  );
@@ -2813,7 +3343,7 @@ function useGlideTable(options) {
2813
3343
  );
2814
3344
  const columnSizing = controlledColumnSizing ?? internalColumnSizing;
2815
3345
  const columnOrder = controlledColumnOrder ?? internalColumnOrder;
2816
- const tableColumns = useMemo3(() => {
3346
+ const tableColumns = useMemo5(() => {
2817
3347
  if (!enableColumnReorder) return columns;
2818
3348
  return applyLeafColumnOrder(columns, columnOrder);
2819
3349
  }, [columnOrder, columns, enableColumnReorder]);
@@ -2847,8 +3377,10 @@ function useGlideTable(options) {
2847
3377
  qtyField,
2848
3378
  expandedRows,
2849
3379
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2850
- preventExpand
3380
+ preventExpand,
3381
+ autoExpandOnLoad
2851
3382
  });
3383
+ const sourceData = useMemo5(() => data ?? [], [data]);
2852
3384
  const table = useReactTable({
2853
3385
  data: tableData,
2854
3386
  columns: tableColumns,
@@ -2887,15 +3419,19 @@ function useGlideTable(options) {
2887
3419
  );
2888
3420
  },
2889
3421
  getCoreRowModel: getCoreRowModel(),
2890
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
3422
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
3423
+ // Tree rows: their path in the original data, which (unlike the
3424
+ // flattened index) survives expanding/collapsing rows above.
3425
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
3426
+ )
2891
3427
  });
2892
- const rowSpanColumnKeys = useMemo3(() => {
3428
+ const rowSpanColumnKeys = useMemo5(() => {
2893
3429
  if (!enableRowSpan) return [];
2894
3430
  return collectRowSpanColumns(columns);
2895
3431
  }, [enableRowSpan, columns]);
2896
3432
  const primaryRowSpanKey = rowSpanColumnKeys[0]?.rowSpanKey;
2897
3433
  const primaryRowSpanColumnId = rowSpanColumnKeys[0]?.columnId;
2898
- const columnRowSpanMap = useMemo3(
3434
+ const columnRowSpanMap = useMemo5(
2899
3435
  () => buildColumnRowSpanMap(tableData, rowSpanColumnKeys),
2900
3436
  [tableData, rowSpanColumnKeys]
2901
3437
  );
@@ -2904,7 +3440,21 @@ function useGlideTable(options) {
2904
3440
  const rows = table.getRowModel().rows;
2905
3441
  const columnCount = table.getAllLeafColumns().length || 1;
2906
3442
  const visibleLeafColumns = table.getVisibleLeafColumns();
2907
- const columnFreezeOffsets = useMemo3(() => {
3443
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
3444
+ const warnedBooleanColumnsRef = useRef5(/* @__PURE__ */ new Set());
3445
+ useEffect5(() => {
3446
+ if (!hasWriteCallback || isProductionBuild()) return;
3447
+ for (const column of visibleLeafColumns) {
3448
+ const meta = column.columnDef.meta;
3449
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
3450
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
3451
+ warnedBooleanColumnsRef.current.add(column.id);
3452
+ console.warn(
3453
+ `[react-glide-table] Column "${column.id}" (kind "boolean") has no \`editable\` prop, so its checkbox writes on click. Set editable={true} to keep that, or editable={false} for a read-only checkbox. A future major release will make boolean cells read-only unless editable is set, like other cells.`
3454
+ );
3455
+ }
3456
+ }, [hasWriteCallback, visibleLeafColumns]);
3457
+ const columnFreezeOffsets = useMemo5(() => {
2908
3458
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
2909
3459
  return buildColumnFreezeOffsets(
2910
3460
  visibleLeafColumns.map((column) => ({
@@ -2924,7 +3474,7 @@ function useGlideTable(options) {
2924
3474
  const totalSize = rowVirtualizer.getTotalSize();
2925
3475
  const paddingTop = virtualRows.length > 0 ? virtualRows[0]?.start ?? 0 : 0;
2926
3476
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0) : 0;
2927
- const selectedRowIndices = useMemo3(() => {
3477
+ const selectedRowIndices = useMemo5(() => {
2928
3478
  const indices = /* @__PURE__ */ new Set();
2929
3479
  for (const selectedRow of selectedRows) {
2930
3480
  indices.add(selectedRow.index);
@@ -2946,7 +3496,7 @@ function useGlideTable(options) {
2946
3496
  const cell = scrollElement.querySelector(
2947
3497
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
2948
3498
  );
2949
- if (cell instanceof HTMLElement) {
3499
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
2950
3500
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
2951
3501
  }
2952
3502
  };
@@ -2964,6 +3514,10 @@ function useGlideTable(options) {
2964
3514
  },
2965
3515
  [scrollCellIntoView]
2966
3516
  );
3517
+ const editKeyRef = useRef5(() => {
3518
+ });
3519
+ const clearKeyRef = useRef5(() => {
3520
+ });
2967
3521
  const {
2968
3522
  dragState,
2969
3523
  activeSelectionBounds,
@@ -2971,20 +3525,27 @@ function useGlideTable(options) {
2971
3525
  handleCellMouseEnter,
2972
3526
  handleFillHandleMouseDown,
2973
3527
  clearSelection: clearCellSelection,
2974
- copySelection
3528
+ copySelection,
3529
+ selectCell,
3530
+ focusSelection
2975
3531
  } = useCellSelection({
2976
- data: tableData,
3532
+ data: sourceData,
2977
3533
  rows,
2978
3534
  enabled: enableCellSelection,
2979
3535
  columnCount: visibleLeafColumns.length,
3536
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
2980
3537
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3538
+ escapeCopyFormulas,
2981
3539
  enableInsertPaste: enableInsertPaste ?? true,
2982
3540
  onDataChange,
2983
3541
  onBatchChange,
2984
3542
  onRowsPaste,
2985
3543
  onCellNavigate: handleCellNavigate,
2986
3544
  cellRendererRegistry,
2987
- rootRef
3545
+ rootRef,
3546
+ enableWasdNavigation,
3547
+ onEditKey: (position) => editKeyRef.current(position),
3548
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
2988
3549
  });
2989
3550
  const clearRowSelection = useCallback4(() => {
2990
3551
  if (rowSelectionMode === "none") return;
@@ -3005,22 +3566,79 @@ function useGlideTable(options) {
3005
3566
  const {
3006
3567
  editingCell,
3007
3568
  draftValue,
3569
+ draftInvalid,
3570
+ setDraftInvalid,
3008
3571
  setDraftValue,
3009
3572
  startEdit,
3010
3573
  commitEdit,
3011
3574
  cancelEdit
3012
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
3575
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
3576
+ editKeyRef.current = (position) => {
3577
+ startEdit(position.row, position.col);
3578
+ };
3579
+ clearKeyRef.current = (bounds) => {
3580
+ const changes = [];
3581
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
3582
+ const row = rows[rowIndex];
3583
+ if (!row) continue;
3584
+ const cells = row.getVisibleCells();
3585
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
3586
+ const cell = cells[colIndex];
3587
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
3588
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
3589
+ }
3590
+ }
3591
+ if (changes.length === 0) return;
3592
+ if (onBatchChange) {
3593
+ onBatchChange(changes);
3594
+ return;
3595
+ }
3596
+ if (!onDataChange) return;
3597
+ let next = sourceData;
3598
+ for (const change of changes) {
3599
+ const row = rows.find((item) => item.id === change.rowId);
3600
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
3601
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
3602
+ if (!row || !accessorKey) continue;
3603
+ next = applyCellChangesToData(next, [
3604
+ { original: row.original, index: row.index, accessorKey, value: null }
3605
+ ]);
3606
+ }
3607
+ if (next !== sourceData) onDataChange(next);
3608
+ };
3609
+ const commitEditAndMove = useCallback4(
3610
+ (raw, delta) => {
3611
+ const current = editingCell;
3612
+ if (!commitEdit(raw)) return false;
3613
+ if (current) {
3614
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
3615
+ }
3616
+ rootRef.current?.focus({ preventScroll: true });
3617
+ return true;
3618
+ },
3619
+ [commitEdit, editingCell, selectCell]
3620
+ );
3621
+ const cancelEditAndRefocus = useCallback4(() => {
3622
+ cancelEdit();
3623
+ rootRef.current?.focus({ preventScroll: true });
3624
+ }, [cancelEdit]);
3013
3625
  const commitRenderedCellValue = useCallback4(
3014
- (rowId, columnId, value) => commitCellValue({
3015
- data: tableData,
3016
- rows,
3017
- rowId,
3018
- columnId,
3019
- value,
3020
- onCellChange,
3021
- onDataChange
3022
- }),
3023
- [onCellChange, onDataChange, rows, tableData]
3626
+ (rowId, columnId, value) => {
3627
+ const columnDef = table.getColumn(columnId)?.columnDef;
3628
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
3629
+ return false;
3630
+ }
3631
+ return commitCellValue({
3632
+ data: sourceData,
3633
+ rows,
3634
+ rowId,
3635
+ columnId,
3636
+ value,
3637
+ onCellChange,
3638
+ onDataChange
3639
+ });
3640
+ },
3641
+ [onCellChange, onDataChange, rows, sourceData, table]
3024
3642
  );
3025
3643
  const getCellContext = useCallback4(
3026
3644
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3048,27 +3666,14 @@ function useGlideTable(options) {
3048
3666
  (row, index) => {
3049
3667
  if (getRowId) return getRowId(row, index);
3050
3668
  if (enableExpand) {
3051
- const record = row;
3052
- const idValue = record.id;
3053
- if (idValue != null && String(idValue).length > 0) {
3054
- return String(idValue);
3055
- }
3056
- const uniqueId = record.uniqueId;
3057
- if (uniqueId != null && String(uniqueId).length > 0) {
3058
- return String(uniqueId);
3059
- }
3060
- if (toggleField) {
3061
- const toggleValue = record[toggleField];
3062
- if (toggleValue != null && String(toggleValue).length > 0) {
3063
- return String(toggleValue);
3064
- }
3065
- }
3669
+ const treeKey = getTreeRowKey(row);
3670
+ if (treeKey) return treeKey;
3066
3671
  }
3067
3672
  return String(index);
3068
3673
  },
3069
- [enableExpand, getRowId, toggleField]
3674
+ [enableExpand, getRowId]
3070
3675
  );
3071
- const searchCorpus = useMemo3(() => {
3676
+ const searchCorpus = useMemo5(() => {
3072
3677
  if (!enableInlineSearch) return [];
3073
3678
  if (enableExpand && toggleField) {
3074
3679
  return buildTreeSearchCorpus(tableData, {
@@ -3086,35 +3691,66 @@ function useGlideTable(options) {
3086
3691
  ]);
3087
3692
  const searchCorpusRef = useRef5(searchCorpus);
3088
3693
  searchCorpusRef.current = searchCorpus;
3089
- const visibleRowIndexById = useMemo3(() => {
3694
+ const visibleRowIndexById = useMemo5(() => {
3090
3695
  const map = /* @__PURE__ */ new Map();
3091
3696
  for (const row of rows) {
3092
3697
  map.set(resolveSearchRowId(row.original, row.index), row.index);
3093
3698
  }
3094
3699
  return map;
3095
3700
  }, [resolveSearchRowId, rows]);
3096
- const getSearchCellValue = useCallback4(
3097
- (rowIndex, colIndex) => {
3098
- const corpusRow = searchCorpusRef.current[rowIndex];
3099
- const column = visibleLeafColumns[colIndex];
3100
- if (!corpusRow || !column) return void 0;
3701
+ const readSearchRawValue = useCallback4(
3702
+ (corpusRow, rowIndex, column) => {
3101
3703
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3102
3704
  if (visibleIndex !== void 0) {
3103
3705
  const visibleRow = rows[visibleIndex];
3104
3706
  if (visibleRow) {
3105
- return visibleRow.getValue(column.id);
3707
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3106
3708
  }
3107
3709
  }
3108
3710
  const columnDef = column.columnDef;
3109
3711
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3110
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3712
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3111
3713
  }
3112
3714
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3113
- return corpusRow.data[String(columnDef.accessorKey)];
3715
+ return {
3716
+ value: corpusRow.data[String(columnDef.accessorKey)],
3717
+ row: void 0
3718
+ };
3719
+ }
3720
+ return { value: corpusRow.data[column.id], row: void 0 };
3721
+ },
3722
+ [rows, visibleRowIndexById]
3723
+ );
3724
+ const getSearchCellValue = useCallback4(
3725
+ (rowIndex, colIndex) => {
3726
+ const corpusRow = searchCorpusRef.current[rowIndex];
3727
+ const column = visibleLeafColumns[colIndex];
3728
+ if (!corpusRow || !column) return void 0;
3729
+ if (isProtectedColumn(column.columnDef)) return void 0;
3730
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
3731
+ const meta = column.columnDef.meta;
3732
+ const searchValue2 = meta?.searchValue;
3733
+ if (!searchValue2 || searchValue2 === "value") return value;
3734
+ const ctx = {
3735
+ value,
3736
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
3737
+ index: row?.index ?? rowIndex,
3738
+ columnId: column.id,
3739
+ cellProps: meta?.cellProps,
3740
+ update: () => {
3741
+ }
3742
+ };
3743
+ try {
3744
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
3745
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
3746
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
3747
+ if (renderer) return reactNodeToText(renderer.render(ctx));
3748
+ } catch {
3749
+ return value;
3114
3750
  }
3115
- return corpusRow.data[column.id];
3751
+ return value;
3116
3752
  },
3117
- [rows, visibleLeafColumns, visibleRowIndexById]
3753
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3118
3754
  );
3119
3755
  const pendingSearchNavRef = useRef5(null);
3120
3756
  const focusSearchResult = useCallback4(
@@ -3165,11 +3801,19 @@ function useGlideTable(options) {
3165
3801
  focusSearchResult(pending.colIndex, visibleRowIndex);
3166
3802
  }, [focusSearchResult, rows, visibleRowIndexById]);
3167
3803
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
3804
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
3805
+ const searchContentKey = useMemo5(
3806
+ () => ({ data: sourceData, columns: searchColumnSignature }),
3807
+ [sourceData, searchColumnSignature]
3808
+ );
3168
3809
  const inlineSearch = useInlineSearch({
3169
3810
  enabled: enableInlineSearch,
3170
3811
  rowCount: searchCorpus.length,
3171
3812
  columnCount: visibleLeafColumns.length,
3172
3813
  getCellValue: getSearchCellValue,
3814
+ // Re-scan when the rows' content/order or the column order changes
3815
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
3816
+ contentKey: searchContentKey,
3173
3817
  initialStartRow: initialSearchStartRow,
3174
3818
  showSearch,
3175
3819
  searchValue,
@@ -3180,7 +3824,7 @@ function useGlideTable(options) {
3180
3824
  onNavigateToResult: navigateToCorpusSearchResult,
3181
3825
  rootRef
3182
3826
  });
3183
- const visibleSearchMatchKeys = useMemo3(() => {
3827
+ const visibleSearchMatchKeys = useMemo5(() => {
3184
3828
  if (!enableInlineSearch) return EMPTY_SEARCH_MATCH_KEYS;
3185
3829
  return mapSearchResultsToVisibleKeys(
3186
3830
  inlineSearch.searchResults,
@@ -3193,7 +3837,7 @@ function useGlideTable(options) {
3193
3837
  searchCorpus,
3194
3838
  visibleRowIndexById
3195
3839
  ]);
3196
- const visibleActiveMatch = useMemo3(() => {
3840
+ const visibleActiveMatch = useMemo5(() => {
3197
3841
  if (!enableInlineSearch || !inlineSearch.activeMatch) return null;
3198
3842
  return mapSearchResultToVisibleItem(
3199
3843
  inlineSearch.activeMatch,
@@ -3207,11 +3851,14 @@ function useGlideTable(options) {
3207
3851
  visibleRowIndexById
3208
3852
  ]);
3209
3853
  const clearHover = useCallback4(() => {
3210
- setHoveredRowIndex(null);
3211
- }, []);
3212
- const handleRowHover = useCallback4((rowIndex, _rowData) => {
3213
- setHoveredRowIndex(rowIndex);
3214
- }, []);
3854
+ hoverStore.setHoveredRowIndex(null);
3855
+ }, [hoverStore]);
3856
+ const handleRowHover = useCallback4(
3857
+ (rowIndex, _rowData) => {
3858
+ hoverStore.setHoveredRowIndex(rowIndex);
3859
+ },
3860
+ [hoverStore]
3861
+ );
3215
3862
  const handleToggleSelect = useCallback4(
3216
3863
  (row) => {
3217
3864
  if (!row.getCanSelect()) return;
@@ -3229,14 +3876,14 @@ function useGlideTable(options) {
3229
3876
  },
3230
3877
  [preventExpand, handleExpandedRowsChange, expandedRows]
3231
3878
  );
3232
- const rowContextValue = useMemo3(() => {
3879
+ const rowContextValue = useMemo5(() => {
3233
3880
  return {
3234
3881
  rowSpan: {
3235
3882
  enableRowSpan,
3236
3883
  primaryRowSpanKey,
3237
3884
  primaryRowSpanColumnId,
3238
3885
  columnRowSpanMap,
3239
- hoveredRowIndex,
3886
+ hoverStore,
3240
3887
  selectedRowIndices,
3241
3888
  onRowHover: handleRowHover
3242
3889
  },
@@ -3250,6 +3897,7 @@ function useGlideTable(options) {
3250
3897
  enableCellSelection,
3251
3898
  activeSelectionBounds,
3252
3899
  dragState,
3900
+ canFill,
3253
3901
  onCellMouseDown: handleCellMouseDownWithCommit,
3254
3902
  onCellMouseEnter: handleCellMouseEnter,
3255
3903
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3257,18 +3905,23 @@ function useGlideTable(options) {
3257
3905
  cellEdit: {
3258
3906
  editingCell,
3259
3907
  draftValue,
3908
+ draftInvalid,
3909
+ onDraftInvalidChange: setDraftInvalid,
3260
3910
  onDraftValueChange: setDraftValue,
3261
3911
  onStartEdit: startEdit,
3262
3912
  onCommitEdit: commitEdit,
3263
- onCancelEdit: cancelEdit
3913
+ onCommitEditAndMove: commitEditAndMove,
3914
+ onCancelEdit: cancelEditAndRefocus
3264
3915
  },
3265
3916
  cellRender: {
3266
3917
  registry: cellRendererRegistry,
3267
- commitValue: commitRenderedCellValue
3918
+ commitValue: commitRenderedCellValue,
3919
+ protectedLabel: labels.protectedCell
3268
3920
  },
3269
3921
  expand: {
3270
3922
  enableExpand,
3271
3923
  toggleField,
3924
+ expandColumn,
3272
3925
  expandedRows,
3273
3926
  preventExpand,
3274
3927
  onToggleExpand: handleToggleExpand,
@@ -3293,7 +3946,7 @@ function useGlideTable(options) {
3293
3946
  primaryRowSpanKey,
3294
3947
  primaryRowSpanColumnId,
3295
3948
  columnRowSpanMap,
3296
- hoveredRowIndex,
3949
+ hoverStore,
3297
3950
  selectedRowIndices,
3298
3951
  handleRowHover,
3299
3952
  rowSelectionMode,
@@ -3303,19 +3956,25 @@ function useGlideTable(options) {
3303
3956
  enableCellSelection,
3304
3957
  activeSelectionBounds,
3305
3958
  dragState,
3959
+ canFill,
3306
3960
  handleCellMouseDownWithCommit,
3307
3961
  handleCellMouseEnter,
3308
3962
  handleFillHandleMouseDown,
3309
3963
  editingCell,
3310
3964
  draftValue,
3965
+ draftInvalid,
3966
+ setDraftInvalid,
3311
3967
  setDraftValue,
3312
3968
  startEdit,
3313
3969
  commitEdit,
3314
- cancelEdit,
3970
+ commitEditAndMove,
3971
+ cancelEditAndRefocus,
3315
3972
  cellRendererRegistry,
3316
3973
  commitRenderedCellValue,
3974
+ labels.protectedCell,
3317
3975
  enableExpand,
3318
3976
  toggleField,
3977
+ expandColumn,
3319
3978
  expandedRows,
3320
3979
  preventExpand,
3321
3980
  handleToggleExpand,
@@ -3363,6 +4022,7 @@ function useGlideTable(options) {
3363
4022
  handleToggleSelect,
3364
4023
  clearHover,
3365
4024
  setColumnOrder,
4025
+ handleRootFocus: focusSelection,
3366
4026
  copySelection: stableCopySelection,
3367
4027
  inlineSearch: {
3368
4028
  showSearch: inlineSearch.showSearch,
@@ -3419,12 +4079,16 @@ function ResolvedTableCell({
3419
4079
  },
3420
4080
  [cellRender, columnId, row.id]
3421
4081
  );
4082
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
4083
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
4084
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
4085
+ }
3422
4086
  const ctx = {
3423
4087
  value,
3424
4088
  row,
3425
4089
  index: row.index,
3426
4090
  columnId,
3427
- cellProps: meta?.cellProps,
4091
+ cellProps,
3428
4092
  update
3429
4093
  };
3430
4094
  if (meta?.cellRender) {
@@ -3789,11 +4453,15 @@ function useColumnReorder(options) {
3789
4453
 
3790
4454
  // src/components/ui/table/components/DataTable/DataTable.tsx
3791
4455
  import { flexRender as flexRender2 } from "@tanstack/react-table";
3792
- import { useEffect as useEffect8, useMemo as useMemo4, useState as useState6 } from "react";
4456
+ import { useEffect as useEffect8, useLayoutEffect, useMemo as useMemo6, useState as useState6 } from "react";
3793
4457
 
3794
4458
  // src/components/ui/table/components/DataTable/DataTableRow.tsx
3795
4459
  import { flexRender } from "@tanstack/react-table";
3796
- import { useEffect as useEffect7, useRef as useRef7 } from "react";
4460
+ import {
4461
+ useEffect as useEffect7,
4462
+ useRef as useRef7,
4463
+ useSyncExternalStore
4464
+ } from "react";
3797
4465
 
3798
4466
  // src/components/ui/table/components/icons.tsx
3799
4467
  import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
@@ -3961,7 +4629,11 @@ function blurActiveElementOutside(container) {
3961
4629
  if (container instanceof Node && container.contains(active)) return;
3962
4630
  active.blur();
3963
4631
  }
3964
- function resolveExpandCellIndex(cells, toggleField) {
4632
+ function resolveExpandCellIndex(cells, toggleField, expandColumn) {
4633
+ if (expandColumn) {
4634
+ const explicitIndex = cells.findIndex((cell) => cell.column.id === expandColumn);
4635
+ if (explicitIndex >= 0) return explicitIndex;
4636
+ }
3965
4637
  if (!toggleField) return 0;
3966
4638
  const matchedIndex = cells.findIndex(
3967
4639
  (cell) => cell.column.id === toggleField
@@ -4004,7 +4676,7 @@ function DataTableRow({
4004
4676
  enableRowSpan,
4005
4677
  primaryRowSpanColumnId,
4006
4678
  columnRowSpanMap,
4007
- hoveredRowIndex,
4679
+ hoverStore,
4008
4680
  selectedRowIndices,
4009
4681
  onRowHover
4010
4682
  } = rowSpan;
@@ -4013,6 +4685,7 @@ function DataTableRow({
4013
4685
  enableCellSelection,
4014
4686
  activeSelectionBounds,
4015
4687
  dragState,
4688
+ canFill = true,
4016
4689
  onCellMouseDown,
4017
4690
  onCellMouseEnter,
4018
4691
  onFillHandleMouseDown
@@ -4020,9 +4693,12 @@ function DataTableRow({
4020
4693
  const {
4021
4694
  editingCell,
4022
4695
  draftValue,
4696
+ draftInvalid = false,
4697
+ onDraftInvalidChange,
4023
4698
  onDraftValueChange,
4024
4699
  onStartEdit,
4025
4700
  onCommitEdit,
4701
+ onCommitEditAndMove,
4026
4702
  onCancelEdit
4027
4703
  } = cellEdit;
4028
4704
  const renderCell = (tableCell) => flexRender(
@@ -4032,6 +4708,7 @@ function DataTableRow({
4032
4708
  const {
4033
4709
  enableExpand,
4034
4710
  toggleField,
4711
+ expandColumn,
4035
4712
  expandedRows,
4036
4713
  preventExpand,
4037
4714
  onToggleExpand,
@@ -4040,13 +4717,50 @@ function DataTableRow({
4040
4717
  } = expand;
4041
4718
  const rowIndex = row.index;
4042
4719
  const rowData = row.original;
4043
- const isRowHovered = hoveredRowIndex === rowIndex;
4044
4720
  const isRowSelected = row.getIsSelected();
4045
4721
  const { startRow: primaryGroupStart, rowSpan: primaryGroupSpan } = resolveRowSpanAt(
4046
4722
  primaryRowSpanColumnId ? columnRowSpanMap.get(primaryRowSpanColumnId) : void 0,
4047
4723
  rowIndex
4048
4724
  );
4049
- const isGroupHovered = enableRowSpan && hoveredRowIndex !== null && hoveredRowIndex >= primaryGroupStart && hoveredRowIndex <= primaryGroupStart + primaryGroupSpan - 1;
4725
+ const isRowHovered2 = useSyncExternalStore(
4726
+ hoverStore.subscribe,
4727
+ () => isRowHovered(hoverStore.getHoveredRowIndex(), rowIndex),
4728
+ () => false
4729
+ );
4730
+ const isGroupHovered = useSyncExternalStore(
4731
+ hoverStore.subscribe,
4732
+ () => isRowGroupHovered(
4733
+ hoverStore.getHoveredRowIndex(),
4734
+ enableRowSpan,
4735
+ primaryGroupStart,
4736
+ primaryGroupSpan
4737
+ ),
4738
+ () => false
4739
+ );
4740
+ const rowSpanColumnIds = enableRowSpan ? [...columnRowSpanMap.keys()].filter((id) => id !== primaryRowSpanColumnId) : [];
4741
+ const nestedRowSpanRanges = rowSpanColumnIds.map((columnId) => {
4742
+ const { startRow, rowSpan: span } = resolveRowSpanAt(
4743
+ columnRowSpanMap.get(columnId),
4744
+ rowIndex
4745
+ );
4746
+ return { columnId, startRow, span };
4747
+ });
4748
+ const nestedHoverSignature = useSyncExternalStore(
4749
+ hoverStore.subscribe,
4750
+ () => {
4751
+ const hovered = hoverStore.getHoveredRowIndex();
4752
+ return nestedRowSpanRanges.map(
4753
+ ({ startRow, span }) => isRowGroupHovered(hovered, true, startRow, span) ? "1" : "0"
4754
+ ).join("");
4755
+ },
4756
+ () => rowSpanColumnIds.map(() => "0").join("")
4757
+ );
4758
+ const nestedHoverByColumn = new Map(
4759
+ rowSpanColumnIds.map((columnId, index) => [
4760
+ columnId,
4761
+ nestedHoverSignature[index] === "1"
4762
+ ])
4763
+ );
4050
4764
  const visibleCells = row.getVisibleCells();
4051
4765
  const columnIdsByIndex = visibleCells.map((cell) => cell.column.id);
4052
4766
  row.getIsCellDragSelected = (columnId) => {
@@ -4092,12 +4806,13 @@ function DataTableRow({
4092
4806
  span
4093
4807
  );
4094
4808
  } : void 0;
4095
- const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField) : -1;
4809
+ const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField, expandColumn) : -1;
4096
4810
  const canExpand = enableExpand && !preventExpand && canExpandRow(rowData);
4097
4811
  const expandKey = toggleField && rowData[toggleField] !== null && rowData[toggleField] !== void 0 ? String(rowData[toggleField]) : null;
4098
4812
  const isExpanded = expandKey !== null && Boolean(expandedRows?.has(expandKey));
4099
4813
  const rowLevel = typeof rowData.level === "number" ? rowData.level : 0;
4100
4814
  const editInputRef = useRef7(null);
4815
+ const cellPressRef = useRef7(false);
4101
4816
  const isRowEditing = editingCell?.rowIndex === rowIndex;
4102
4817
  useEffect7(() => {
4103
4818
  if (!isRowEditing) return;
@@ -4110,23 +4825,29 @@ function DataTableRow({
4110
4825
  ref: measureElement,
4111
4826
  "data-index": virtualIndex,
4112
4827
  "data-selected": isRowSelected ? "" : void 0,
4113
- "data-hovered": isRowHovered || isGroupHovered ? "" : void 0,
4828
+ "data-hovered": isRowHovered2 || isGroupHovered ? "" : void 0,
4114
4829
  "data-expandable": enableExpand && canExpand ? "" : void 0,
4115
4830
  "data-expanded": isExpanded ? "" : void 0,
4831
+ "data-level": enableExpand ? rowLevel : void 0,
4116
4832
  className: cn(
4117
4833
  "DataTableRowJSX",
4118
4834
  !enableRowSpan && ROW_HOVER_CLASS,
4119
- enableRowSpan && isRowHovered && !isRowSelected && ROW_HOVERED_BG_CLASS,
4835
+ enableRowSpan && isRowHovered2 && !isRowSelected && ROW_HOVERED_BG_CLASS,
4120
4836
  isRowSelected && "is-selected",
4121
4837
  enableExpand && canExpand && "is-expandable",
4122
4838
  classNames?.row,
4123
4839
  getRowClassName?.(rowData, rowIndex)
4124
4840
  ),
4125
4841
  onMouseEnter: () => onRowHover(rowIndex, rowData),
4842
+ onMouseDownCapture: () => {
4843
+ cellPressRef.current = false;
4844
+ },
4126
4845
  onClick: () => {
4846
+ const startedCellSelection = cellPressRef.current;
4847
+ cellPressRef.current = false;
4127
4848
  if (isRowEditing) return;
4128
4849
  onRowClick?.(rowData, rowIndex);
4129
- if (rowSelectionMode !== "none" && selectOnRowClick) {
4850
+ if (rowSelectionMode !== "none" && selectOnRowClick && !startedCellSelection) {
4130
4851
  onToggleSelect();
4131
4852
  }
4132
4853
  },
@@ -4149,8 +4870,8 @@ function DataTableRow({
4149
4870
  }
4150
4871
  const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === cellIndex;
4151
4872
  const cellRowSpan = rowSpanInfo?.rowSpan ?? 1;
4152
- const isMergedCellHovered = hoveredRowIndex !== null && hoveredRowIndex >= rowIndex && hoveredRowIndex <= rowIndex + cellRowSpan - 1;
4153
- const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered;
4873
+ const isMergedCellHovered = columnId === primaryRowSpanColumnId ? isGroupHovered : nestedHoverByColumn.get(columnId) ?? false;
4874
+ const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered2;
4154
4875
  let isMergedCellSelected = false;
4155
4876
  if (isRowSpanColumn) {
4156
4877
  for (let r = rowIndex; r < rowIndex + cellRowSpan; r += 1) {
@@ -4172,7 +4893,7 @@ function DataTableRow({
4172
4893
  activeSelectionBounds,
4173
4894
  cellRowSpan
4174
4895
  );
4175
- const isBottomRightCell = !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4896
+ const isBottomRightCell = canFill && !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4176
4897
  const spanRowHeights = enableCellSelection && activeSelectionBounds && isCellDragSelected && cellRowSpan > 1 ? measureMergedSpanRowHeights(rowIndex, cellRowSpan) : void 0;
4177
4898
  const selectionEdgeStyle = getCellSelectionEdgeStyle(
4178
4899
  rowIndex,
@@ -4230,6 +4951,7 @@ function DataTableRow({
4230
4951
  if (isInteractiveMouseTarget(event.target)) return;
4231
4952
  event.preventDefault();
4232
4953
  blurActiveElementOutside(event.currentTarget);
4954
+ cellPressRef.current = true;
4233
4955
  onCellMouseDown(
4234
4956
  resolveCellRowIndex(event.clientY, event.currentTarget),
4235
4957
  cellIndex,
@@ -4283,6 +5005,8 @@ function DataTableRow({
4283
5005
  ref: editInputRef,
4284
5006
  type: editType === "number" ? "number" : "text",
4285
5007
  defaultValue: draftValue,
5008
+ "aria-invalid": draftInvalid ? true : void 0,
5009
+ "data-invalid": draftInvalid ? "" : void 0,
4286
5010
  className: cn(
4287
5011
  "cell-edit-input",
4288
5012
  CELL_ALIGN_CLASS[align],
@@ -4291,6 +5015,7 @@ function DataTableRow({
4291
5015
  ),
4292
5016
  onChange: (event) => {
4293
5017
  editInputProps?.onChange?.(event);
5018
+ onDraftInvalidChange?.(Boolean(event.target.validity?.badInput));
4294
5019
  onDraftValueChange(event.target.value);
4295
5020
  },
4296
5021
  onMouseDown: (event) => {
@@ -4304,9 +5029,22 @@ function DataTableRow({
4304
5029
  onKeyDown: (event) => {
4305
5030
  editInputProps?.onKeyDown?.(event);
4306
5031
  if (event.defaultPrevented) return;
4307
- if (event.key === "Enter") {
5032
+ if (event.nativeEvent.isComposing || event.keyCode === 229) {
5033
+ return;
5034
+ }
5035
+ if (event.key === "Enter" || event.key === "Tab") {
4308
5036
  event.preventDefault();
4309
- onCommitEdit(event.currentTarget.value);
5037
+ if (event.currentTarget.validity?.badInput) {
5038
+ onDraftInvalidChange?.(true);
5039
+ return;
5040
+ }
5041
+ const delta = event.key === "Enter" ? { row: event.shiftKey ? -1 : 1, col: 0 } : { row: 0, col: event.shiftKey ? -1 : 1 };
5042
+ if (onCommitEditAndMove) {
5043
+ onCommitEditAndMove(event.currentTarget.value, delta);
5044
+ } else {
5045
+ onCommitEdit(event.currentTarget.value);
5046
+ }
5047
+ return;
4310
5048
  }
4311
5049
  if (event.key === "Escape") {
4312
5050
  event.preventDefault();
@@ -4316,6 +5054,10 @@ function DataTableRow({
4316
5054
  onBlur: (event) => {
4317
5055
  editInputProps?.onBlur?.(event);
4318
5056
  if (event.defaultPrevented) return;
5057
+ if (event.currentTarget.validity?.badInput) {
5058
+ onDraftInvalidChange?.(true);
5059
+ return;
5060
+ }
4319
5061
  onCommitEdit(event.currentTarget.value);
4320
5062
  }
4321
5063
  }
@@ -4327,6 +5069,7 @@ function DataTableRow({
4327
5069
  "expand-cell-content",
4328
5070
  classNames?.expandCellContent
4329
5071
  ),
5072
+ style: { "--table-row-level": rowLevel },
4330
5073
  children: [
4331
5074
  rowLevel > 0 && /* @__PURE__ */ jsx4(
4332
5075
  "span",
@@ -4356,6 +5099,7 @@ function DataTableRow({
4356
5099
  {
4357
5100
  type: "button",
4358
5101
  "aria-label": isExpanded ? collapseRowLabel : expandRowLabel,
5102
+ "aria-expanded": isExpanded,
4359
5103
  className: cn(
4360
5104
  "expand-toggle-button",
4361
5105
  classNames?.expandToggle
@@ -4442,6 +5186,7 @@ function DataTableSearch({
4442
5186
  previousLabel,
4443
5187
  nextLabel,
4444
5188
  closeLabel,
5189
+ formatResult = formatSearchResultLabel,
4445
5190
  rowsTotal,
4446
5191
  classNames,
4447
5192
  onSearchValueChange,
@@ -4450,9 +5195,10 @@ function DataTableSearch({
4450
5195
  onPrevious
4451
5196
  }) {
4452
5197
  if (!showSearch) return null;
4453
- const resultString = searchStatus ? formatSearchResultLabel(searchStatus) : resultHint;
5198
+ const resultString = searchStatus ? formatResult(searchStatus) : resultHint;
4454
5199
  const progress = rowsTotal > 0 ? Math.floor((searchStatus?.rowsSearched ?? 0) / rowsTotal * 100) : 0;
4455
5200
  const handleKeyDown = (event) => {
5201
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
4456
5202
  if ((event.ctrlKey || event.metaKey) && event.code === "KeyF" || event.key === "Escape") {
4457
5203
  event.preventDefault();
4458
5204
  event.stopPropagation();
@@ -4576,6 +5322,7 @@ function DataTableToolbar({
4576
5322
  summary,
4577
5323
  selectedCount,
4578
5324
  selectionLabel,
5325
+ countLabel,
4579
5326
  toolbar,
4580
5327
  className,
4581
5328
  classNames
@@ -4589,7 +5336,7 @@ function DataTableToolbar({
4589
5336
  if (!hasLeftContent && !hasToolbar && !hasSelectionContent) return null;
4590
5337
  return /* @__PURE__ */ jsxs5("div", { className: cn("DataTableToolbarJSX", classNames?.toolbar, className), children: [
4591
5338
  /* @__PURE__ */ jsxs5("div", { className: cn("toolbar-left", classNames?.toolbarLeft), children: [
4592
- hasCount && /* @__PURE__ */ jsx6("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ jsxs5(Fragment, { children: [
5339
+ hasCount && /* @__PURE__ */ jsx6("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: countLabel ? countLabel(displayFiltered, totalCount) : displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ jsxs5(Fragment, { children: [
4593
5340
  /* @__PURE__ */ jsx6("span", { className: "toolbar-count-primary", children: displayFiltered }),
4594
5341
  /* @__PURE__ */ jsxs5("span", { className: "toolbar-count-placeholder", children: [
4595
5342
  " / ",
@@ -4716,7 +5463,8 @@ function DataTable({
4716
5463
  handleToggleSelect,
4717
5464
  clearHover,
4718
5465
  setColumnOrder,
4719
- inlineSearch
5466
+ inlineSearch,
5467
+ handleRootFocus
4720
5468
  } = useGlideTable(glideOptions);
4721
5469
  const ToolbarSlot = slots?.Toolbar ?? DataTableToolbar;
4722
5470
  const ScrollSlot = slots?.Scroll ?? DefaultScroll;
@@ -4750,7 +5498,7 @@ function DataTable({
4750
5498
  observer.observe(element);
4751
5499
  return () => observer.disconnect();
4752
5500
  }, [enableColumnResize, isPending, scrollRef, rows.length, leafColumnIds.join("|")]);
4753
- const layoutWidths = useMemo4(() => {
5501
+ const layoutWidths = useMemo6(() => {
4754
5502
  if (enableColumnResize) return void 0;
4755
5503
  const columns = table.getVisibleLeafColumns().map((column) => ({
4756
5504
  id: column.id,
@@ -4760,13 +5508,33 @@ function DataTable({
4760
5508
  }));
4761
5509
  return resolveColumnLayoutWidths(containerWidth, columns);
4762
5510
  }, [enableColumnResize, containerWidth, table, columnLayoutMetaSignature]);
4763
- const freezeOffsets = useMemo4(() => {
5511
+ const [measuredWidths, setMeasuredWidths] = useState6(
5512
+ () => /* @__PURE__ */ new Map()
5513
+ );
5514
+ useLayoutEffect(() => {
5515
+ if (!enableColumnFreeze || enableColumnResize) return;
5516
+ const element = scrollRef.current;
5517
+ if (!element) return;
5518
+ const next = /* @__PURE__ */ new Map();
5519
+ element.querySelectorAll("th[data-leaf-column-id]").forEach((th) => {
5520
+ const id = th.getAttribute("data-leaf-column-id");
5521
+ const width = th.getBoundingClientRect().width;
5522
+ if (id && width > 0) next.set(id, width);
5523
+ });
5524
+ setMeasuredWidths((previous) => {
5525
+ if (previous.size === next.size && [...next].every(([id, width]) => previous.get(id) === width)) {
5526
+ return previous;
5527
+ }
5528
+ return next;
5529
+ });
5530
+ });
5531
+ const freezeOffsets = useMemo6(() => {
4764
5532
  if (!enableColumnFreeze || enableColumnResize || !layoutWidths) {
4765
5533
  return rowContextValue.columnFreeze.offsets;
4766
5534
  }
4767
5535
  const columns = table.getVisibleLeafColumns().map((column) => ({
4768
5536
  id: column.id,
4769
- size: layoutWidths.get(column.id) ?? column.getSize(),
5537
+ size: measuredWidths.get(column.id) ?? layoutWidths.get(column.id) ?? column.getSize(),
4770
5538
  side: resolveColumnFreezeSide(column.columnDef.meta?.frozen)
4771
5539
  }));
4772
5540
  return buildColumnFreezeOffsets(columns);
@@ -4774,10 +5542,11 @@ function DataTable({
4774
5542
  enableColumnFreeze,
4775
5543
  enableColumnResize,
4776
5544
  layoutWidths,
5545
+ measuredWidths,
4777
5546
  rowContextValue.columnFreeze.offsets,
4778
5547
  table
4779
5548
  ]);
4780
- const contextValue = useMemo4(
5549
+ const contextValue = useMemo6(
4781
5550
  () => ({
4782
5551
  ...rowContextValue,
4783
5552
  classNames,
@@ -4806,6 +5575,10 @@ function DataTable({
4806
5575
  "div",
4807
5576
  {
4808
5577
  ref: rootRef,
5578
+ tabIndex: enableCellSelection ? 0 : void 0,
5579
+ onFocus: enableCellSelection ? (event) => {
5580
+ if (event.target === event.currentTarget) handleRootFocus();
5581
+ } : void 0,
4809
5582
  className: cn(
4810
5583
  "DataTableJSX",
4811
5584
  !enableCellSelection && "DataTableJSX--no-cell-selection",
@@ -4826,6 +5599,7 @@ function DataTable({
4826
5599
  summary,
4827
5600
  selectedCount,
4828
5601
  selectionLabel,
5602
+ countLabel: labels.count,
4829
5603
  toolbar,
4830
5604
  classNames
4831
5605
  }
@@ -4844,6 +5618,7 @@ function DataTable({
4844
5618
  previousLabel: labels.searchPrevious,
4845
5619
  nextLabel: labels.searchNext,
4846
5620
  closeLabel: labels.searchClose,
5621
+ formatResult: labels.searchResultCount,
4847
5622
  rowsTotal: inlineSearch.searchRowCount,
4848
5623
  classNames,
4849
5624
  onSearchValueChange: inlineSearch.setSearchValue,
@@ -4893,6 +5668,8 @@ function DataTable({
4893
5668
  (leafColumn) => isColumnReorderable(leafColumn.columnDef.meta)
4894
5669
  );
4895
5670
  const isDragging = draggingColumnId === header.column.id;
5671
+ const sortDirection = isPlaceholder ? void 0 : header.column.columnDef.meta?.sortDirection;
5672
+ const ariaSort = sortDirection === void 0 ? void 0 : sortDirection === "asc" ? "ascending" : sortDirection === "desc" ? "descending" : "none";
4896
5673
  const dropEdge = !isPlaceholder && dropTarget?.columnId === header.column.id ? dropTarget.edge : void 0;
4897
5674
  return /* @__PURE__ */ jsxs6(
4898
5675
  "th",
@@ -4908,7 +5685,8 @@ function DataTable({
4908
5685
  "data-resizing": header.column.getIsResizing() ? "" : void 0,
4909
5686
  "data-frozen": freezeOffset?.side,
4910
5687
  "data-freeze-edge": getColumnFreezeEdgeAttr(freezeOffset),
4911
- "aria-grabbed": isDragging ? true : void 0,
5688
+ "data-leaf-column-id": isLeafHeader ? header.column.id : void 0,
5689
+ "aria-sort": ariaSort,
4912
5690
  title: canDrag ? labels.reorderColumn : void 0,
4913
5691
  onPointerDown: enableColumnReorder ? (event) => onHeaderPointerDown(event, {
4914
5692
  columnId: header.column.id,
@@ -4935,7 +5713,31 @@ function DataTable({
4935
5713
  role: "separator",
4936
5714
  "aria-orientation": "vertical",
4937
5715
  "aria-label": labels.resizeColumn,
5716
+ "aria-valuenow": header.getSize(),
5717
+ tabIndex: 0,
4938
5718
  "data-table-disable-cell-selection": "",
5719
+ onKeyDown: (event) => {
5720
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {
5721
+ return;
5722
+ }
5723
+ event.preventDefault();
5724
+ event.stopPropagation();
5725
+ const step = event.shiftKey ? 50 : 10;
5726
+ const columnDef = header.column.columnDef;
5727
+ const min = columnDef.minSize ?? DATA_TABLE_COLUMN_MIN_SIZE;
5728
+ const max = columnDef.maxSize ?? DATA_TABLE_COLUMN_MAX_SIZE;
5729
+ const nextSize = Math.min(
5730
+ max,
5731
+ Math.max(
5732
+ min,
5733
+ header.getSize() + (event.key === "ArrowRight" ? step : -step)
5734
+ )
5735
+ );
5736
+ table.setColumnSizing((previous) => ({
5737
+ ...previous,
5738
+ [header.column.id]: nextSize
5739
+ }));
5740
+ },
4939
5741
  className: cn(
4940
5742
  "data-table-resize-handle",
4941
5743
  classNames?.resizeHandle
@@ -5043,16 +5845,21 @@ function DataTable({
5043
5845
  }
5044
5846
 
5045
5847
  // src/components/ui/table/components/Table/Table.tsx
5046
- import { useCallback as useCallback7, useMemo as useMemo5, useState as useState7 } from "react";
5848
+ import { useCallback as useCallback7, useMemo as useMemo7, useRef as useRef8, useState as useState7 } from "react";
5047
5849
 
5048
5850
  // src/components/ui/table/components/Table/buildColumnDef.tsx
5851
+ import { createContext as createContext2, use as use2 } from "react";
5049
5852
  import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
5853
+ var TableSortContext = createContext2(null);
5050
5854
  function SortableHeader({
5051
5855
  label,
5052
5856
  field,
5053
- sort,
5054
- onSort
5857
+ sort: sortProp,
5858
+ onSort: onSortProp
5055
5859
  }) {
5860
+ const context = use2(TableSortContext);
5861
+ const sort = context ? context.sort : sortProp;
5862
+ const onSort = context ? context.onSort : onSortProp;
5056
5863
  const isActive = sort?.field === field;
5057
5864
  const Icon = isActive ? sort.direction === "asc" ? ArrowUp : ArrowDown : ArrowUpDown;
5058
5865
  return /* @__PURE__ */ jsxs7(
@@ -5071,7 +5878,7 @@ function SortableHeader({
5071
5878
  }
5072
5879
  );
5073
5880
  }
5074
- function buildColumnDef(props, sort, onSort) {
5881
+ function buildColumnDef(props, sort, onSort, headerCache) {
5075
5882
  const {
5076
5883
  field,
5077
5884
  virtual = false,
@@ -5097,8 +5904,29 @@ function buildColumnDef(props, sort, onSort) {
5097
5904
  className,
5098
5905
  headerClassName,
5099
5906
  render,
5100
- copyValue
5907
+ copyValue,
5908
+ searchValue
5101
5909
  } = props;
5910
+ const createHeader = () => sortable ? () => /* @__PURE__ */ jsx8(
5911
+ SortableHeader,
5912
+ {
5913
+ label: children,
5914
+ field,
5915
+ sort,
5916
+ onSort
5917
+ }
5918
+ ) : (
5919
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
5920
+ () => children
5921
+ );
5922
+ const cached = headerCache?.get(field);
5923
+ let header;
5924
+ if (cached && cached.label === children && cached.sortable === sortable) {
5925
+ header = cached.render;
5926
+ } else {
5927
+ header = createHeader();
5928
+ headerCache?.set(field, { label: children, sortable, render: header });
5929
+ }
5102
5930
  return {
5103
5931
  id: field,
5104
5932
  ...!virtual ? { accessorKey: field } : {},
@@ -5106,18 +5934,7 @@ function buildColumnDef(props, sort, onSort) {
5106
5934
  ...minResizeWidth != null ? { minSize: minResizeWidth } : {},
5107
5935
  ...maxResizeWidth != null ? { maxSize: maxResizeWidth } : {},
5108
5936
  ...resizable === false ? { enableResizing: false } : {},
5109
- header: sortable ? () => /* @__PURE__ */ jsx8(
5110
- SortableHeader,
5111
- {
5112
- label: children,
5113
- field,
5114
- sort,
5115
- onSort
5116
- }
5117
- ) : (
5118
- // eslint-disable-next-line @typescript-eslint/promise-function-async
5119
- () => children
5120
- ),
5937
+ header,
5121
5938
  // eslint-disable-next-line @typescript-eslint/promise-function-async
5122
5939
  cell: (info) => /* @__PURE__ */ jsx8(ResolvedTableCell, { info }),
5123
5940
  meta: {
@@ -5132,6 +5949,8 @@ function buildColumnDef(props, sort, onSort) {
5132
5949
  cellProps,
5133
5950
  cellRender: render,
5134
5951
  copyValue,
5952
+ searchValue,
5953
+ sortDirection: sortable ? sort?.field === field ? sort.direction : false : void 0,
5135
5954
  frozen,
5136
5955
  reorderable,
5137
5956
  width,
@@ -5149,12 +5968,12 @@ function resolveGroupId(props, index) {
5149
5968
  }
5150
5969
  return `group:${index}`;
5151
5970
  }
5152
- function buildColumnDefsFromTree(nodes, sort, onSort) {
5971
+ function buildColumnDefsFromTree(nodes, sort, onSort, headerCache) {
5153
5972
  return nodes.map((node, index) => {
5154
5973
  if (node.type === "leaf") {
5155
- return buildColumnDef(node.props, sort, onSort);
5974
+ return buildColumnDef(node.props, sort, onSort, headerCache);
5156
5975
  }
5157
- const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort);
5976
+ const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort, headerCache);
5158
5977
  const { header, align, headerClassName } = node.props;
5159
5978
  return {
5160
5979
  id: resolveGroupId(node.props, index),
@@ -5290,13 +6109,22 @@ function TableColumnGroup(props) {
5290
6109
  TableColumnGroup.displayName = TABLE_COLUMN_GROUP_DISPLAY_NAME;
5291
6110
 
5292
6111
  // src/components/ui/table/components/Table/tableDataPipeline.ts
5293
- function sortTableData(data, sort) {
6112
+ function readField(row, field) {
6113
+ if (field in row || !field.includes(".")) return row[field];
6114
+ return field.split(".").reduce((current, key) => {
6115
+ if (current === null || current === void 0 || typeof current !== "object") {
6116
+ return void 0;
6117
+ }
6118
+ return current[key];
6119
+ }, row);
6120
+ }
6121
+ function sortTableData(data, sort, locale = "ko") {
5294
6122
  if (!sort) return data;
5295
6123
  const { field, direction } = sort;
5296
6124
  const multiplier = direction === "asc" ? 1 : -1;
5297
6125
  return [...data].sort((left, right) => {
5298
- const leftValue = left[field];
5299
- const rightValue = right[field];
6126
+ const leftValue = readField(left, field);
6127
+ const rightValue = readField(right, field);
5300
6128
  if ((leftValue === null || leftValue === void 0) && (rightValue === null || rightValue === void 0)) {
5301
6129
  return 0;
5302
6130
  }
@@ -5305,11 +6133,12 @@ function sortTableData(data, sort) {
5305
6133
  if (typeof leftValue === "number" && typeof rightValue === "number") {
5306
6134
  return (leftValue - rightValue) * multiplier;
5307
6135
  }
5308
- return String(leftValue).localeCompare(String(rightValue), "ko") * multiplier;
6136
+ return String(leftValue).localeCompare(String(rightValue), locale, { numeric: true }) * multiplier;
5309
6137
  });
5310
6138
  }
5311
6139
  function paginateTableData(data, page, pageSize) {
5312
- const safePage = Math.max(1, page);
6140
+ const lastPage = getTotalPages(data.length, pageSize);
6141
+ const safePage = Math.min(Math.max(1, page), lastPage);
5313
6142
  const start = (safePage - 1) * pageSize;
5314
6143
  return data.slice(start, start + pageSize);
5315
6144
  }
@@ -5317,6 +6146,36 @@ function getTotalPages(totalCount, pageSize) {
5317
6146
  if (pageSize <= 0) return 1;
5318
6147
  return Math.max(1, Math.ceil(totalCount / pageSize));
5319
6148
  }
6149
+ function buildTreeRootBlocks(data, fields, sort, locale) {
6150
+ const childrenByRow = /* @__PURE__ */ new Map();
6151
+ const roots = [];
6152
+ const latestById = /* @__PURE__ */ new Map();
6153
+ for (const row of data) {
6154
+ const parentKey = row[fields.parentIdField];
6155
+ const parent = parentKey !== null && parentKey !== void 0 && parentKey !== "" ? latestById.get(parentKey) : void 0;
6156
+ if (parent) {
6157
+ const siblings = childrenByRow.get(parent);
6158
+ if (siblings) siblings.push(row);
6159
+ else childrenByRow.set(parent, [row]);
6160
+ } else {
6161
+ roots.push(row);
6162
+ }
6163
+ latestById.set(row[fields.idField], row);
6164
+ }
6165
+ const appendSubtree = (row, out) => {
6166
+ out.push(row);
6167
+ const children = childrenByRow.get(row);
6168
+ if (!children) return;
6169
+ for (const child of sortTableData(children, sort, locale)) {
6170
+ appendSubtree(child, out);
6171
+ }
6172
+ };
6173
+ return sortTableData(roots, sort, locale).map((root) => {
6174
+ const block = [];
6175
+ appendSubtree(root, block);
6176
+ return block;
6177
+ });
6178
+ }
5320
6179
 
5321
6180
  // src/components/ui/table/components/Table/TableHeader.tsx
5322
6181
  function TableHeader(props) {
@@ -5332,7 +6191,9 @@ function TablePagination({
5332
6191
  pageSize = 10,
5333
6192
  totalCount = 0,
5334
6193
  onChange,
5335
- className
6194
+ className,
6195
+ previousLabel = "Previous page",
6196
+ nextLabel = "Next page"
5336
6197
  }) {
5337
6198
  const totalPages = getTotalPages(totalCount, pageSize);
5338
6199
  const safePage = Math.min(Math.max(1, page), totalPages);
@@ -5346,7 +6207,7 @@ function TablePagination({
5346
6207
  className: "pagination-button",
5347
6208
  disabled: !canGoPrev,
5348
6209
  onClick: () => onChange(safePage - 1),
5349
- "aria-label": "Previous page",
6210
+ "aria-label": previousLabel,
5350
6211
  children: /* @__PURE__ */ jsx9(ChevronLeft, { className: "pagination-button-icon" })
5351
6212
  }
5352
6213
  ),
@@ -5362,7 +6223,7 @@ function TablePagination({
5362
6223
  className: "pagination-button",
5363
6224
  disabled: !canGoNext,
5364
6225
  onClick: () => onChange(safePage + 1),
5365
- "aria-label": "Next page",
6226
+ "aria-label": nextLabel,
5366
6227
  children: /* @__PURE__ */ jsx9(ChevronRight, { className: "pagination-button-icon" })
5367
6228
  }
5368
6229
  )
@@ -5376,63 +6237,124 @@ function TableRoot({
5376
6237
  data,
5377
6238
  children,
5378
6239
  className,
6240
+ classNames,
5379
6241
  totalCount,
5380
6242
  filteredCount,
6243
+ onDataChange,
6244
+ getRowId,
6245
+ sort: controlledSort,
6246
+ defaultSort = null,
6247
+ onSortChange,
6248
+ sortLocale,
5381
6249
  ...dataTableProps
5382
6250
  }) {
5383
- const { header, pagination: paginationElement } = useMemo5(
6251
+ const { header, pagination: paginationElement } = useMemo7(
5384
6252
  () => parseTableChildren(children),
5385
6253
  [children]
5386
6254
  );
5387
- const [sort, setSort] = useState7(null);
5388
- const handleSort = useCallback7((field) => {
5389
- setSort((previous) => {
5390
- if (previous?.field !== field) {
5391
- return { field, direction: "asc" };
5392
- }
5393
- if (previous.direction === "asc") {
5394
- return { field, direction: "desc" };
6255
+ const [internalSort, setInternalSort] = useState7(defaultSort);
6256
+ const sort = controlledSort !== void 0 ? controlledSort : internalSort;
6257
+ const handleSort = useCallback7(
6258
+ (field) => {
6259
+ let next;
6260
+ if (sort?.field !== field) {
6261
+ next = { field, direction: "asc" };
6262
+ } else if (sort.direction === "asc") {
6263
+ next = { field, direction: "desc" };
6264
+ } else {
6265
+ next = null;
5395
6266
  }
5396
- return null;
5397
- });
5398
- }, []);
5399
- const columnTree = useMemo5(() => extractColumnTree(header), [header]);
5400
- const columns = useMemo5(
5401
- () => buildColumnDefsFromTree(columnTree, sort, handleSort),
6267
+ if (controlledSort === void 0) setInternalSort(next);
6268
+ onSortChange?.(next);
6269
+ },
6270
+ [controlledSort, onSortChange, sort]
6271
+ );
6272
+ const columnTree = useMemo7(() => extractColumnTree(header), [header]);
6273
+ const headerCacheRef = useRef8(/* @__PURE__ */ new Map());
6274
+ const columns = useMemo7(
6275
+ () => buildColumnDefsFromTree(columnTree, sort, handleSort, headerCacheRef.current),
5402
6276
  [columnTree, sort, handleSort]
5403
6277
  );
6278
+ const sortContextValue = useMemo7(() => ({ sort, onSort: handleSort }), [sort, handleSort]);
5404
6279
  const paginationProps = paginationElement?.props;
5405
6280
  const pageSize = paginationProps?.pageSize ?? 10;
5406
6281
  const page = paginationProps?.page ?? 1;
5407
6282
  const resolvedTotalCount = paginationProps?.totalCount ?? totalCount ?? data.length;
5408
- const tableData = useMemo5(() => {
5409
- const sortedData = sortTableData(data, sort);
5410
- if (!paginationProps) return sortedData;
6283
+ const isManualPagination = Boolean(paginationProps?.manual);
6284
+ const treeIdField = dataTableProps.toggleField ?? dataTableProps.idField;
6285
+ const isTree = Boolean(treeIdField);
6286
+ const treeParentIdField = dataTableProps.childField ?? dataTableProps.parentIdField ?? DEFAULT_TREE_PARENT_ID_FIELD;
6287
+ const treeBlocks = useMemo7(() => {
6288
+ if (!isTree || !treeIdField) return null;
6289
+ if (!sort && (!paginationProps || isManualPagination)) return null;
6290
+ return buildTreeRootBlocks(
6291
+ data,
6292
+ { idField: treeIdField, parentIdField: treeParentIdField },
6293
+ sort,
6294
+ sortLocale
6295
+ );
6296
+ }, [data, isManualPagination, isTree, paginationProps, sort, sortLocale, treeIdField, treeParentIdField]);
6297
+ const pageTotalCount = paginationProps?.totalCount ?? totalCount ?? (treeBlocks ? treeBlocks.length : data.length);
6298
+ const tableData = useMemo7(() => {
6299
+ if (treeBlocks) {
6300
+ const blocks = !paginationProps || isManualPagination ? treeBlocks : paginateTableData(treeBlocks, page, pageSize);
6301
+ return blocks.flat();
6302
+ }
6303
+ const sortedData = sortTableData(data, sort, sortLocale);
6304
+ if (!paginationProps || isManualPagination) return sortedData;
5411
6305
  return paginateTableData(sortedData, page, pageSize);
5412
- }, [data, sort, paginationProps, page, pageSize]);
6306
+ }, [treeBlocks, data, sort, sortLocale, paginationProps, isManualPagination, page, pageSize]);
6307
+ const originalIndexByRow = useMemo7(() => {
6308
+ const map = /* @__PURE__ */ new Map();
6309
+ data.forEach((row, index) => map.set(row, index));
6310
+ return map;
6311
+ }, [data]);
6312
+ const resolvedGetRowId = useMemo7(() => {
6313
+ if (getRowId) return getRowId;
6314
+ if (isTree) return void 0;
6315
+ return (row, index) => String(originalIndexByRow.get(row) ?? index);
6316
+ }, [isTree, getRowId, originalIndexByRow]);
6317
+ const handleDataChange = useMemo7(() => {
6318
+ if (!onDataChange) return void 0;
6319
+ return (next) => {
6320
+ const merged = data.slice();
6321
+ tableData.forEach((row, index) => {
6322
+ const nextRow = next[index];
6323
+ if (nextRow === void 0 || nextRow === row) return;
6324
+ const originalIndex = originalIndexByRow.get(row);
6325
+ if (originalIndex !== void 0) merged[originalIndex] = nextRow;
6326
+ });
6327
+ onDataChange(merged);
6328
+ };
6329
+ }, [data, onDataChange, originalIndexByRow, tableData]);
5413
6330
  if (countLeafColumns(columnTree) === 0) {
5414
6331
  console.warn("[Table] Declare at least one Table.Column inside Table.Header.");
5415
6332
  }
5416
- return /* @__PURE__ */ jsxs9("div", { className: "TableJSX", children: [
5417
- /* @__PURE__ */ jsx10(
6333
+ return /* @__PURE__ */ jsxs9("div", { className: cn("TableJSX", classNames?.tableRoot), children: [
6334
+ /* @__PURE__ */ jsx10(TableSortContext, { value: sortContextValue, children: /* @__PURE__ */ jsx10(
5418
6335
  DataTable,
5419
6336
  {
5420
6337
  ...dataTableProps,
6338
+ classNames,
6339
+ getRowId: resolvedGetRowId,
6340
+ onDataChange: handleDataChange,
5421
6341
  data: tableData,
5422
6342
  columns,
5423
6343
  totalCount: paginationProps ? resolvedTotalCount : totalCount,
5424
6344
  filteredCount: filteredCount ?? data.length,
5425
6345
  className: cn(className, paginationProps && "DataTableJSX--with-pagination")
5426
6346
  }
5427
- ),
6347
+ ) }),
5428
6348
  paginationProps && /* @__PURE__ */ jsx10(
5429
6349
  TablePagination,
5430
6350
  {
5431
6351
  page,
5432
6352
  pageSize,
5433
- totalCount: resolvedTotalCount,
6353
+ totalCount: pageTotalCount,
5434
6354
  onChange: paginationProps.onChange,
5435
- className: paginationProps.className
6355
+ className: cn(classNames?.pagination, paginationProps.className),
6356
+ previousLabel: paginationProps.previousLabel ?? dataTableProps.labels?.paginationPrevious,
6357
+ nextLabel: paginationProps.nextLabel ?? dataTableProps.labels?.paginationNext
5436
6358
  }
5437
6359
  )
5438
6360
  ] });
@@ -5505,6 +6427,7 @@ export {
5505
6427
  createSearchRegex,
5506
6428
  createTable,
5507
6429
  escapeSearchRegex,
6430
+ escapeSpreadsheetFormula,
5508
6431
  flattenSubtreeRows,
5509
6432
  formatCellValue,
5510
6433
  formatDefaultCellValue,