react-glide-table 2.3.5 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.cjs CHANGED
@@ -53,6 +53,7 @@ __export(core_exports, {
53
53
  createCellRendererRegistry: () => createCellRendererRegistry,
54
54
  createSearchRegex: () => createSearchRegex,
55
55
  escapeSearchRegex: () => escapeSearchRegex,
56
+ escapeSpreadsheetFormula: () => escapeSpreadsheetFormula,
56
57
  flattenSubtreeRows: () => flattenSubtreeRows,
57
58
  formatCellValue: () => formatCellValue,
58
59
  formatDefaultCellValue: () => formatDefaultCellValue,
@@ -103,6 +104,163 @@ __export(core_exports, {
103
104
  });
104
105
  module.exports = __toCommonJS(core_exports);
105
106
 
107
+ // src/components/ui/table/features/inline-search/inlineSearch.ts
108
+ var INLINE_SEARCH_MAX_RESULTS = 1e3;
109
+ var INLINE_SEARCH_TARGET_TICK_MS = 10;
110
+ var INLINE_SEARCH_INITIAL_STRIDE = 10;
111
+ function escapeSearchRegex(value) {
112
+ return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
113
+ }
114
+ function createSearchRegex(query) {
115
+ const trimmed = query.trim();
116
+ if (!trimmed) return null;
117
+ return new RegExp(escapeSearchRegex(trimmed), "i");
118
+ }
119
+ function cellValueToSearchText(value) {
120
+ if (value == null) return void 0;
121
+ if (typeof value === "string") return value;
122
+ if (typeof value === "number" || typeof value === "boolean") {
123
+ return String(value);
124
+ }
125
+ if (Array.isArray(value)) {
126
+ return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
127
+ }
128
+ if (typeof value === "object") {
129
+ try {
130
+ return JSON.stringify(value);
131
+ } catch {
132
+ return String(value);
133
+ }
134
+ }
135
+ return String(value);
136
+ }
137
+ function formatSearchResultLabel(status) {
138
+ const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
139
+ if (status.selectedIndex >= 0 && status.results > 0) {
140
+ return `${status.selectedIndex + 1} of ${countLabel}`;
141
+ }
142
+ return countLabel;
143
+ }
144
+ function nextSearchIndex(selectedIndex, results) {
145
+ if (results <= 0) return -1;
146
+ if (selectedIndex < 0) return 0;
147
+ return (selectedIndex + 1) % results;
148
+ }
149
+ function previousSearchIndex(selectedIndex, results) {
150
+ if (results <= 0) return -1;
151
+ if (selectedIndex < 0) return results - 1;
152
+ let next = (selectedIndex - 1) % results;
153
+ if (next < 0) next += results;
154
+ return next;
155
+ }
156
+ function buildSearchMatchKey(colIndex, rowIndex) {
157
+ return `${colIndex}:${rowIndex}`;
158
+ }
159
+ function buildSearchMatchKeys(results) {
160
+ const keys = /* @__PURE__ */ new Set();
161
+ for (const [colIndex, rowIndex] of results) {
162
+ keys.add(buildSearchMatchKey(colIndex, rowIndex));
163
+ }
164
+ return keys;
165
+ }
166
+ function collectSearchMatchesInRange(options) {
167
+ const {
168
+ query,
169
+ startRow,
170
+ rowCount,
171
+ columnCount,
172
+ getCellValue,
173
+ maxResults = INLINE_SEARCH_MAX_RESULTS
174
+ } = options;
175
+ const regex = createSearchRegex(query);
176
+ if (!regex || rowCount <= 0 || columnCount <= 0) return [];
177
+ const matches = [];
178
+ for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
179
+ const rowIndex = startRow + rowOffset;
180
+ for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
181
+ const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
182
+ if (text !== void 0 && regex.test(text)) {
183
+ matches.push([colIndex, rowIndex]);
184
+ if (matches.length >= maxResults) {
185
+ return matches;
186
+ }
187
+ }
188
+ }
189
+ }
190
+ return matches;
191
+ }
192
+ function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
193
+ const rounded = Math.max(elapsedMs, 1);
194
+ const scalar = targetMs / rounded;
195
+ return Math.max(1, Math.ceil(currentStride * scalar));
196
+ }
197
+ function buildFlatSearchCorpus(rows, getRowId) {
198
+ return rows.map((data, index) => ({
199
+ id: getRowId(data, index),
200
+ data,
201
+ ancestorToggleKeys: []
202
+ }));
203
+ }
204
+ function buildTreeSearchCorpus(visibleRows, options) {
205
+ const { toggleField, getRowId } = options;
206
+ const corpus = [];
207
+ const seen = /* @__PURE__ */ new Set();
208
+ const walk = (node, ancestorToggleKeys) => {
209
+ const id = getRowId(node, corpus.length);
210
+ if (seen.has(id)) return;
211
+ seen.add(id);
212
+ corpus.push({
213
+ id,
214
+ data: node,
215
+ ancestorToggleKeys
216
+ });
217
+ const children = node.children;
218
+ if (!Array.isArray(children) || children.length === 0) return;
219
+ const toggleValue = node[toggleField];
220
+ const toggleKey = toggleValue === null || toggleValue === void 0 ? "" : String(toggleValue);
221
+ const childAncestors = toggleKey.length > 0 ? [...ancestorToggleKeys, toggleKey] : ancestorToggleKeys;
222
+ for (const child of children) {
223
+ if (child && typeof child === "object") {
224
+ walk(child, childAncestors);
225
+ }
226
+ }
227
+ };
228
+ for (const row of visibleRows) {
229
+ const level = row.level;
230
+ if (level === 0 || level === void 0) {
231
+ walk(row, []);
232
+ }
233
+ }
234
+ for (const row of visibleRows) {
235
+ const id = getRowId(row, corpus.length);
236
+ if (seen.has(id)) continue;
237
+ walk(row, []);
238
+ }
239
+ return corpus;
240
+ }
241
+ function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
242
+ const keys = /* @__PURE__ */ new Set();
243
+ for (const [colIndex, corpusRowIndex] of results) {
244
+ const corpusRow = corpus[corpusRowIndex];
245
+ if (!corpusRow) continue;
246
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
247
+ if (visibleRowIndex === void 0) continue;
248
+ keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
249
+ }
250
+ return keys;
251
+ }
252
+ function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
253
+ const [colIndex, corpusRowIndex] = item;
254
+ const corpusRow = corpus[corpusRowIndex];
255
+ if (!corpusRow) return null;
256
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
257
+ if (visibleRowIndex === void 0) return null;
258
+ return [colIndex, visibleRowIndex];
259
+ }
260
+ function collectAncestorKeysToExpand(corpusRow, expandedRows) {
261
+ return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
262
+ }
263
+
106
264
  // src/core/labels.ts
107
265
  var DEFAULT_DATA_TABLE_LABELS = {
108
266
  empty: "No data",
@@ -116,7 +274,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
116
274
  searchResultHint: "Type to search",
117
275
  searchPrevious: "Previous result",
118
276
  searchNext: "Next result",
119
- searchClose: "Close search"
277
+ searchClose: "Close search",
278
+ searchResultCount: formatSearchResultLabel,
279
+ protectedCell: "protected",
280
+ paginationPrevious: "Previous page",
281
+ paginationNext: "Next page"
120
282
  };
121
283
  function resolveDataTableLabels(partial) {
122
284
  return {
@@ -147,6 +309,61 @@ var DATA_TABLE_COLUMN_REORDER_THRESHOLD = 4;
147
309
  // src/components/ui/table/features/cell-edit/useCellEdit.ts
148
310
  var import_react = require("react");
149
311
 
312
+ // src/components/ui/table/features/data-patch/dataPatch.ts
313
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
314
+ function getTreeSource(row) {
315
+ if (!row || typeof row !== "object") return void 0;
316
+ return row[TREE_SOURCE];
317
+ }
318
+ function getTreeRowKey(row) {
319
+ const source = getTreeSource(row);
320
+ if (!source) return void 0;
321
+ return `tree:${source.path.join(".")}`;
322
+ }
323
+ function setValueAtAccessor(record, accessorKey, value) {
324
+ if (!accessorKey.includes(".") || accessorKey in record) {
325
+ return { ...record, [accessorKey]: value };
326
+ }
327
+ const [head, ...rest] = accessorKey.split(".");
328
+ const current = record[head];
329
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
330
+ return {
331
+ ...record,
332
+ [head]: setValueAtAccessor(child, rest.join("."), value)
333
+ };
334
+ }
335
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
336
+ const [head, ...rest] = path;
337
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
338
+ const node = nodes[head];
339
+ if (!node || typeof node !== "object") return null;
340
+ const record = node;
341
+ let nextNode;
342
+ if (rest.length === 0) {
343
+ nextNode = setValueAtAccessor(record, accessorKey, value);
344
+ } else {
345
+ const children = record[childrenField];
346
+ if (!Array.isArray(children)) return null;
347
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
348
+ if (!nextChildren) return null;
349
+ nextNode = { ...record, [childrenField]: nextChildren };
350
+ }
351
+ const next = nodes.slice();
352
+ next[head] = nextNode;
353
+ return next;
354
+ }
355
+ function applyCellChangesToData(data, changes) {
356
+ let next = data;
357
+ for (const change of changes) {
358
+ const source = getTreeSource(change.original);
359
+ const path = source ? source.path : [change.index];
360
+ const childrenField = source?.childrenField ?? "";
361
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
362
+ if (patched) next = patched;
363
+ }
364
+ return next === data ? data.slice() : next;
365
+ }
366
+
150
367
  // src/components/ui/table/features/cell-edit/cellEdit.ts
151
368
  function getColumnAccessorKey(columnDef) {
152
369
  if (columnDef.accessorKey !== void 0 && columnDef.accessorKey !== null) {
@@ -154,7 +371,11 @@ function getColumnAccessorKey(columnDef) {
154
371
  }
155
372
  return columnDef.id;
156
373
  }
374
+ function isProtectedColumn(columnDef) {
375
+ return columnDef.meta?.kind === "protected";
376
+ }
157
377
  function isColumnEditable(columnDef) {
378
+ if (isProtectedColumn(columnDef)) return false;
158
379
  return Boolean(columnDef.meta?.editable);
159
380
  }
160
381
  function getColumnEditType(columnDef) {
@@ -187,10 +408,11 @@ function applyCellEdit(data, rows, rowIndex, colIndex, raw) {
187
408
  if (!accessorKey) return null;
188
409
  const parsed = parseCellEditValue(raw, getColumnEditType(columnDef));
189
410
  if (!parsed.ok) return null;
190
- const newData = data.map((row) => ({ ...row }));
191
- if (!newData[rowIndex]) return null;
192
- newData[rowIndex][accessorKey] = parsed.value;
193
- return newData;
411
+ const row = rows[rowIndex];
412
+ if (!row) return null;
413
+ return applyCellChangesToData(data, [
414
+ { original: row.original, index: row.index, accessorKey, value: parsed.value }
415
+ ]);
194
416
  }
195
417
 
196
418
  // src/components/ui/table/features/cell-render/commitCellValue.ts
@@ -214,12 +436,12 @@ function commitCellValue({
214
436
  if (!cell) return false;
215
437
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
216
438
  if (!accessorKey) return false;
217
- const dataIndex = row.index;
218
- if (dataIndex < 0 || dataIndex >= data.length) return false;
219
- const next = data.map((item) => ({ ...item }));
220
- const target = next[dataIndex];
221
- if (!target) return false;
222
- target[accessorKey] = value;
439
+ const next = applyCellChangesToData(data, [
440
+ { original: row.original, index: row.index, accessorKey, value }
441
+ ]);
442
+ if (next === data || next.every((item, index) => item === data[index])) {
443
+ return false;
444
+ }
223
445
  onDataChange?.(next);
224
446
  return true;
225
447
  }
@@ -231,19 +453,36 @@ function useCellEdit({
231
453
  onDataChange,
232
454
  onCellChange
233
455
  }) {
234
- const [editingCell, setEditingCell] = (0, import_react.useState)(null);
456
+ const [editingKey, setEditingKey] = (0, import_react.useState)(null);
235
457
  const [draftValue, setDraftValue] = (0, import_react.useState)("");
236
458
  const draftValueRef = (0, import_react.useRef)(draftValue);
237
- const editingCellRef = (0, import_react.useRef)(editingCell);
459
+ const [draftInvalid, setDraftInvalidState] = (0, import_react.useState)(false);
460
+ const draftInvalidRef = (0, import_react.useRef)(false);
461
+ const setDraftInvalid = (0, import_react.useCallback)((invalid) => {
462
+ draftInvalidRef.current = invalid;
463
+ setDraftInvalidState(invalid);
464
+ }, []);
238
465
  (0, import_react.useEffect)(() => {
239
466
  draftValueRef.current = draftValue;
240
467
  }, [draftValue]);
468
+ const editingCell = (0, import_react.useMemo)(
469
+ () => resolveEditingCell(rows, editingKey),
470
+ [rows, editingKey]
471
+ );
472
+ const editingCellRef = (0, import_react.useRef)(editingCell);
473
+ editingCellRef.current = editingCell;
241
474
  (0, import_react.useEffect)(() => {
242
- editingCellRef.current = editingCell;
243
- }, [editingCell]);
475
+ if (editingKey && !editingCell) {
476
+ setEditingKey(null);
477
+ setDraftValue("");
478
+ }
479
+ }, [editingCell, editingKey]);
244
480
  const cancelEdit = (0, import_react.useCallback)(() => {
245
- setEditingCell(null);
481
+ editingCellRef.current = null;
482
+ setEditingKey(null);
246
483
  setDraftValue("");
484
+ draftInvalidRef.current = false;
485
+ setDraftInvalidState(false);
247
486
  }, []);
248
487
  const commitEdit = (0, import_react.useCallback)(
249
488
  (raw) => {
@@ -263,6 +502,7 @@ function useCellEdit({
263
502
  cancelEdit();
264
503
  return true;
265
504
  }
505
+ if (draftInvalidRef.current) return false;
266
506
  const value = raw ?? draftValueRef.current;
267
507
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
268
508
  if (!parsed.ok) return false;
@@ -283,13 +523,15 @@ function useCellEdit({
283
523
  );
284
524
  const startEdit = (0, import_react.useCallback)(
285
525
  (rowIndex, colIndex) => {
286
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
287
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
526
+ const row = rows[rowIndex];
527
+ const cell = row?.getVisibleCells()[colIndex];
528
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
529
+ if (!isTextEditableValue(cell.getValue())) return;
288
530
  const current = editingCellRef.current;
289
531
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
290
532
  return;
291
533
  }
292
- setEditingCell({ rowIndex, colIndex });
534
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
293
535
  setDraftValue(getCellEditDraftValue(cell.getValue()));
294
536
  },
295
537
  [commitEdit, rows]
@@ -297,12 +539,55 @@ function useCellEdit({
297
539
  return {
298
540
  editingCell,
299
541
  draftValue,
542
+ draftInvalid,
543
+ setDraftInvalid,
300
544
  setDraftValue,
301
545
  startEdit,
302
546
  commitEdit,
303
547
  cancelEdit
304
548
  };
305
549
  }
550
+ function resolveEditingCell(rows, key) {
551
+ if (!key) return null;
552
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
553
+ if (rowIndex < 0) return null;
554
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
555
+ if (colIndex < 0) return null;
556
+ return { rowIndex, colIndex };
557
+ }
558
+ function isTextEditableValue(value) {
559
+ return value === null || value === void 0 || typeof value !== "object";
560
+ }
561
+
562
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
563
+ function formatObjectValue(value) {
564
+ const text = value.text ?? value.label ?? value.name ?? value.title;
565
+ if (text != null && text !== "") {
566
+ return formatCellValue(text);
567
+ }
568
+ try {
569
+ return JSON.stringify(value);
570
+ } catch {
571
+ return "";
572
+ }
573
+ }
574
+ function formatCellValue(value) {
575
+ if (value === null || value === void 0) return "";
576
+ if (value instanceof Date) {
577
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
578
+ }
579
+ if (Array.isArray(value)) {
580
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
581
+ }
582
+ if (typeof value === "object") {
583
+ return formatObjectValue(value);
584
+ }
585
+ if (typeof value === "string") return value;
586
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
587
+ return String(value);
588
+ }
589
+ return "";
590
+ }
306
591
 
307
592
  // src/components/ui/table/features/cell-render/builtins.tsx
308
593
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -326,8 +611,9 @@ function asDrilldownItems(value) {
326
611
  const record = item;
327
612
  const text = asString(record.text ?? record.label ?? "");
328
613
  if (!text) return [];
329
- const img = record.img ?? record.image;
330
- return [{ text, ...typeof img === "string" ? { img } : {} }];
614
+ const rawImg = record.img ?? record.image;
615
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
616
+ return [{ text, ...img ? { img } : {} }];
331
617
  }
332
618
  return [{ text: asString(item) }];
333
619
  });
@@ -388,6 +674,22 @@ function sanitizeUriHref(raw) {
388
674
  return href;
389
675
  }
390
676
  }
677
+ function sanitizeImageSrc(raw) {
678
+ const src = raw.trim();
679
+ if (!src) return null;
680
+ try {
681
+ const parsed = new URL(src);
682
+ const protocol = parsed.protocol.toLowerCase();
683
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
684
+ return src;
685
+ }
686
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
687
+ return null;
688
+ } catch {
689
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
690
+ return src;
691
+ }
692
+ }
391
693
  function UriCell({ value }) {
392
694
  const raw = asString(value);
393
695
  if (!raw) return null;
@@ -409,7 +711,10 @@ function UriCell({ value }) {
409
711
  );
410
712
  }
411
713
  function ImageCell({ value }) {
412
- const urls = asStringList(value);
714
+ const urls = asStringList(value).flatMap((url) => {
715
+ const src = sanitizeImageSrc(url);
716
+ return src ? [src] : [];
717
+ });
413
718
  if (urls.length === 0) return null;
414
719
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
415
720
  "img",
@@ -462,8 +767,33 @@ function DrilldownCell({ value }) {
462
767
  function LoadingCell() {
463
768
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-loading", "aria-busy": "true" });
464
769
  }
465
- function ProtectedCell() {
466
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
770
+ function ProtectedCell({ cellProps }) {
771
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
772
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
773
+ }
774
+ function RowSelectCell({ row, cellProps }) {
775
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
776
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
777
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
778
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
779
+ "input",
780
+ {
781
+ type: "checkbox",
782
+ className: "data-table-cell-row-select",
783
+ checked,
784
+ disabled: !canSelect,
785
+ "aria-label": label,
786
+ onChange: () => {
787
+ if (canSelect) row.toggleSelected();
788
+ },
789
+ onClick: (event) => {
790
+ event.stopPropagation();
791
+ },
792
+ onMouseDown: (event) => {
793
+ event.stopPropagation();
794
+ }
795
+ }
796
+ );
467
797
  }
468
798
  function RowIdCell({ value }) {
469
799
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -479,7 +809,8 @@ var BUILTIN_RENDER_MAP = {
479
809
  drilldown: DrilldownCell,
480
810
  loading: LoadingCell,
481
811
  protected: ProtectedCell,
482
- "row-id": RowIdCell
812
+ "row-id": RowIdCell,
813
+ "row-select": RowSelectCell
483
814
  };
484
815
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
485
816
  kind,
@@ -513,496 +844,170 @@ function formatDefaultCellValue(value) {
513
844
  return String(value);
514
845
  }
515
846
  if (typeof value === "bigint") return value.toString();
516
- return String(value);
847
+ return formatCellValue(value);
517
848
  }
518
849
 
519
- // src/components/ui/table/features/cell-render/withCellUpdate.ts
520
- function withCellUpdate(context, commitValue) {
521
- return {
522
- ...context,
523
- update: (next) => {
524
- commitValue(context.row.id, context.column.id, next);
525
- }
526
- };
527
- }
850
+ // src/components/ui/table/features/cell-selection/copyData.ts
851
+ var import_react2 = require("react");
528
852
 
529
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
530
- var import_react3 = require("react");
853
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
854
+ var lastSubtreeCopy = null;
855
+ function normalize(text) {
856
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
857
+ }
858
+ function rememberSubtreeCopy(text) {
859
+ lastSubtreeCopy = normalize(text);
860
+ }
861
+ function isOwnSubtreeCopy(text) {
862
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
863
+ }
531
864
 
532
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
533
- var activeOwner = null;
534
- var clearByOwner = /* @__PURE__ */ new Map();
535
- function createCellSelectionOwner() {
536
- return /* @__PURE__ */ Symbol("cell-selection-owner");
865
+ // src/components/ui/table/features/cell-selection/copyData.ts
866
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
867
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
868
+ function escapeSpreadsheetFormula(text) {
869
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
870
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
871
+ return `'${text}`;
537
872
  }
538
- function registerCellSelectionOwner(owner, clearSelection) {
539
- clearByOwner.set(owner, clearSelection);
540
- return () => {
541
- clearByOwner.delete(owner);
542
- if (activeOwner === owner) {
543
- activeOwner = null;
544
- }
545
- };
873
+ function isReactNodeIterable(node) {
874
+ return typeof node === "object" && node !== null && !(0, import_react2.isValidElement)(node) && Symbol.iterator in node;
546
875
  }
547
- function claimCellSelectionOwner(owner) {
548
- if (activeOwner === owner) return;
549
- activeOwner = owner;
550
- for (const [id, clearSelection] of clearByOwner) {
551
- if (id !== owner) {
552
- clearSelection();
553
- }
876
+ function getElementTypeName(type) {
877
+ if (typeof type === "string") return type;
878
+ if (typeof type === "function") {
879
+ const fn = type;
880
+ return fn.displayName || fn.name || "";
554
881
  }
555
- }
556
- function isActiveCellSelectionOwner(owner) {
557
- return activeOwner === owner;
558
- }
559
- function releaseCellSelectionOwner(owner) {
560
- if (activeOwner === owner) {
561
- activeOwner = null;
882
+ if (typeof type === "object" && type !== null) {
883
+ const component = type;
884
+ return component.displayName || component.render?.displayName || component.render?.name || "";
562
885
  }
886
+ return "";
563
887
  }
564
-
565
- // src/components/ui/table/features/cell-selection/cellSelection.ts
566
- var INITIAL_DRAG_STATE = {
567
- isSelecting: false,
568
- isFillDragging: false,
569
- start: null,
570
- end: null,
571
- fillAnchor: null,
572
- fillEnd: null
573
- };
574
- function getCellSelectionBounds(start, end) {
575
- if (!start || !end) return null;
576
- return {
577
- startRow: Math.min(start.row, end.row),
578
- endRow: Math.max(start.row, end.row),
579
- startCol: Math.min(start.col, end.col),
580
- endCol: Math.max(start.col, end.col)
581
- };
888
+ function isButtonReactElement(node) {
889
+ const typeName = getElementTypeName(node.type);
890
+ if (typeName === "button" || /button/i.test(typeName)) return true;
891
+ const props = node.props;
892
+ if (props.role === "button") return true;
893
+ if (typeName === "input" && props.type === "button") return true;
894
+ return false;
582
895
  }
583
- function getCellNavigationDelta(key) {
584
- switch (key) {
585
- case "ArrowUp":
586
- case "w":
587
- case "W":
588
- return { row: -1, col: 0 };
589
- case "ArrowDown":
590
- case "s":
591
- case "S":
592
- return { row: 1, col: 0 };
593
- case "ArrowLeft":
594
- case "a":
595
- case "A":
596
- return { row: 0, col: -1 };
597
- case "ArrowRight":
598
- case "d":
599
- case "D":
600
- return { row: 0, col: 1 };
601
- default:
602
- return null;
603
- }
896
+ function isImageReactElement(node) {
897
+ const typeName = getElementTypeName(node.type);
898
+ return typeName === "img" || typeName === "image" || /image/i.test(typeName);
604
899
  }
605
- function clampCellPosition(position, rowCount, columnCount) {
606
- const maxRow = Math.max(rowCount - 1, 0);
607
- const maxCol = Math.max(columnCount - 1, 0);
608
- return {
609
- row: Math.min(Math.max(position.row, 0), maxRow),
610
- col: Math.min(Math.max(position.col, 0), maxCol)
611
- };
900
+ var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
901
+ function isLikelyUrl(value) {
902
+ const trimmed = value.trim();
903
+ if (!trimmed) return false;
904
+ if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
905
+ if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
906
+ return false;
612
907
  }
613
- function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
614
- if (rowSpan <= 1) return void 0;
615
- const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
616
- if (!tbody) return void 0;
617
- const rows = tbody.querySelectorAll(":scope > tr");
618
- if (rows.length < rowIndex + rowSpan) return void 0;
619
- const heights = [];
620
- for (let i = 0; i < rowSpan; i++) {
621
- const row = rows[rowIndex + i];
622
- const height = row?.getBoundingClientRect().height ?? 0;
623
- if (height <= 0) return void 0;
624
- heights.push(height);
908
+ function pickUrlFromUnknown(value) {
909
+ if (typeof value === "string") {
910
+ return isLikelyUrl(value) ? value.trim() : "";
625
911
  }
626
- return heights;
627
- }
628
- function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
629
- if (rowSpan <= 1) return rowIndex;
630
- const rect = cellElement.getBoundingClientRect();
631
- const relativeY = clientY - rect.top;
632
- const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
633
- if (heights && heights.length === rowSpan) {
634
- let accrued = 0;
635
- for (let i = 0; i < rowSpan; i++) {
636
- accrued += heights[i];
637
- if (relativeY < accrued) {
638
- return rowIndex + i;
912
+ if (Array.isArray(value)) {
913
+ return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
914
+ }
915
+ if (value && typeof value === "object") {
916
+ const record = value;
917
+ for (const key of IMAGE_URL_PROP_KEYS) {
918
+ const candidate = record[key];
919
+ if (typeof candidate === "string" && candidate.trim()) {
920
+ return candidate.trim();
639
921
  }
640
922
  }
641
- return rowIndex + rowSpan - 1;
642
923
  }
643
- const rowHeight = rect.height / rowSpan;
644
- const offset = Math.min(
645
- Math.max(Math.floor(relativeY / rowHeight), 0),
646
- rowSpan - 1
647
- );
648
- return rowIndex + offset;
924
+ return "";
649
925
  }
650
- function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
651
- if (!bounds) return false;
652
- const cellEndRow = rowIndex + rowSpan - 1;
653
- return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
926
+ function imageElementText(node) {
927
+ const props = node.props;
928
+ for (const key of IMAGE_URL_PROP_KEYS) {
929
+ const candidate = props[key];
930
+ if (typeof candidate === "string" && candidate.trim()) {
931
+ return candidate.trim();
932
+ }
933
+ }
934
+ return "";
654
935
  }
655
- function getActiveSelectionBounds(dragState, selectionBounds) {
656
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
657
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
936
+ function reactNodeContainsImage(node) {
937
+ if ((0, import_react2.isValidElement)(node)) {
938
+ if (isImageReactElement(node)) return true;
939
+ return reactNodeContainsImage(node.props.children);
658
940
  }
659
- return selectionBounds;
941
+ if (isReactNodeIterable(node)) {
942
+ for (const child of node) {
943
+ if (reactNodeContainsImage(child)) return true;
944
+ }
945
+ }
946
+ return false;
660
947
  }
661
- var SELECTION_EDGE_WIDTH_PX = 2;
662
- var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
663
- var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
664
- function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
665
- const clampedFrom = Math.max(fromRow, rowIndex);
666
- const clampedTo = Math.min(toRowExclusive, rowIndex + span);
667
- if (clampedTo <= clampedFrom) {
668
- return { offsetRatio: 0, lengthRatio: 0 };
948
+ function readImgUrl(img) {
949
+ const attr = img.getAttribute("src")?.trim() ?? "";
950
+ if (attr) return attr;
951
+ if (img instanceof HTMLImageElement) {
952
+ const current = img.currentSrc?.trim() ?? "";
953
+ if (current && current !== img.baseURI) return current;
669
954
  }
670
- if (!rowHeights || rowHeights.length !== span) {
671
- return {
672
- offsetRatio: (clampedFrom - rowIndex) / span,
673
- lengthRatio: (clampedTo - clampedFrom) / span
674
- };
955
+ return "";
956
+ }
957
+ function readDomImageUrls(rowIndex, colIndex, root) {
958
+ const scope = root ?? (typeof document === "undefined" ? null : document);
959
+ if (!scope) return "";
960
+ const cells = scope.querySelectorAll(
961
+ `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
962
+ );
963
+ for (const cell of cells) {
964
+ const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
965
+ const url = readImgUrl(img);
966
+ return url ? [url] : [];
967
+ });
968
+ if (urls.length > 0) return urls.join(", ");
675
969
  }
676
- const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
677
- let offsetPx = 0;
678
- for (let i = 0; i < clampedFrom - rowIndex; i++) {
679
- offsetPx += rowHeights[i] ?? 0;
970
+ return "";
971
+ }
972
+ function reactNodeToText(node) {
973
+ if (node == null || typeof node === "boolean") return "";
974
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
975
+ return String(node);
680
976
  }
681
- let lengthPx = 0;
682
- for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
683
- lengthPx += rowHeights[i] ?? 0;
977
+ if (isReactNodeIterable(node)) {
978
+ let text = "";
979
+ for (const child of node) {
980
+ text += reactNodeToText(child);
981
+ }
982
+ return text;
983
+ }
984
+ if ((0, import_react2.isValidElement)(node)) {
985
+ if (isButtonReactElement(node)) return "";
986
+ const props = node.props;
987
+ const childText = reactNodeToText(props.children);
988
+ if (childText) return childText;
989
+ const fromImage = imageElementText(node);
990
+ if (fromImage) return fromImage;
991
+ if (isImageReactElement(node)) return "";
992
+ if (typeof props.alt === "string" && props.alt) return props.alt;
993
+ if (typeof props.title === "string" && props.title) return props.title;
994
+ return "";
684
995
  }
996
+ return "";
997
+ }
998
+ function quoteTsvCell(text) {
999
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
1000
+ return `"${text.replace(/"/g, '""')}"`;
1001
+ }
1002
+ function sanitizeClipboardCell(text) {
1003
+ return text.replace(/\s+/g, " ").trim();
1004
+ }
1005
+ function createCopyRenderRow(rowData, index) {
685
1006
  return {
686
- offsetRatio: offsetPx / total,
687
- lengthRatio: lengthPx / total,
688
- offsetPx,
689
- lengthPx
690
- };
691
- }
692
- function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
693
- const cellEndRow = rowIndex + rowSpan - 1;
694
- const span = cellEndRow - rowIndex + 1;
695
- if (span <= 1) return [];
696
- const edges = [];
697
- const isNeighborSelected = (row, neighborCol) => {
698
- if (isVisuallySelectedAt) {
699
- return isVisuallySelectedAt(row, neighborCol);
700
- }
701
- return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
702
- };
703
- const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
704
- let runStart = null;
705
- for (let row = fromRow; row < toRowExclusive; row++) {
706
- if (!isNeighborSelected(row, neighborCol)) {
707
- if (runStart === null) runStart = row;
708
- continue;
709
- }
710
- if (runStart !== null) {
711
- const ratios = rowRangeToHeightRatios(
712
- rowIndex,
713
- span,
714
- runStart,
715
- row,
716
- rowHeights
717
- );
718
- if (ratios.lengthRatio > 0) {
719
- edges.push({ side, ...ratios });
720
- }
721
- runStart = null;
722
- }
723
- }
724
- if (runStart !== null) {
725
- const ratios = rowRangeToHeightRatios(
726
- rowIndex,
727
- span,
728
- runStart,
729
- toRowExclusive,
730
- rowHeights
731
- );
732
- if (ratios.lengthRatio > 0) {
733
- edges.push({ side, ...ratios });
734
- }
735
- }
736
- };
737
- const collectSide = (side, neighborCol) => {
738
- if (bounds.startRow > rowIndex) {
739
- pushUnselectedRuns(
740
- side,
741
- neighborCol,
742
- rowIndex,
743
- Math.min(bounds.startRow, cellEndRow + 1)
744
- );
745
- }
746
- if (bounds.endRow < cellEndRow) {
747
- pushUnselectedRuns(
748
- side,
749
- neighborCol,
750
- Math.max(bounds.endRow + 1, rowIndex),
751
- cellEndRow + 1
752
- );
753
- }
754
- };
755
- if (colIndex < bounds.endCol) {
756
- collectSide("right", colIndex + 1);
757
- }
758
- if (colIndex > bounds.startCol) {
759
- collectSide("left", colIndex - 1);
760
- }
761
- return edges;
762
- }
763
- function buildPartialEdgeGradient(edge) {
764
- const usePx = edge.offsetPx != null && edge.lengthPx != null;
765
- const startPct = edge.offsetRatio * 100;
766
- const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
767
- const startPx = edge.offsetPx ?? 0;
768
- const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
769
- const overlapPx = SELECTION_EDGE_WIDTH_PX;
770
- const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
771
- const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
772
- const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
773
- const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
774
- const xPos = edge.side === "left" ? "0" : "100%";
775
- const layers = [
776
- {
777
- image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
778
- size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
779
- position: `${xPos} 0`
780
- }
781
- ];
782
- if (isTopProtrusion || isBottomProtrusion) {
783
- const capTop = usePx ? isTopProtrusion ? `${Math.max(0, endPx - SELECTION_EDGE_WIDTH_PX)}px` : `${Math.max(0, startPx - SELECTION_EDGE_WIDTH_PX)}px` : isTopProtrusion ? `calc(${endPct}% - ${SELECTION_EDGE_WIDTH_PX}px)` : `calc(${startPct}% - ${SELECTION_EDGE_WIDTH_PX}px)`;
784
- layers.push({
785
- image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
786
- size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
787
- position: `${xPos} ${capTop}`
788
- });
789
- }
790
- return layers;
791
- }
792
- function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
793
- if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
794
- return void 0;
795
- const cellEndRow = rowIndex + rowSpan - 1;
796
- const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
797
- const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
798
- const isLeftEdge = colIndex === bounds.startCol;
799
- const isRightEdge = colIndex === bounds.endCol;
800
- const selectionContinuesBelow = cellEndRow < bounds.endRow;
801
- const stepEdges = getMergedCellStepEdges(
802
- rowIndex,
803
- colIndex,
804
- bounds,
805
- rowSpan,
806
- isVisuallySelectedAt,
807
- rowHeights
808
- );
809
- const shadows = [];
810
- const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
811
- if (hasFullPerimeter) {
812
- shadows.push(
813
- `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
814
- );
815
- } else {
816
- if (isTopEdge) {
817
- shadows.push(
818
- `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
819
- );
820
- }
821
- if (isBottomEdge) {
822
- shadows.push(
823
- `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
824
- );
825
- }
826
- if (isLeftEdge) {
827
- shadows.push(
828
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
829
- );
830
- }
831
- if (isRightEdge) {
832
- shadows.push(
833
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
834
- );
835
- }
836
- }
837
- const gradients = [];
838
- const sizes = [];
839
- const positions = [];
840
- for (const edge of stepEdges) {
841
- for (const partial of buildPartialEdgeGradient(edge)) {
842
- gradients.push(partial.image);
843
- sizes.push(partial.size);
844
- positions.push(partial.position);
845
- }
846
- }
847
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
848
- return void 0;
849
- }
850
- const style = {};
851
- if (shadows.length > 0) {
852
- style["--selection-edge-shadows"] = shadows.join(", ");
853
- }
854
- if (gradients.length > 0) {
855
- style["--selection-edge-gradients"] = gradients.join(", ");
856
- style["--selection-edge-sizes"] = sizes.join(", ");
857
- style["--selection-edge-positions"] = positions.join(", ");
858
- }
859
- if (selectionContinuesBelow) {
860
- style.borderBottomColor = "var(--color-brand-surface)";
861
- }
862
- return style;
863
- }
864
- function hasCellSelectionEdges(style) {
865
- return Boolean(
866
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
867
- );
868
- }
869
-
870
- // src/components/ui/table/features/cell-selection/copyData.ts
871
- var import_react2 = require("react");
872
- function isReactNodeIterable(node) {
873
- return typeof node === "object" && node !== null && !(0, import_react2.isValidElement)(node) && Symbol.iterator in node;
874
- }
875
- function getElementTypeName(type) {
876
- if (typeof type === "string") return type;
877
- if (typeof type === "function") {
878
- const fn = type;
879
- return fn.displayName || fn.name || "";
880
- }
881
- if (typeof type === "object" && type !== null) {
882
- const component = type;
883
- return component.displayName || component.render?.displayName || component.render?.name || "";
884
- }
885
- return "";
886
- }
887
- function isButtonReactElement(node) {
888
- const typeName = getElementTypeName(node.type);
889
- if (typeName === "button" || /button/i.test(typeName)) return true;
890
- const props = node.props;
891
- if (props.role === "button") return true;
892
- if (typeName === "input" && props.type === "button") return true;
893
- return false;
894
- }
895
- function isImageReactElement(node) {
896
- const typeName = getElementTypeName(node.type);
897
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
898
- }
899
- var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
900
- function isLikelyUrl(value) {
901
- const trimmed = value.trim();
902
- if (!trimmed) return false;
903
- if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
904
- if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
905
- return false;
906
- }
907
- function pickUrlFromUnknown(value) {
908
- if (typeof value === "string") {
909
- return isLikelyUrl(value) ? value.trim() : "";
910
- }
911
- if (Array.isArray(value)) {
912
- return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
913
- }
914
- if (value && typeof value === "object") {
915
- const record = value;
916
- for (const key of IMAGE_URL_PROP_KEYS) {
917
- const candidate = record[key];
918
- if (typeof candidate === "string" && candidate.trim()) {
919
- return candidate.trim();
920
- }
921
- }
922
- }
923
- return "";
924
- }
925
- function imageElementText(node) {
926
- const props = node.props;
927
- for (const key of IMAGE_URL_PROP_KEYS) {
928
- const candidate = props[key];
929
- if (typeof candidate === "string" && candidate.trim()) {
930
- return candidate.trim();
931
- }
932
- }
933
- return "";
934
- }
935
- function reactNodeContainsImage(node) {
936
- if ((0, import_react2.isValidElement)(node)) {
937
- if (isImageReactElement(node)) return true;
938
- return reactNodeContainsImage(node.props.children);
939
- }
940
- if (isReactNodeIterable(node)) {
941
- for (const child of node) {
942
- if (reactNodeContainsImage(child)) return true;
943
- }
944
- }
945
- return false;
946
- }
947
- function readImgUrl(img) {
948
- const attr = img.getAttribute("src")?.trim() ?? "";
949
- if (attr) return attr;
950
- if (img instanceof HTMLImageElement) {
951
- const current = img.currentSrc?.trim() ?? "";
952
- if (current && current !== img.baseURI) return current;
953
- }
954
- return "";
955
- }
956
- function readDomImageUrls(rowIndex, colIndex, root) {
957
- const scope = root ?? (typeof document === "undefined" ? null : document);
958
- if (!scope) return "";
959
- const cells = scope.querySelectorAll(
960
- `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
961
- );
962
- for (const cell of cells) {
963
- const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
964
- const url = readImgUrl(img);
965
- return url ? [url] : [];
966
- });
967
- if (urls.length > 0) return urls.join(", ");
968
- }
969
- return "";
970
- }
971
- function reactNodeToText(node) {
972
- if (node == null || typeof node === "boolean") return "";
973
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
974
- return String(node);
975
- }
976
- if (isReactNodeIterable(node)) {
977
- let text = "";
978
- for (const child of node) {
979
- text += reactNodeToText(child);
980
- }
981
- return text;
982
- }
983
- if ((0, import_react2.isValidElement)(node)) {
984
- if (isButtonReactElement(node)) return "";
985
- const props = node.props;
986
- const childText = reactNodeToText(props.children);
987
- if (childText) return childText;
988
- const fromImage = imageElementText(node);
989
- if (fromImage) return fromImage;
990
- if (isImageReactElement(node)) return "";
991
- if (typeof props.alt === "string" && props.alt) return props.alt;
992
- if (typeof props.title === "string" && props.title) return props.title;
993
- return "";
994
- }
995
- return "";
996
- }
997
- function sanitizeClipboardCell(text) {
998
- return text.replace(/\s+/g, " ").trim();
999
- }
1000
- function createCopyRenderRow(rowData, index) {
1001
- return {
1002
- id: getOriginalRowId(rowData) || String(index),
1003
- index,
1004
- original: rowData,
1005
- getIsCellDragSelected: () => false
1007
+ id: getOriginalRowId(rowData) || String(index),
1008
+ index,
1009
+ original: rowData,
1010
+ getIsCellDragSelected: () => false
1006
1011
  };
1007
1012
  }
1008
1013
  function buildVisibleRowLookup(visibleRows) {
@@ -1069,204 +1074,550 @@ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIn
1069
1074
  return formatCellValue(value);
1070
1075
  }
1071
1076
  }
1072
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
1073
- try {
1074
- const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
1075
- if (renderer) {
1076
- const node = renderer.render(ctx);
1077
- const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
1078
- if (rendered) return rendered;
1077
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
1078
+ try {
1079
+ const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
1080
+ if (renderer) {
1081
+ const node = renderer.render(ctx);
1082
+ const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
1083
+ if (rendered) return rendered;
1084
+ }
1085
+ } catch {
1086
+ return formatCellValue(value);
1087
+ }
1088
+ }
1089
+ return formatCellValue(value);
1090
+ }
1091
+ function getNestedValue(row, path) {
1092
+ if (!path.includes(".")) return row[path];
1093
+ return path.split(".").reduce((current, key) => {
1094
+ if (current === null || current === void 0 || typeof current !== "object") {
1095
+ return void 0;
1096
+ }
1097
+ return current[key];
1098
+ }, row);
1099
+ }
1100
+ function readRowColumnValue(rowData, columnDef) {
1101
+ if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1102
+ return columnDef.accessorFn(rowData, 0);
1103
+ }
1104
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1105
+ return getNestedValue(rowData, String(columnDef.accessorKey));
1106
+ }
1107
+ return void 0;
1108
+ }
1109
+ function flattenSubtreeRows(row) {
1110
+ const children = row.children;
1111
+ if (!Array.isArray(children) || children.length === 0) return [];
1112
+ const result = [];
1113
+ const walk = (nodes) => {
1114
+ for (const node of nodes) {
1115
+ result.push(node);
1116
+ const nested = node.children;
1117
+ if (Array.isArray(nested) && nested.length > 0) {
1118
+ walk(nested);
1119
+ }
1120
+ }
1121
+ };
1122
+ walk(children);
1123
+ return result;
1124
+ }
1125
+ function hasSubtree(row) {
1126
+ const children = row.children;
1127
+ return Array.isArray(children) && children.length > 0;
1128
+ }
1129
+ function getOriginalRowId(original) {
1130
+ return String(original.id ?? original.uniqueId ?? "");
1131
+ }
1132
+ function getRowDepth(original) {
1133
+ return typeof original.level === "number" ? original.level : 0;
1134
+ }
1135
+ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1136
+ const { startRow, endRow } = bounds;
1137
+ const result = [];
1138
+ if (mode !== "subtree") {
1139
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1140
+ const row = visibleRows[rowIndex];
1141
+ if (row) result.push({ row: row.original, depth: 0 });
1142
+ }
1143
+ return result;
1144
+ }
1145
+ const included = /* @__PURE__ */ new Set();
1146
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
1147
+ const appendSubtree = (node, depth) => {
1148
+ const children = node.children;
1149
+ if (!Array.isArray(children) || children.length === 0) return;
1150
+ for (const child of children) {
1151
+ const key = keyOf(child);
1152
+ if (!included.has(key)) {
1153
+ result.push({ row: child, depth });
1154
+ included.add(key);
1155
+ }
1156
+ appendSubtree(child, depth + 1);
1157
+ }
1158
+ };
1159
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1160
+ const row = visibleRows[rowIndex];
1161
+ if (!row) continue;
1162
+ const key = keyOf(row.original);
1163
+ if (included.has(key)) continue;
1164
+ const depth = getRowDepth(row.original);
1165
+ result.push({ row: row.original, depth });
1166
+ included.add(key);
1167
+ if (!hasSubtree(row.original)) continue;
1168
+ appendSubtree(row.original, depth + 1);
1169
+ }
1170
+ return result;
1171
+ }
1172
+ function collectCopyRows(visibleRows, bounds, mode = "visible") {
1173
+ return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1174
+ }
1175
+ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1176
+ if (copyRows.length === 0) return "";
1177
+ const { startCol, endCol } = bounds;
1178
+ const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1179
+ if (columnCells.length === 0) return "";
1180
+ const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1181
+ const minDepth = Math.min(...resolvedDepths);
1182
+ const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1183
+ const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1184
+ const meta = templateCell.column.columnDef.meta;
1185
+ if (meta?.copyValue === "omit") return [];
1186
+ return [{ templateCell, colOffset }];
1187
+ });
1188
+ return copyRows.map((rowData, index) => {
1189
+ const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1190
+ const visibleRow = visibleRowByOriginal.get(rowData);
1191
+ const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1192
+ const line = copyableColumns.map(({ templateCell, colOffset }) => {
1193
+ const sourceCell = matchingCells?.[colOffset];
1194
+ const column = sourceCell?.column ?? templateCell.column;
1195
+ const text = formatCopyCellText(
1196
+ rowData,
1197
+ column.columnDef,
1198
+ resolveCopyColumnId(sourceCell ?? templateCell),
1199
+ visibleRow,
1200
+ visibleRow?.index ?? index,
1201
+ sourceCell,
1202
+ visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1203
+ options
1204
+ );
1205
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
1206
+ return quoteTsvCell(escaped);
1207
+ }).join(" ");
1208
+ return `${" ".repeat(relativeDepth)}${line}`;
1209
+ }).join("\n");
1210
+ }
1211
+ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1212
+ const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1213
+ return serializeCopyRowsToTSV(
1214
+ entries.map((entry) => entry.row),
1215
+ visibleRows,
1216
+ bounds,
1217
+ entries.map((entry) => entry.depth),
1218
+ options
1219
+ );
1220
+ }
1221
+ function writeTextWithExecCommand(text) {
1222
+ if (typeof document === "undefined") return false;
1223
+ const textarea = document.createElement("textarea");
1224
+ textarea.value = text;
1225
+ textarea.setAttribute("readonly", "");
1226
+ textarea.style.position = "fixed";
1227
+ textarea.style.top = "0";
1228
+ textarea.style.left = "0";
1229
+ textarea.style.opacity = "0";
1230
+ textarea.style.pointerEvents = "none";
1231
+ document.body.appendChild(textarea);
1232
+ const previouslyFocused = document.activeElement;
1233
+ try {
1234
+ textarea.focus();
1235
+ textarea.select();
1236
+ return document.execCommand("copy");
1237
+ } catch {
1238
+ return false;
1239
+ } finally {
1240
+ document.body.removeChild(textarea);
1241
+ previouslyFocused?.focus?.();
1242
+ }
1243
+ }
1244
+ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1245
+ const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1246
+ if (!text) return false;
1247
+ if (mode === "subtree") rememberSubtreeCopy(text);
1248
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1249
+ return writeTextWithExecCommand(text);
1250
+ }
1251
+ try {
1252
+ await navigator.clipboard.writeText(text);
1253
+ return true;
1254
+ } catch {
1255
+ return false;
1256
+ }
1257
+ }
1258
+
1259
+ // src/components/ui/table/features/cell-render/withCellUpdate.ts
1260
+ function withCellUpdate(context, commitValue) {
1261
+ return {
1262
+ ...context,
1263
+ update: (next) => {
1264
+ commitValue(context.row.id, context.column.id, next);
1265
+ }
1266
+ };
1267
+ }
1268
+
1269
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
1270
+ var import_react3 = require("react");
1271
+
1272
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
1273
+ var activeOwner = null;
1274
+ var clearByOwner = /* @__PURE__ */ new Map();
1275
+ function createCellSelectionOwner() {
1276
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
1277
+ }
1278
+ function registerCellSelectionOwner(owner, clearSelection) {
1279
+ clearByOwner.set(owner, clearSelection);
1280
+ return () => {
1281
+ clearByOwner.delete(owner);
1282
+ if (activeOwner === owner) {
1283
+ activeOwner = null;
1284
+ }
1285
+ };
1286
+ }
1287
+ function claimCellSelectionOwner(owner) {
1288
+ if (activeOwner === owner) return;
1289
+ activeOwner = owner;
1290
+ for (const [id, clearSelection] of clearByOwner) {
1291
+ if (id !== owner) {
1292
+ clearSelection();
1293
+ }
1294
+ }
1295
+ }
1296
+ function isActiveCellSelectionOwner(owner) {
1297
+ return activeOwner === owner;
1298
+ }
1299
+ function releaseCellSelectionOwner(owner) {
1300
+ if (activeOwner === owner) {
1301
+ activeOwner = null;
1302
+ }
1303
+ }
1304
+
1305
+ // src/components/ui/table/features/cell-selection/cellSelection.ts
1306
+ var INITIAL_DRAG_STATE = {
1307
+ isSelecting: false,
1308
+ isFillDragging: false,
1309
+ start: null,
1310
+ end: null,
1311
+ fillAnchor: null,
1312
+ fillEnd: null
1313
+ };
1314
+ function getCellSelectionBounds(start, end) {
1315
+ if (!start || !end) return null;
1316
+ return {
1317
+ startRow: Math.min(start.row, end.row),
1318
+ endRow: Math.max(start.row, end.row),
1319
+ startCol: Math.min(start.col, end.col),
1320
+ endCol: Math.max(start.col, end.col)
1321
+ };
1322
+ }
1323
+ function getCellNavigationDelta(key) {
1324
+ switch (key) {
1325
+ case "ArrowUp":
1326
+ case "w":
1327
+ case "W":
1328
+ return { row: -1, col: 0 };
1329
+ case "ArrowDown":
1330
+ case "s":
1331
+ case "S":
1332
+ return { row: 1, col: 0 };
1333
+ case "ArrowLeft":
1334
+ case "a":
1335
+ case "A":
1336
+ return { row: 0, col: -1 };
1337
+ case "ArrowRight":
1338
+ case "d":
1339
+ case "D":
1340
+ return { row: 0, col: 1 };
1341
+ default:
1342
+ return null;
1343
+ }
1344
+ }
1345
+ function clampCellPosition(position, rowCount, columnCount) {
1346
+ const maxRow = Math.max(rowCount - 1, 0);
1347
+ const maxCol = Math.max(columnCount - 1, 0);
1348
+ return {
1349
+ row: Math.min(Math.max(position.row, 0), maxRow),
1350
+ col: Math.min(Math.max(position.col, 0), maxCol)
1351
+ };
1352
+ }
1353
+ function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
1354
+ if (rowSpan <= 1) return void 0;
1355
+ const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
1356
+ if (!tbody) return void 0;
1357
+ const rows = tbody.querySelectorAll(":scope > tr");
1358
+ if (rows.length < rowIndex + rowSpan) return void 0;
1359
+ const heights = [];
1360
+ for (let i = 0; i < rowSpan; i++) {
1361
+ const row = rows[rowIndex + i];
1362
+ const height = row?.getBoundingClientRect().height ?? 0;
1363
+ if (height <= 0) return void 0;
1364
+ heights.push(height);
1365
+ }
1366
+ return heights;
1367
+ }
1368
+ function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
1369
+ if (rowSpan <= 1) return rowIndex;
1370
+ const rect = cellElement.getBoundingClientRect();
1371
+ const relativeY = clientY - rect.top;
1372
+ const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
1373
+ if (heights && heights.length === rowSpan) {
1374
+ let accrued = 0;
1375
+ for (let i = 0; i < rowSpan; i++) {
1376
+ accrued += heights[i];
1377
+ if (relativeY < accrued) {
1378
+ return rowIndex + i;
1079
1379
  }
1080
- } catch {
1081
- return formatCellValue(value);
1082
1380
  }
1381
+ return rowIndex + rowSpan - 1;
1083
1382
  }
1084
- return formatCellValue(value);
1383
+ const rowHeight = rect.height / rowSpan;
1384
+ const offset = Math.min(
1385
+ Math.max(Math.floor(relativeY / rowHeight), 0),
1386
+ rowSpan - 1
1387
+ );
1388
+ return rowIndex + offset;
1085
1389
  }
1086
- function formatPrimitive(value) {
1087
- if (value === null || value === void 0) return "";
1088
- if (typeof value === "string") return value;
1089
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1090
- return String(value);
1091
- }
1092
- return "";
1390
+ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
1391
+ if (!bounds) return false;
1392
+ const cellEndRow = rowIndex + rowSpan - 1;
1393
+ return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
1093
1394
  }
1094
- function formatObjectValue(value) {
1095
- const text = value.text ?? value.label ?? value.name ?? value.title;
1096
- if (text != null && text !== "") {
1097
- return formatCellValue(text);
1395
+ function resolveFillBounds(source, pointer) {
1396
+ const below = pointer.row - source.endRow;
1397
+ const above = source.startRow - pointer.row;
1398
+ const right = pointer.col - source.endCol;
1399
+ const left = source.startCol - pointer.col;
1400
+ const vertical = Math.max(below, above, 0);
1401
+ const horizontal = Math.max(right, left, 0);
1402
+ if (vertical === 0 && horizontal === 0) return { ...source };
1403
+ if (vertical >= horizontal) {
1404
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
1098
1405
  }
1099
- try {
1100
- return JSON.stringify(value);
1101
- } catch {
1102
- return "";
1406
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1407
+ }
1408
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1409
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1410
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1103
1411
  }
1412
+ return selectionBounds;
1104
1413
  }
1105
- function formatCellValue(value) {
1106
- if (value === null || value === void 0) return "";
1107
- if (Array.isArray(value)) {
1108
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
1414
+ var SELECTION_EDGE_WIDTH_PX = 2;
1415
+ var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
1416
+ var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
1417
+ function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
1418
+ const clampedFrom = Math.max(fromRow, rowIndex);
1419
+ const clampedTo = Math.min(toRowExclusive, rowIndex + span);
1420
+ if (clampedTo <= clampedFrom) {
1421
+ return { offsetRatio: 0, lengthRatio: 0 };
1109
1422
  }
1110
- if (typeof value === "object") {
1111
- return formatObjectValue(value);
1423
+ if (!rowHeights || rowHeights.length !== span) {
1424
+ return {
1425
+ offsetRatio: (clampedFrom - rowIndex) / span,
1426
+ lengthRatio: (clampedTo - clampedFrom) / span
1427
+ };
1112
1428
  }
1113
- return formatPrimitive(value);
1114
- }
1115
- function getNestedValue(row, path) {
1116
- if (!path.includes(".")) return row[path];
1117
- return path.split(".").reduce((current, key) => {
1118
- if (current === null || current === void 0 || typeof current !== "object") {
1119
- return void 0;
1120
- }
1121
- return current[key];
1122
- }, row);
1123
- }
1124
- function readRowColumnValue(rowData, columnDef) {
1125
- if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1126
- return columnDef.accessorFn(rowData, 0);
1429
+ const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
1430
+ let offsetPx = 0;
1431
+ for (let i = 0; i < clampedFrom - rowIndex; i++) {
1432
+ offsetPx += rowHeights[i] ?? 0;
1127
1433
  }
1128
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1129
- return getNestedValue(rowData, String(columnDef.accessorKey));
1434
+ let lengthPx = 0;
1435
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1436
+ lengthPx += rowHeights[i] ?? 0;
1130
1437
  }
1131
- return void 0;
1438
+ return {
1439
+ offsetRatio: offsetPx / total,
1440
+ lengthRatio: lengthPx / total,
1441
+ offsetPx,
1442
+ lengthPx
1443
+ };
1132
1444
  }
1133
- function flattenSubtreeRows(row) {
1134
- const children = row.children;
1135
- if (!Array.isArray(children) || children.length === 0) return [];
1136
- const result = [];
1137
- const walk = (nodes) => {
1138
- for (const node of nodes) {
1139
- result.push(node);
1140
- const nested = node.children;
1141
- if (Array.isArray(nested) && nested.length > 0) {
1142
- walk(nested);
1143
- }
1445
+ function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
1446
+ const cellEndRow = rowIndex + rowSpan - 1;
1447
+ const span = cellEndRow - rowIndex + 1;
1448
+ if (span <= 1) return [];
1449
+ const edges = [];
1450
+ const isNeighborSelected = (row, neighborCol) => {
1451
+ if (isVisuallySelectedAt) {
1452
+ return isVisuallySelectedAt(row, neighborCol);
1144
1453
  }
1454
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
1145
1455
  };
1146
- walk(children);
1147
- return result;
1148
- }
1149
- function hasSubtree(row) {
1150
- const children = row.children;
1151
- return Array.isArray(children) && children.length > 0;
1152
- }
1153
- function getOriginalRowId(original) {
1154
- return String(original.id ?? original.uniqueId ?? "");
1155
- }
1156
- function getRowDepth(original) {
1157
- return typeof original.level === "number" ? original.level : 0;
1158
- }
1159
- function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1160
- const { startRow, endRow } = bounds;
1161
- const result = [];
1162
- const includedOriginalIds = /* @__PURE__ */ new Set();
1163
- const appendSubtree = (node, depth) => {
1164
- const children = node.children;
1165
- if (!Array.isArray(children) || children.length === 0) return;
1166
- for (const child of children) {
1167
- const childId = getOriginalRowId(child);
1168
- if (!(childId && includedOriginalIds.has(childId))) {
1169
- result.push({ row: child, depth });
1170
- if (childId) includedOriginalIds.add(childId);
1456
+ const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
1457
+ let runStart = null;
1458
+ for (let row = fromRow; row < toRowExclusive; row++) {
1459
+ if (!isNeighborSelected(row, neighborCol)) {
1460
+ if (runStart === null) runStart = row;
1461
+ continue;
1462
+ }
1463
+ if (runStart !== null) {
1464
+ const ratios = rowRangeToHeightRatios(
1465
+ rowIndex,
1466
+ span,
1467
+ runStart,
1468
+ row,
1469
+ rowHeights
1470
+ );
1471
+ if (ratios.lengthRatio > 0) {
1472
+ edges.push({ side, ...ratios });
1473
+ }
1474
+ runStart = null;
1475
+ }
1476
+ }
1477
+ if (runStart !== null) {
1478
+ const ratios = rowRangeToHeightRatios(
1479
+ rowIndex,
1480
+ span,
1481
+ runStart,
1482
+ toRowExclusive,
1483
+ rowHeights
1484
+ );
1485
+ if (ratios.lengthRatio > 0) {
1486
+ edges.push({ side, ...ratios });
1171
1487
  }
1172
- appendSubtree(child, depth + 1);
1173
1488
  }
1174
1489
  };
1175
- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1176
- const row = visibleRows[rowIndex];
1177
- if (!row) continue;
1178
- const originalId = getOriginalRowId(row.original);
1179
- if (originalId && includedOriginalIds.has(originalId)) continue;
1180
- const depth = getRowDepth(row.original);
1181
- result.push({ row: row.original, depth });
1182
- if (originalId) includedOriginalIds.add(originalId);
1183
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
1184
- appendSubtree(row.original, depth + 1);
1490
+ const collectSide = (side, neighborCol) => {
1491
+ if (bounds.startRow > rowIndex) {
1492
+ pushUnselectedRuns(
1493
+ side,
1494
+ neighborCol,
1495
+ rowIndex,
1496
+ Math.min(bounds.startRow, cellEndRow + 1)
1497
+ );
1498
+ }
1499
+ if (bounds.endRow < cellEndRow) {
1500
+ pushUnselectedRuns(
1501
+ side,
1502
+ neighborCol,
1503
+ Math.max(bounds.endRow + 1, rowIndex),
1504
+ cellEndRow + 1
1505
+ );
1506
+ }
1507
+ };
1508
+ if (colIndex < bounds.endCol) {
1509
+ collectSide("right", colIndex + 1);
1510
+ }
1511
+ if (colIndex > bounds.startCol) {
1512
+ collectSide("left", colIndex - 1);
1513
+ }
1514
+ return edges;
1515
+ }
1516
+ function buildPartialEdgeGradient(edge) {
1517
+ const usePx = edge.offsetPx != null && edge.lengthPx != null;
1518
+ const startPct = edge.offsetRatio * 100;
1519
+ const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
1520
+ const startPx = edge.offsetPx ?? 0;
1521
+ const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
1522
+ const overlapPx = SELECTION_EDGE_WIDTH_PX;
1523
+ const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
1524
+ const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
1525
+ const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
1526
+ const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
1527
+ const xPos = edge.side === "left" ? "0" : "100%";
1528
+ const layers = [
1529
+ {
1530
+ image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
1531
+ size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
1532
+ position: `${xPos} 0`
1533
+ }
1534
+ ];
1535
+ if (isTopProtrusion || isBottomProtrusion) {
1536
+ const capTop = usePx ? isTopProtrusion ? `${Math.max(0, endPx - SELECTION_EDGE_WIDTH_PX)}px` : `${Math.max(0, startPx - SELECTION_EDGE_WIDTH_PX)}px` : isTopProtrusion ? `calc(${endPct}% - ${SELECTION_EDGE_WIDTH_PX}px)` : `calc(${startPct}% - ${SELECTION_EDGE_WIDTH_PX}px)`;
1537
+ layers.push({
1538
+ image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
1539
+ size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
1540
+ position: `${xPos} ${capTop}`
1541
+ });
1185
1542
  }
1186
- return result;
1187
- }
1188
- function collectCopyRows(visibleRows, bounds, mode = "visible") {
1189
- return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1190
- }
1191
- function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1192
- if (copyRows.length === 0) return "";
1193
- const { startCol, endCol } = bounds;
1194
- const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1195
- if (columnCells.length === 0) return "";
1196
- const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1197
- const minDepth = Math.min(...resolvedDepths);
1198
- const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1199
- const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1200
- const meta = templateCell.column.columnDef.meta;
1201
- if (meta?.copyValue === "omit") return [];
1202
- return [{ templateCell, colOffset }];
1203
- });
1204
- return copyRows.map((rowData, index) => {
1205
- const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1206
- const visibleRow = visibleRowByOriginal.get(rowData);
1207
- const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1208
- const line = copyableColumns.map(({ templateCell, colOffset }) => {
1209
- const sourceCell = matchingCells?.[colOffset];
1210
- const column = sourceCell?.column ?? templateCell.column;
1211
- return formatCopyCellText(
1212
- rowData,
1213
- column.columnDef,
1214
- resolveCopyColumnId(sourceCell ?? templateCell),
1215
- visibleRow,
1216
- visibleRow?.index ?? index,
1217
- sourceCell,
1218
- visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1219
- options
1220
- );
1221
- }).join(" ");
1222
- return `${" ".repeat(relativeDepth)}${line}`;
1223
- }).join("\n");
1543
+ return layers;
1224
1544
  }
1225
- function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1226
- const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1227
- return serializeCopyRowsToTSV(
1228
- entries.map((entry) => entry.row),
1229
- visibleRows,
1545
+ function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
1546
+ if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
1547
+ return void 0;
1548
+ const cellEndRow = rowIndex + rowSpan - 1;
1549
+ const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
1550
+ const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
1551
+ const isLeftEdge = colIndex === bounds.startCol;
1552
+ const isRightEdge = colIndex === bounds.endCol;
1553
+ const selectionContinuesBelow = cellEndRow < bounds.endRow;
1554
+ const stepEdges = getMergedCellStepEdges(
1555
+ rowIndex,
1556
+ colIndex,
1230
1557
  bounds,
1231
- entries.map((entry) => entry.depth),
1232
- options
1558
+ rowSpan,
1559
+ isVisuallySelectedAt,
1560
+ rowHeights
1233
1561
  );
1234
- }
1235
- function writeTextWithExecCommand(text) {
1236
- if (typeof document === "undefined") return false;
1237
- const textarea = document.createElement("textarea");
1238
- textarea.value = text;
1239
- textarea.setAttribute("readonly", "");
1240
- textarea.style.position = "fixed";
1241
- textarea.style.top = "0";
1242
- textarea.style.left = "0";
1243
- textarea.style.opacity = "0";
1244
- textarea.style.pointerEvents = "none";
1245
- document.body.appendChild(textarea);
1246
- const previouslyFocused = document.activeElement;
1247
- try {
1248
- textarea.focus();
1249
- textarea.select();
1250
- return document.execCommand("copy");
1251
- } catch {
1252
- return false;
1253
- } finally {
1254
- document.body.removeChild(textarea);
1255
- previouslyFocused?.focus?.();
1562
+ const shadows = [];
1563
+ const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
1564
+ if (hasFullPerimeter) {
1565
+ shadows.push(
1566
+ `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
1567
+ );
1568
+ } else {
1569
+ if (isTopEdge) {
1570
+ shadows.push(
1571
+ `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1572
+ );
1573
+ }
1574
+ if (isBottomEdge) {
1575
+ shadows.push(
1576
+ `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1577
+ );
1578
+ }
1579
+ if (isLeftEdge) {
1580
+ shadows.push(
1581
+ `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1582
+ );
1583
+ }
1584
+ if (isRightEdge) {
1585
+ shadows.push(
1586
+ `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1587
+ );
1588
+ }
1256
1589
  }
1257
- }
1258
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1259
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1260
- if (!text) return false;
1261
- if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1262
- return writeTextWithExecCommand(text);
1590
+ const gradients = [];
1591
+ const sizes = [];
1592
+ const positions = [];
1593
+ for (const edge of stepEdges) {
1594
+ for (const partial of buildPartialEdgeGradient(edge)) {
1595
+ gradients.push(partial.image);
1596
+ sizes.push(partial.size);
1597
+ positions.push(partial.position);
1598
+ }
1263
1599
  }
1264
- try {
1265
- await navigator.clipboard.writeText(text);
1266
- return true;
1267
- } catch {
1268
- return false;
1600
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1601
+ return void 0;
1602
+ }
1603
+ const style = {};
1604
+ if (shadows.length > 0) {
1605
+ style["--selection-edge-shadows"] = shadows.join(", ");
1606
+ }
1607
+ if (gradients.length > 0) {
1608
+ style["--selection-edge-gradients"] = gradients.join(", ");
1609
+ style["--selection-edge-sizes"] = sizes.join(", ");
1610
+ style["--selection-edge-positions"] = positions.join(", ");
1269
1611
  }
1612
+ if (selectionContinuesBelow) {
1613
+ style.borderBottomColor = "var(--color-brand-surface)";
1614
+ }
1615
+ return style;
1616
+ }
1617
+ function hasCellSelectionEdges(style) {
1618
+ return Boolean(
1619
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1620
+ );
1270
1621
  }
1271
1622
 
1272
1623
  // src/components/ui/table/features/cell-selection/fillData.ts
@@ -1291,6 +1642,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1291
1642
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1292
1643
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1293
1644
  if (!targetRow || !targetCell || !sourceCell) continue;
1645
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1646
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1294
1647
  const accessorKey = getColumnAccessorKey2(
1295
1648
  targetCell.column.columnDef
1296
1649
  );
@@ -1312,13 +1665,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1312
1665
  );
1313
1666
  }
1314
1667
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1315
- const newData = data.map((row) => ({ ...row }));
1316
1668
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1317
- for (const target of targets) {
1318
- if (!newData[target.rowIndex]) continue;
1319
- newData[target.rowIndex][target.accessorKey] = target.value;
1320
- }
1321
- return newData;
1669
+ return applyCellChangesToData(
1670
+ data,
1671
+ targets.flatMap((target) => {
1672
+ const row = rows[target.rowIndex];
1673
+ if (!row) return [];
1674
+ return [
1675
+ {
1676
+ original: row.original,
1677
+ index: row.index,
1678
+ accessorKey: target.accessorKey,
1679
+ value: target.value
1680
+ }
1681
+ ];
1682
+ })
1683
+ );
1322
1684
  }
1323
1685
  function hasFillExtension(sourceBounds, fillBounds) {
1324
1686
  if (!sourceBounds) return false;
@@ -1339,17 +1701,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1339
1701
  if (firstDepth !== 0) return false;
1340
1702
  return leadingEmptyCounts.some((depth) => depth > 0);
1341
1703
  }
1704
+ function splitTSV(text) {
1705
+ const rows = [];
1706
+ let row = [];
1707
+ let index = 0;
1708
+ while (index <= text.length) {
1709
+ let cell = "";
1710
+ if (text[index] === '"') {
1711
+ index += 1;
1712
+ while (index < text.length) {
1713
+ const char = text[index];
1714
+ if (char === '"') {
1715
+ if (text[index + 1] === '"') {
1716
+ cell += '"';
1717
+ index += 2;
1718
+ continue;
1719
+ }
1720
+ index += 1;
1721
+ break;
1722
+ }
1723
+ cell += char;
1724
+ index += 1;
1725
+ }
1726
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1727
+ cell += text[index];
1728
+ index += 1;
1729
+ }
1730
+ } else {
1731
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1732
+ cell += text[index];
1733
+ index += 1;
1734
+ }
1735
+ }
1736
+ row.push(cell);
1737
+ if (index >= text.length) {
1738
+ rows.push(row);
1739
+ break;
1740
+ }
1741
+ if (text[index] === "\n") {
1742
+ rows.push(row);
1743
+ row = [];
1744
+ }
1745
+ index += 1;
1746
+ }
1747
+ return rows;
1748
+ }
1342
1749
  function parseClipboardTSV(text) {
1343
1750
  return parseClipboardTSVWithDepths(text).values;
1344
1751
  }
1345
- function parseClipboardTSVWithDepths(text) {
1752
+ function parseClipboardTSVWithDepths(text, options) {
1346
1753
  if (!text) return { values: [], depths: [] };
1347
1754
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1348
1755
  const withoutTrailing = normalized.replace(/\n+$/, "");
1349
1756
  if (!withoutTrailing) return { values: [], depths: [] };
1350
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1757
+ const rows = splitTSV(withoutTrailing);
1351
1758
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1352
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1759
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1353
1760
  const values = [];
1354
1761
  const depths = [];
1355
1762
  for (let index = 0; index < rows.length; index += 1) {
@@ -1376,8 +1783,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1376
1783
  }
1377
1784
  return columnIds;
1378
1785
  }
1379
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1380
- const { values, depths } = parseClipboardTSVWithDepths(text);
1786
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1787
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1381
1788
  if (values.length === 0) return null;
1382
1789
  const width = Math.max(...values.map((row) => row.length), 0);
1383
1790
  if (width === 0) return null;
@@ -1410,6 +1817,19 @@ function isEditablePasteTarget(target) {
1410
1817
  }
1411
1818
 
1412
1819
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
1820
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
1821
+ function isInteractiveFocus() {
1822
+ const active = document.activeElement;
1823
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
1824
+ }
1825
+ function hasPageTextSelectionOutside(root) {
1826
+ if (typeof window.getSelection !== "function") return false;
1827
+ const selection = window.getSelection();
1828
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
1829
+ if (!selection.toString()) return false;
1830
+ const anchor = selection.anchorNode;
1831
+ return !(root && anchor && root.contains(anchor));
1832
+ }
1413
1833
  function isFocusOutsideRoot(rootRef) {
1414
1834
  const root = rootRef?.current;
1415
1835
  if (!root) return false;
@@ -1422,29 +1842,50 @@ function useCellSelection({
1422
1842
  rows,
1423
1843
  enabled = true,
1424
1844
  columnCount = 0,
1845
+ columnSignature,
1425
1846
  enableSubtreeCopy = false,
1847
+ escapeCopyFormulas = false,
1426
1848
  enableInsertPaste = true,
1427
1849
  onDataChange,
1428
1850
  onBatchChange,
1429
1851
  onRowsPaste,
1430
1852
  onCellNavigate,
1431
1853
  cellRendererRegistry,
1432
- rootRef
1854
+ rootRef,
1855
+ enableWasdNavigation = true,
1856
+ onEditKey,
1857
+ onClearKey
1433
1858
  }) {
1434
1859
  const ownerRef = (0, import_react3.useRef)(createCellSelectionOwner());
1435
1860
  const [dragState, setDragState] = (0, import_react3.useState)(INITIAL_DRAG_STATE);
1436
1861
  const pendingPasteModeRef = (0, import_react3.useRef)(null);
1437
1862
  const dragStateRef = (0, import_react3.useRef)(dragState);
1438
1863
  const onCellNavigateRef = (0, import_react3.useRef)(onCellNavigate);
1864
+ const onEditKeyRef = (0, import_react3.useRef)(onEditKey);
1865
+ const onClearKeyRef = (0, import_react3.useRef)(onClearKey);
1439
1866
  dragStateRef.current = dragState;
1440
1867
  onCellNavigateRef.current = onCellNavigate;
1441
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1442
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
1868
+ onEditKeyRef.current = onEditKey;
1869
+ onClearKeyRef.current = onClearKey;
1870
+ const updateDragState = (0, import_react3.useCallback)((update) => {
1871
+ const prev = dragStateRef.current;
1872
+ const next = update(prev);
1873
+ if (next === prev) return;
1874
+ dragStateRef.current = next;
1875
+ setDragState(next);
1876
+ }, []);
1877
+ const activeSelectionBounds = (0, import_react3.useMemo)(() => {
1878
+ if (!enabled) return null;
1879
+ return getActiveSelectionBounds(
1880
+ dragState,
1881
+ getCellSelectionBounds(dragState.start, dragState.end)
1882
+ );
1883
+ }, [dragState, enabled]);
1443
1884
  const handleCellMouseDown = (0, import_react3.useCallback)(
1444
1885
  (rowIndex, colIndex, options) => {
1445
1886
  if (!enabled) return;
1446
1887
  claimCellSelectionOwner(ownerRef.current);
1447
- setDragState((prev) => {
1888
+ updateDragState((prev) => {
1448
1889
  if (options?.shiftKey && prev.start) {
1449
1890
  return {
1450
1891
  ...prev,
@@ -1465,28 +1906,30 @@ function useCellSelection({
1465
1906
  };
1466
1907
  });
1467
1908
  },
1468
- [enabled]
1909
+ [enabled, updateDragState]
1469
1910
  );
1470
1911
  const handleCellMouseEnter = (0, import_react3.useCallback)(
1471
1912
  (rowIndex, colIndex) => {
1472
1913
  if (!enabled) return;
1473
- setDragState((prev) => {
1914
+ updateDragState((prev) => {
1474
1915
  if (prev.isSelecting) {
1916
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1475
1917
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1476
1918
  }
1477
1919
  if (prev.isFillDragging) {
1920
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1478
1921
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1479
1922
  }
1480
1923
  return prev;
1481
1924
  });
1482
1925
  },
1483
- [enabled]
1926
+ [enabled, updateDragState]
1484
1927
  );
1485
1928
  const handleFillHandleMouseDown = (0, import_react3.useCallback)(
1486
1929
  (rowIndex, colIndex) => {
1487
1930
  if (!enabled) return;
1488
1931
  claimCellSelectionOwner(ownerRef.current);
1489
- setDragState((prev) => {
1932
+ updateDragState((prev) => {
1490
1933
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1491
1934
  if (!bounds) return prev;
1492
1935
  return {
@@ -1498,7 +1941,7 @@ function useCellSelection({
1498
1941
  };
1499
1942
  });
1500
1943
  },
1501
- [enabled]
1944
+ [enabled, updateDragState]
1502
1945
  );
1503
1946
  const clearSelection = (0, import_react3.useCallback)(() => {
1504
1947
  const prev = dragStateRef.current;
@@ -1517,6 +1960,130 @@ function useCellSelection({
1517
1960
  (0, import_react3.useEffect)(() => {
1518
1961
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1519
1962
  }, [clearSelection]);
1963
+ const previousColumnSignatureRef = (0, import_react3.useRef)(columnSignature);
1964
+ (0, import_react3.useEffect)(() => {
1965
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
1966
+ previousColumnSignatureRef.current = columnSignature;
1967
+ const prev = dragStateRef.current;
1968
+ if (!prev.start || !prev.end) return;
1969
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1970
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
1971
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
1972
+ if (columnsChanged || outOfRange) {
1973
+ clearSelection();
1974
+ }
1975
+ }, [clearSelection, columnCount, columnSignature, rows]);
1976
+ (0, import_react3.useEffect)(() => {
1977
+ if (!enabled) return;
1978
+ const handlePointerDown = (event) => {
1979
+ const root = rootRef?.current;
1980
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
1981
+ if (event.target instanceof Node && root.contains(event.target)) return;
1982
+ releaseCellSelectionOwner(ownerRef.current);
1983
+ };
1984
+ document.addEventListener("pointerdown", handlePointerDown, true);
1985
+ document.addEventListener("mousedown", handlePointerDown, true);
1986
+ return () => {
1987
+ document.removeEventListener("pointerdown", handlePointerDown, true);
1988
+ document.removeEventListener("mousedown", handlePointerDown, true);
1989
+ };
1990
+ }, [enabled, rootRef]);
1991
+ const getColumnCount = (0, import_react3.useCallback)(
1992
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
1993
+ [columnCount, rows]
1994
+ );
1995
+ const selectCell = (0, import_react3.useCallback)(
1996
+ (row, col) => {
1997
+ if (!enabled) return;
1998
+ const resolvedColumnCount = getColumnCount();
1999
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
2000
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
2001
+ claimCellSelectionOwner(ownerRef.current);
2002
+ const nextState = {
2003
+ isSelecting: false,
2004
+ isFillDragging: false,
2005
+ start: position,
2006
+ end: position,
2007
+ fillAnchor: null,
2008
+ fillEnd: null
2009
+ };
2010
+ dragStateRef.current = nextState;
2011
+ setDragState(nextState);
2012
+ onCellNavigateRef.current?.(position);
2013
+ },
2014
+ [enabled, getColumnCount, rows.length]
2015
+ );
2016
+ const focusSelection = (0, import_react3.useCallback)(() => {
2017
+ if (!enabled) return;
2018
+ const prev = dragStateRef.current;
2019
+ if (prev.start && prev.end) {
2020
+ claimCellSelectionOwner(ownerRef.current);
2021
+ return;
2022
+ }
2023
+ selectCell(0, 0);
2024
+ }, [enabled, selectCell]);
2025
+ (0, import_react3.useEffect)(() => {
2026
+ if (!enabled) return;
2027
+ const handleKeyDown = (e) => {
2028
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
2029
+ if (e.altKey) return;
2030
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
2031
+ return;
2032
+ }
2033
+ if (isFocusOutsideRoot(rootRef)) return;
2034
+ const prev = dragStateRef.current;
2035
+ if (!prev.start || !prev.end) return;
2036
+ if (prev.isSelecting || prev.isFillDragging) return;
2037
+ const rowCount = rows.length;
2038
+ const resolvedColumnCount = getColumnCount();
2039
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
2040
+ const withModifier = e.ctrlKey || e.metaKey;
2041
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
2042
+ e.preventDefault();
2043
+ claimCellSelectionOwner(ownerRef.current);
2044
+ const nextState = {
2045
+ isSelecting: false,
2046
+ isFillDragging: false,
2047
+ start: { row: 0, col: 0 },
2048
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
2049
+ fillAnchor: null,
2050
+ fillEnd: null
2051
+ };
2052
+ dragStateRef.current = nextState;
2053
+ setDragState(nextState);
2054
+ return;
2055
+ }
2056
+ if (e.key === "Home" || e.key === "End") {
2057
+ e.preventDefault();
2058
+ const toEnd = e.key === "End";
2059
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
2060
+ if (e.shiftKey) {
2061
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
2062
+ dragStateRef.current = nextState;
2063
+ setDragState(nextState);
2064
+ onCellNavigateRef.current?.(target);
2065
+ } else {
2066
+ selectCell(target.row, target.col);
2067
+ }
2068
+ return;
2069
+ }
2070
+ if (withModifier || isInteractiveFocus()) return;
2071
+ if (e.key === "Enter" || e.key === "F2") {
2072
+ if (!onEditKeyRef.current) return;
2073
+ e.preventDefault();
2074
+ onEditKeyRef.current(prev.end);
2075
+ return;
2076
+ }
2077
+ if (e.key === "Delete" || e.key === "Backspace") {
2078
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
2079
+ if (!bounds || !onClearKeyRef.current) return;
2080
+ e.preventDefault();
2081
+ onClearKeyRef.current(bounds);
2082
+ }
2083
+ };
2084
+ window.addEventListener("keydown", handleKeyDown);
2085
+ return () => window.removeEventListener("keydown", handleKeyDown);
2086
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
1520
2087
  (0, import_react3.useEffect)(() => {
1521
2088
  if (!enabled) return;
1522
2089
  const handleKeyDown = (e) => {
@@ -1526,6 +2093,7 @@ function useCellSelection({
1526
2093
  return;
1527
2094
  }
1528
2095
  if (isFocusOutsideRoot(rootRef)) return;
2096
+ if (!enableWasdNavigation && e.key.length === 1) return;
1529
2097
  const delta = getCellNavigationDelta(e.key);
1530
2098
  if (!delta) return;
1531
2099
  const prev = dragStateRef.current;
@@ -1565,14 +2133,15 @@ function useCellSelection({
1565
2133
  };
1566
2134
  window.addEventListener("keydown", handleKeyDown);
1567
2135
  return () => window.removeEventListener("keydown", handleKeyDown);
1568
- }, [columnCount, enabled, rows]);
2136
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1569
2137
  const copySelection = (0, import_react3.useCallback)(
1570
2138
  async (options) => {
1571
2139
  if (!enabled || !activeSelectionBounds) return false;
1572
2140
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1573
2141
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1574
2142
  registry: cellRendererRegistry,
1575
- root: rootRef?.current
2143
+ root: rootRef?.current,
2144
+ escapeFormulas: escapeCopyFormulas
1576
2145
  });
1577
2146
  },
1578
2147
  [
@@ -1580,6 +2149,7 @@ function useCellSelection({
1580
2149
  cellRendererRegistry,
1581
2150
  enableSubtreeCopy,
1582
2151
  enabled,
2152
+ escapeCopyFormulas,
1583
2153
  rootRef,
1584
2154
  rows
1585
2155
  ]
@@ -1597,6 +2167,7 @@ function useCellSelection({
1597
2167
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1598
2168
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1599
2169
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2170
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1600
2171
  e.preventDefault();
1601
2172
  void copySelection({ includeDescendants: isSubtreeShortcut });
1602
2173
  };
@@ -1612,9 +2183,17 @@ function useCellSelection({
1612
2183
  activeSelectionBounds.startCol,
1613
2184
  text,
1614
2185
  mode,
1615
- activeSelectionBounds.endRow
2186
+ activeSelectionBounds.endRow,
2187
+ // Leading blank cells are tree depth only in this table's own subtree
2188
+ // copy; from a spreadsheet they are real (empty) cells.
2189
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
1616
2190
  );
1617
2191
  if (!payload) return false;
2192
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
2193
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
2194
+ const cell = cells.find((item) => item.column.id === columnId);
2195
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
2196
+ });
1618
2197
  onRowsPaste(payload);
1619
2198
  return true;
1620
2199
  },
@@ -1645,7 +2224,10 @@ function useCellSelection({
1645
2224
  void (async () => {
1646
2225
  try {
1647
2226
  const text = await navigator.clipboard.readText();
1648
- if (pasteHandledRef.current) return;
2227
+ if (pasteHandledRef.current) {
2228
+ pasteHandledRef.current = false;
2229
+ return;
2230
+ }
1649
2231
  if (pendingPasteModeRef.current !== mode) return;
1650
2232
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1651
2233
  if (!text) return;
@@ -1670,6 +2252,7 @@ function useCellSelection({
1670
2252
  }
1671
2253
  const mode = pendingPasteModeRef.current ?? "overwrite";
1672
2254
  if (pasteHandledRef.current) {
2255
+ pasteHandledRef.current = false;
1673
2256
  e.preventDefault();
1674
2257
  return;
1675
2258
  }
@@ -1696,39 +2279,41 @@ function useCellSelection({
1696
2279
  (0, import_react3.useEffect)(() => {
1697
2280
  if (!enabled) return;
1698
2281
  const handleMouseUp = () => {
1699
- setDragState((prev) => {
1700
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1701
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1702
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1703
- if (newBounds) {
1704
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1705
- if (onBatchChange) {
1706
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1707
- if (changes.length > 0) {
1708
- onBatchChange(changes);
1709
- }
1710
- } else if (onDataChange) {
1711
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
2282
+ const prev = dragStateRef.current;
2283
+ let next = prev;
2284
+ if (prev.isFillDragging && prev.fillEnd) {
2285
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
2286
+ if (sourceBounds) {
2287
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
2288
+ if (hasFillExtension(sourceBounds, newBounds)) {
2289
+ if (onBatchChange) {
2290
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
2291
+ if (changes.length > 0) {
2292
+ onBatchChange(changes);
1712
2293
  }
2294
+ } else if (onDataChange) {
2295
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1713
2296
  }
1714
- return {
1715
- isSelecting: false,
1716
- isFillDragging: false,
1717
- start: { row: newBounds.startRow, col: newBounds.startCol },
1718
- end: { row: newBounds.endRow, col: newBounds.endCol },
1719
- fillAnchor: null,
1720
- fillEnd: null
1721
- };
1722
2297
  }
2298
+ next = {
2299
+ isSelecting: false,
2300
+ isFillDragging: false,
2301
+ start: { row: newBounds.startRow, col: newBounds.startCol },
2302
+ end: { row: newBounds.endRow, col: newBounds.endCol },
2303
+ fillAnchor: null,
2304
+ fillEnd: null
2305
+ };
2306
+ } else {
2307
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1723
2308
  }
1724
- if (prev.isSelecting) {
1725
- return { ...prev, isSelecting: false };
1726
- }
1727
- if (prev.isFillDragging) {
1728
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1729
- }
1730
- return prev;
1731
- });
2309
+ } else if (prev.isSelecting) {
2310
+ next = { ...prev, isSelecting: false };
2311
+ } else if (prev.isFillDragging) {
2312
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
2313
+ }
2314
+ if (next === prev) return;
2315
+ dragStateRef.current = next;
2316
+ setDragState(next);
1732
2317
  };
1733
2318
  window.addEventListener("mouseup", handleMouseUp);
1734
2319
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1740,7 +2325,27 @@ function useCellSelection({
1740
2325
  handleCellMouseEnter,
1741
2326
  handleFillHandleMouseDown,
1742
2327
  clearSelection,
1743
- copySelection
2328
+ copySelection,
2329
+ selectCell,
2330
+ focusSelection
2331
+ };
2332
+ }
2333
+
2334
+ // src/components/ui/table/features/row-hover/rowHover.ts
2335
+ function createRowHoverStore() {
2336
+ let hoveredRowIndex = null;
2337
+ const listeners = /* @__PURE__ */ new Set();
2338
+ return {
2339
+ getHoveredRowIndex: () => hoveredRowIndex,
2340
+ setHoveredRowIndex: (nextRowIndex) => {
2341
+ if (nextRowIndex === hoveredRowIndex) return;
2342
+ hoveredRowIndex = nextRowIndex;
2343
+ listeners.forEach((listener) => listener());
2344
+ },
2345
+ subscribe: (listener) => {
2346
+ listeners.add(listener);
2347
+ return () => listeners.delete(listener);
2348
+ }
1744
2349
  };
1745
2350
  }
1746
2351
 
@@ -2034,170 +2639,33 @@ function flattenHeaderLeaves(column) {
2034
2639
  return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2035
2640
  }
2036
2641
 
2037
- // src/components/ui/table/features/inline-search/inlineSearch.ts
2038
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
2039
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
2040
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
2041
- function escapeSearchRegex(value) {
2042
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
2043
- }
2044
- function createSearchRegex(query) {
2045
- const trimmed = query.trim();
2046
- if (!trimmed) return null;
2047
- return new RegExp(escapeSearchRegex(trimmed), "i");
2048
- }
2049
- function cellValueToSearchText(value) {
2050
- if (value == null) return void 0;
2051
- if (typeof value === "string") return value;
2052
- if (typeof value === "number" || typeof value === "boolean") {
2053
- return String(value);
2054
- }
2055
- if (Array.isArray(value)) {
2056
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
2057
- }
2058
- if (typeof value === "object") {
2059
- try {
2060
- return JSON.stringify(value);
2061
- } catch {
2062
- return String(value);
2063
- }
2064
- }
2065
- return String(value);
2066
- }
2067
- function formatSearchResultLabel(status) {
2068
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
2069
- if (status.selectedIndex >= 0 && status.results > 0) {
2070
- return `${status.selectedIndex + 1} of ${countLabel}`;
2071
- }
2072
- return countLabel;
2073
- }
2074
- function nextSearchIndex(selectedIndex, results) {
2075
- if (results <= 0) return -1;
2076
- if (selectedIndex < 0) return 0;
2077
- return (selectedIndex + 1) % results;
2078
- }
2079
- function previousSearchIndex(selectedIndex, results) {
2080
- if (results <= 0) return -1;
2081
- if (selectedIndex < 0) return results - 1;
2082
- let next = (selectedIndex - 1) % results;
2083
- if (next < 0) next += results;
2084
- return next;
2085
- }
2086
- function buildSearchMatchKey(colIndex, rowIndex) {
2087
- return `${colIndex}:${rowIndex}`;
2088
- }
2089
- function buildSearchMatchKeys(results) {
2090
- const keys = /* @__PURE__ */ new Set();
2091
- for (const [colIndex, rowIndex] of results) {
2092
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
2093
- }
2094
- return keys;
2095
- }
2096
- function collectSearchMatchesInRange(options) {
2097
- const {
2098
- query,
2099
- startRow,
2100
- rowCount,
2101
- columnCount,
2102
- getCellValue,
2103
- maxResults = INLINE_SEARCH_MAX_RESULTS
2104
- } = options;
2105
- const regex = createSearchRegex(query);
2106
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
2107
- const matches = [];
2108
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2109
- const rowIndex = startRow + rowOffset;
2110
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2111
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2112
- if (text !== void 0 && regex.test(text)) {
2113
- matches.push([colIndex, rowIndex]);
2114
- if (matches.length >= maxResults) {
2115
- return matches;
2116
- }
2117
- }
2118
- }
2642
+ // src/components/ui/table/features/inline-search/useInlineSearch.ts
2643
+ var import_react4 = require("react");
2644
+ var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2645
+ var searchInstanceCount = 0;
2646
+ var lastPointerTarget = null;
2647
+ function trackPointerTarget(event) {
2648
+ lastPointerTarget = event.target;
2649
+ }
2650
+ function registerSearchInstance() {
2651
+ if (searchInstanceCount === 0) {
2652
+ document.addEventListener("pointerdown", trackPointerTarget, true);
2119
2653
  }
2120
- return matches;
2121
- }
2122
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2123
- const rounded = Math.max(elapsedMs, 1);
2124
- const scalar = targetMs / rounded;
2125
- return Math.max(1, Math.ceil(currentStride * scalar));
2126
- }
2127
- function buildFlatSearchCorpus(rows, getRowId) {
2128
- return rows.map((data, index) => ({
2129
- id: getRowId(data, index),
2130
- data,
2131
- ancestorToggleKeys: []
2132
- }));
2133
- }
2134
- function buildTreeSearchCorpus(visibleRows, options) {
2135
- const { toggleField, getRowId } = options;
2136
- const corpus = [];
2137
- const seen = /* @__PURE__ */ new Set();
2138
- const walk = (node, ancestorToggleKeys) => {
2139
- const id = getRowId(node, corpus.length);
2140
- if (seen.has(id)) return;
2141
- seen.add(id);
2142
- corpus.push({
2143
- id,
2144
- data: node,
2145
- ancestorToggleKeys
2146
- });
2147
- const children = node.children;
2148
- if (!Array.isArray(children) || children.length === 0) return;
2149
- const toggleValue = node[toggleField];
2150
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2151
- for (const child of children) {
2152
- if (child && typeof child === "object") {
2153
- walk(child, childAncestors);
2154
- }
2654
+ searchInstanceCount += 1;
2655
+ return () => {
2656
+ searchInstanceCount -= 1;
2657
+ if (searchInstanceCount === 0) {
2658
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2659
+ lastPointerTarget = null;
2155
2660
  }
2156
2661
  };
2157
- for (const row of visibleRows) {
2158
- const level = row.level;
2159
- if (level === 0 || level === void 0) {
2160
- walk(row, []);
2161
- }
2162
- }
2163
- for (const row of visibleRows) {
2164
- const id = getRowId(row, corpus.length);
2165
- if (seen.has(id)) continue;
2166
- walk(row, []);
2167
- }
2168
- return corpus;
2169
- }
2170
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2171
- const keys = /* @__PURE__ */ new Set();
2172
- for (const [colIndex, corpusRowIndex] of results) {
2173
- const corpusRow = corpus[corpusRowIndex];
2174
- if (!corpusRow) continue;
2175
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2176
- if (visibleRowIndex === void 0) continue;
2177
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2178
- }
2179
- return keys;
2180
- }
2181
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2182
- const [colIndex, corpusRowIndex] = item;
2183
- const corpusRow = corpus[corpusRowIndex];
2184
- if (!corpusRow) return null;
2185
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2186
- if (visibleRowIndex === void 0) return null;
2187
- return [colIndex, visibleRowIndex];
2188
- }
2189
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2190
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2191
2662
  }
2192
-
2193
- // src/components/ui/table/features/inline-search/useInlineSearch.ts
2194
- var import_react4 = require("react");
2195
- var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2196
2663
  function useInlineSearch({
2197
2664
  enabled = false,
2198
2665
  rowCount,
2199
2666
  columnCount,
2200
2667
  getCellValue,
2668
+ contentKey,
2201
2669
  initialStartRow = 0,
2202
2670
  showSearch: controlledShowSearch,
2203
2671
  searchValue: controlledSearchValue,
@@ -2406,6 +2874,7 @@ function useInlineSearch({
2406
2874
  }
2407
2875
  beginSearch(searchValue);
2408
2876
  }, [
2877
+ contentKey,
2409
2878
  beginSearch,
2410
2879
  cancelSearch,
2411
2880
  controlledSearchResults,
@@ -2426,6 +2895,9 @@ function useInlineSearch({
2426
2895
  if (!focusInside && active !== document.body) {
2427
2896
  return;
2428
2897
  }
2898
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2899
+ return;
2900
+ }
2429
2901
  }
2430
2902
  event.preventDefault();
2431
2903
  event.stopPropagation();
@@ -2439,7 +2911,11 @@ function useInlineSearch({
2439
2911
  }
2440
2912
  };
2441
2913
  window.addEventListener("keydown", handleKeyDown, true);
2442
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2914
+ const releaseInstance = registerSearchInstance();
2915
+ return () => {
2916
+ window.removeEventListener("keydown", handleKeyDown, true);
2917
+ releaseInstance();
2918
+ };
2443
2919
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2444
2920
  (0, import_react4.useEffect)(() => () => cancelSearch(), [cancelSearch]);
2445
2921
  const searchMatchKeys = (0, import_react4.useMemo)(
@@ -2495,8 +2971,12 @@ function getFieldValue(row, key) {
2495
2971
  }
2496
2972
  function canExpandRow(row) {
2497
2973
  const children = row.children;
2498
- const level = row.level;
2499
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
2974
+ return Array.isArray(children) && children.length > 0;
2975
+ }
2976
+ function toTreeToggleKey(value) {
2977
+ if (value === null || value === void 0) return null;
2978
+ const key = String(value);
2979
+ return key.length > 0 ? key : null;
2500
2980
  }
2501
2981
  function toggleExpandedRowId(rowId, previous) {
2502
2982
  const next = new Set(previous);
@@ -2517,7 +2997,8 @@ var useConvertTreeData = ({
2517
2997
  preventExpand = false,
2518
2998
  startIndex = 1,
2519
2999
  expandedRows,
2520
- onExpandedRowsChange
3000
+ onExpandedRowsChange,
3001
+ autoExpandOnLoad = true
2521
3002
  }) => {
2522
3003
  const onExpandedRowsChangeRef = (0, import_react5.useRef)(onExpandedRowsChange);
2523
3004
  const hasInitializedRef = (0, import_react5.useRef)(false);
@@ -2530,16 +3011,33 @@ var useConvertTreeData = ({
2530
3011
  return;
2531
3012
  }
2532
3013
  if (!enabled || hasInitializedRef.current) return;
2533
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2534
- onExpandedRowsChangeRef.current?.(new Set(ids));
2535
3014
  hasInitializedRef.current = true;
2536
- }, [enabled, data, toggleField]);
3015
+ if (!autoExpandOnLoad) return;
3016
+ const ids = /* @__PURE__ */ new Set();
3017
+ const collect = (items) => {
3018
+ for (const item of items) {
3019
+ if (!item || typeof item !== "object") continue;
3020
+ const record = item;
3021
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
3022
+ if (key) ids.add(key);
3023
+ const nested = record[flattenField];
3024
+ if (Array.isArray(nested)) collect(nested);
3025
+ }
3026
+ };
3027
+ collect(data);
3028
+ onExpandedRowsChangeRef.current?.(ids);
3029
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
2537
3030
  const processedData = (0, import_react5.useMemo)(() => {
2538
3031
  if (!enabled || !data || data.length === 0) return [];
2539
3032
  const flattenedData = [];
2540
- const flattenItems = (items) => {
2541
- items.forEach((item) => {
2542
- const newItem = { ...item };
3033
+ const flattenItems = (items, parentPath) => {
3034
+ items.forEach((item, itemIndex) => {
3035
+ if (!item || typeof item !== "object") return;
3036
+ const source = {
3037
+ path: [...parentPath, itemIndex],
3038
+ childrenField: flattenField
3039
+ };
3040
+ const newItem = { ...item, [TREE_SOURCE]: source };
2543
3041
  const nested = newItem[flattenField];
2544
3042
  if (Array.isArray(nested)) {
2545
3043
  const children = nested.map(
@@ -2553,89 +3051,68 @@ var useConvertTreeData = ({
2553
3051
  child[childField] = newItem[toggleField];
2554
3052
  }
2555
3053
  });
2556
- flattenItems(children);
3054
+ flattenItems(children, source.path);
2557
3055
  } else {
2558
3056
  flattenedData.push(newItem);
2559
3057
  }
2560
3058
  });
2561
3059
  };
2562
- flattenItems(data);
3060
+ flattenItems(data, []);
2563
3061
  const dataWithLevels = flattenedData.map((item) => ({
2564
3062
  ...item,
2565
3063
  level: 0,
2566
3064
  children: [],
2567
3065
  processed: false
2568
3066
  }));
2569
- const findNearestPrecedingParent = (index, parentKey) => {
2570
- for (let i = index - 1; i >= 0; i -= 1) {
2571
- const candidate = dataWithLevels[i];
2572
- if (!candidate) continue;
2573
- if (getFieldValue(candidate, toggleField) === parentKey) {
2574
- return candidate;
2575
- }
2576
- }
2577
- return void 0;
2578
- };
2579
3067
  const rootItems = [];
3068
+ const latestByKey = /* @__PURE__ */ new Map();
2580
3069
  dataWithLevels.forEach((item) => {
2581
- if (!getFieldValue(item, childField)) {
2582
- rootItems.push(item);
2583
- item.processed = true;
2584
- }
2585
- });
2586
- dataWithLevels.forEach((item, index) => {
2587
3070
  const parentKey = getFieldValue(item, childField);
2588
- if (!parentKey || item.processed) return;
2589
- const parent = findNearestPrecedingParent(index, parentKey);
3071
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2590
3072
  if (parent) {
2591
3073
  item.level = parent.level + 1;
2592
3074
  parent.children.push(item);
2593
- item.processed = true;
2594
- return;
3075
+ } else {
3076
+ rootItems.push(item);
2595
3077
  }
2596
- rootItems.push(item);
2597
3078
  item.processed = true;
3079
+ latestByKey.set(getFieldValue(item, toggleField), item);
2598
3080
  });
2599
3081
  return rootItems;
2600
3082
  }, [enabled, data, toggleField, childField, flattenField]);
2601
3083
  const flattenTree = (0, import_react5.useMemo)(() => {
2602
3084
  if (!enabled) return [];
2603
- const flatten = (nodes, result = [], level = 0) => {
3085
+ const flatten = (nodes, result, parentTreeNo) => {
2604
3086
  nodes.forEach((node, index) => {
2605
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
3087
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2606
3088
  const toggleValue = getFieldValue(node, toggleField);
2607
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3089
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2608
3090
  result.push({
2609
3091
  ...node,
2610
3092
  treeNo: currentIndex,
2611
3093
  uniqueId,
2612
3094
  processed: true
2613
3095
  });
2614
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
3096
+ const toggleKey = toTreeToggleKey(toggleValue);
3097
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
2615
3098
  if (shouldExpandChildren) {
2616
- flatten(node.children, result, index + startIndex);
3099
+ flatten(node.children, result, currentIndex);
2617
3100
  }
2618
3101
  });
2619
3102
  return result;
2620
3103
  };
2621
- const flattenedData = flatten(processedData, [], 0);
2622
- flattenedData.forEach((item, index) => {
3104
+ const flattenedData = flatten(processedData, [], null);
3105
+ const latestByKey = /* @__PURE__ */ new Map();
3106
+ flattenedData.forEach((item) => {
2623
3107
  const parentKey = getFieldValue(item, childField);
2624
3108
  if (!parentKey) {
2625
3109
  item.parentCount = 1;
2626
- return;
2627
- }
2628
- let parentItem;
2629
- for (let i = index - 1; i >= 0; i -= 1) {
2630
- const candidate = flattenedData[i];
2631
- if (!candidate) continue;
2632
- if (getFieldValue(candidate, toggleField) === parentKey) {
2633
- parentItem = candidate;
2634
- break;
2635
- }
3110
+ } else {
3111
+ const parentItem = latestByKey.get(parentKey);
3112
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3113
+ item.parentCount = parentAmount || 1;
2636
3114
  }
2637
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2638
- item.parentCount = parentAmount || 1;
3115
+ latestByKey.set(getFieldValue(item, toggleField), item);
2639
3116
  });
2640
3117
  return flattenedData;
2641
3118
  }, [
@@ -2652,18 +3129,7 @@ var useConvertTreeData = ({
2652
3129
  if (!enabled) {
2653
3130
  return data ?? [];
2654
3131
  }
2655
- return [...flattenTree].sort((a, b) => {
2656
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2657
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2658
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2659
- const aVal = aParts[i] || 0;
2660
- const bVal = bParts[i] || 0;
2661
- if (aVal !== bVal) {
2662
- return aVal - bVal;
2663
- }
2664
- }
2665
- return 0;
2666
- });
3132
+ return flattenTree;
2667
3133
  }, [enabled, data, flattenTree]);
2668
3134
  return sortedData;
2669
3135
  };
@@ -2721,13 +3187,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2721
3187
  for (let index = 0; index < data.length; index++) {
2722
3188
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2723
3189
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2724
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3190
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2725
3191
  result.push({ rowSpan: 0, isFirstInGroup: false });
2726
3192
  continue;
2727
3193
  }
2728
3194
  let span = 1;
2729
3195
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2730
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3196
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2731
3197
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2732
3198
  span++;
2733
3199
  }
@@ -2820,6 +3286,9 @@ function collectRowSpanColumns(columns) {
2820
3286
  }
2821
3287
 
2822
3288
  // src/core/useGlideTable.ts
3289
+ function isProductionBuild() {
3290
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3291
+ }
2823
3292
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2824
3293
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2825
3294
  function useGlideTable(options) {
@@ -2841,18 +3310,24 @@ function useGlideTable(options) {
2841
3310
  selectOnRowClick = true,
2842
3311
  enableCellSelection = true,
2843
3312
  onDataChange,
2844
- onCellChange,
2845
- onBatchChange,
3313
+ onCellChange: onCellChangeProp,
3314
+ onBatchChange: onBatchChangeProp,
2846
3315
  cellRenderers,
2847
3316
  preserveRowSelection = false,
2848
- toggleField,
2849
- childField,
2850
- flattenField,
3317
+ toggleField: toggleFieldProp,
3318
+ idField,
3319
+ childField: childFieldProp,
3320
+ parentIdField,
3321
+ flattenField: flattenFieldProp,
3322
+ childrenField,
2851
3323
  qtyField,
3324
+ expandColumn,
2852
3325
  expandedRows: controlledExpandedRows,
2853
3326
  onExpandedRowsChange,
2854
3327
  preventExpand = false,
3328
+ autoExpandOnLoad = true,
2855
3329
  enableSubtreeCopy,
3330
+ escapeCopyFormulas = false,
2856
3331
  onCopyActionsReady,
2857
3332
  onRowsPaste,
2858
3333
  enableInsertPaste,
@@ -2873,8 +3348,27 @@ function useGlideTable(options) {
2873
3348
  onSearchValueChange,
2874
3349
  onSearchClose,
2875
3350
  searchResults,
2876
- onSearchResultsChanged
3351
+ onSearchResultsChanged,
3352
+ enableWasdNavigation = true
2877
3353
  } = options;
3354
+ const toggleField = toggleFieldProp ?? idField;
3355
+ const childField = childFieldProp ?? parentIdField;
3356
+ const flattenField = flattenFieldProp ?? childrenField;
3357
+ const onCellChange = (0, import_react6.useMemo)(() => {
3358
+ if (onCellChangeProp) return onCellChangeProp;
3359
+ if (!onBatchChangeProp) return void 0;
3360
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
3361
+ }, [onBatchChangeProp, onCellChangeProp]);
3362
+ const onBatchChange = (0, import_react6.useMemo)(() => {
3363
+ if (onBatchChangeProp) return onBatchChangeProp;
3364
+ if (!onCellChangeProp) return void 0;
3365
+ return (changes) => {
3366
+ for (const change of changes) {
3367
+ onCellChangeProp(change.rowId, change.columnId, change.value);
3368
+ }
3369
+ };
3370
+ }, [onBatchChangeProp, onCellChangeProp]);
3371
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
2878
3372
  const labels = (0, import_react6.useMemo)(() => {
2879
3373
  const resolved = resolveDataTableLabels(labelsProp);
2880
3374
  return {
@@ -2892,7 +3386,7 @@ function useGlideTable(options) {
2892
3386
  const [internalExpandedRows, setInternalExpandedRows] = (0, import_react6.useState)(
2893
3387
  () => /* @__PURE__ */ new Set()
2894
3388
  );
2895
- const [hoveredRowIndex, setHoveredRowIndex] = (0, import_react6.useState)(null);
3389
+ const [hoverStore] = (0, import_react6.useState)(createRowHoverStore);
2896
3390
  const scrollRef = (0, import_react6.useRef)(null);
2897
3391
  const rootRef = (0, import_react6.useRef)(null);
2898
3392
  const escapeDismissOwnerRef = (0, import_react6.useRef)(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
@@ -2949,8 +3443,10 @@ function useGlideTable(options) {
2949
3443
  qtyField,
2950
3444
  expandedRows,
2951
3445
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2952
- preventExpand
3446
+ preventExpand,
3447
+ autoExpandOnLoad
2953
3448
  });
3449
+ const sourceData = (0, import_react6.useMemo)(() => data ?? [], [data]);
2954
3450
  const table = (0, import_react_table.useReactTable)({
2955
3451
  data: tableData,
2956
3452
  columns: tableColumns,
@@ -2989,7 +3485,11 @@ function useGlideTable(options) {
2989
3485
  );
2990
3486
  },
2991
3487
  getCoreRowModel: (0, import_react_table.getCoreRowModel)(),
2992
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
3488
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
3489
+ // Tree rows: their path in the original data, which (unlike the
3490
+ // flattened index) survives expanding/collapsing rows above.
3491
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
3492
+ )
2993
3493
  });
2994
3494
  const rowSpanColumnKeys = (0, import_react6.useMemo)(() => {
2995
3495
  if (!enableRowSpan) return [];
@@ -3006,6 +3506,20 @@ function useGlideTable(options) {
3006
3506
  const rows = table.getRowModel().rows;
3007
3507
  const columnCount = table.getAllLeafColumns().length || 1;
3008
3508
  const visibleLeafColumns = table.getVisibleLeafColumns();
3509
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
3510
+ const warnedBooleanColumnsRef = (0, import_react6.useRef)(/* @__PURE__ */ new Set());
3511
+ (0, import_react6.useEffect)(() => {
3512
+ if (!hasWriteCallback || isProductionBuild()) return;
3513
+ for (const column of visibleLeafColumns) {
3514
+ const meta = column.columnDef.meta;
3515
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
3516
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
3517
+ warnedBooleanColumnsRef.current.add(column.id);
3518
+ console.warn(
3519
+ `[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.`
3520
+ );
3521
+ }
3522
+ }, [hasWriteCallback, visibleLeafColumns]);
3009
3523
  const columnFreezeOffsets = (0, import_react6.useMemo)(() => {
3010
3524
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
3011
3525
  return buildColumnFreezeOffsets(
@@ -3048,7 +3562,7 @@ function useGlideTable(options) {
3048
3562
  const cell = scrollElement.querySelector(
3049
3563
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
3050
3564
  );
3051
- if (cell instanceof HTMLElement) {
3565
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
3052
3566
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
3053
3567
  }
3054
3568
  };
@@ -3066,6 +3580,10 @@ function useGlideTable(options) {
3066
3580
  },
3067
3581
  [scrollCellIntoView]
3068
3582
  );
3583
+ const editKeyRef = (0, import_react6.useRef)(() => {
3584
+ });
3585
+ const clearKeyRef = (0, import_react6.useRef)(() => {
3586
+ });
3069
3587
  const {
3070
3588
  dragState,
3071
3589
  activeSelectionBounds,
@@ -3073,20 +3591,27 @@ function useGlideTable(options) {
3073
3591
  handleCellMouseEnter,
3074
3592
  handleFillHandleMouseDown,
3075
3593
  clearSelection: clearCellSelection,
3076
- copySelection
3594
+ copySelection,
3595
+ selectCell,
3596
+ focusSelection
3077
3597
  } = useCellSelection({
3078
- data: tableData,
3598
+ data: sourceData,
3079
3599
  rows,
3080
3600
  enabled: enableCellSelection,
3081
3601
  columnCount: visibleLeafColumns.length,
3602
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
3082
3603
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3604
+ escapeCopyFormulas,
3083
3605
  enableInsertPaste: enableInsertPaste ?? true,
3084
3606
  onDataChange,
3085
3607
  onBatchChange,
3086
3608
  onRowsPaste,
3087
3609
  onCellNavigate: handleCellNavigate,
3088
3610
  cellRendererRegistry,
3089
- rootRef
3611
+ rootRef,
3612
+ enableWasdNavigation,
3613
+ onEditKey: (position) => editKeyRef.current(position),
3614
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
3090
3615
  });
3091
3616
  const clearRowSelection = (0, import_react6.useCallback)(() => {
3092
3617
  if (rowSelectionMode === "none") return;
@@ -3107,22 +3632,79 @@ function useGlideTable(options) {
3107
3632
  const {
3108
3633
  editingCell,
3109
3634
  draftValue,
3635
+ draftInvalid,
3636
+ setDraftInvalid,
3110
3637
  setDraftValue,
3111
3638
  startEdit,
3112
3639
  commitEdit,
3113
3640
  cancelEdit
3114
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
3641
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
3642
+ editKeyRef.current = (position) => {
3643
+ startEdit(position.row, position.col);
3644
+ };
3645
+ clearKeyRef.current = (bounds) => {
3646
+ const changes = [];
3647
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
3648
+ const row = rows[rowIndex];
3649
+ if (!row) continue;
3650
+ const cells = row.getVisibleCells();
3651
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
3652
+ const cell = cells[colIndex];
3653
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
3654
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
3655
+ }
3656
+ }
3657
+ if (changes.length === 0) return;
3658
+ if (onBatchChange) {
3659
+ onBatchChange(changes);
3660
+ return;
3661
+ }
3662
+ if (!onDataChange) return;
3663
+ let next = sourceData;
3664
+ for (const change of changes) {
3665
+ const row = rows.find((item) => item.id === change.rowId);
3666
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
3667
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
3668
+ if (!row || !accessorKey) continue;
3669
+ next = applyCellChangesToData(next, [
3670
+ { original: row.original, index: row.index, accessorKey, value: null }
3671
+ ]);
3672
+ }
3673
+ if (next !== sourceData) onDataChange(next);
3674
+ };
3675
+ const commitEditAndMove = (0, import_react6.useCallback)(
3676
+ (raw, delta) => {
3677
+ const current = editingCell;
3678
+ if (!commitEdit(raw)) return false;
3679
+ if (current) {
3680
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
3681
+ }
3682
+ rootRef.current?.focus({ preventScroll: true });
3683
+ return true;
3684
+ },
3685
+ [commitEdit, editingCell, selectCell]
3686
+ );
3687
+ const cancelEditAndRefocus = (0, import_react6.useCallback)(() => {
3688
+ cancelEdit();
3689
+ rootRef.current?.focus({ preventScroll: true });
3690
+ }, [cancelEdit]);
3115
3691
  const commitRenderedCellValue = (0, import_react6.useCallback)(
3116
- (rowId, columnId, value) => commitCellValue({
3117
- data: tableData,
3118
- rows,
3119
- rowId,
3120
- columnId,
3121
- value,
3122
- onCellChange,
3123
- onDataChange
3124
- }),
3125
- [onCellChange, onDataChange, rows, tableData]
3692
+ (rowId, columnId, value) => {
3693
+ const columnDef = table.getColumn(columnId)?.columnDef;
3694
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
3695
+ return false;
3696
+ }
3697
+ return commitCellValue({
3698
+ data: sourceData,
3699
+ rows,
3700
+ rowId,
3701
+ columnId,
3702
+ value,
3703
+ onCellChange,
3704
+ onDataChange
3705
+ });
3706
+ },
3707
+ [onCellChange, onDataChange, rows, sourceData, table]
3126
3708
  );
3127
3709
  const getCellContext = (0, import_react6.useCallback)(
3128
3710
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3150,25 +3732,12 @@ function useGlideTable(options) {
3150
3732
  (row, index) => {
3151
3733
  if (getRowId) return getRowId(row, index);
3152
3734
  if (enableExpand) {
3153
- const record = row;
3154
- const idValue = record.id;
3155
- if (idValue != null && String(idValue).length > 0) {
3156
- return String(idValue);
3157
- }
3158
- const uniqueId = record.uniqueId;
3159
- if (uniqueId != null && String(uniqueId).length > 0) {
3160
- return String(uniqueId);
3161
- }
3162
- if (toggleField) {
3163
- const toggleValue = record[toggleField];
3164
- if (toggleValue != null && String(toggleValue).length > 0) {
3165
- return String(toggleValue);
3166
- }
3167
- }
3735
+ const treeKey = getTreeRowKey(row);
3736
+ if (treeKey) return treeKey;
3168
3737
  }
3169
3738
  return String(index);
3170
3739
  },
3171
- [enableExpand, getRowId, toggleField]
3740
+ [enableExpand, getRowId]
3172
3741
  );
3173
3742
  const searchCorpus = (0, import_react6.useMemo)(() => {
3174
3743
  if (!enableInlineSearch) return [];
@@ -3195,28 +3764,59 @@ function useGlideTable(options) {
3195
3764
  }
3196
3765
  return map;
3197
3766
  }, [resolveSearchRowId, rows]);
3198
- const getSearchCellValue = (0, import_react6.useCallback)(
3199
- (rowIndex, colIndex) => {
3200
- const corpusRow = searchCorpusRef.current[rowIndex];
3201
- const column = visibleLeafColumns[colIndex];
3202
- if (!corpusRow || !column) return void 0;
3767
+ const readSearchRawValue = (0, import_react6.useCallback)(
3768
+ (corpusRow, rowIndex, column) => {
3203
3769
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3204
3770
  if (visibleIndex !== void 0) {
3205
3771
  const visibleRow = rows[visibleIndex];
3206
3772
  if (visibleRow) {
3207
- return visibleRow.getValue(column.id);
3773
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3208
3774
  }
3209
3775
  }
3210
3776
  const columnDef = column.columnDef;
3211
3777
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3212
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3778
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3213
3779
  }
3214
3780
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3215
- return corpusRow.data[String(columnDef.accessorKey)];
3781
+ return {
3782
+ value: corpusRow.data[String(columnDef.accessorKey)],
3783
+ row: void 0
3784
+ };
3785
+ }
3786
+ return { value: corpusRow.data[column.id], row: void 0 };
3787
+ },
3788
+ [rows, visibleRowIndexById]
3789
+ );
3790
+ const getSearchCellValue = (0, import_react6.useCallback)(
3791
+ (rowIndex, colIndex) => {
3792
+ const corpusRow = searchCorpusRef.current[rowIndex];
3793
+ const column = visibleLeafColumns[colIndex];
3794
+ if (!corpusRow || !column) return void 0;
3795
+ if (isProtectedColumn(column.columnDef)) return void 0;
3796
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
3797
+ const meta = column.columnDef.meta;
3798
+ const searchValue2 = meta?.searchValue;
3799
+ if (!searchValue2 || searchValue2 === "value") return value;
3800
+ const ctx = {
3801
+ value,
3802
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
3803
+ index: row?.index ?? rowIndex,
3804
+ columnId: column.id,
3805
+ cellProps: meta?.cellProps,
3806
+ update: () => {
3807
+ }
3808
+ };
3809
+ try {
3810
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
3811
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
3812
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
3813
+ if (renderer) return reactNodeToText(renderer.render(ctx));
3814
+ } catch {
3815
+ return value;
3216
3816
  }
3217
- return corpusRow.data[column.id];
3817
+ return value;
3218
3818
  },
3219
- [rows, visibleLeafColumns, visibleRowIndexById]
3819
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3220
3820
  );
3221
3821
  const pendingSearchNavRef = (0, import_react6.useRef)(null);
3222
3822
  const focusSearchResult = (0, import_react6.useCallback)(
@@ -3267,11 +3867,19 @@ function useGlideTable(options) {
3267
3867
  focusSearchResult(pending.colIndex, visibleRowIndex);
3268
3868
  }, [focusSearchResult, rows, visibleRowIndexById]);
3269
3869
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
3870
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
3871
+ const searchContentKey = (0, import_react6.useMemo)(
3872
+ () => ({ data: sourceData, columns: searchColumnSignature }),
3873
+ [sourceData, searchColumnSignature]
3874
+ );
3270
3875
  const inlineSearch = useInlineSearch({
3271
3876
  enabled: enableInlineSearch,
3272
3877
  rowCount: searchCorpus.length,
3273
3878
  columnCount: visibleLeafColumns.length,
3274
3879
  getCellValue: getSearchCellValue,
3880
+ // Re-scan when the rows' content/order or the column order changes
3881
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
3882
+ contentKey: searchContentKey,
3275
3883
  initialStartRow: initialSearchStartRow,
3276
3884
  showSearch,
3277
3885
  searchValue,
@@ -3309,11 +3917,14 @@ function useGlideTable(options) {
3309
3917
  visibleRowIndexById
3310
3918
  ]);
3311
3919
  const clearHover = (0, import_react6.useCallback)(() => {
3312
- setHoveredRowIndex(null);
3313
- }, []);
3314
- const handleRowHover = (0, import_react6.useCallback)((rowIndex, _rowData) => {
3315
- setHoveredRowIndex(rowIndex);
3316
- }, []);
3920
+ hoverStore.setHoveredRowIndex(null);
3921
+ }, [hoverStore]);
3922
+ const handleRowHover = (0, import_react6.useCallback)(
3923
+ (rowIndex, _rowData) => {
3924
+ hoverStore.setHoveredRowIndex(rowIndex);
3925
+ },
3926
+ [hoverStore]
3927
+ );
3317
3928
  const handleToggleSelect = (0, import_react6.useCallback)(
3318
3929
  (row) => {
3319
3930
  if (!row.getCanSelect()) return;
@@ -3338,7 +3949,7 @@ function useGlideTable(options) {
3338
3949
  primaryRowSpanKey,
3339
3950
  primaryRowSpanColumnId,
3340
3951
  columnRowSpanMap,
3341
- hoveredRowIndex,
3952
+ hoverStore,
3342
3953
  selectedRowIndices,
3343
3954
  onRowHover: handleRowHover
3344
3955
  },
@@ -3352,6 +3963,7 @@ function useGlideTable(options) {
3352
3963
  enableCellSelection,
3353
3964
  activeSelectionBounds,
3354
3965
  dragState,
3966
+ canFill,
3355
3967
  onCellMouseDown: handleCellMouseDownWithCommit,
3356
3968
  onCellMouseEnter: handleCellMouseEnter,
3357
3969
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3359,18 +3971,23 @@ function useGlideTable(options) {
3359
3971
  cellEdit: {
3360
3972
  editingCell,
3361
3973
  draftValue,
3974
+ draftInvalid,
3975
+ onDraftInvalidChange: setDraftInvalid,
3362
3976
  onDraftValueChange: setDraftValue,
3363
3977
  onStartEdit: startEdit,
3364
3978
  onCommitEdit: commitEdit,
3365
- onCancelEdit: cancelEdit
3979
+ onCommitEditAndMove: commitEditAndMove,
3980
+ onCancelEdit: cancelEditAndRefocus
3366
3981
  },
3367
3982
  cellRender: {
3368
3983
  registry: cellRendererRegistry,
3369
- commitValue: commitRenderedCellValue
3984
+ commitValue: commitRenderedCellValue,
3985
+ protectedLabel: labels.protectedCell
3370
3986
  },
3371
3987
  expand: {
3372
3988
  enableExpand,
3373
3989
  toggleField,
3990
+ expandColumn,
3374
3991
  expandedRows,
3375
3992
  preventExpand,
3376
3993
  onToggleExpand: handleToggleExpand,
@@ -3395,7 +4012,7 @@ function useGlideTable(options) {
3395
4012
  primaryRowSpanKey,
3396
4013
  primaryRowSpanColumnId,
3397
4014
  columnRowSpanMap,
3398
- hoveredRowIndex,
4015
+ hoverStore,
3399
4016
  selectedRowIndices,
3400
4017
  handleRowHover,
3401
4018
  rowSelectionMode,
@@ -3405,19 +4022,25 @@ function useGlideTable(options) {
3405
4022
  enableCellSelection,
3406
4023
  activeSelectionBounds,
3407
4024
  dragState,
4025
+ canFill,
3408
4026
  handleCellMouseDownWithCommit,
3409
4027
  handleCellMouseEnter,
3410
4028
  handleFillHandleMouseDown,
3411
4029
  editingCell,
3412
4030
  draftValue,
4031
+ draftInvalid,
4032
+ setDraftInvalid,
3413
4033
  setDraftValue,
3414
4034
  startEdit,
3415
4035
  commitEdit,
3416
- cancelEdit,
4036
+ commitEditAndMove,
4037
+ cancelEditAndRefocus,
3417
4038
  cellRendererRegistry,
3418
4039
  commitRenderedCellValue,
4040
+ labels.protectedCell,
3419
4041
  enableExpand,
3420
4042
  toggleField,
4043
+ expandColumn,
3421
4044
  expandedRows,
3422
4045
  preventExpand,
3423
4046
  handleToggleExpand,
@@ -3465,6 +4088,7 @@ function useGlideTable(options) {
3465
4088
  handleToggleSelect,
3466
4089
  clearHover,
3467
4090
  setColumnOrder,
4091
+ handleRootFocus: focusSelection,
3468
4092
  copySelection: stableCopySelection,
3469
4093
  inlineSearch: {
3470
4094
  showSearch: inlineSearch.showSearch,
@@ -3515,12 +4139,16 @@ function ResolvedTableCell({
3515
4139
  },
3516
4140
  [cellRender, columnId, row.id]
3517
4141
  );
4142
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
4143
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
4144
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
4145
+ }
3518
4146
  const ctx = {
3519
4147
  value,
3520
4148
  row,
3521
4149
  index: row.index,
3522
4150
  columnId,
3523
- cellProps: meta?.cellProps,
4151
+ cellProps,
3524
4152
  update
3525
4153
  };
3526
4154
  if (meta?.cellRender) {
@@ -3912,6 +4540,7 @@ function useColumnReorder(options) {
3912
4540
  createCellRendererRegistry,
3913
4541
  createSearchRegex,
3914
4542
  escapeSearchRegex,
4543
+ escapeSpreadsheetFormula,
3915
4544
  flattenSubtreeRows,
3916
4545
  formatCellValue,
3917
4546
  formatDefaultCellValue,