react-glide-table 2.3.4 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.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,735 +844,781 @@ 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
1007
+ id: getOriginalRowId(rowData) || String(index),
1008
+ index,
1009
+ original: rowData,
1010
+ getIsCellDragSelected: () => false
690
1011
  };
691
1012
  }
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);
1013
+ function buildVisibleRowLookup(visibleRows) {
1014
+ const lookup = /* @__PURE__ */ new Map();
1015
+ for (const row of visibleRows) {
1016
+ lookup.set(row.original, row);
757
1017
  }
758
- if (colIndex > bounds.startCol) {
759
- collectSide("left", colIndex - 1);
1018
+ return lookup;
1019
+ }
1020
+ function resolveCopyColumnId(cell) {
1021
+ if (cell.column.id) return cell.column.id;
1022
+ const columnDef = cell.column.columnDef;
1023
+ if (columnDef.id) return columnDef.id;
1024
+ if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1025
+ return String(columnDef.accessorKey);
760
1026
  }
761
- return edges;
1027
+ return "";
762
1028
  }
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
- });
1029
+ function isPrimitiveCopyValue(value) {
1030
+ return value == null || typeof value !== "object";
1031
+ }
1032
+ function extractRenderedCopyText(node, value, cellPosition, root) {
1033
+ const rendered = sanitizeClipboardCell(reactNodeToText(node));
1034
+ if (reactNodeContainsImage(node)) {
1035
+ const fromDom = cellPosition != null ? sanitizeClipboardCell(
1036
+ readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
1037
+ ) : "";
1038
+ if (fromDom) return fromDom;
1039
+ if (rendered && isLikelyUrl(rendered)) return rendered;
1040
+ return sanitizeClipboardCell(pickUrlFromUnknown(value));
789
1041
  }
790
- return layers;
1042
+ return rendered;
791
1043
  }
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
- );
1044
+ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
1045
+ const meta = columnDef.meta;
1046
+ const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
1047
+ const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
1048
+ const ctx = {
1049
+ value,
1050
+ row,
1051
+ index: row.index,
1052
+ columnId,
1053
+ cellProps: meta?.cellProps,
1054
+ update: () => {
825
1055
  }
826
- if (isLeftEdge) {
827
- shadows.push(
828
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
829
- );
1056
+ };
1057
+ const copyValue = meta?.copyValue;
1058
+ if (typeof copyValue === "function") {
1059
+ try {
1060
+ return sanitizeClipboardCell(copyValue(ctx));
1061
+ } catch {
1062
+ return formatCellValue(value);
830
1063
  }
831
- if (isRightEdge) {
832
- shadows.push(
833
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
834
- );
1064
+ }
1065
+ if (copyValue === "value") {
1066
+ return formatCellValue(value);
1067
+ }
1068
+ const cellRender = meta?.cellRender;
1069
+ if (typeof cellRender === "function") {
1070
+ try {
1071
+ const node = cellRender(ctx);
1072
+ return extractRenderedCopyText(node, value, cellPosition, options?.root);
1073
+ } catch {
1074
+ return formatCellValue(value);
835
1075
  }
836
1076
  }
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);
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);
845
1087
  }
846
1088
  }
847
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
848
- return void 0;
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);
849
1103
  }
850
- const style = {};
851
- if (shadows.length > 0) {
852
- style["--selection-edge-shadows"] = shadows.join(", ");
1104
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1105
+ return getNestedValue(rowData, String(columnDef.accessorKey));
853
1106
  }
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(", ");
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;
858
1144
  }
859
- if (selectionContinuesBelow) {
860
- style.borderBottomColor = "var(--color-brand-surface)";
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);
861
1169
  }
862
- return style;
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");
863
1210
  }
864
- function hasCellSelectionEdges(style) {
865
- return Boolean(
866
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
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
867
1219
  );
868
1220
  }
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;
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
+ }
874
1243
  }
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 || "";
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);
880
1250
  }
881
- if (typeof type === "object" && type !== null) {
882
- const component = type;
883
- return component.displayName || component.render?.displayName || component.render?.name || "";
1251
+ try {
1252
+ await navigator.clipboard.writeText(text);
1253
+ return true;
1254
+ } catch {
1255
+ return false;
884
1256
  }
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
1257
  }
895
- function isImageReactElement(node) {
896
- const typeName = getElementTypeName(node.type);
897
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
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
+ };
898
1267
  }
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;
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");
906
1277
  }
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
- }
1278
+ function registerCellSelectionOwner(owner, clearSelection) {
1279
+ clearByOwner.set(owner, clearSelection);
1280
+ return () => {
1281
+ clearByOwner.delete(owner);
1282
+ if (activeOwner === owner) {
1283
+ activeOwner = null;
921
1284
  }
922
- }
923
- return "";
1285
+ };
924
1286
  }
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();
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();
931
1293
  }
932
1294
  }
933
- return "";
934
1295
  }
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;
1296
+ function isActiveCellSelectionOwner(owner) {
1297
+ return activeOwner === owner;
946
1298
  }
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;
1299
+ function releaseCellSelectionOwner(owner) {
1300
+ if (activeOwner === owner) {
1301
+ activeOwner = null;
953
1302
  }
954
- return "";
955
1303
  }
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(", ");
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;
968
1343
  }
969
- return "";
970
1344
  }
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);
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);
975
1365
  }
976
- if (isReactNodeIterable(node)) {
977
- let text = "";
978
- for (const child of node) {
979
- text += reactNodeToText(child);
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;
1379
+ }
980
1380
  }
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 "";
1381
+ return rowIndex + rowSpan - 1;
994
1382
  }
995
- return "";
996
- }
997
- function sanitizeClipboardCell(text) {
998
- return text.replace(/\s+/g, " ").trim();
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;
999
1389
  }
1000
- function createCopyRenderRow(rowData, index) {
1001
- return {
1002
- id: getOriginalRowId(rowData) || String(index),
1003
- index,
1004
- original: rowData,
1005
- getIsCellDragSelected: () => false
1006
- };
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;
1007
1394
  }
1008
- function buildVisibleRowLookup(visibleRows) {
1009
- const lookup = /* @__PURE__ */ new Map();
1010
- for (const row of visibleRows) {
1011
- lookup.set(row.original, row);
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 };
1012
1405
  }
1013
- return lookup;
1406
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1014
1407
  }
1015
- function resolveCopyColumnId(cell) {
1016
- if (cell.column.id) return cell.column.id;
1017
- const columnDef = cell.column.columnDef;
1018
- if (columnDef.id) return columnDef.id;
1019
- if (columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1020
- return String(columnDef.accessorKey);
1408
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1409
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1410
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1021
1411
  }
1022
- return "";
1023
- }
1024
- function isPrimitiveCopyValue(value) {
1025
- return value == null || typeof value !== "object";
1412
+ return selectionBounds;
1026
1413
  }
1027
- function extractRenderedCopyText(node, value, cellPosition, root) {
1028
- const rendered = sanitizeClipboardCell(reactNodeToText(node));
1029
- if (reactNodeContainsImage(node)) {
1030
- const fromDom = cellPosition != null ? sanitizeClipboardCell(
1031
- readDomImageUrls(cellPosition.rowIndex, cellPosition.colIndex, root)
1032
- ) : "";
1033
- if (fromDom) return fromDom;
1034
- if (rendered && isLikelyUrl(rendered)) return rendered;
1035
- return sanitizeClipboardCell(pickUrlFromUnknown(value));
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 };
1036
1422
  }
1037
- return rendered;
1423
+ if (!rowHeights || rowHeights.length !== span) {
1424
+ return {
1425
+ offsetRatio: (clampedFrom - rowIndex) / span,
1426
+ lengthRatio: (clampedTo - clampedFrom) / span
1427
+ };
1428
+ }
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;
1433
+ }
1434
+ let lengthPx = 0;
1435
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1436
+ lengthPx += rowHeights[i] ?? 0;
1437
+ }
1438
+ return {
1439
+ offsetRatio: offsetPx / total,
1440
+ lengthRatio: lengthPx / total,
1441
+ offsetPx,
1442
+ lengthPx
1443
+ };
1038
1444
  }
1039
- function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIndex, sourceCell, cellPosition, options) {
1040
- const meta = columnDef.meta;
1041
- const value = sourceCell ? sourceCell.getValue() : readRowColumnValue(rowData, columnDef);
1042
- const row = visibleRow ?? createCopyRenderRow(rowData, fallbackIndex);
1043
- const ctx = {
1044
- value,
1045
- row,
1046
- index: row.index,
1047
- columnId,
1048
- cellProps: meta?.cellProps,
1049
- update: () => {
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);
1050
1453
  }
1454
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
1051
1455
  };
1052
- const copyValue = meta?.copyValue;
1053
- if (typeof copyValue === "function") {
1054
- try {
1055
- return sanitizeClipboardCell(copyValue(ctx));
1056
- } catch {
1057
- return formatCellValue(value);
1058
- }
1059
- }
1060
- if (copyValue === "value") {
1061
- return formatCellValue(value);
1062
- }
1063
- const cellRender = meta?.cellRender;
1064
- if (typeof cellRender === "function") {
1065
- try {
1066
- const node = cellRender(ctx);
1067
- return extractRenderedCopyText(node, value, cellPosition, options?.root);
1068
- } catch {
1069
- return formatCellValue(value);
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
+ }
1070
1476
  }
1071
- }
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;
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 });
1079
1487
  }
1080
- } catch {
1081
- return formatCellValue(value);
1082
1488
  }
1489
+ };
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);
1083
1510
  }
1084
- return formatCellValue(value);
1085
- }
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);
1511
+ if (colIndex > bounds.startCol) {
1512
+ collectSide("left", colIndex - 1);
1091
1513
  }
1092
- return "";
1514
+ return edges;
1093
1515
  }
1094
- function formatObjectValue(value) {
1095
- const text = value.text ?? value.label ?? value.name ?? value.title;
1096
- if (text != null && text !== "") {
1097
- return formatCellValue(text);
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
+ });
1098
1542
  }
1099
- try {
1100
- return JSON.stringify(value);
1101
- } catch {
1102
- return "";
1543
+ return layers;
1544
+ }
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,
1557
+ bounds,
1558
+ rowSpan,
1559
+ isVisuallySelectedAt,
1560
+ rowHeights
1561
+ );
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
+ }
1103
1589
  }
1104
- }
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(", ");
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
+ }
1109
1599
  }
1110
- if (typeof value === "object") {
1111
- return formatObjectValue(value);
1600
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1601
+ return void 0;
1112
1602
  }
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);
1603
+ const style = {};
1604
+ if (shadows.length > 0) {
1605
+ style["--selection-edge-shadows"] = shadows.join(", ");
1127
1606
  }
1128
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1129
- return getNestedValue(rowData, String(columnDef.accessorKey));
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(", ");
1130
1611
  }
1131
- return void 0;
1132
- }
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
- }
1144
- }
1145
- };
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);
1171
- }
1172
- appendSubtree(child, depth + 1);
1173
- }
1174
- };
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);
1612
+ if (selectionContinuesBelow) {
1613
+ style.borderBottomColor = "var(--color-brand-surface)";
1185
1614
  }
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");
1615
+ return style;
1224
1616
  }
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,
1230
- bounds,
1231
- entries.map((entry) => entry.depth),
1232
- options
1617
+ function hasCellSelectionEdges(style) {
1618
+ return Boolean(
1619
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1233
1620
  );
1234
1621
  }
1235
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1236
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1237
- if (!text) return false;
1238
- try {
1239
- await navigator.clipboard.writeText(text);
1240
- } catch {
1241
- return false;
1242
- }
1243
- return true;
1244
- }
1245
1622
 
1246
1623
  // src/components/ui/table/features/cell-selection/fillData.ts
1247
1624
  function getColumnAccessorKey2(columnDef) {
@@ -1265,6 +1642,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1265
1642
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1266
1643
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1267
1644
  if (!targetRow || !targetCell || !sourceCell) continue;
1645
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1646
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1268
1647
  const accessorKey = getColumnAccessorKey2(
1269
1648
  targetCell.column.columnDef
1270
1649
  );
@@ -1286,13 +1665,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1286
1665
  );
1287
1666
  }
1288
1667
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1289
- const newData = data.map((row) => ({ ...row }));
1290
1668
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1291
- for (const target of targets) {
1292
- if (!newData[target.rowIndex]) continue;
1293
- newData[target.rowIndex][target.accessorKey] = target.value;
1294
- }
1295
- 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
+ );
1296
1684
  }
1297
1685
  function hasFillExtension(sourceBounds, fillBounds) {
1298
1686
  if (!sourceBounds) return false;
@@ -1313,17 +1701,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1313
1701
  if (firstDepth !== 0) return false;
1314
1702
  return leadingEmptyCounts.some((depth) => depth > 0);
1315
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
+ }
1316
1749
  function parseClipboardTSV(text) {
1317
1750
  return parseClipboardTSVWithDepths(text).values;
1318
1751
  }
1319
- function parseClipboardTSVWithDepths(text) {
1752
+ function parseClipboardTSVWithDepths(text, options) {
1320
1753
  if (!text) return { values: [], depths: [] };
1321
1754
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1322
1755
  const withoutTrailing = normalized.replace(/\n+$/, "");
1323
1756
  if (!withoutTrailing) return { values: [], depths: [] };
1324
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1757
+ const rows = splitTSV(withoutTrailing);
1325
1758
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1326
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1759
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1327
1760
  const values = [];
1328
1761
  const depths = [];
1329
1762
  for (let index = 0; index < rows.length; index += 1) {
@@ -1350,8 +1783,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1350
1783
  }
1351
1784
  return columnIds;
1352
1785
  }
1353
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1354
- const { values, depths } = parseClipboardTSVWithDepths(text);
1786
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1787
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1355
1788
  if (values.length === 0) return null;
1356
1789
  const width = Math.max(...values.map((row) => row.length), 0);
1357
1790
  if (width === 0) return null;
@@ -1384,6 +1817,19 @@ function isEditablePasteTarget(target) {
1384
1817
  }
1385
1818
 
1386
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
+ }
1387
1833
  function isFocusOutsideRoot(rootRef) {
1388
1834
  const root = rootRef?.current;
1389
1835
  if (!root) return false;
@@ -1396,29 +1842,50 @@ function useCellSelection({
1396
1842
  rows,
1397
1843
  enabled = true,
1398
1844
  columnCount = 0,
1845
+ columnSignature,
1399
1846
  enableSubtreeCopy = false,
1847
+ escapeCopyFormulas = false,
1400
1848
  enableInsertPaste = true,
1401
1849
  onDataChange,
1402
1850
  onBatchChange,
1403
1851
  onRowsPaste,
1404
1852
  onCellNavigate,
1405
1853
  cellRendererRegistry,
1406
- rootRef
1854
+ rootRef,
1855
+ enableWasdNavigation = true,
1856
+ onEditKey,
1857
+ onClearKey
1407
1858
  }) {
1408
1859
  const ownerRef = (0, import_react3.useRef)(createCellSelectionOwner());
1409
1860
  const [dragState, setDragState] = (0, import_react3.useState)(INITIAL_DRAG_STATE);
1410
1861
  const pendingPasteModeRef = (0, import_react3.useRef)(null);
1411
1862
  const dragStateRef = (0, import_react3.useRef)(dragState);
1412
1863
  const onCellNavigateRef = (0, import_react3.useRef)(onCellNavigate);
1864
+ const onEditKeyRef = (0, import_react3.useRef)(onEditKey);
1865
+ const onClearKeyRef = (0, import_react3.useRef)(onClearKey);
1413
1866
  dragStateRef.current = dragState;
1414
1867
  onCellNavigateRef.current = onCellNavigate;
1415
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1416
- 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]);
1417
1884
  const handleCellMouseDown = (0, import_react3.useCallback)(
1418
1885
  (rowIndex, colIndex, options) => {
1419
1886
  if (!enabled) return;
1420
1887
  claimCellSelectionOwner(ownerRef.current);
1421
- setDragState((prev) => {
1888
+ updateDragState((prev) => {
1422
1889
  if (options?.shiftKey && prev.start) {
1423
1890
  return {
1424
1891
  ...prev,
@@ -1439,28 +1906,30 @@ function useCellSelection({
1439
1906
  };
1440
1907
  });
1441
1908
  },
1442
- [enabled]
1909
+ [enabled, updateDragState]
1443
1910
  );
1444
1911
  const handleCellMouseEnter = (0, import_react3.useCallback)(
1445
1912
  (rowIndex, colIndex) => {
1446
1913
  if (!enabled) return;
1447
- setDragState((prev) => {
1914
+ updateDragState((prev) => {
1448
1915
  if (prev.isSelecting) {
1916
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1449
1917
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1450
1918
  }
1451
1919
  if (prev.isFillDragging) {
1920
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1452
1921
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1453
1922
  }
1454
1923
  return prev;
1455
1924
  });
1456
1925
  },
1457
- [enabled]
1926
+ [enabled, updateDragState]
1458
1927
  );
1459
1928
  const handleFillHandleMouseDown = (0, import_react3.useCallback)(
1460
1929
  (rowIndex, colIndex) => {
1461
1930
  if (!enabled) return;
1462
1931
  claimCellSelectionOwner(ownerRef.current);
1463
- setDragState((prev) => {
1932
+ updateDragState((prev) => {
1464
1933
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1465
1934
  if (!bounds) return prev;
1466
1935
  return {
@@ -1472,7 +1941,7 @@ function useCellSelection({
1472
1941
  };
1473
1942
  });
1474
1943
  },
1475
- [enabled]
1944
+ [enabled, updateDragState]
1476
1945
  );
1477
1946
  const clearSelection = (0, import_react3.useCallback)(() => {
1478
1947
  const prev = dragStateRef.current;
@@ -1491,6 +1960,130 @@ function useCellSelection({
1491
1960
  (0, import_react3.useEffect)(() => {
1492
1961
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
1493
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]);
1494
2087
  (0, import_react3.useEffect)(() => {
1495
2088
  if (!enabled) return;
1496
2089
  const handleKeyDown = (e) => {
@@ -1500,6 +2093,7 @@ function useCellSelection({
1500
2093
  return;
1501
2094
  }
1502
2095
  if (isFocusOutsideRoot(rootRef)) return;
2096
+ if (!enableWasdNavigation && e.key.length === 1) return;
1503
2097
  const delta = getCellNavigationDelta(e.key);
1504
2098
  if (!delta) return;
1505
2099
  const prev = dragStateRef.current;
@@ -1539,14 +2133,15 @@ function useCellSelection({
1539
2133
  };
1540
2134
  window.addEventListener("keydown", handleKeyDown);
1541
2135
  return () => window.removeEventListener("keydown", handleKeyDown);
1542
- }, [columnCount, enabled, rows]);
2136
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1543
2137
  const copySelection = (0, import_react3.useCallback)(
1544
2138
  async (options) => {
1545
2139
  if (!enabled || !activeSelectionBounds) return false;
1546
2140
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1547
2141
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1548
2142
  registry: cellRendererRegistry,
1549
- root: rootRef?.current
2143
+ root: rootRef?.current,
2144
+ escapeFormulas: escapeCopyFormulas
1550
2145
  });
1551
2146
  },
1552
2147
  [
@@ -1554,6 +2149,7 @@ function useCellSelection({
1554
2149
  cellRendererRegistry,
1555
2150
  enableSubtreeCopy,
1556
2151
  enabled,
2152
+ escapeCopyFormulas,
1557
2153
  rootRef,
1558
2154
  rows
1559
2155
  ]
@@ -1571,6 +2167,7 @@ function useCellSelection({
1571
2167
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1572
2168
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1573
2169
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2170
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1574
2171
  e.preventDefault();
1575
2172
  void copySelection({ includeDescendants: isSubtreeShortcut });
1576
2173
  };
@@ -1586,9 +2183,17 @@ function useCellSelection({
1586
2183
  activeSelectionBounds.startCol,
1587
2184
  text,
1588
2185
  mode,
1589
- 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" }
1590
2190
  );
1591
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
+ });
1592
2197
  onRowsPaste(payload);
1593
2198
  return true;
1594
2199
  },
@@ -1619,7 +2224,10 @@ function useCellSelection({
1619
2224
  void (async () => {
1620
2225
  try {
1621
2226
  const text = await navigator.clipboard.readText();
1622
- if (pasteHandledRef.current) return;
2227
+ if (pasteHandledRef.current) {
2228
+ pasteHandledRef.current = false;
2229
+ return;
2230
+ }
1623
2231
  if (pendingPasteModeRef.current !== mode) return;
1624
2232
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1625
2233
  if (!text) return;
@@ -1644,6 +2252,7 @@ function useCellSelection({
1644
2252
  }
1645
2253
  const mode = pendingPasteModeRef.current ?? "overwrite";
1646
2254
  if (pasteHandledRef.current) {
2255
+ pasteHandledRef.current = false;
1647
2256
  e.preventDefault();
1648
2257
  return;
1649
2258
  }
@@ -1670,39 +2279,41 @@ function useCellSelection({
1670
2279
  (0, import_react3.useEffect)(() => {
1671
2280
  if (!enabled) return;
1672
2281
  const handleMouseUp = () => {
1673
- setDragState((prev) => {
1674
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1675
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1676
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1677
- if (newBounds) {
1678
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1679
- if (onBatchChange) {
1680
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1681
- if (changes.length > 0) {
1682
- onBatchChange(changes);
1683
- }
1684
- } else if (onDataChange) {
1685
- 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);
1686
2293
  }
2294
+ } else if (onDataChange) {
2295
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1687
2296
  }
1688
- return {
1689
- isSelecting: false,
1690
- isFillDragging: false,
1691
- start: { row: newBounds.startRow, col: newBounds.startCol },
1692
- end: { row: newBounds.endRow, col: newBounds.endCol },
1693
- fillAnchor: null,
1694
- fillEnd: null
1695
- };
1696
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 };
1697
2308
  }
1698
- if (prev.isSelecting) {
1699
- return { ...prev, isSelecting: false };
1700
- }
1701
- if (prev.isFillDragging) {
1702
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1703
- }
1704
- return prev;
1705
- });
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);
1706
2317
  };
1707
2318
  window.addEventListener("mouseup", handleMouseUp);
1708
2319
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1714,7 +2325,27 @@ function useCellSelection({
1714
2325
  handleCellMouseEnter,
1715
2326
  handleFillHandleMouseDown,
1716
2327
  clearSelection,
1717
- 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
+ }
1718
2349
  };
1719
2350
  }
1720
2351
 
@@ -1749,8 +2380,12 @@ function handleEscape(event) {
1749
2380
  if (isOverlayDismissIgnoreTarget(event.target) || isOverlayDismissIgnoreTarget(document.activeElement)) {
1750
2381
  return;
1751
2382
  }
1752
- for (const clearAllSelections of clearAllByOwner.values()) {
1753
- clearAllSelections();
2383
+ for (const clearAllSelections of [...clearAllByOwner.values()]) {
2384
+ try {
2385
+ clearAllSelections();
2386
+ } catch (error) {
2387
+ console.error("[react-glide-table] escape-dismiss callback failed", error);
2388
+ }
1754
2389
  }
1755
2390
  }
1756
2391
  function registerEscapeDismiss(owner, clearAllSelections) {
@@ -2004,170 +2639,33 @@ function flattenHeaderLeaves(column) {
2004
2639
  return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2005
2640
  }
2006
2641
 
2007
- // src/components/ui/table/features/inline-search/inlineSearch.ts
2008
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
2009
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
2010
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
2011
- function escapeSearchRegex(value) {
2012
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
2013
- }
2014
- function createSearchRegex(query) {
2015
- const trimmed = query.trim();
2016
- if (!trimmed) return null;
2017
- return new RegExp(escapeSearchRegex(trimmed), "i");
2018
- }
2019
- function cellValueToSearchText(value) {
2020
- if (value == null) return void 0;
2021
- if (typeof value === "string") return value;
2022
- if (typeof value === "number" || typeof value === "boolean") {
2023
- return String(value);
2024
- }
2025
- if (Array.isArray(value)) {
2026
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
2027
- }
2028
- if (typeof value === "object") {
2029
- try {
2030
- return JSON.stringify(value);
2031
- } catch {
2032
- return String(value);
2033
- }
2034
- }
2035
- return String(value);
2036
- }
2037
- function formatSearchResultLabel(status) {
2038
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
2039
- if (status.selectedIndex >= 0 && status.results > 0) {
2040
- return `${status.selectedIndex + 1} of ${countLabel}`;
2041
- }
2042
- return countLabel;
2043
- }
2044
- function nextSearchIndex(selectedIndex, results) {
2045
- if (results <= 0) return -1;
2046
- if (selectedIndex < 0) return 0;
2047
- return (selectedIndex + 1) % results;
2048
- }
2049
- function previousSearchIndex(selectedIndex, results) {
2050
- if (results <= 0) return -1;
2051
- if (selectedIndex < 0) return results - 1;
2052
- let next = (selectedIndex - 1) % results;
2053
- if (next < 0) next += results;
2054
- return next;
2055
- }
2056
- function buildSearchMatchKey(colIndex, rowIndex) {
2057
- return `${colIndex}:${rowIndex}`;
2058
- }
2059
- function buildSearchMatchKeys(results) {
2060
- const keys = /* @__PURE__ */ new Set();
2061
- for (const [colIndex, rowIndex] of results) {
2062
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
2063
- }
2064
- return keys;
2065
- }
2066
- function collectSearchMatchesInRange(options) {
2067
- const {
2068
- query,
2069
- startRow,
2070
- rowCount,
2071
- columnCount,
2072
- getCellValue,
2073
- maxResults = INLINE_SEARCH_MAX_RESULTS
2074
- } = options;
2075
- const regex = createSearchRegex(query);
2076
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
2077
- const matches = [];
2078
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2079
- const rowIndex = startRow + rowOffset;
2080
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2081
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2082
- if (text !== void 0 && regex.test(text)) {
2083
- matches.push([colIndex, rowIndex]);
2084
- if (matches.length >= maxResults) {
2085
- return matches;
2086
- }
2087
- }
2088
- }
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);
2089
2653
  }
2090
- return matches;
2091
- }
2092
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2093
- const rounded = Math.max(elapsedMs, 1);
2094
- const scalar = targetMs / rounded;
2095
- return Math.max(1, Math.ceil(currentStride * scalar));
2096
- }
2097
- function buildFlatSearchCorpus(rows, getRowId) {
2098
- return rows.map((data, index) => ({
2099
- id: getRowId(data, index),
2100
- data,
2101
- ancestorToggleKeys: []
2102
- }));
2103
- }
2104
- function buildTreeSearchCorpus(visibleRows, options) {
2105
- const { toggleField, getRowId } = options;
2106
- const corpus = [];
2107
- const seen = /* @__PURE__ */ new Set();
2108
- const walk = (node, ancestorToggleKeys) => {
2109
- const id = getRowId(node, corpus.length);
2110
- if (seen.has(id)) return;
2111
- seen.add(id);
2112
- corpus.push({
2113
- id,
2114
- data: node,
2115
- ancestorToggleKeys
2116
- });
2117
- const children = node.children;
2118
- if (!Array.isArray(children) || children.length === 0) return;
2119
- const toggleValue = node[toggleField];
2120
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2121
- for (const child of children) {
2122
- if (child && typeof child === "object") {
2123
- walk(child, childAncestors);
2124
- }
2654
+ searchInstanceCount += 1;
2655
+ return () => {
2656
+ searchInstanceCount -= 1;
2657
+ if (searchInstanceCount === 0) {
2658
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2659
+ lastPointerTarget = null;
2125
2660
  }
2126
2661
  };
2127
- for (const row of visibleRows) {
2128
- const level = row.level;
2129
- if (level === 0 || level === void 0) {
2130
- walk(row, []);
2131
- }
2132
- }
2133
- for (const row of visibleRows) {
2134
- const id = getRowId(row, corpus.length);
2135
- if (seen.has(id)) continue;
2136
- walk(row, []);
2137
- }
2138
- return corpus;
2139
- }
2140
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2141
- const keys = /* @__PURE__ */ new Set();
2142
- for (const [colIndex, corpusRowIndex] of results) {
2143
- const corpusRow = corpus[corpusRowIndex];
2144
- if (!corpusRow) continue;
2145
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2146
- if (visibleRowIndex === void 0) continue;
2147
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2148
- }
2149
- return keys;
2150
- }
2151
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2152
- const [colIndex, corpusRowIndex] = item;
2153
- const corpusRow = corpus[corpusRowIndex];
2154
- if (!corpusRow) return null;
2155
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2156
- if (visibleRowIndex === void 0) return null;
2157
- return [colIndex, visibleRowIndex];
2158
- }
2159
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2160
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2161
2662
  }
2162
-
2163
- // src/components/ui/table/features/inline-search/useInlineSearch.ts
2164
- var import_react4 = require("react");
2165
- var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2166
2663
  function useInlineSearch({
2167
2664
  enabled = false,
2168
2665
  rowCount,
2169
2666
  columnCount,
2170
2667
  getCellValue,
2668
+ contentKey,
2171
2669
  initialStartRow = 0,
2172
2670
  showSearch: controlledShowSearch,
2173
2671
  searchValue: controlledSearchValue,
@@ -2376,6 +2874,7 @@ function useInlineSearch({
2376
2874
  }
2377
2875
  beginSearch(searchValue);
2378
2876
  }, [
2877
+ contentKey,
2379
2878
  beginSearch,
2380
2879
  cancelSearch,
2381
2880
  controlledSearchResults,
@@ -2396,6 +2895,9 @@ function useInlineSearch({
2396
2895
  if (!focusInside && active !== document.body) {
2397
2896
  return;
2398
2897
  }
2898
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2899
+ return;
2900
+ }
2399
2901
  }
2400
2902
  event.preventDefault();
2401
2903
  event.stopPropagation();
@@ -2409,7 +2911,11 @@ function useInlineSearch({
2409
2911
  }
2410
2912
  };
2411
2913
  window.addEventListener("keydown", handleKeyDown, true);
2412
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2914
+ const releaseInstance = registerSearchInstance();
2915
+ return () => {
2916
+ window.removeEventListener("keydown", handleKeyDown, true);
2917
+ releaseInstance();
2918
+ };
2413
2919
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2414
2920
  (0, import_react4.useEffect)(() => () => cancelSearch(), [cancelSearch]);
2415
2921
  const searchMatchKeys = (0, import_react4.useMemo)(
@@ -2465,8 +2971,12 @@ function getFieldValue(row, key) {
2465
2971
  }
2466
2972
  function canExpandRow(row) {
2467
2973
  const children = row.children;
2468
- const level = row.level;
2469
- 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;
2470
2980
  }
2471
2981
  function toggleExpandedRowId(rowId, previous) {
2472
2982
  const next = new Set(previous);
@@ -2487,7 +2997,8 @@ var useConvertTreeData = ({
2487
2997
  preventExpand = false,
2488
2998
  startIndex = 1,
2489
2999
  expandedRows,
2490
- onExpandedRowsChange
3000
+ onExpandedRowsChange,
3001
+ autoExpandOnLoad = true
2491
3002
  }) => {
2492
3003
  const onExpandedRowsChangeRef = (0, import_react5.useRef)(onExpandedRowsChange);
2493
3004
  const hasInitializedRef = (0, import_react5.useRef)(false);
@@ -2500,16 +3011,33 @@ var useConvertTreeData = ({
2500
3011
  return;
2501
3012
  }
2502
3013
  if (!enabled || hasInitializedRef.current) return;
2503
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2504
- onExpandedRowsChangeRef.current?.(new Set(ids));
2505
3014
  hasInitializedRef.current = true;
2506
- }, [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]);
2507
3030
  const processedData = (0, import_react5.useMemo)(() => {
2508
3031
  if (!enabled || !data || data.length === 0) return [];
2509
3032
  const flattenedData = [];
2510
- const flattenItems = (items) => {
2511
- items.forEach((item) => {
2512
- 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 };
2513
3041
  const nested = newItem[flattenField];
2514
3042
  if (Array.isArray(nested)) {
2515
3043
  const children = nested.map(
@@ -2523,89 +3051,68 @@ var useConvertTreeData = ({
2523
3051
  child[childField] = newItem[toggleField];
2524
3052
  }
2525
3053
  });
2526
- flattenItems(children);
3054
+ flattenItems(children, source.path);
2527
3055
  } else {
2528
3056
  flattenedData.push(newItem);
2529
3057
  }
2530
3058
  });
2531
3059
  };
2532
- flattenItems(data);
3060
+ flattenItems(data, []);
2533
3061
  const dataWithLevels = flattenedData.map((item) => ({
2534
3062
  ...item,
2535
3063
  level: 0,
2536
3064
  children: [],
2537
3065
  processed: false
2538
3066
  }));
2539
- const findNearestPrecedingParent = (index, parentKey) => {
2540
- for (let i = index - 1; i >= 0; i -= 1) {
2541
- const candidate = dataWithLevels[i];
2542
- if (!candidate) continue;
2543
- if (getFieldValue(candidate, toggleField) === parentKey) {
2544
- return candidate;
2545
- }
2546
- }
2547
- return void 0;
2548
- };
2549
3067
  const rootItems = [];
3068
+ const latestByKey = /* @__PURE__ */ new Map();
2550
3069
  dataWithLevels.forEach((item) => {
2551
- if (!getFieldValue(item, childField)) {
2552
- rootItems.push(item);
2553
- item.processed = true;
2554
- }
2555
- });
2556
- dataWithLevels.forEach((item, index) => {
2557
3070
  const parentKey = getFieldValue(item, childField);
2558
- if (!parentKey || item.processed) return;
2559
- const parent = findNearestPrecedingParent(index, parentKey);
3071
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2560
3072
  if (parent) {
2561
3073
  item.level = parent.level + 1;
2562
3074
  parent.children.push(item);
2563
- item.processed = true;
2564
- return;
3075
+ } else {
3076
+ rootItems.push(item);
2565
3077
  }
2566
- rootItems.push(item);
2567
3078
  item.processed = true;
3079
+ latestByKey.set(getFieldValue(item, toggleField), item);
2568
3080
  });
2569
3081
  return rootItems;
2570
3082
  }, [enabled, data, toggleField, childField, flattenField]);
2571
3083
  const flattenTree = (0, import_react5.useMemo)(() => {
2572
3084
  if (!enabled) return [];
2573
- const flatten = (nodes, result = [], level = 0) => {
3085
+ const flatten = (nodes, result, parentTreeNo) => {
2574
3086
  nodes.forEach((node, index) => {
2575
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
3087
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2576
3088
  const toggleValue = getFieldValue(node, toggleField);
2577
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3089
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2578
3090
  result.push({
2579
3091
  ...node,
2580
3092
  treeNo: currentIndex,
2581
3093
  uniqueId,
2582
3094
  processed: true
2583
3095
  });
2584
- 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)));
2585
3098
  if (shouldExpandChildren) {
2586
- flatten(node.children, result, index + startIndex);
3099
+ flatten(node.children, result, currentIndex);
2587
3100
  }
2588
3101
  });
2589
3102
  return result;
2590
3103
  };
2591
- const flattenedData = flatten(processedData, [], 0);
2592
- flattenedData.forEach((item, index) => {
3104
+ const flattenedData = flatten(processedData, [], null);
3105
+ const latestByKey = /* @__PURE__ */ new Map();
3106
+ flattenedData.forEach((item) => {
2593
3107
  const parentKey = getFieldValue(item, childField);
2594
3108
  if (!parentKey) {
2595
3109
  item.parentCount = 1;
2596
- return;
2597
- }
2598
- let parentItem;
2599
- for (let i = index - 1; i >= 0; i -= 1) {
2600
- const candidate = flattenedData[i];
2601
- if (!candidate) continue;
2602
- if (getFieldValue(candidate, toggleField) === parentKey) {
2603
- parentItem = candidate;
2604
- break;
2605
- }
3110
+ } else {
3111
+ const parentItem = latestByKey.get(parentKey);
3112
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3113
+ item.parentCount = parentAmount || 1;
2606
3114
  }
2607
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2608
- item.parentCount = parentAmount || 1;
3115
+ latestByKey.set(getFieldValue(item, toggleField), item);
2609
3116
  });
2610
3117
  return flattenedData;
2611
3118
  }, [
@@ -2622,18 +3129,7 @@ var useConvertTreeData = ({
2622
3129
  if (!enabled) {
2623
3130
  return data ?? [];
2624
3131
  }
2625
- return [...flattenTree].sort((a, b) => {
2626
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2627
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2628
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2629
- const aVal = aParts[i] || 0;
2630
- const bVal = bParts[i] || 0;
2631
- if (aVal !== bVal) {
2632
- return aVal - bVal;
2633
- }
2634
- }
2635
- return 0;
2636
- });
3132
+ return flattenTree;
2637
3133
  }, [enabled, data, flattenTree]);
2638
3134
  return sortedData;
2639
3135
  };
@@ -2691,13 +3187,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2691
3187
  for (let index = 0; index < data.length; index++) {
2692
3188
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2693
3189
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2694
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3190
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2695
3191
  result.push({ rowSpan: 0, isFirstInGroup: false });
2696
3192
  continue;
2697
3193
  }
2698
3194
  let span = 1;
2699
3195
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2700
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3196
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2701
3197
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2702
3198
  span++;
2703
3199
  }
@@ -2790,6 +3286,9 @@ function collectRowSpanColumns(columns) {
2790
3286
  }
2791
3287
 
2792
3288
  // src/core/useGlideTable.ts
3289
+ function isProductionBuild() {
3290
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3291
+ }
2793
3292
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2794
3293
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2795
3294
  function useGlideTable(options) {
@@ -2811,18 +3310,24 @@ function useGlideTable(options) {
2811
3310
  selectOnRowClick = true,
2812
3311
  enableCellSelection = true,
2813
3312
  onDataChange,
2814
- onCellChange,
2815
- onBatchChange,
3313
+ onCellChange: onCellChangeProp,
3314
+ onBatchChange: onBatchChangeProp,
2816
3315
  cellRenderers,
2817
3316
  preserveRowSelection = false,
2818
- toggleField,
2819
- childField,
2820
- flattenField,
3317
+ toggleField: toggleFieldProp,
3318
+ idField,
3319
+ childField: childFieldProp,
3320
+ parentIdField,
3321
+ flattenField: flattenFieldProp,
3322
+ childrenField,
2821
3323
  qtyField,
3324
+ expandColumn,
2822
3325
  expandedRows: controlledExpandedRows,
2823
3326
  onExpandedRowsChange,
2824
3327
  preventExpand = false,
3328
+ autoExpandOnLoad = true,
2825
3329
  enableSubtreeCopy,
3330
+ escapeCopyFormulas = false,
2826
3331
  onCopyActionsReady,
2827
3332
  onRowsPaste,
2828
3333
  enableInsertPaste,
@@ -2843,8 +3348,27 @@ function useGlideTable(options) {
2843
3348
  onSearchValueChange,
2844
3349
  onSearchClose,
2845
3350
  searchResults,
2846
- onSearchResultsChanged
3351
+ onSearchResultsChanged,
3352
+ enableWasdNavigation = true
2847
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);
2848
3372
  const labels = (0, import_react6.useMemo)(() => {
2849
3373
  const resolved = resolveDataTableLabels(labelsProp);
2850
3374
  return {
@@ -2862,7 +3386,7 @@ function useGlideTable(options) {
2862
3386
  const [internalExpandedRows, setInternalExpandedRows] = (0, import_react6.useState)(
2863
3387
  () => /* @__PURE__ */ new Set()
2864
3388
  );
2865
- const [hoveredRowIndex, setHoveredRowIndex] = (0, import_react6.useState)(null);
3389
+ const [hoverStore] = (0, import_react6.useState)(createRowHoverStore);
2866
3390
  const scrollRef = (0, import_react6.useRef)(null);
2867
3391
  const rootRef = (0, import_react6.useRef)(null);
2868
3392
  const escapeDismissOwnerRef = (0, import_react6.useRef)(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
@@ -2919,8 +3443,10 @@ function useGlideTable(options) {
2919
3443
  qtyField,
2920
3444
  expandedRows,
2921
3445
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2922
- preventExpand
3446
+ preventExpand,
3447
+ autoExpandOnLoad
2923
3448
  });
3449
+ const sourceData = (0, import_react6.useMemo)(() => data ?? [], [data]);
2924
3450
  const table = (0, import_react_table.useReactTable)({
2925
3451
  data: tableData,
2926
3452
  columns: tableColumns,
@@ -2959,7 +3485,11 @@ function useGlideTable(options) {
2959
3485
  );
2960
3486
  },
2961
3487
  getCoreRowModel: (0, import_react_table.getCoreRowModel)(),
2962
- 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
+ )
2963
3493
  });
2964
3494
  const rowSpanColumnKeys = (0, import_react6.useMemo)(() => {
2965
3495
  if (!enableRowSpan) return [];
@@ -2976,6 +3506,20 @@ function useGlideTable(options) {
2976
3506
  const rows = table.getRowModel().rows;
2977
3507
  const columnCount = table.getAllLeafColumns().length || 1;
2978
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]);
2979
3523
  const columnFreezeOffsets = (0, import_react6.useMemo)(() => {
2980
3524
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
2981
3525
  return buildColumnFreezeOffsets(
@@ -3018,7 +3562,7 @@ function useGlideTable(options) {
3018
3562
  const cell = scrollElement.querySelector(
3019
3563
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
3020
3564
  );
3021
- if (cell instanceof HTMLElement) {
3565
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
3022
3566
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
3023
3567
  }
3024
3568
  };
@@ -3036,6 +3580,10 @@ function useGlideTable(options) {
3036
3580
  },
3037
3581
  [scrollCellIntoView]
3038
3582
  );
3583
+ const editKeyRef = (0, import_react6.useRef)(() => {
3584
+ });
3585
+ const clearKeyRef = (0, import_react6.useRef)(() => {
3586
+ });
3039
3587
  const {
3040
3588
  dragState,
3041
3589
  activeSelectionBounds,
@@ -3043,20 +3591,27 @@ function useGlideTable(options) {
3043
3591
  handleCellMouseEnter,
3044
3592
  handleFillHandleMouseDown,
3045
3593
  clearSelection: clearCellSelection,
3046
- copySelection
3594
+ copySelection,
3595
+ selectCell,
3596
+ focusSelection
3047
3597
  } = useCellSelection({
3048
- data: tableData,
3598
+ data: sourceData,
3049
3599
  rows,
3050
3600
  enabled: enableCellSelection,
3051
3601
  columnCount: visibleLeafColumns.length,
3602
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
3052
3603
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3604
+ escapeCopyFormulas,
3053
3605
  enableInsertPaste: enableInsertPaste ?? true,
3054
3606
  onDataChange,
3055
3607
  onBatchChange,
3056
3608
  onRowsPaste,
3057
3609
  onCellNavigate: handleCellNavigate,
3058
3610
  cellRendererRegistry,
3059
- rootRef
3611
+ rootRef,
3612
+ enableWasdNavigation,
3613
+ onEditKey: (position) => editKeyRef.current(position),
3614
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
3060
3615
  });
3061
3616
  const clearRowSelection = (0, import_react6.useCallback)(() => {
3062
3617
  if (rowSelectionMode === "none") return;
@@ -3077,22 +3632,79 @@ function useGlideTable(options) {
3077
3632
  const {
3078
3633
  editingCell,
3079
3634
  draftValue,
3635
+ draftInvalid,
3636
+ setDraftInvalid,
3080
3637
  setDraftValue,
3081
3638
  startEdit,
3082
3639
  commitEdit,
3083
3640
  cancelEdit
3084
- } = 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]);
3085
3691
  const commitRenderedCellValue = (0, import_react6.useCallback)(
3086
- (rowId, columnId, value) => commitCellValue({
3087
- data: tableData,
3088
- rows,
3089
- rowId,
3090
- columnId,
3091
- value,
3092
- onCellChange,
3093
- onDataChange
3094
- }),
3095
- [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]
3096
3708
  );
3097
3709
  const getCellContext = (0, import_react6.useCallback)(
3098
3710
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3120,25 +3732,12 @@ function useGlideTable(options) {
3120
3732
  (row, index) => {
3121
3733
  if (getRowId) return getRowId(row, index);
3122
3734
  if (enableExpand) {
3123
- const record = row;
3124
- const idValue = record.id;
3125
- if (idValue != null && String(idValue).length > 0) {
3126
- return String(idValue);
3127
- }
3128
- const uniqueId = record.uniqueId;
3129
- if (uniqueId != null && String(uniqueId).length > 0) {
3130
- return String(uniqueId);
3131
- }
3132
- if (toggleField) {
3133
- const toggleValue = record[toggleField];
3134
- if (toggleValue != null && String(toggleValue).length > 0) {
3135
- return String(toggleValue);
3136
- }
3137
- }
3735
+ const treeKey = getTreeRowKey(row);
3736
+ if (treeKey) return treeKey;
3138
3737
  }
3139
3738
  return String(index);
3140
3739
  },
3141
- [enableExpand, getRowId, toggleField]
3740
+ [enableExpand, getRowId]
3142
3741
  );
3143
3742
  const searchCorpus = (0, import_react6.useMemo)(() => {
3144
3743
  if (!enableInlineSearch) return [];
@@ -3165,28 +3764,59 @@ function useGlideTable(options) {
3165
3764
  }
3166
3765
  return map;
3167
3766
  }, [resolveSearchRowId, rows]);
3168
- const getSearchCellValue = (0, import_react6.useCallback)(
3169
- (rowIndex, colIndex) => {
3170
- const corpusRow = searchCorpusRef.current[rowIndex];
3171
- const column = visibleLeafColumns[colIndex];
3172
- if (!corpusRow || !column) return void 0;
3767
+ const readSearchRawValue = (0, import_react6.useCallback)(
3768
+ (corpusRow, rowIndex, column) => {
3173
3769
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3174
3770
  if (visibleIndex !== void 0) {
3175
3771
  const visibleRow = rows[visibleIndex];
3176
3772
  if (visibleRow) {
3177
- return visibleRow.getValue(column.id);
3773
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3178
3774
  }
3179
3775
  }
3180
3776
  const columnDef = column.columnDef;
3181
3777
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3182
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3778
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3183
3779
  }
3184
3780
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3185
- 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;
3186
3816
  }
3187
- return corpusRow.data[column.id];
3817
+ return value;
3188
3818
  },
3189
- [rows, visibleLeafColumns, visibleRowIndexById]
3819
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3190
3820
  );
3191
3821
  const pendingSearchNavRef = (0, import_react6.useRef)(null);
3192
3822
  const focusSearchResult = (0, import_react6.useCallback)(
@@ -3237,11 +3867,19 @@ function useGlideTable(options) {
3237
3867
  focusSearchResult(pending.colIndex, visibleRowIndex);
3238
3868
  }, [focusSearchResult, rows, visibleRowIndexById]);
3239
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
+ );
3240
3875
  const inlineSearch = useInlineSearch({
3241
3876
  enabled: enableInlineSearch,
3242
3877
  rowCount: searchCorpus.length,
3243
3878
  columnCount: visibleLeafColumns.length,
3244
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,
3245
3883
  initialStartRow: initialSearchStartRow,
3246
3884
  showSearch,
3247
3885
  searchValue,
@@ -3279,11 +3917,14 @@ function useGlideTable(options) {
3279
3917
  visibleRowIndexById
3280
3918
  ]);
3281
3919
  const clearHover = (0, import_react6.useCallback)(() => {
3282
- setHoveredRowIndex(null);
3283
- }, []);
3284
- const handleRowHover = (0, import_react6.useCallback)((rowIndex, _rowData) => {
3285
- setHoveredRowIndex(rowIndex);
3286
- }, []);
3920
+ hoverStore.setHoveredRowIndex(null);
3921
+ }, [hoverStore]);
3922
+ const handleRowHover = (0, import_react6.useCallback)(
3923
+ (rowIndex, _rowData) => {
3924
+ hoverStore.setHoveredRowIndex(rowIndex);
3925
+ },
3926
+ [hoverStore]
3927
+ );
3287
3928
  const handleToggleSelect = (0, import_react6.useCallback)(
3288
3929
  (row) => {
3289
3930
  if (!row.getCanSelect()) return;
@@ -3308,7 +3949,7 @@ function useGlideTable(options) {
3308
3949
  primaryRowSpanKey,
3309
3950
  primaryRowSpanColumnId,
3310
3951
  columnRowSpanMap,
3311
- hoveredRowIndex,
3952
+ hoverStore,
3312
3953
  selectedRowIndices,
3313
3954
  onRowHover: handleRowHover
3314
3955
  },
@@ -3322,6 +3963,7 @@ function useGlideTable(options) {
3322
3963
  enableCellSelection,
3323
3964
  activeSelectionBounds,
3324
3965
  dragState,
3966
+ canFill,
3325
3967
  onCellMouseDown: handleCellMouseDownWithCommit,
3326
3968
  onCellMouseEnter: handleCellMouseEnter,
3327
3969
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3329,18 +3971,23 @@ function useGlideTable(options) {
3329
3971
  cellEdit: {
3330
3972
  editingCell,
3331
3973
  draftValue,
3974
+ draftInvalid,
3975
+ onDraftInvalidChange: setDraftInvalid,
3332
3976
  onDraftValueChange: setDraftValue,
3333
3977
  onStartEdit: startEdit,
3334
3978
  onCommitEdit: commitEdit,
3335
- onCancelEdit: cancelEdit
3979
+ onCommitEditAndMove: commitEditAndMove,
3980
+ onCancelEdit: cancelEditAndRefocus
3336
3981
  },
3337
3982
  cellRender: {
3338
3983
  registry: cellRendererRegistry,
3339
- commitValue: commitRenderedCellValue
3984
+ commitValue: commitRenderedCellValue,
3985
+ protectedLabel: labels.protectedCell
3340
3986
  },
3341
3987
  expand: {
3342
3988
  enableExpand,
3343
3989
  toggleField,
3990
+ expandColumn,
3344
3991
  expandedRows,
3345
3992
  preventExpand,
3346
3993
  onToggleExpand: handleToggleExpand,
@@ -3365,7 +4012,7 @@ function useGlideTable(options) {
3365
4012
  primaryRowSpanKey,
3366
4013
  primaryRowSpanColumnId,
3367
4014
  columnRowSpanMap,
3368
- hoveredRowIndex,
4015
+ hoverStore,
3369
4016
  selectedRowIndices,
3370
4017
  handleRowHover,
3371
4018
  rowSelectionMode,
@@ -3375,19 +4022,25 @@ function useGlideTable(options) {
3375
4022
  enableCellSelection,
3376
4023
  activeSelectionBounds,
3377
4024
  dragState,
4025
+ canFill,
3378
4026
  handleCellMouseDownWithCommit,
3379
4027
  handleCellMouseEnter,
3380
4028
  handleFillHandleMouseDown,
3381
4029
  editingCell,
3382
4030
  draftValue,
4031
+ draftInvalid,
4032
+ setDraftInvalid,
3383
4033
  setDraftValue,
3384
4034
  startEdit,
3385
4035
  commitEdit,
3386
- cancelEdit,
4036
+ commitEditAndMove,
4037
+ cancelEditAndRefocus,
3387
4038
  cellRendererRegistry,
3388
4039
  commitRenderedCellValue,
4040
+ labels.protectedCell,
3389
4041
  enableExpand,
3390
4042
  toggleField,
4043
+ expandColumn,
3391
4044
  expandedRows,
3392
4045
  preventExpand,
3393
4046
  handleToggleExpand,
@@ -3435,6 +4088,7 @@ function useGlideTable(options) {
3435
4088
  handleToggleSelect,
3436
4089
  clearHover,
3437
4090
  setColumnOrder,
4091
+ handleRootFocus: focusSelection,
3438
4092
  copySelection: stableCopySelection,
3439
4093
  inlineSearch: {
3440
4094
  showSearch: inlineSearch.showSearch,
@@ -3485,12 +4139,16 @@ function ResolvedTableCell({
3485
4139
  },
3486
4140
  [cellRender, columnId, row.id]
3487
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
+ }
3488
4146
  const ctx = {
3489
4147
  value,
3490
4148
  row,
3491
4149
  index: row.index,
3492
4150
  columnId,
3493
- cellProps: meta?.cellProps,
4151
+ cellProps,
3494
4152
  update
3495
4153
  };
3496
4154
  if (meta?.cellRender) {
@@ -3882,6 +4540,7 @@ function useColumnReorder(options) {
3882
4540
  createCellRendererRegistry,
3883
4541
  createSearchRegex,
3884
4542
  escapeSearchRegex,
4543
+ escapeSpreadsheetFormula,
3885
4544
  flattenSubtreeRows,
3886
4545
  formatCellValue,
3887
4546
  formatDefaultCellValue,