react-glide-table 2.3.5 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -56,6 +56,7 @@ __export(src_exports, {
56
56
  createSearchRegex: () => createSearchRegex,
57
57
  createTable: () => createTable,
58
58
  escapeSearchRegex: () => escapeSearchRegex,
59
+ escapeSpreadsheetFormula: () => escapeSpreadsheetFormula,
59
60
  flattenSubtreeRows: () => flattenSubtreeRows,
60
61
  formatCellValue: () => formatCellValue,
61
62
  formatDefaultCellValue: () => formatDefaultCellValue,
@@ -106,6 +107,163 @@ __export(src_exports, {
106
107
  });
107
108
  module.exports = __toCommonJS(src_exports);
108
109
 
110
+ // src/components/ui/table/features/inline-search/inlineSearch.ts
111
+ var INLINE_SEARCH_MAX_RESULTS = 1e3;
112
+ var INLINE_SEARCH_TARGET_TICK_MS = 10;
113
+ var INLINE_SEARCH_INITIAL_STRIDE = 10;
114
+ function escapeSearchRegex(value) {
115
+ return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
116
+ }
117
+ function createSearchRegex(query) {
118
+ const trimmed = query.trim();
119
+ if (!trimmed) return null;
120
+ return new RegExp(escapeSearchRegex(trimmed), "i");
121
+ }
122
+ function cellValueToSearchText(value) {
123
+ if (value == null) return void 0;
124
+ if (typeof value === "string") return value;
125
+ if (typeof value === "number" || typeof value === "boolean") {
126
+ return String(value);
127
+ }
128
+ if (Array.isArray(value)) {
129
+ return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
130
+ }
131
+ if (typeof value === "object") {
132
+ try {
133
+ return JSON.stringify(value);
134
+ } catch {
135
+ return String(value);
136
+ }
137
+ }
138
+ return String(value);
139
+ }
140
+ function formatSearchResultLabel(status) {
141
+ const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
142
+ if (status.selectedIndex >= 0 && status.results > 0) {
143
+ return `${status.selectedIndex + 1} of ${countLabel}`;
144
+ }
145
+ return countLabel;
146
+ }
147
+ function nextSearchIndex(selectedIndex, results) {
148
+ if (results <= 0) return -1;
149
+ if (selectedIndex < 0) return 0;
150
+ return (selectedIndex + 1) % results;
151
+ }
152
+ function previousSearchIndex(selectedIndex, results) {
153
+ if (results <= 0) return -1;
154
+ if (selectedIndex < 0) return results - 1;
155
+ let next = (selectedIndex - 1) % results;
156
+ if (next < 0) next += results;
157
+ return next;
158
+ }
159
+ function buildSearchMatchKey(colIndex, rowIndex) {
160
+ return `${colIndex}:${rowIndex}`;
161
+ }
162
+ function buildSearchMatchKeys(results) {
163
+ const keys = /* @__PURE__ */ new Set();
164
+ for (const [colIndex, rowIndex] of results) {
165
+ keys.add(buildSearchMatchKey(colIndex, rowIndex));
166
+ }
167
+ return keys;
168
+ }
169
+ function collectSearchMatchesInRange(options) {
170
+ const {
171
+ query,
172
+ startRow,
173
+ rowCount,
174
+ columnCount,
175
+ getCellValue,
176
+ maxResults = INLINE_SEARCH_MAX_RESULTS
177
+ } = options;
178
+ const regex = createSearchRegex(query);
179
+ if (!regex || rowCount <= 0 || columnCount <= 0) return [];
180
+ const matches = [];
181
+ for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
182
+ const rowIndex = startRow + rowOffset;
183
+ for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
184
+ const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
185
+ if (text !== void 0 && regex.test(text)) {
186
+ matches.push([colIndex, rowIndex]);
187
+ if (matches.length >= maxResults) {
188
+ return matches;
189
+ }
190
+ }
191
+ }
192
+ }
193
+ return matches;
194
+ }
195
+ function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
196
+ const rounded = Math.max(elapsedMs, 1);
197
+ const scalar = targetMs / rounded;
198
+ return Math.max(1, Math.ceil(currentStride * scalar));
199
+ }
200
+ function buildFlatSearchCorpus(rows, getRowId) {
201
+ return rows.map((data, index) => ({
202
+ id: getRowId(data, index),
203
+ data,
204
+ ancestorToggleKeys: []
205
+ }));
206
+ }
207
+ function buildTreeSearchCorpus(visibleRows, options) {
208
+ const { toggleField, getRowId } = options;
209
+ const corpus = [];
210
+ const seen = /* @__PURE__ */ new Set();
211
+ const walk = (node, ancestorToggleKeys) => {
212
+ const id = getRowId(node, corpus.length);
213
+ if (seen.has(id)) return;
214
+ seen.add(id);
215
+ corpus.push({
216
+ id,
217
+ data: node,
218
+ ancestorToggleKeys
219
+ });
220
+ const children = node.children;
221
+ if (!Array.isArray(children) || children.length === 0) return;
222
+ const toggleValue = node[toggleField];
223
+ const toggleKey = toggleValue === null || toggleValue === void 0 ? "" : String(toggleValue);
224
+ const childAncestors = toggleKey.length > 0 ? [...ancestorToggleKeys, toggleKey] : ancestorToggleKeys;
225
+ for (const child of children) {
226
+ if (child && typeof child === "object") {
227
+ walk(child, childAncestors);
228
+ }
229
+ }
230
+ };
231
+ for (const row of visibleRows) {
232
+ const level = row.level;
233
+ if (level === 0 || level === void 0) {
234
+ walk(row, []);
235
+ }
236
+ }
237
+ for (const row of visibleRows) {
238
+ const id = getRowId(row, corpus.length);
239
+ if (seen.has(id)) continue;
240
+ walk(row, []);
241
+ }
242
+ return corpus;
243
+ }
244
+ function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
245
+ const keys = /* @__PURE__ */ new Set();
246
+ for (const [colIndex, corpusRowIndex] of results) {
247
+ const corpusRow = corpus[corpusRowIndex];
248
+ if (!corpusRow) continue;
249
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
250
+ if (visibleRowIndex === void 0) continue;
251
+ keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
252
+ }
253
+ return keys;
254
+ }
255
+ function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
256
+ const [colIndex, corpusRowIndex] = item;
257
+ const corpusRow = corpus[corpusRowIndex];
258
+ if (!corpusRow) return null;
259
+ const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
260
+ if (visibleRowIndex === void 0) return null;
261
+ return [colIndex, visibleRowIndex];
262
+ }
263
+ function collectAncestorKeysToExpand(corpusRow, expandedRows) {
264
+ return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
265
+ }
266
+
109
267
  // src/core/labels.ts
110
268
  var DEFAULT_DATA_TABLE_LABELS = {
111
269
  empty: "No data",
@@ -119,7 +277,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
119
277
  searchResultHint: "Type to search",
120
278
  searchPrevious: "Previous result",
121
279
  searchNext: "Next result",
122
- searchClose: "Close search"
280
+ searchClose: "Close search",
281
+ searchResultCount: formatSearchResultLabel,
282
+ protectedCell: "protected",
283
+ paginationPrevious: "Previous page",
284
+ paginationNext: "Next page"
123
285
  };
124
286
  function resolveDataTableLabels(partial) {
125
287
  return {
@@ -159,6 +321,61 @@ var DATA_TABLE_COLUMN_REORDER_THRESHOLD = 4;
159
321
  // src/components/ui/table/features/cell-edit/useCellEdit.ts
160
322
  var import_react = require("react");
161
323
 
324
+ // src/components/ui/table/features/data-patch/dataPatch.ts
325
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
326
+ function getTreeSource(row) {
327
+ if (!row || typeof row !== "object") return void 0;
328
+ return row[TREE_SOURCE];
329
+ }
330
+ function getTreeRowKey(row) {
331
+ const source = getTreeSource(row);
332
+ if (!source) return void 0;
333
+ return `tree:${source.path.join(".")}`;
334
+ }
335
+ function setValueAtAccessor(record, accessorKey, value) {
336
+ if (!accessorKey.includes(".") || accessorKey in record) {
337
+ return { ...record, [accessorKey]: value };
338
+ }
339
+ const [head, ...rest] = accessorKey.split(".");
340
+ const current = record[head];
341
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
342
+ return {
343
+ ...record,
344
+ [head]: setValueAtAccessor(child, rest.join("."), value)
345
+ };
346
+ }
347
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
348
+ const [head, ...rest] = path;
349
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
350
+ const node = nodes[head];
351
+ if (!node || typeof node !== "object") return null;
352
+ const record = node;
353
+ let nextNode;
354
+ if (rest.length === 0) {
355
+ nextNode = setValueAtAccessor(record, accessorKey, value);
356
+ } else {
357
+ const children = record[childrenField];
358
+ if (!Array.isArray(children)) return null;
359
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
360
+ if (!nextChildren) return null;
361
+ nextNode = { ...record, [childrenField]: nextChildren };
362
+ }
363
+ const next = nodes.slice();
364
+ next[head] = nextNode;
365
+ return next;
366
+ }
367
+ function applyCellChangesToData(data, changes) {
368
+ let next = data;
369
+ for (const change of changes) {
370
+ const source = getTreeSource(change.original);
371
+ const path = source ? source.path : [change.index];
372
+ const childrenField = source?.childrenField ?? "";
373
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
374
+ if (patched) next = patched;
375
+ }
376
+ return next === data ? data.slice() : next;
377
+ }
378
+
162
379
  // src/components/ui/table/features/cell-edit/cellEdit.ts
163
380
  function getColumnAccessorKey(columnDef) {
164
381
  if (columnDef.accessorKey !== void 0 && columnDef.accessorKey !== null) {
@@ -166,7 +383,11 @@ function getColumnAccessorKey(columnDef) {
166
383
  }
167
384
  return columnDef.id;
168
385
  }
386
+ function isProtectedColumn(columnDef) {
387
+ return columnDef.meta?.kind === "protected";
388
+ }
169
389
  function isColumnEditable(columnDef) {
390
+ if (isProtectedColumn(columnDef)) return false;
170
391
  return Boolean(columnDef.meta?.editable);
171
392
  }
172
393
  function getColumnEditType(columnDef) {
@@ -199,10 +420,11 @@ function applyCellEdit(data, rows, rowIndex, colIndex, raw) {
199
420
  if (!accessorKey) return null;
200
421
  const parsed = parseCellEditValue(raw, getColumnEditType(columnDef));
201
422
  if (!parsed.ok) return null;
202
- const newData = data.map((row) => ({ ...row }));
203
- if (!newData[rowIndex]) return null;
204
- newData[rowIndex][accessorKey] = parsed.value;
205
- return newData;
423
+ const row = rows[rowIndex];
424
+ if (!row) return null;
425
+ return applyCellChangesToData(data, [
426
+ { original: row.original, index: row.index, accessorKey, value: parsed.value }
427
+ ]);
206
428
  }
207
429
 
208
430
  // src/components/ui/table/features/cell-render/commitCellValue.ts
@@ -226,12 +448,12 @@ function commitCellValue({
226
448
  if (!cell) return false;
227
449
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
228
450
  if (!accessorKey) return false;
229
- const dataIndex = row.index;
230
- if (dataIndex < 0 || dataIndex >= data.length) return false;
231
- const next = data.map((item) => ({ ...item }));
232
- const target = next[dataIndex];
233
- if (!target) return false;
234
- target[accessorKey] = value;
451
+ const next = applyCellChangesToData(data, [
452
+ { original: row.original, index: row.index, accessorKey, value }
453
+ ]);
454
+ if (next === data || next.every((item, index) => item === data[index])) {
455
+ return false;
456
+ }
235
457
  onDataChange?.(next);
236
458
  return true;
237
459
  }
@@ -243,19 +465,36 @@ function useCellEdit({
243
465
  onDataChange,
244
466
  onCellChange
245
467
  }) {
246
- const [editingCell, setEditingCell] = (0, import_react.useState)(null);
468
+ const [editingKey, setEditingKey] = (0, import_react.useState)(null);
247
469
  const [draftValue, setDraftValue] = (0, import_react.useState)("");
248
470
  const draftValueRef = (0, import_react.useRef)(draftValue);
249
- const editingCellRef = (0, import_react.useRef)(editingCell);
471
+ const [draftInvalid, setDraftInvalidState] = (0, import_react.useState)(false);
472
+ const draftInvalidRef = (0, import_react.useRef)(false);
473
+ const setDraftInvalid = (0, import_react.useCallback)((invalid) => {
474
+ draftInvalidRef.current = invalid;
475
+ setDraftInvalidState(invalid);
476
+ }, []);
250
477
  (0, import_react.useEffect)(() => {
251
478
  draftValueRef.current = draftValue;
252
479
  }, [draftValue]);
480
+ const editingCell = (0, import_react.useMemo)(
481
+ () => resolveEditingCell(rows, editingKey),
482
+ [rows, editingKey]
483
+ );
484
+ const editingCellRef = (0, import_react.useRef)(editingCell);
485
+ editingCellRef.current = editingCell;
253
486
  (0, import_react.useEffect)(() => {
254
- editingCellRef.current = editingCell;
255
- }, [editingCell]);
487
+ if (editingKey && !editingCell) {
488
+ setEditingKey(null);
489
+ setDraftValue("");
490
+ }
491
+ }, [editingCell, editingKey]);
256
492
  const cancelEdit = (0, import_react.useCallback)(() => {
257
- setEditingCell(null);
493
+ editingCellRef.current = null;
494
+ setEditingKey(null);
258
495
  setDraftValue("");
496
+ draftInvalidRef.current = false;
497
+ setDraftInvalidState(false);
259
498
  }, []);
260
499
  const commitEdit = (0, import_react.useCallback)(
261
500
  (raw) => {
@@ -275,6 +514,7 @@ function useCellEdit({
275
514
  cancelEdit();
276
515
  return true;
277
516
  }
517
+ if (draftInvalidRef.current) return false;
278
518
  const value = raw ?? draftValueRef.current;
279
519
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
280
520
  if (!parsed.ok) return false;
@@ -295,13 +535,15 @@ function useCellEdit({
295
535
  );
296
536
  const startEdit = (0, import_react.useCallback)(
297
537
  (rowIndex, colIndex) => {
298
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
299
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
538
+ const row = rows[rowIndex];
539
+ const cell = row?.getVisibleCells()[colIndex];
540
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
541
+ if (!isTextEditableValue(cell.getValue())) return;
300
542
  const current = editingCellRef.current;
301
543
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
302
544
  return;
303
545
  }
304
- setEditingCell({ rowIndex, colIndex });
546
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
305
547
  setDraftValue(getCellEditDraftValue(cell.getValue()));
306
548
  },
307
549
  [commitEdit, rows]
@@ -309,12 +551,55 @@ function useCellEdit({
309
551
  return {
310
552
  editingCell,
311
553
  draftValue,
554
+ draftInvalid,
555
+ setDraftInvalid,
312
556
  setDraftValue,
313
557
  startEdit,
314
558
  commitEdit,
315
559
  cancelEdit
316
560
  };
317
561
  }
562
+ function resolveEditingCell(rows, key) {
563
+ if (!key) return null;
564
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
565
+ if (rowIndex < 0) return null;
566
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
567
+ if (colIndex < 0) return null;
568
+ return { rowIndex, colIndex };
569
+ }
570
+ function isTextEditableValue(value) {
571
+ return value === null || value === void 0 || typeof value !== "object";
572
+ }
573
+
574
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
575
+ function formatObjectValue(value) {
576
+ const text = value.text ?? value.label ?? value.name ?? value.title;
577
+ if (text != null && text !== "") {
578
+ return formatCellValue(text);
579
+ }
580
+ try {
581
+ return JSON.stringify(value);
582
+ } catch {
583
+ return "";
584
+ }
585
+ }
586
+ function formatCellValue(value) {
587
+ if (value === null || value === void 0) return "";
588
+ if (value instanceof Date) {
589
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
590
+ }
591
+ if (Array.isArray(value)) {
592
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
593
+ }
594
+ if (typeof value === "object") {
595
+ return formatObjectValue(value);
596
+ }
597
+ if (typeof value === "string") return value;
598
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
599
+ return String(value);
600
+ }
601
+ return "";
602
+ }
318
603
 
319
604
  // src/components/ui/table/features/cell-render/builtins.tsx
320
605
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -338,8 +623,9 @@ function asDrilldownItems(value) {
338
623
  const record = item;
339
624
  const text = asString(record.text ?? record.label ?? "");
340
625
  if (!text) return [];
341
- const img = record.img ?? record.image;
342
- return [{ text, ...typeof img === "string" ? { img } : {} }];
626
+ const rawImg = record.img ?? record.image;
627
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
628
+ return [{ text, ...img ? { img } : {} }];
343
629
  }
344
630
  return [{ text: asString(item) }];
345
631
  });
@@ -400,6 +686,22 @@ function sanitizeUriHref(raw) {
400
686
  return href;
401
687
  }
402
688
  }
689
+ function sanitizeImageSrc(raw) {
690
+ const src = raw.trim();
691
+ if (!src) return null;
692
+ try {
693
+ const parsed = new URL(src);
694
+ const protocol = parsed.protocol.toLowerCase();
695
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
696
+ return src;
697
+ }
698
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
699
+ return null;
700
+ } catch {
701
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
702
+ return src;
703
+ }
704
+ }
403
705
  function UriCell({ value }) {
404
706
  const raw = asString(value);
405
707
  if (!raw) return null;
@@ -421,7 +723,10 @@ function UriCell({ value }) {
421
723
  );
422
724
  }
423
725
  function ImageCell({ value }) {
424
- const urls = asStringList(value);
726
+ const urls = asStringList(value).flatMap((url) => {
727
+ const src = sanitizeImageSrc(url);
728
+ return src ? [src] : [];
729
+ });
425
730
  if (urls.length === 0) return null;
426
731
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
427
732
  "img",
@@ -474,8 +779,33 @@ function DrilldownCell({ value }) {
474
779
  function LoadingCell() {
475
780
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-loading", "aria-busy": "true" });
476
781
  }
477
- function ProtectedCell() {
478
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
782
+ function ProtectedCell({ cellProps }) {
783
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
784
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
785
+ }
786
+ function RowSelectCell({ row, cellProps }) {
787
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
788
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
789
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
790
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
791
+ "input",
792
+ {
793
+ type: "checkbox",
794
+ className: "data-table-cell-row-select",
795
+ checked,
796
+ disabled: !canSelect,
797
+ "aria-label": label,
798
+ onChange: () => {
799
+ if (canSelect) row.toggleSelected();
800
+ },
801
+ onClick: (event) => {
802
+ event.stopPropagation();
803
+ },
804
+ onMouseDown: (event) => {
805
+ event.stopPropagation();
806
+ }
807
+ }
808
+ );
479
809
  }
480
810
  function RowIdCell({ value }) {
481
811
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -491,7 +821,8 @@ var BUILTIN_RENDER_MAP = {
491
821
  drilldown: DrilldownCell,
492
822
  loading: LoadingCell,
493
823
  protected: ProtectedCell,
494
- "row-id": RowIdCell
824
+ "row-id": RowIdCell,
825
+ "row-select": RowSelectCell
495
826
  };
496
827
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
497
828
  kind,
@@ -525,496 +856,170 @@ function formatDefaultCellValue(value) {
525
856
  return String(value);
526
857
  }
527
858
  if (typeof value === "bigint") return value.toString();
528
- return String(value);
529
- }
530
-
531
- // src/components/ui/table/features/cell-render/withCellUpdate.ts
532
- function withCellUpdate(context, commitValue) {
533
- return {
534
- ...context,
535
- update: (next) => {
536
- commitValue(context.row.id, context.column.id, next);
537
- }
538
- };
859
+ return formatCellValue(value);
539
860
  }
540
861
 
541
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
542
- var import_react3 = require("react");
862
+ // src/components/ui/table/features/cell-selection/copyData.ts
863
+ var import_react2 = require("react");
543
864
 
544
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
545
- var activeOwner = null;
546
- var clearByOwner = /* @__PURE__ */ new Map();
547
- function createCellSelectionOwner() {
548
- return /* @__PURE__ */ Symbol("cell-selection-owner");
865
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
866
+ var lastSubtreeCopy = null;
867
+ function normalize(text) {
868
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
549
869
  }
550
- function registerCellSelectionOwner(owner, clearSelection) {
551
- clearByOwner.set(owner, clearSelection);
552
- return () => {
553
- clearByOwner.delete(owner);
554
- if (activeOwner === owner) {
555
- activeOwner = null;
556
- }
557
- };
870
+ function rememberSubtreeCopy(text) {
871
+ lastSubtreeCopy = normalize(text);
558
872
  }
559
- function claimCellSelectionOwner(owner) {
560
- if (activeOwner === owner) return;
561
- activeOwner = owner;
562
- for (const [id, clearSelection] of clearByOwner) {
563
- if (id !== owner) {
564
- clearSelection();
565
- }
566
- }
873
+ function isOwnSubtreeCopy(text) {
874
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
567
875
  }
568
- function isActiveCellSelectionOwner(owner) {
569
- return activeOwner === owner;
876
+
877
+ // src/components/ui/table/features/cell-selection/copyData.ts
878
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
879
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
880
+ function escapeSpreadsheetFormula(text) {
881
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
882
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
883
+ return `'${text}`;
570
884
  }
571
- function releaseCellSelectionOwner(owner) {
572
- if (activeOwner === owner) {
573
- activeOwner = null;
885
+ function isReactNodeIterable(node) {
886
+ return typeof node === "object" && node !== null && !(0, import_react2.isValidElement)(node) && Symbol.iterator in node;
887
+ }
888
+ function getElementTypeName(type) {
889
+ if (typeof type === "string") return type;
890
+ if (typeof type === "function") {
891
+ const fn = type;
892
+ return fn.displayName || fn.name || "";
893
+ }
894
+ if (typeof type === "object" && type !== null) {
895
+ const component = type;
896
+ return component.displayName || component.render?.displayName || component.render?.name || "";
574
897
  }
898
+ return "";
575
899
  }
576
-
577
- // src/components/ui/table/features/cell-selection/cellSelection.ts
578
- var INITIAL_DRAG_STATE = {
579
- isSelecting: false,
580
- isFillDragging: false,
581
- start: null,
582
- end: null,
583
- fillAnchor: null,
584
- fillEnd: null
585
- };
586
- function getCellSelectionBounds(start, end) {
587
- if (!start || !end) return null;
588
- return {
589
- startRow: Math.min(start.row, end.row),
590
- endRow: Math.max(start.row, end.row),
591
- startCol: Math.min(start.col, end.col),
592
- endCol: Math.max(start.col, end.col)
593
- };
900
+ function isButtonReactElement(node) {
901
+ const typeName = getElementTypeName(node.type);
902
+ if (typeName === "button" || /button/i.test(typeName)) return true;
903
+ const props = node.props;
904
+ if (props.role === "button") return true;
905
+ if (typeName === "input" && props.type === "button") return true;
906
+ return false;
594
907
  }
595
- function getCellNavigationDelta(key) {
596
- switch (key) {
597
- case "ArrowUp":
598
- case "w":
599
- case "W":
600
- return { row: -1, col: 0 };
601
- case "ArrowDown":
602
- case "s":
603
- case "S":
604
- return { row: 1, col: 0 };
605
- case "ArrowLeft":
606
- case "a":
607
- case "A":
608
- return { row: 0, col: -1 };
609
- case "ArrowRight":
610
- case "d":
611
- case "D":
612
- return { row: 0, col: 1 };
613
- default:
614
- return null;
615
- }
908
+ function isImageReactElement(node) {
909
+ const typeName = getElementTypeName(node.type);
910
+ return typeName === "img" || typeName === "image" || /image/i.test(typeName);
616
911
  }
617
- function clampCellPosition(position, rowCount, columnCount) {
618
- const maxRow = Math.max(rowCount - 1, 0);
619
- const maxCol = Math.max(columnCount - 1, 0);
620
- return {
621
- row: Math.min(Math.max(position.row, 0), maxRow),
622
- col: Math.min(Math.max(position.col, 0), maxCol)
623
- };
912
+ var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
913
+ function isLikelyUrl(value) {
914
+ const trimmed = value.trim();
915
+ if (!trimmed) return false;
916
+ if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
917
+ if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
918
+ return false;
624
919
  }
625
- function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
626
- if (rowSpan <= 1) return void 0;
627
- const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
628
- if (!tbody) return void 0;
629
- const rows = tbody.querySelectorAll(":scope > tr");
630
- if (rows.length < rowIndex + rowSpan) return void 0;
631
- const heights = [];
632
- for (let i = 0; i < rowSpan; i++) {
633
- const row = rows[rowIndex + i];
634
- const height = row?.getBoundingClientRect().height ?? 0;
635
- if (height <= 0) return void 0;
636
- heights.push(height);
920
+ function pickUrlFromUnknown(value) {
921
+ if (typeof value === "string") {
922
+ return isLikelyUrl(value) ? value.trim() : "";
637
923
  }
638
- return heights;
639
- }
640
- function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
641
- if (rowSpan <= 1) return rowIndex;
642
- const rect = cellElement.getBoundingClientRect();
643
- const relativeY = clientY - rect.top;
644
- const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
645
- if (heights && heights.length === rowSpan) {
646
- let accrued = 0;
647
- for (let i = 0; i < rowSpan; i++) {
648
- accrued += heights[i];
649
- if (relativeY < accrued) {
650
- return rowIndex + i;
924
+ if (Array.isArray(value)) {
925
+ return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
926
+ }
927
+ if (value && typeof value === "object") {
928
+ const record = value;
929
+ for (const key of IMAGE_URL_PROP_KEYS) {
930
+ const candidate = record[key];
931
+ if (typeof candidate === "string" && candidate.trim()) {
932
+ return candidate.trim();
651
933
  }
652
934
  }
653
- return rowIndex + rowSpan - 1;
654
935
  }
655
- const rowHeight = rect.height / rowSpan;
656
- const offset = Math.min(
657
- Math.max(Math.floor(relativeY / rowHeight), 0),
658
- rowSpan - 1
659
- );
660
- return rowIndex + offset;
936
+ return "";
661
937
  }
662
- function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
663
- if (!bounds) return false;
664
- const cellEndRow = rowIndex + rowSpan - 1;
665
- return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
938
+ function imageElementText(node) {
939
+ const props = node.props;
940
+ for (const key of IMAGE_URL_PROP_KEYS) {
941
+ const candidate = props[key];
942
+ if (typeof candidate === "string" && candidate.trim()) {
943
+ return candidate.trim();
944
+ }
945
+ }
946
+ return "";
666
947
  }
667
- function getActiveSelectionBounds(dragState, selectionBounds) {
668
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
669
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
948
+ function reactNodeContainsImage(node) {
949
+ if ((0, import_react2.isValidElement)(node)) {
950
+ if (isImageReactElement(node)) return true;
951
+ return reactNodeContainsImage(node.props.children);
670
952
  }
671
- return selectionBounds;
953
+ if (isReactNodeIterable(node)) {
954
+ for (const child of node) {
955
+ if (reactNodeContainsImage(child)) return true;
956
+ }
957
+ }
958
+ return false;
672
959
  }
673
- var SELECTION_EDGE_WIDTH_PX = 2;
674
- var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
675
- var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
676
- function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
677
- const clampedFrom = Math.max(fromRow, rowIndex);
678
- const clampedTo = Math.min(toRowExclusive, rowIndex + span);
679
- if (clampedTo <= clampedFrom) {
680
- return { offsetRatio: 0, lengthRatio: 0 };
960
+ function readImgUrl(img) {
961
+ const attr = img.getAttribute("src")?.trim() ?? "";
962
+ if (attr) return attr;
963
+ if (img instanceof HTMLImageElement) {
964
+ const current = img.currentSrc?.trim() ?? "";
965
+ if (current && current !== img.baseURI) return current;
681
966
  }
682
- if (!rowHeights || rowHeights.length !== span) {
683
- return {
684
- offsetRatio: (clampedFrom - rowIndex) / span,
685
- lengthRatio: (clampedTo - clampedFrom) / span
686
- };
967
+ return "";
968
+ }
969
+ function readDomImageUrls(rowIndex, colIndex, root) {
970
+ const scope = root ?? (typeof document === "undefined" ? null : document);
971
+ if (!scope) return "";
972
+ const cells = scope.querySelectorAll(
973
+ `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
974
+ );
975
+ for (const cell of cells) {
976
+ const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
977
+ const url = readImgUrl(img);
978
+ return url ? [url] : [];
979
+ });
980
+ if (urls.length > 0) return urls.join(", ");
687
981
  }
688
- const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
689
- let offsetPx = 0;
690
- for (let i = 0; i < clampedFrom - rowIndex; i++) {
691
- offsetPx += rowHeights[i] ?? 0;
982
+ return "";
983
+ }
984
+ function reactNodeToText(node) {
985
+ if (node == null || typeof node === "boolean") return "";
986
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
987
+ return String(node);
692
988
  }
693
- let lengthPx = 0;
694
- for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
695
- lengthPx += rowHeights[i] ?? 0;
989
+ if (isReactNodeIterable(node)) {
990
+ let text = "";
991
+ for (const child of node) {
992
+ text += reactNodeToText(child);
993
+ }
994
+ return text;
995
+ }
996
+ if ((0, import_react2.isValidElement)(node)) {
997
+ if (isButtonReactElement(node)) return "";
998
+ const props = node.props;
999
+ const childText = reactNodeToText(props.children);
1000
+ if (childText) return childText;
1001
+ const fromImage = imageElementText(node);
1002
+ if (fromImage) return fromImage;
1003
+ if (isImageReactElement(node)) return "";
1004
+ if (typeof props.alt === "string" && props.alt) return props.alt;
1005
+ if (typeof props.title === "string" && props.title) return props.title;
1006
+ return "";
696
1007
  }
1008
+ return "";
1009
+ }
1010
+ function quoteTsvCell(text) {
1011
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
1012
+ return `"${text.replace(/"/g, '""')}"`;
1013
+ }
1014
+ function sanitizeClipboardCell(text) {
1015
+ return text.replace(/\s+/g, " ").trim();
1016
+ }
1017
+ function createCopyRenderRow(rowData, index) {
697
1018
  return {
698
- offsetRatio: offsetPx / total,
699
- lengthRatio: lengthPx / total,
700
- offsetPx,
701
- lengthPx
702
- };
703
- }
704
- function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
705
- const cellEndRow = rowIndex + rowSpan - 1;
706
- const span = cellEndRow - rowIndex + 1;
707
- if (span <= 1) return [];
708
- const edges = [];
709
- const isNeighborSelected = (row, neighborCol) => {
710
- if (isVisuallySelectedAt) {
711
- return isVisuallySelectedAt(row, neighborCol);
712
- }
713
- return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
714
- };
715
- const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
716
- let runStart = null;
717
- for (let row = fromRow; row < toRowExclusive; row++) {
718
- if (!isNeighborSelected(row, neighborCol)) {
719
- if (runStart === null) runStart = row;
720
- continue;
721
- }
722
- if (runStart !== null) {
723
- const ratios = rowRangeToHeightRatios(
724
- rowIndex,
725
- span,
726
- runStart,
727
- row,
728
- rowHeights
729
- );
730
- if (ratios.lengthRatio > 0) {
731
- edges.push({ side, ...ratios });
732
- }
733
- runStart = null;
734
- }
735
- }
736
- if (runStart !== null) {
737
- const ratios = rowRangeToHeightRatios(
738
- rowIndex,
739
- span,
740
- runStart,
741
- toRowExclusive,
742
- rowHeights
743
- );
744
- if (ratios.lengthRatio > 0) {
745
- edges.push({ side, ...ratios });
746
- }
747
- }
748
- };
749
- const collectSide = (side, neighborCol) => {
750
- if (bounds.startRow > rowIndex) {
751
- pushUnselectedRuns(
752
- side,
753
- neighborCol,
754
- rowIndex,
755
- Math.min(bounds.startRow, cellEndRow + 1)
756
- );
757
- }
758
- if (bounds.endRow < cellEndRow) {
759
- pushUnselectedRuns(
760
- side,
761
- neighborCol,
762
- Math.max(bounds.endRow + 1, rowIndex),
763
- cellEndRow + 1
764
- );
765
- }
766
- };
767
- if (colIndex < bounds.endCol) {
768
- collectSide("right", colIndex + 1);
769
- }
770
- if (colIndex > bounds.startCol) {
771
- collectSide("left", colIndex - 1);
772
- }
773
- return edges;
774
- }
775
- function buildPartialEdgeGradient(edge) {
776
- const usePx = edge.offsetPx != null && edge.lengthPx != null;
777
- const startPct = edge.offsetRatio * 100;
778
- const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
779
- const startPx = edge.offsetPx ?? 0;
780
- const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
781
- const overlapPx = SELECTION_EDGE_WIDTH_PX;
782
- const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
783
- const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
784
- const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
785
- const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
786
- const xPos = edge.side === "left" ? "0" : "100%";
787
- const layers = [
788
- {
789
- image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
790
- size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
791
- position: `${xPos} 0`
792
- }
793
- ];
794
- if (isTopProtrusion || isBottomProtrusion) {
795
- 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)`;
796
- layers.push({
797
- image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
798
- size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
799
- position: `${xPos} ${capTop}`
800
- });
801
- }
802
- return layers;
803
- }
804
- function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
805
- if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
806
- return void 0;
807
- const cellEndRow = rowIndex + rowSpan - 1;
808
- const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
809
- const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
810
- const isLeftEdge = colIndex === bounds.startCol;
811
- const isRightEdge = colIndex === bounds.endCol;
812
- const selectionContinuesBelow = cellEndRow < bounds.endRow;
813
- const stepEdges = getMergedCellStepEdges(
814
- rowIndex,
815
- colIndex,
816
- bounds,
817
- rowSpan,
818
- isVisuallySelectedAt,
819
- rowHeights
820
- );
821
- const shadows = [];
822
- const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
823
- if (hasFullPerimeter) {
824
- shadows.push(
825
- `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
826
- );
827
- } else {
828
- if (isTopEdge) {
829
- shadows.push(
830
- `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
831
- );
832
- }
833
- if (isBottomEdge) {
834
- shadows.push(
835
- `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
836
- );
837
- }
838
- if (isLeftEdge) {
839
- shadows.push(
840
- `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
841
- );
842
- }
843
- if (isRightEdge) {
844
- shadows.push(
845
- `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
846
- );
847
- }
848
- }
849
- const gradients = [];
850
- const sizes = [];
851
- const positions = [];
852
- for (const edge of stepEdges) {
853
- for (const partial of buildPartialEdgeGradient(edge)) {
854
- gradients.push(partial.image);
855
- sizes.push(partial.size);
856
- positions.push(partial.position);
857
- }
858
- }
859
- if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
860
- return void 0;
861
- }
862
- const style = {};
863
- if (shadows.length > 0) {
864
- style["--selection-edge-shadows"] = shadows.join(", ");
865
- }
866
- if (gradients.length > 0) {
867
- style["--selection-edge-gradients"] = gradients.join(", ");
868
- style["--selection-edge-sizes"] = sizes.join(", ");
869
- style["--selection-edge-positions"] = positions.join(", ");
870
- }
871
- if (selectionContinuesBelow) {
872
- style.borderBottomColor = "var(--color-brand-surface)";
873
- }
874
- return style;
875
- }
876
- function hasCellSelectionEdges(style) {
877
- return Boolean(
878
- style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
879
- );
880
- }
881
-
882
- // src/components/ui/table/features/cell-selection/copyData.ts
883
- var import_react2 = require("react");
884
- function isReactNodeIterable(node) {
885
- return typeof node === "object" && node !== null && !(0, import_react2.isValidElement)(node) && Symbol.iterator in node;
886
- }
887
- function getElementTypeName(type) {
888
- if (typeof type === "string") return type;
889
- if (typeof type === "function") {
890
- const fn = type;
891
- return fn.displayName || fn.name || "";
892
- }
893
- if (typeof type === "object" && type !== null) {
894
- const component = type;
895
- return component.displayName || component.render?.displayName || component.render?.name || "";
896
- }
897
- return "";
898
- }
899
- function isButtonReactElement(node) {
900
- const typeName = getElementTypeName(node.type);
901
- if (typeName === "button" || /button/i.test(typeName)) return true;
902
- const props = node.props;
903
- if (props.role === "button") return true;
904
- if (typeName === "input" && props.type === "button") return true;
905
- return false;
906
- }
907
- function isImageReactElement(node) {
908
- const typeName = getElementTypeName(node.type);
909
- return typeName === "img" || typeName === "image" || /image/i.test(typeName);
910
- }
911
- var IMAGE_URL_PROP_KEYS = ["src", "url", "href", "imageUrl", "srcUrl"];
912
- function isLikelyUrl(value) {
913
- const trimmed = value.trim();
914
- if (!trimmed) return false;
915
- if (/^(https?:|blob:|data:|\/\/)/i.test(trimmed)) return true;
916
- if (trimmed.startsWith("/") && trimmed.includes("/")) return true;
917
- return false;
918
- }
919
- function pickUrlFromUnknown(value) {
920
- if (typeof value === "string") {
921
- return isLikelyUrl(value) ? value.trim() : "";
922
- }
923
- if (Array.isArray(value)) {
924
- return value.map((item) => pickUrlFromUnknown(item)).filter((item) => item.length > 0).join(", ");
925
- }
926
- if (value && typeof value === "object") {
927
- const record = value;
928
- for (const key of IMAGE_URL_PROP_KEYS) {
929
- const candidate = record[key];
930
- if (typeof candidate === "string" && candidate.trim()) {
931
- return candidate.trim();
932
- }
933
- }
934
- }
935
- return "";
936
- }
937
- function imageElementText(node) {
938
- const props = node.props;
939
- for (const key of IMAGE_URL_PROP_KEYS) {
940
- const candidate = props[key];
941
- if (typeof candidate === "string" && candidate.trim()) {
942
- return candidate.trim();
943
- }
944
- }
945
- return "";
946
- }
947
- function reactNodeContainsImage(node) {
948
- if ((0, import_react2.isValidElement)(node)) {
949
- if (isImageReactElement(node)) return true;
950
- return reactNodeContainsImage(node.props.children);
951
- }
952
- if (isReactNodeIterable(node)) {
953
- for (const child of node) {
954
- if (reactNodeContainsImage(child)) return true;
955
- }
956
- }
957
- return false;
958
- }
959
- function readImgUrl(img) {
960
- const attr = img.getAttribute("src")?.trim() ?? "";
961
- if (attr) return attr;
962
- if (img instanceof HTMLImageElement) {
963
- const current = img.currentSrc?.trim() ?? "";
964
- if (current && current !== img.baseURI) return current;
965
- }
966
- return "";
967
- }
968
- function readDomImageUrls(rowIndex, colIndex, root) {
969
- const scope = root ?? (typeof document === "undefined" ? null : document);
970
- if (!scope) return "";
971
- const cells = scope.querySelectorAll(
972
- `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
973
- );
974
- for (const cell of cells) {
975
- const urls = Array.from(cell.querySelectorAll("img")).flatMap((img) => {
976
- const url = readImgUrl(img);
977
- return url ? [url] : [];
978
- });
979
- if (urls.length > 0) return urls.join(", ");
980
- }
981
- return "";
982
- }
983
- function reactNodeToText(node) {
984
- if (node == null || typeof node === "boolean") return "";
985
- if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") {
986
- return String(node);
987
- }
988
- if (isReactNodeIterable(node)) {
989
- let text = "";
990
- for (const child of node) {
991
- text += reactNodeToText(child);
992
- }
993
- return text;
994
- }
995
- if ((0, import_react2.isValidElement)(node)) {
996
- if (isButtonReactElement(node)) return "";
997
- const props = node.props;
998
- const childText = reactNodeToText(props.children);
999
- if (childText) return childText;
1000
- const fromImage = imageElementText(node);
1001
- if (fromImage) return fromImage;
1002
- if (isImageReactElement(node)) return "";
1003
- if (typeof props.alt === "string" && props.alt) return props.alt;
1004
- if (typeof props.title === "string" && props.title) return props.title;
1005
- return "";
1006
- }
1007
- return "";
1008
- }
1009
- function sanitizeClipboardCell(text) {
1010
- return text.replace(/\s+/g, " ").trim();
1011
- }
1012
- function createCopyRenderRow(rowData, index) {
1013
- return {
1014
- id: getOriginalRowId(rowData) || String(index),
1015
- index,
1016
- original: rowData,
1017
- getIsCellDragSelected: () => false
1019
+ id: getOriginalRowId(rowData) || String(index),
1020
+ index,
1021
+ original: rowData,
1022
+ getIsCellDragSelected: () => false
1018
1023
  };
1019
1024
  }
1020
1025
  function buildVisibleRowLookup(visibleRows) {
@@ -1081,204 +1086,550 @@ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIn
1081
1086
  return formatCellValue(value);
1082
1087
  }
1083
1088
  }
1084
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
1085
- try {
1086
- const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
1087
- if (renderer) {
1088
- const node = renderer.render(ctx);
1089
- const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
1090
- if (rendered) return rendered;
1089
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
1090
+ try {
1091
+ const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
1092
+ if (renderer) {
1093
+ const node = renderer.render(ctx);
1094
+ const rendered = extractRenderedCopyText(node, value, cellPosition, options.root);
1095
+ if (rendered) return rendered;
1096
+ }
1097
+ } catch {
1098
+ return formatCellValue(value);
1099
+ }
1100
+ }
1101
+ return formatCellValue(value);
1102
+ }
1103
+ function getNestedValue(row, path) {
1104
+ if (!path.includes(".")) return row[path];
1105
+ return path.split(".").reduce((current, key) => {
1106
+ if (current === null || current === void 0 || typeof current !== "object") {
1107
+ return void 0;
1108
+ }
1109
+ return current[key];
1110
+ }, row);
1111
+ }
1112
+ function readRowColumnValue(rowData, columnDef) {
1113
+ if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1114
+ return columnDef.accessorFn(rowData, 0);
1115
+ }
1116
+ if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1117
+ return getNestedValue(rowData, String(columnDef.accessorKey));
1118
+ }
1119
+ return void 0;
1120
+ }
1121
+ function flattenSubtreeRows(row) {
1122
+ const children = row.children;
1123
+ if (!Array.isArray(children) || children.length === 0) return [];
1124
+ const result = [];
1125
+ const walk = (nodes) => {
1126
+ for (const node of nodes) {
1127
+ result.push(node);
1128
+ const nested = node.children;
1129
+ if (Array.isArray(nested) && nested.length > 0) {
1130
+ walk(nested);
1131
+ }
1132
+ }
1133
+ };
1134
+ walk(children);
1135
+ return result;
1136
+ }
1137
+ function hasSubtree(row) {
1138
+ const children = row.children;
1139
+ return Array.isArray(children) && children.length > 0;
1140
+ }
1141
+ function getOriginalRowId(original) {
1142
+ return String(original.id ?? original.uniqueId ?? "");
1143
+ }
1144
+ function getRowDepth(original) {
1145
+ return typeof original.level === "number" ? original.level : 0;
1146
+ }
1147
+ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1148
+ const { startRow, endRow } = bounds;
1149
+ const result = [];
1150
+ if (mode !== "subtree") {
1151
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1152
+ const row = visibleRows[rowIndex];
1153
+ if (row) result.push({ row: row.original, depth: 0 });
1154
+ }
1155
+ return result;
1156
+ }
1157
+ const included = /* @__PURE__ */ new Set();
1158
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
1159
+ const appendSubtree = (node, depth) => {
1160
+ const children = node.children;
1161
+ if (!Array.isArray(children) || children.length === 0) return;
1162
+ for (const child of children) {
1163
+ const key = keyOf(child);
1164
+ if (!included.has(key)) {
1165
+ result.push({ row: child, depth });
1166
+ included.add(key);
1167
+ }
1168
+ appendSubtree(child, depth + 1);
1169
+ }
1170
+ };
1171
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1172
+ const row = visibleRows[rowIndex];
1173
+ if (!row) continue;
1174
+ const key = keyOf(row.original);
1175
+ if (included.has(key)) continue;
1176
+ const depth = getRowDepth(row.original);
1177
+ result.push({ row: row.original, depth });
1178
+ included.add(key);
1179
+ if (!hasSubtree(row.original)) continue;
1180
+ appendSubtree(row.original, depth + 1);
1181
+ }
1182
+ return result;
1183
+ }
1184
+ function collectCopyRows(visibleRows, bounds, mode = "visible") {
1185
+ return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1186
+ }
1187
+ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1188
+ if (copyRows.length === 0) return "";
1189
+ const { startCol, endCol } = bounds;
1190
+ const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1191
+ if (columnCells.length === 0) return "";
1192
+ const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1193
+ const minDepth = Math.min(...resolvedDepths);
1194
+ const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1195
+ const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1196
+ const meta = templateCell.column.columnDef.meta;
1197
+ if (meta?.copyValue === "omit") return [];
1198
+ return [{ templateCell, colOffset }];
1199
+ });
1200
+ return copyRows.map((rowData, index) => {
1201
+ const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1202
+ const visibleRow = visibleRowByOriginal.get(rowData);
1203
+ const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1204
+ const line = copyableColumns.map(({ templateCell, colOffset }) => {
1205
+ const sourceCell = matchingCells?.[colOffset];
1206
+ const column = sourceCell?.column ?? templateCell.column;
1207
+ const text = formatCopyCellText(
1208
+ rowData,
1209
+ column.columnDef,
1210
+ resolveCopyColumnId(sourceCell ?? templateCell),
1211
+ visibleRow,
1212
+ visibleRow?.index ?? index,
1213
+ sourceCell,
1214
+ visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1215
+ options
1216
+ );
1217
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
1218
+ return quoteTsvCell(escaped);
1219
+ }).join(" ");
1220
+ return `${" ".repeat(relativeDepth)}${line}`;
1221
+ }).join("\n");
1222
+ }
1223
+ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1224
+ const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1225
+ return serializeCopyRowsToTSV(
1226
+ entries.map((entry) => entry.row),
1227
+ visibleRows,
1228
+ bounds,
1229
+ entries.map((entry) => entry.depth),
1230
+ options
1231
+ );
1232
+ }
1233
+ function writeTextWithExecCommand(text) {
1234
+ if (typeof document === "undefined") return false;
1235
+ const textarea = document.createElement("textarea");
1236
+ textarea.value = text;
1237
+ textarea.setAttribute("readonly", "");
1238
+ textarea.style.position = "fixed";
1239
+ textarea.style.top = "0";
1240
+ textarea.style.left = "0";
1241
+ textarea.style.opacity = "0";
1242
+ textarea.style.pointerEvents = "none";
1243
+ document.body.appendChild(textarea);
1244
+ const previouslyFocused = document.activeElement;
1245
+ try {
1246
+ textarea.focus();
1247
+ textarea.select();
1248
+ return document.execCommand("copy");
1249
+ } catch {
1250
+ return false;
1251
+ } finally {
1252
+ document.body.removeChild(textarea);
1253
+ previouslyFocused?.focus?.();
1254
+ }
1255
+ }
1256
+ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1257
+ const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1258
+ if (!text) return false;
1259
+ if (mode === "subtree") rememberSubtreeCopy(text);
1260
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1261
+ return writeTextWithExecCommand(text);
1262
+ }
1263
+ try {
1264
+ await navigator.clipboard.writeText(text);
1265
+ return true;
1266
+ } catch {
1267
+ return false;
1268
+ }
1269
+ }
1270
+
1271
+ // src/components/ui/table/features/cell-render/withCellUpdate.ts
1272
+ function withCellUpdate(context, commitValue) {
1273
+ return {
1274
+ ...context,
1275
+ update: (next) => {
1276
+ commitValue(context.row.id, context.column.id, next);
1277
+ }
1278
+ };
1279
+ }
1280
+
1281
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
1282
+ var import_react3 = require("react");
1283
+
1284
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
1285
+ var activeOwner = null;
1286
+ var clearByOwner = /* @__PURE__ */ new Map();
1287
+ function createCellSelectionOwner() {
1288
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
1289
+ }
1290
+ function registerCellSelectionOwner(owner, clearSelection) {
1291
+ clearByOwner.set(owner, clearSelection);
1292
+ return () => {
1293
+ clearByOwner.delete(owner);
1294
+ if (activeOwner === owner) {
1295
+ activeOwner = null;
1296
+ }
1297
+ };
1298
+ }
1299
+ function claimCellSelectionOwner(owner) {
1300
+ if (activeOwner === owner) return;
1301
+ activeOwner = owner;
1302
+ for (const [id, clearSelection] of clearByOwner) {
1303
+ if (id !== owner) {
1304
+ clearSelection();
1305
+ }
1306
+ }
1307
+ }
1308
+ function isActiveCellSelectionOwner(owner) {
1309
+ return activeOwner === owner;
1310
+ }
1311
+ function releaseCellSelectionOwner(owner) {
1312
+ if (activeOwner === owner) {
1313
+ activeOwner = null;
1314
+ }
1315
+ }
1316
+
1317
+ // src/components/ui/table/features/cell-selection/cellSelection.ts
1318
+ var INITIAL_DRAG_STATE = {
1319
+ isSelecting: false,
1320
+ isFillDragging: false,
1321
+ start: null,
1322
+ end: null,
1323
+ fillAnchor: null,
1324
+ fillEnd: null
1325
+ };
1326
+ function getCellSelectionBounds(start, end) {
1327
+ if (!start || !end) return null;
1328
+ return {
1329
+ startRow: Math.min(start.row, end.row),
1330
+ endRow: Math.max(start.row, end.row),
1331
+ startCol: Math.min(start.col, end.col),
1332
+ endCol: Math.max(start.col, end.col)
1333
+ };
1334
+ }
1335
+ function getCellNavigationDelta(key) {
1336
+ switch (key) {
1337
+ case "ArrowUp":
1338
+ case "w":
1339
+ case "W":
1340
+ return { row: -1, col: 0 };
1341
+ case "ArrowDown":
1342
+ case "s":
1343
+ case "S":
1344
+ return { row: 1, col: 0 };
1345
+ case "ArrowLeft":
1346
+ case "a":
1347
+ case "A":
1348
+ return { row: 0, col: -1 };
1349
+ case "ArrowRight":
1350
+ case "d":
1351
+ case "D":
1352
+ return { row: 0, col: 1 };
1353
+ default:
1354
+ return null;
1355
+ }
1356
+ }
1357
+ function clampCellPosition(position, rowCount, columnCount) {
1358
+ const maxRow = Math.max(rowCount - 1, 0);
1359
+ const maxCol = Math.max(columnCount - 1, 0);
1360
+ return {
1361
+ row: Math.min(Math.max(position.row, 0), maxRow),
1362
+ col: Math.min(Math.max(position.col, 0), maxCol)
1363
+ };
1364
+ }
1365
+ function measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement) {
1366
+ if (rowSpan <= 1) return void 0;
1367
+ const tbody = cellElement?.closest("tbody") ?? (typeof document !== "undefined" ? document.querySelector("tbody.data-table-body") : null);
1368
+ if (!tbody) return void 0;
1369
+ const rows = tbody.querySelectorAll(":scope > tr");
1370
+ if (rows.length < rowIndex + rowSpan) return void 0;
1371
+ const heights = [];
1372
+ for (let i = 0; i < rowSpan; i++) {
1373
+ const row = rows[rowIndex + i];
1374
+ const height = row?.getBoundingClientRect().height ?? 0;
1375
+ if (height <= 0) return void 0;
1376
+ heights.push(height);
1377
+ }
1378
+ return heights;
1379
+ }
1380
+ function getRowIndexInMergedCell(clientY, cellElement, rowIndex, rowSpan) {
1381
+ if (rowSpan <= 1) return rowIndex;
1382
+ const rect = cellElement.getBoundingClientRect();
1383
+ const relativeY = clientY - rect.top;
1384
+ const heights = measureMergedSpanRowHeights(rowIndex, rowSpan, cellElement);
1385
+ if (heights && heights.length === rowSpan) {
1386
+ let accrued = 0;
1387
+ for (let i = 0; i < rowSpan; i++) {
1388
+ accrued += heights[i];
1389
+ if (relativeY < accrued) {
1390
+ return rowIndex + i;
1091
1391
  }
1092
- } catch {
1093
- return formatCellValue(value);
1094
1392
  }
1393
+ return rowIndex + rowSpan - 1;
1095
1394
  }
1096
- return formatCellValue(value);
1395
+ const rowHeight = rect.height / rowSpan;
1396
+ const offset = Math.min(
1397
+ Math.max(Math.floor(relativeY / rowHeight), 0),
1398
+ rowSpan - 1
1399
+ );
1400
+ return rowIndex + offset;
1097
1401
  }
1098
- function formatPrimitive(value) {
1099
- if (value === null || value === void 0) return "";
1100
- if (typeof value === "string") return value;
1101
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1102
- return String(value);
1103
- }
1104
- return "";
1402
+ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
1403
+ if (!bounds) return false;
1404
+ const cellEndRow = rowIndex + rowSpan - 1;
1405
+ return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
1105
1406
  }
1106
- function formatObjectValue(value) {
1107
- const text = value.text ?? value.label ?? value.name ?? value.title;
1108
- if (text != null && text !== "") {
1109
- return formatCellValue(text);
1407
+ function resolveFillBounds(source, pointer) {
1408
+ const below = pointer.row - source.endRow;
1409
+ const above = source.startRow - pointer.row;
1410
+ const right = pointer.col - source.endCol;
1411
+ const left = source.startCol - pointer.col;
1412
+ const vertical = Math.max(below, above, 0);
1413
+ const horizontal = Math.max(right, left, 0);
1414
+ if (vertical === 0 && horizontal === 0) return { ...source };
1415
+ if (vertical >= horizontal) {
1416
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
1110
1417
  }
1111
- try {
1112
- return JSON.stringify(value);
1113
- } catch {
1114
- return "";
1418
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
1419
+ }
1420
+ function getActiveSelectionBounds(dragState, selectionBounds) {
1421
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
1422
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
1115
1423
  }
1424
+ return selectionBounds;
1116
1425
  }
1117
- function formatCellValue(value) {
1118
- if (value === null || value === void 0) return "";
1119
- if (Array.isArray(value)) {
1120
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
1426
+ var SELECTION_EDGE_WIDTH_PX = 2;
1427
+ var SELECTION_EDGE_COLOR = "var(--color-brand-primary)";
1428
+ var CELL_SELECTION_EDGES_CLASS = "cell-selection-edges";
1429
+ function rowRangeToHeightRatios(rowIndex, span, fromRow, toRowExclusive, rowHeights) {
1430
+ const clampedFrom = Math.max(fromRow, rowIndex);
1431
+ const clampedTo = Math.min(toRowExclusive, rowIndex + span);
1432
+ if (clampedTo <= clampedFrom) {
1433
+ return { offsetRatio: 0, lengthRatio: 0 };
1121
1434
  }
1122
- if (typeof value === "object") {
1123
- return formatObjectValue(value);
1435
+ if (!rowHeights || rowHeights.length !== span) {
1436
+ return {
1437
+ offsetRatio: (clampedFrom - rowIndex) / span,
1438
+ lengthRatio: (clampedTo - clampedFrom) / span
1439
+ };
1124
1440
  }
1125
- return formatPrimitive(value);
1126
- }
1127
- function getNestedValue(row, path) {
1128
- if (!path.includes(".")) return row[path];
1129
- return path.split(".").reduce((current, key) => {
1130
- if (current === null || current === void 0 || typeof current !== "object") {
1131
- return void 0;
1132
- }
1133
- return current[key];
1134
- }, row);
1135
- }
1136
- function readRowColumnValue(rowData, columnDef) {
1137
- if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
1138
- return columnDef.accessorFn(rowData, 0);
1441
+ const total = rowHeights.reduce((sum, height) => sum + height, 0) || 1;
1442
+ let offsetPx = 0;
1443
+ for (let i = 0; i < clampedFrom - rowIndex; i++) {
1444
+ offsetPx += rowHeights[i] ?? 0;
1139
1445
  }
1140
- if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
1141
- return getNestedValue(rowData, String(columnDef.accessorKey));
1446
+ let lengthPx = 0;
1447
+ for (let i = clampedFrom - rowIndex; i < clampedTo - rowIndex; i++) {
1448
+ lengthPx += rowHeights[i] ?? 0;
1142
1449
  }
1143
- return void 0;
1450
+ return {
1451
+ offsetRatio: offsetPx / total,
1452
+ lengthRatio: lengthPx / total,
1453
+ offsetPx,
1454
+ lengthPx
1455
+ };
1144
1456
  }
1145
- function flattenSubtreeRows(row) {
1146
- const children = row.children;
1147
- if (!Array.isArray(children) || children.length === 0) return [];
1148
- const result = [];
1149
- const walk = (nodes) => {
1150
- for (const node of nodes) {
1151
- result.push(node);
1152
- const nested = node.children;
1153
- if (Array.isArray(nested) && nested.length > 0) {
1154
- walk(nested);
1155
- }
1457
+ function getMergedCellStepEdges(rowIndex, colIndex, bounds, rowSpan, isVisuallySelectedAt, rowHeights) {
1458
+ const cellEndRow = rowIndex + rowSpan - 1;
1459
+ const span = cellEndRow - rowIndex + 1;
1460
+ if (span <= 1) return [];
1461
+ const edges = [];
1462
+ const isNeighborSelected = (row, neighborCol) => {
1463
+ if (isVisuallySelectedAt) {
1464
+ return isVisuallySelectedAt(row, neighborCol);
1156
1465
  }
1466
+ return row >= bounds.startRow && row <= bounds.endRow && neighborCol >= bounds.startCol && neighborCol <= bounds.endCol;
1157
1467
  };
1158
- walk(children);
1159
- return result;
1160
- }
1161
- function hasSubtree(row) {
1162
- const children = row.children;
1163
- return Array.isArray(children) && children.length > 0;
1164
- }
1165
- function getOriginalRowId(original) {
1166
- return String(original.id ?? original.uniqueId ?? "");
1167
- }
1168
- function getRowDepth(original) {
1169
- return typeof original.level === "number" ? original.level : 0;
1170
- }
1171
- function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
1172
- const { startRow, endRow } = bounds;
1173
- const result = [];
1174
- const includedOriginalIds = /* @__PURE__ */ new Set();
1175
- const appendSubtree = (node, depth) => {
1176
- const children = node.children;
1177
- if (!Array.isArray(children) || children.length === 0) return;
1178
- for (const child of children) {
1179
- const childId = getOriginalRowId(child);
1180
- if (!(childId && includedOriginalIds.has(childId))) {
1181
- result.push({ row: child, depth });
1182
- if (childId) includedOriginalIds.add(childId);
1468
+ const pushUnselectedRuns = (side, neighborCol, fromRow, toRowExclusive) => {
1469
+ let runStart = null;
1470
+ for (let row = fromRow; row < toRowExclusive; row++) {
1471
+ if (!isNeighborSelected(row, neighborCol)) {
1472
+ if (runStart === null) runStart = row;
1473
+ continue;
1474
+ }
1475
+ if (runStart !== null) {
1476
+ const ratios = rowRangeToHeightRatios(
1477
+ rowIndex,
1478
+ span,
1479
+ runStart,
1480
+ row,
1481
+ rowHeights
1482
+ );
1483
+ if (ratios.lengthRatio > 0) {
1484
+ edges.push({ side, ...ratios });
1485
+ }
1486
+ runStart = null;
1487
+ }
1488
+ }
1489
+ if (runStart !== null) {
1490
+ const ratios = rowRangeToHeightRatios(
1491
+ rowIndex,
1492
+ span,
1493
+ runStart,
1494
+ toRowExclusive,
1495
+ rowHeights
1496
+ );
1497
+ if (ratios.lengthRatio > 0) {
1498
+ edges.push({ side, ...ratios });
1183
1499
  }
1184
- appendSubtree(child, depth + 1);
1185
1500
  }
1186
1501
  };
1187
- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
1188
- const row = visibleRows[rowIndex];
1189
- if (!row) continue;
1190
- const originalId = getOriginalRowId(row.original);
1191
- if (originalId && includedOriginalIds.has(originalId)) continue;
1192
- const depth = getRowDepth(row.original);
1193
- result.push({ row: row.original, depth });
1194
- if (originalId) includedOriginalIds.add(originalId);
1195
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
1196
- appendSubtree(row.original, depth + 1);
1197
- }
1198
- return result;
1199
- }
1200
- function collectCopyRows(visibleRows, bounds, mode = "visible") {
1201
- return collectCopyRowEntries(visibleRows, bounds, mode).map((entry) => entry.row);
1202
- }
1203
- function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options) {
1204
- if (copyRows.length === 0) return "";
1205
- const { startCol, endCol } = bounds;
1206
- const columnCells = visibleRows[0]?.getVisibleCells().slice(startCol, endCol + 1) ?? [];
1207
- if (columnCells.length === 0) return "";
1208
- const resolvedDepths = depths && depths.length === copyRows.length ? depths : copyRows.map((row) => getRowDepth(row));
1209
- const minDepth = Math.min(...resolvedDepths);
1210
- const visibleRowByOriginal = buildVisibleRowLookup(visibleRows);
1211
- const copyableColumns = columnCells.flatMap((templateCell, colOffset) => {
1212
- const meta = templateCell.column.columnDef.meta;
1213
- if (meta?.copyValue === "omit") return [];
1214
- return [{ templateCell, colOffset }];
1215
- });
1216
- return copyRows.map((rowData, index) => {
1217
- const relativeDepth = Math.max(0, (resolvedDepths[index] ?? 0) - minDepth);
1218
- const visibleRow = visibleRowByOriginal.get(rowData);
1219
- const matchingCells = visibleRow?.getVisibleCells().slice(startCol, endCol + 1);
1220
- const line = copyableColumns.map(({ templateCell, colOffset }) => {
1221
- const sourceCell = matchingCells?.[colOffset];
1222
- const column = sourceCell?.column ?? templateCell.column;
1223
- return formatCopyCellText(
1224
- rowData,
1225
- column.columnDef,
1226
- resolveCopyColumnId(sourceCell ?? templateCell),
1227
- visibleRow,
1228
- visibleRow?.index ?? index,
1229
- sourceCell,
1230
- visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
1231
- options
1502
+ const collectSide = (side, neighborCol) => {
1503
+ if (bounds.startRow > rowIndex) {
1504
+ pushUnselectedRuns(
1505
+ side,
1506
+ neighborCol,
1507
+ rowIndex,
1508
+ Math.min(bounds.startRow, cellEndRow + 1)
1232
1509
  );
1233
- }).join(" ");
1234
- return `${" ".repeat(relativeDepth)}${line}`;
1235
- }).join("\n");
1510
+ }
1511
+ if (bounds.endRow < cellEndRow) {
1512
+ pushUnselectedRuns(
1513
+ side,
1514
+ neighborCol,
1515
+ Math.max(bounds.endRow + 1, rowIndex),
1516
+ cellEndRow + 1
1517
+ );
1518
+ }
1519
+ };
1520
+ if (colIndex < bounds.endCol) {
1521
+ collectSide("right", colIndex + 1);
1522
+ }
1523
+ if (colIndex > bounds.startCol) {
1524
+ collectSide("left", colIndex - 1);
1525
+ }
1526
+ return edges;
1236
1527
  }
1237
- function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options) {
1238
- const entries = collectCopyRowEntries(visibleRows, bounds, mode);
1239
- return serializeCopyRowsToTSV(
1240
- entries.map((entry) => entry.row),
1241
- visibleRows,
1528
+ function buildPartialEdgeGradient(edge) {
1529
+ const usePx = edge.offsetPx != null && edge.lengthPx != null;
1530
+ const startPct = edge.offsetRatio * 100;
1531
+ const endPct = (edge.offsetRatio + edge.lengthRatio) * 100;
1532
+ const startPx = edge.offsetPx ?? 0;
1533
+ const endPx = (edge.offsetPx ?? 0) + (edge.lengthPx ?? 0);
1534
+ const overlapPx = SELECTION_EDGE_WIDTH_PX;
1535
+ const isTopProtrusion = (usePx ? startPx === 0 : edge.offsetRatio === 0) && edge.lengthRatio < 1;
1536
+ const isBottomProtrusion = usePx ? startPx > 0 : edge.offsetRatio > 0;
1537
+ const startStop = usePx ? isBottomProtrusion ? `${Math.max(0, startPx - overlapPx)}px` : `${startPx}px` : isBottomProtrusion ? `calc(${startPct}% - ${overlapPx}px)` : `${startPct}%`;
1538
+ const endStop = usePx ? isTopProtrusion ? `${endPx + overlapPx}px` : `${endPx}px` : isTopProtrusion ? `calc(${endPct}% + ${overlapPx}px)` : `${endPct}%`;
1539
+ const xPos = edge.side === "left" ? "0" : "100%";
1540
+ const layers = [
1541
+ {
1542
+ image: `linear-gradient(to bottom, transparent 0%, transparent ${startStop}, ${SELECTION_EDGE_COLOR} ${startStop}, ${SELECTION_EDGE_COLOR} ${endStop}, transparent ${endStop}, transparent 100%)`,
1543
+ size: `${SELECTION_EDGE_WIDTH_PX}px 100%`,
1544
+ position: `${xPos} 0`
1545
+ }
1546
+ ];
1547
+ if (isTopProtrusion || isBottomProtrusion) {
1548
+ 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)`;
1549
+ layers.push({
1550
+ image: `linear-gradient(${SELECTION_EDGE_COLOR}, ${SELECTION_EDGE_COLOR})`,
1551
+ size: `${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_WIDTH_PX}px`,
1552
+ position: `${xPos} ${capTop}`
1553
+ });
1554
+ }
1555
+ return layers;
1556
+ }
1557
+ function getCellSelectionEdgeStyle(rowIndex, colIndex, bounds, rowSpan = 1, isVisuallySelectedAt, rowHeights) {
1558
+ if (!isCellInSelection(rowIndex, colIndex, bounds, rowSpan) || !bounds)
1559
+ return void 0;
1560
+ const cellEndRow = rowIndex + rowSpan - 1;
1561
+ const isTopEdge = bounds.startRow >= rowIndex && bounds.startRow <= cellEndRow;
1562
+ const isBottomEdge = bounds.endRow >= rowIndex && bounds.endRow <= cellEndRow;
1563
+ const isLeftEdge = colIndex === bounds.startCol;
1564
+ const isRightEdge = colIndex === bounds.endCol;
1565
+ const selectionContinuesBelow = cellEndRow < bounds.endRow;
1566
+ const stepEdges = getMergedCellStepEdges(
1567
+ rowIndex,
1568
+ colIndex,
1242
1569
  bounds,
1243
- entries.map((entry) => entry.depth),
1244
- options
1570
+ rowSpan,
1571
+ isVisuallySelectedAt,
1572
+ rowHeights
1245
1573
  );
1246
- }
1247
- function writeTextWithExecCommand(text) {
1248
- if (typeof document === "undefined") return false;
1249
- const textarea = document.createElement("textarea");
1250
- textarea.value = text;
1251
- textarea.setAttribute("readonly", "");
1252
- textarea.style.position = "fixed";
1253
- textarea.style.top = "0";
1254
- textarea.style.left = "0";
1255
- textarea.style.opacity = "0";
1256
- textarea.style.pointerEvents = "none";
1257
- document.body.appendChild(textarea);
1258
- const previouslyFocused = document.activeElement;
1259
- try {
1260
- textarea.focus();
1261
- textarea.select();
1262
- return document.execCommand("copy");
1263
- } catch {
1264
- return false;
1265
- } finally {
1266
- document.body.removeChild(textarea);
1267
- previouslyFocused?.focus?.();
1574
+ const shadows = [];
1575
+ const hasFullPerimeter = isTopEdge && isBottomEdge && isLeftEdge && isRightEdge && stepEdges.length === 0;
1576
+ if (hasFullPerimeter) {
1577
+ shadows.push(
1578
+ `inset 0 0 0 ${SELECTION_EDGE_WIDTH_PX}px ${SELECTION_EDGE_COLOR}`
1579
+ );
1580
+ } else {
1581
+ if (isTopEdge) {
1582
+ shadows.push(
1583
+ `inset 0 ${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1584
+ );
1585
+ }
1586
+ if (isBottomEdge) {
1587
+ shadows.push(
1588
+ `inset 0 -${SELECTION_EDGE_WIDTH_PX}px 0 0 ${SELECTION_EDGE_COLOR}`
1589
+ );
1590
+ }
1591
+ if (isLeftEdge) {
1592
+ shadows.push(
1593
+ `inset ${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1594
+ );
1595
+ }
1596
+ if (isRightEdge) {
1597
+ shadows.push(
1598
+ `inset -${SELECTION_EDGE_WIDTH_PX}px 0 0 0 ${SELECTION_EDGE_COLOR}`
1599
+ );
1600
+ }
1268
1601
  }
1269
- }
1270
- async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
1271
- const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
1272
- if (!text) return false;
1273
- if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
1274
- return writeTextWithExecCommand(text);
1602
+ const gradients = [];
1603
+ const sizes = [];
1604
+ const positions = [];
1605
+ for (const edge of stepEdges) {
1606
+ for (const partial of buildPartialEdgeGradient(edge)) {
1607
+ gradients.push(partial.image);
1608
+ sizes.push(partial.size);
1609
+ positions.push(partial.position);
1610
+ }
1275
1611
  }
1276
- try {
1277
- await navigator.clipboard.writeText(text);
1278
- return true;
1279
- } catch {
1280
- return false;
1612
+ if (shadows.length === 0 && gradients.length === 0 && !selectionContinuesBelow) {
1613
+ return void 0;
1614
+ }
1615
+ const style = {};
1616
+ if (shadows.length > 0) {
1617
+ style["--selection-edge-shadows"] = shadows.join(", ");
1281
1618
  }
1619
+ if (gradients.length > 0) {
1620
+ style["--selection-edge-gradients"] = gradients.join(", ");
1621
+ style["--selection-edge-sizes"] = sizes.join(", ");
1622
+ style["--selection-edge-positions"] = positions.join(", ");
1623
+ }
1624
+ if (selectionContinuesBelow) {
1625
+ style.borderBottomColor = "var(--color-brand-surface)";
1626
+ }
1627
+ return style;
1628
+ }
1629
+ function hasCellSelectionEdges(style) {
1630
+ return Boolean(
1631
+ style?.["--selection-edge-shadows"] || style?.["--selection-edge-gradients"]
1632
+ );
1282
1633
  }
1283
1634
 
1284
1635
  // src/components/ui/table/features/cell-selection/fillData.ts
@@ -1303,6 +1654,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
1303
1654
  const targetCell = targetRow?.getVisibleCells()[colIndex];
1304
1655
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
1305
1656
  if (!targetRow || !targetCell || !sourceCell) continue;
1657
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
1658
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
1306
1659
  const accessorKey = getColumnAccessorKey2(
1307
1660
  targetCell.column.columnDef
1308
1661
  );
@@ -1324,13 +1677,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
1324
1677
  );
1325
1678
  }
1326
1679
  function applyFillData(data, rows, sourceBounds, fillBounds) {
1327
- const newData = data.map((row) => ({ ...row }));
1328
1680
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
1329
- for (const target of targets) {
1330
- if (!newData[target.rowIndex]) continue;
1331
- newData[target.rowIndex][target.accessorKey] = target.value;
1332
- }
1333
- return newData;
1681
+ return applyCellChangesToData(
1682
+ data,
1683
+ targets.flatMap((target) => {
1684
+ const row = rows[target.rowIndex];
1685
+ if (!row) return [];
1686
+ return [
1687
+ {
1688
+ original: row.original,
1689
+ index: row.index,
1690
+ accessorKey: target.accessorKey,
1691
+ value: target.value
1692
+ }
1693
+ ];
1694
+ })
1695
+ );
1334
1696
  }
1335
1697
  function hasFillExtension(sourceBounds, fillBounds) {
1336
1698
  if (!sourceBounds) return false;
@@ -1351,17 +1713,62 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
1351
1713
  if (firstDepth !== 0) return false;
1352
1714
  return leadingEmptyCounts.some((depth) => depth > 0);
1353
1715
  }
1716
+ function splitTSV(text) {
1717
+ const rows = [];
1718
+ let row = [];
1719
+ let index = 0;
1720
+ while (index <= text.length) {
1721
+ let cell = "";
1722
+ if (text[index] === '"') {
1723
+ index += 1;
1724
+ while (index < text.length) {
1725
+ const char = text[index];
1726
+ if (char === '"') {
1727
+ if (text[index + 1] === '"') {
1728
+ cell += '"';
1729
+ index += 2;
1730
+ continue;
1731
+ }
1732
+ index += 1;
1733
+ break;
1734
+ }
1735
+ cell += char;
1736
+ index += 1;
1737
+ }
1738
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1739
+ cell += text[index];
1740
+ index += 1;
1741
+ }
1742
+ } else {
1743
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
1744
+ cell += text[index];
1745
+ index += 1;
1746
+ }
1747
+ }
1748
+ row.push(cell);
1749
+ if (index >= text.length) {
1750
+ rows.push(row);
1751
+ break;
1752
+ }
1753
+ if (text[index] === "\n") {
1754
+ rows.push(row);
1755
+ row = [];
1756
+ }
1757
+ index += 1;
1758
+ }
1759
+ return rows;
1760
+ }
1354
1761
  function parseClipboardTSV(text) {
1355
1762
  return parseClipboardTSVWithDepths(text).values;
1356
1763
  }
1357
- function parseClipboardTSVWithDepths(text) {
1764
+ function parseClipboardTSVWithDepths(text, options) {
1358
1765
  if (!text) return { values: [], depths: [] };
1359
1766
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1360
1767
  const withoutTrailing = normalized.replace(/\n+$/, "");
1361
1768
  if (!withoutTrailing) return { values: [], depths: [] };
1362
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
1769
+ const rows = splitTSV(withoutTrailing);
1363
1770
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
1364
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
1771
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
1365
1772
  const values = [];
1366
1773
  const depths = [];
1367
1774
  for (let index = 0; index < rows.length; index += 1) {
@@ -1388,8 +1795,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
1388
1795
  }
1389
1796
  return columnIds;
1390
1797
  }
1391
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
1392
- const { values, depths } = parseClipboardTSVWithDepths(text);
1798
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
1799
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
1393
1800
  if (values.length === 0) return null;
1394
1801
  const width = Math.max(...values.map((row) => row.length), 0);
1395
1802
  if (width === 0) return null;
@@ -1422,6 +1829,19 @@ function isEditablePasteTarget(target) {
1422
1829
  }
1423
1830
 
1424
1831
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
1832
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
1833
+ function isInteractiveFocus() {
1834
+ const active = document.activeElement;
1835
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
1836
+ }
1837
+ function hasPageTextSelectionOutside(root) {
1838
+ if (typeof window.getSelection !== "function") return false;
1839
+ const selection = window.getSelection();
1840
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
1841
+ if (!selection.toString()) return false;
1842
+ const anchor = selection.anchorNode;
1843
+ return !(root && anchor && root.contains(anchor));
1844
+ }
1425
1845
  function isFocusOutsideRoot(rootRef) {
1426
1846
  const root = rootRef?.current;
1427
1847
  if (!root) return false;
@@ -1434,29 +1854,50 @@ function useCellSelection({
1434
1854
  rows,
1435
1855
  enabled = true,
1436
1856
  columnCount = 0,
1857
+ columnSignature,
1437
1858
  enableSubtreeCopy = false,
1859
+ escapeCopyFormulas = false,
1438
1860
  enableInsertPaste = true,
1439
1861
  onDataChange,
1440
1862
  onBatchChange,
1441
1863
  onRowsPaste,
1442
1864
  onCellNavigate,
1443
1865
  cellRendererRegistry,
1444
- rootRef
1866
+ rootRef,
1867
+ enableWasdNavigation = true,
1868
+ onEditKey,
1869
+ onClearKey
1445
1870
  }) {
1446
1871
  const ownerRef = (0, import_react3.useRef)(createCellSelectionOwner());
1447
1872
  const [dragState, setDragState] = (0, import_react3.useState)(INITIAL_DRAG_STATE);
1448
1873
  const pendingPasteModeRef = (0, import_react3.useRef)(null);
1449
1874
  const dragStateRef = (0, import_react3.useRef)(dragState);
1450
1875
  const onCellNavigateRef = (0, import_react3.useRef)(onCellNavigate);
1876
+ const onEditKeyRef = (0, import_react3.useRef)(onEditKey);
1877
+ const onClearKeyRef = (0, import_react3.useRef)(onClearKey);
1451
1878
  dragStateRef.current = dragState;
1452
1879
  onCellNavigateRef.current = onCellNavigate;
1453
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
1454
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
1880
+ onEditKeyRef.current = onEditKey;
1881
+ onClearKeyRef.current = onClearKey;
1882
+ const updateDragState = (0, import_react3.useCallback)((update) => {
1883
+ const prev = dragStateRef.current;
1884
+ const next = update(prev);
1885
+ if (next === prev) return;
1886
+ dragStateRef.current = next;
1887
+ setDragState(next);
1888
+ }, []);
1889
+ const activeSelectionBounds = (0, import_react3.useMemo)(() => {
1890
+ if (!enabled) return null;
1891
+ return getActiveSelectionBounds(
1892
+ dragState,
1893
+ getCellSelectionBounds(dragState.start, dragState.end)
1894
+ );
1895
+ }, [dragState, enabled]);
1455
1896
  const handleCellMouseDown = (0, import_react3.useCallback)(
1456
1897
  (rowIndex, colIndex, options) => {
1457
1898
  if (!enabled) return;
1458
1899
  claimCellSelectionOwner(ownerRef.current);
1459
- setDragState((prev) => {
1900
+ updateDragState((prev) => {
1460
1901
  if (options?.shiftKey && prev.start) {
1461
1902
  return {
1462
1903
  ...prev,
@@ -1477,58 +1918,184 @@ function useCellSelection({
1477
1918
  };
1478
1919
  });
1479
1920
  },
1480
- [enabled]
1921
+ [enabled, updateDragState]
1481
1922
  );
1482
1923
  const handleCellMouseEnter = (0, import_react3.useCallback)(
1483
1924
  (rowIndex, colIndex) => {
1484
1925
  if (!enabled) return;
1485
- setDragState((prev) => {
1926
+ updateDragState((prev) => {
1486
1927
  if (prev.isSelecting) {
1928
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
1487
1929
  return { ...prev, end: { row: rowIndex, col: colIndex } };
1488
1930
  }
1489
1931
  if (prev.isFillDragging) {
1932
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
1490
1933
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
1491
1934
  }
1492
1935
  return prev;
1493
1936
  });
1494
1937
  },
1495
- [enabled]
1938
+ [enabled, updateDragState]
1496
1939
  );
1497
1940
  const handleFillHandleMouseDown = (0, import_react3.useCallback)(
1498
1941
  (rowIndex, colIndex) => {
1499
1942
  if (!enabled) return;
1500
1943
  claimCellSelectionOwner(ownerRef.current);
1501
- setDragState((prev) => {
1944
+ updateDragState((prev) => {
1945
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1946
+ if (!bounds) return prev;
1947
+ return {
1948
+ ...prev,
1949
+ isSelecting: false,
1950
+ isFillDragging: true,
1951
+ fillAnchor: { row: bounds.startRow, col: bounds.startCol },
1952
+ fillEnd: { row: rowIndex, col: colIndex }
1953
+ };
1954
+ });
1955
+ },
1956
+ [enabled, updateDragState]
1957
+ );
1958
+ const clearSelection = (0, import_react3.useCallback)(() => {
1959
+ const prev = dragStateRef.current;
1960
+ if (prev.start === null && prev.end === null && !prev.isSelecting && !prev.isFillDragging) {
1961
+ return;
1962
+ }
1963
+ releaseCellSelectionOwner(ownerRef.current);
1964
+ dragStateRef.current = INITIAL_DRAG_STATE;
1965
+ setDragState(INITIAL_DRAG_STATE);
1966
+ }, []);
1967
+ (0, import_react3.useEffect)(() => {
1968
+ if (!enabled) {
1969
+ clearSelection();
1970
+ }
1971
+ }, [clearSelection, enabled]);
1972
+ (0, import_react3.useEffect)(() => {
1973
+ return registerCellSelectionOwner(ownerRef.current, clearSelection);
1974
+ }, [clearSelection]);
1975
+ const previousColumnSignatureRef = (0, import_react3.useRef)(columnSignature);
1976
+ (0, import_react3.useEffect)(() => {
1977
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
1978
+ previousColumnSignatureRef.current = columnSignature;
1979
+ const prev = dragStateRef.current;
1980
+ if (!prev.start || !prev.end) return;
1981
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
1982
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
1983
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
1984
+ if (columnsChanged || outOfRange) {
1985
+ clearSelection();
1986
+ }
1987
+ }, [clearSelection, columnCount, columnSignature, rows]);
1988
+ (0, import_react3.useEffect)(() => {
1989
+ if (!enabled) return;
1990
+ const handlePointerDown = (event) => {
1991
+ const root = rootRef?.current;
1992
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
1993
+ if (event.target instanceof Node && root.contains(event.target)) return;
1994
+ releaseCellSelectionOwner(ownerRef.current);
1995
+ };
1996
+ document.addEventListener("pointerdown", handlePointerDown, true);
1997
+ document.addEventListener("mousedown", handlePointerDown, true);
1998
+ return () => {
1999
+ document.removeEventListener("pointerdown", handlePointerDown, true);
2000
+ document.removeEventListener("mousedown", handlePointerDown, true);
2001
+ };
2002
+ }, [enabled, rootRef]);
2003
+ const getColumnCount = (0, import_react3.useCallback)(
2004
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
2005
+ [columnCount, rows]
2006
+ );
2007
+ const selectCell = (0, import_react3.useCallback)(
2008
+ (row, col) => {
2009
+ if (!enabled) return;
2010
+ const resolvedColumnCount = getColumnCount();
2011
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
2012
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
2013
+ claimCellSelectionOwner(ownerRef.current);
2014
+ const nextState = {
2015
+ isSelecting: false,
2016
+ isFillDragging: false,
2017
+ start: position,
2018
+ end: position,
2019
+ fillAnchor: null,
2020
+ fillEnd: null
2021
+ };
2022
+ dragStateRef.current = nextState;
2023
+ setDragState(nextState);
2024
+ onCellNavigateRef.current?.(position);
2025
+ },
2026
+ [enabled, getColumnCount, rows.length]
2027
+ );
2028
+ const focusSelection = (0, import_react3.useCallback)(() => {
2029
+ if (!enabled) return;
2030
+ const prev = dragStateRef.current;
2031
+ if (prev.start && prev.end) {
2032
+ claimCellSelectionOwner(ownerRef.current);
2033
+ return;
2034
+ }
2035
+ selectCell(0, 0);
2036
+ }, [enabled, selectCell]);
2037
+ (0, import_react3.useEffect)(() => {
2038
+ if (!enabled) return;
2039
+ const handleKeyDown = (e) => {
2040
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
2041
+ if (e.altKey) return;
2042
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
2043
+ return;
2044
+ }
2045
+ if (isFocusOutsideRoot(rootRef)) return;
2046
+ const prev = dragStateRef.current;
2047
+ if (!prev.start || !prev.end) return;
2048
+ if (prev.isSelecting || prev.isFillDragging) return;
2049
+ const rowCount = rows.length;
2050
+ const resolvedColumnCount = getColumnCount();
2051
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
2052
+ const withModifier = e.ctrlKey || e.metaKey;
2053
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
2054
+ e.preventDefault();
2055
+ claimCellSelectionOwner(ownerRef.current);
2056
+ const nextState = {
2057
+ isSelecting: false,
2058
+ isFillDragging: false,
2059
+ start: { row: 0, col: 0 },
2060
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
2061
+ fillAnchor: null,
2062
+ fillEnd: null
2063
+ };
2064
+ dragStateRef.current = nextState;
2065
+ setDragState(nextState);
2066
+ return;
2067
+ }
2068
+ if (e.key === "Home" || e.key === "End") {
2069
+ e.preventDefault();
2070
+ const toEnd = e.key === "End";
2071
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
2072
+ if (e.shiftKey) {
2073
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
2074
+ dragStateRef.current = nextState;
2075
+ setDragState(nextState);
2076
+ onCellNavigateRef.current?.(target);
2077
+ } else {
2078
+ selectCell(target.row, target.col);
2079
+ }
2080
+ return;
2081
+ }
2082
+ if (withModifier || isInteractiveFocus()) return;
2083
+ if (e.key === "Enter" || e.key === "F2") {
2084
+ if (!onEditKeyRef.current) return;
2085
+ e.preventDefault();
2086
+ onEditKeyRef.current(prev.end);
2087
+ return;
2088
+ }
2089
+ if (e.key === "Delete" || e.key === "Backspace") {
1502
2090
  const bounds = getCellSelectionBounds(prev.start, prev.end);
1503
- if (!bounds) return prev;
1504
- return {
1505
- ...prev,
1506
- isSelecting: false,
1507
- isFillDragging: true,
1508
- fillAnchor: { row: bounds.startRow, col: bounds.startCol },
1509
- fillEnd: { row: rowIndex, col: colIndex }
1510
- };
1511
- });
1512
- },
1513
- [enabled]
1514
- );
1515
- const clearSelection = (0, import_react3.useCallback)(() => {
1516
- const prev = dragStateRef.current;
1517
- if (prev.start === null && prev.end === null && !prev.isSelecting && !prev.isFillDragging) {
1518
- return;
1519
- }
1520
- releaseCellSelectionOwner(ownerRef.current);
1521
- dragStateRef.current = INITIAL_DRAG_STATE;
1522
- setDragState(INITIAL_DRAG_STATE);
1523
- }, []);
1524
- (0, import_react3.useEffect)(() => {
1525
- if (!enabled) {
1526
- clearSelection();
1527
- }
1528
- }, [clearSelection, enabled]);
1529
- (0, import_react3.useEffect)(() => {
1530
- return registerCellSelectionOwner(ownerRef.current, clearSelection);
1531
- }, [clearSelection]);
2091
+ if (!bounds || !onClearKeyRef.current) return;
2092
+ e.preventDefault();
2093
+ onClearKeyRef.current(bounds);
2094
+ }
2095
+ };
2096
+ window.addEventListener("keydown", handleKeyDown);
2097
+ return () => window.removeEventListener("keydown", handleKeyDown);
2098
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
1532
2099
  (0, import_react3.useEffect)(() => {
1533
2100
  if (!enabled) return;
1534
2101
  const handleKeyDown = (e) => {
@@ -1538,6 +2105,7 @@ function useCellSelection({
1538
2105
  return;
1539
2106
  }
1540
2107
  if (isFocusOutsideRoot(rootRef)) return;
2108
+ if (!enableWasdNavigation && e.key.length === 1) return;
1541
2109
  const delta = getCellNavigationDelta(e.key);
1542
2110
  if (!delta) return;
1543
2111
  const prev = dragStateRef.current;
@@ -1577,14 +2145,15 @@ function useCellSelection({
1577
2145
  };
1578
2146
  window.addEventListener("keydown", handleKeyDown);
1579
2147
  return () => window.removeEventListener("keydown", handleKeyDown);
1580
- }, [columnCount, enabled, rows]);
2148
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
1581
2149
  const copySelection = (0, import_react3.useCallback)(
1582
2150
  async (options) => {
1583
2151
  if (!enabled || !activeSelectionBounds) return false;
1584
2152
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
1585
2153
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
1586
2154
  registry: cellRendererRegistry,
1587
- root: rootRef?.current
2155
+ root: rootRef?.current,
2156
+ escapeFormulas: escapeCopyFormulas
1588
2157
  });
1589
2158
  },
1590
2159
  [
@@ -1592,6 +2161,7 @@ function useCellSelection({
1592
2161
  cellRendererRegistry,
1593
2162
  enableSubtreeCopy,
1594
2163
  enabled,
2164
+ escapeCopyFormulas,
1595
2165
  rootRef,
1596
2166
  rows
1597
2167
  ]
@@ -1609,6 +2179,7 @@ function useCellSelection({
1609
2179
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
1610
2180
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
1611
2181
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
2182
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
1612
2183
  e.preventDefault();
1613
2184
  void copySelection({ includeDescendants: isSubtreeShortcut });
1614
2185
  };
@@ -1624,9 +2195,17 @@ function useCellSelection({
1624
2195
  activeSelectionBounds.startCol,
1625
2196
  text,
1626
2197
  mode,
1627
- activeSelectionBounds.endRow
2198
+ activeSelectionBounds.endRow,
2199
+ // Leading blank cells are tree depth only in this table's own subtree
2200
+ // copy; from a spreadsheet they are real (empty) cells.
2201
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
1628
2202
  );
1629
2203
  if (!payload) return false;
2204
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
2205
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
2206
+ const cell = cells.find((item) => item.column.id === columnId);
2207
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
2208
+ });
1630
2209
  onRowsPaste(payload);
1631
2210
  return true;
1632
2211
  },
@@ -1657,7 +2236,10 @@ function useCellSelection({
1657
2236
  void (async () => {
1658
2237
  try {
1659
2238
  const text = await navigator.clipboard.readText();
1660
- if (pasteHandledRef.current) return;
2239
+ if (pasteHandledRef.current) {
2240
+ pasteHandledRef.current = false;
2241
+ return;
2242
+ }
1661
2243
  if (pendingPasteModeRef.current !== mode) return;
1662
2244
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
1663
2245
  if (!text) return;
@@ -1682,6 +2264,7 @@ function useCellSelection({
1682
2264
  }
1683
2265
  const mode = pendingPasteModeRef.current ?? "overwrite";
1684
2266
  if (pasteHandledRef.current) {
2267
+ pasteHandledRef.current = false;
1685
2268
  e.preventDefault();
1686
2269
  return;
1687
2270
  }
@@ -1708,39 +2291,41 @@ function useCellSelection({
1708
2291
  (0, import_react3.useEffect)(() => {
1709
2292
  if (!enabled) return;
1710
2293
  const handleMouseUp = () => {
1711
- setDragState((prev) => {
1712
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
1713
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
1714
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
1715
- if (newBounds) {
1716
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
1717
- if (onBatchChange) {
1718
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
1719
- if (changes.length > 0) {
1720
- onBatchChange(changes);
1721
- }
1722
- } else if (onDataChange) {
1723
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
2294
+ const prev = dragStateRef.current;
2295
+ let next = prev;
2296
+ if (prev.isFillDragging && prev.fillEnd) {
2297
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
2298
+ if (sourceBounds) {
2299
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
2300
+ if (hasFillExtension(sourceBounds, newBounds)) {
2301
+ if (onBatchChange) {
2302
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
2303
+ if (changes.length > 0) {
2304
+ onBatchChange(changes);
1724
2305
  }
2306
+ } else if (onDataChange) {
2307
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
1725
2308
  }
1726
- return {
1727
- isSelecting: false,
1728
- isFillDragging: false,
1729
- start: { row: newBounds.startRow, col: newBounds.startCol },
1730
- end: { row: newBounds.endRow, col: newBounds.endCol },
1731
- fillAnchor: null,
1732
- fillEnd: null
1733
- };
1734
2309
  }
2310
+ next = {
2311
+ isSelecting: false,
2312
+ isFillDragging: false,
2313
+ start: { row: newBounds.startRow, col: newBounds.startCol },
2314
+ end: { row: newBounds.endRow, col: newBounds.endCol },
2315
+ fillAnchor: null,
2316
+ fillEnd: null
2317
+ };
2318
+ } else {
2319
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1735
2320
  }
1736
- if (prev.isSelecting) {
1737
- return { ...prev, isSelecting: false };
1738
- }
1739
- if (prev.isFillDragging) {
1740
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
1741
- }
1742
- return prev;
1743
- });
2321
+ } else if (prev.isSelecting) {
2322
+ next = { ...prev, isSelecting: false };
2323
+ } else if (prev.isFillDragging) {
2324
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
2325
+ }
2326
+ if (next === prev) return;
2327
+ dragStateRef.current = next;
2328
+ setDragState(next);
1744
2329
  };
1745
2330
  window.addEventListener("mouseup", handleMouseUp);
1746
2331
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -1752,9 +2337,36 @@ function useCellSelection({
1752
2337
  handleCellMouseEnter,
1753
2338
  handleFillHandleMouseDown,
1754
2339
  clearSelection,
1755
- copySelection
2340
+ copySelection,
2341
+ selectCell,
2342
+ focusSelection
2343
+ };
2344
+ }
2345
+
2346
+ // src/components/ui/table/features/row-hover/rowHover.ts
2347
+ function createRowHoverStore() {
2348
+ let hoveredRowIndex = null;
2349
+ const listeners = /* @__PURE__ */ new Set();
2350
+ return {
2351
+ getHoveredRowIndex: () => hoveredRowIndex,
2352
+ setHoveredRowIndex: (nextRowIndex) => {
2353
+ if (nextRowIndex === hoveredRowIndex) return;
2354
+ hoveredRowIndex = nextRowIndex;
2355
+ listeners.forEach((listener) => listener());
2356
+ },
2357
+ subscribe: (listener) => {
2358
+ listeners.add(listener);
2359
+ return () => listeners.delete(listener);
2360
+ }
1756
2361
  };
1757
2362
  }
2363
+ function isRowHovered(hoveredRowIndex, rowIndex) {
2364
+ return hoveredRowIndex === rowIndex;
2365
+ }
2366
+ function isRowGroupHovered(hoveredRowIndex, enableRowSpan, groupStart, groupSpan) {
2367
+ if (!enableRowSpan || hoveredRowIndex === null) return false;
2368
+ return hoveredRowIndex >= groupStart && hoveredRowIndex <= groupStart + groupSpan - 1;
2369
+ }
1758
2370
 
1759
2371
  // src/components/ui/table/features/selection-dismiss/isOutsideDismissTarget.ts
1760
2372
  var OVERLAY_DISMISS_IGNORE_SELECTOR = [
@@ -1984,238 +2596,101 @@ function buildColumnFreezeOffsets(columns) {
1984
2596
  rightIds.push(column.id);
1985
2597
  result.set(column.id, {
1986
2598
  side: "right",
1987
- offset: rightOffset,
1988
- isEdge: false,
1989
- edgeLeft: false,
1990
- edgeRight: false,
1991
- stack: 0
1992
- });
1993
- rightOffset += column.size;
1994
- }
1995
- rightIds.forEach((id, index) => {
1996
- const entry = result.get(id);
1997
- if (!entry) return;
1998
- entry.stack = rightIds.length - index;
1999
- });
2000
- columns.forEach((column, index) => {
2001
- if (!column.side) return;
2002
- const entry = result.get(column.id);
2003
- if (!entry) return;
2004
- const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
2005
- const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
2006
- entry.edgeLeft = prevSide !== column.side;
2007
- entry.edgeRight = nextSide !== column.side;
2008
- if (index === 0) entry.edgeLeft = false;
2009
- if (index === columns.length - 1) entry.edgeRight = false;
2010
- entry.isEdge = entry.edgeLeft || entry.edgeRight;
2011
- });
2012
- return result;
2013
- }
2014
- function getColumnFreezeStyle(offset, options) {
2015
- if (!offset) return void 0;
2016
- const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
2017
- return {
2018
- position: "sticky",
2019
- ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
2020
- zIndex: zBase + offset.stack
2021
- };
2022
- }
2023
- function resolveHeaderFreezeOffset(column, freezeOffsets) {
2024
- const direct = freezeOffsets.get(column.id);
2025
- if (direct) return direct;
2026
- const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
2027
- if (leaves.length === 0) return void 0;
2028
- const leafOffsets = [];
2029
- for (const leaf of leaves) {
2030
- const offset2 = freezeOffsets.get(leaf.id);
2031
- if (!offset2) return void 0;
2032
- leafOffsets.push(offset2);
2033
- }
2034
- const side = leafOffsets[0]?.side;
2035
- if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
2036
- return void 0;
2037
- }
2038
- const offset = Math.min(...leafOffsets.map((item) => item.offset));
2039
- const leftmost = leafOffsets[0];
2040
- const rightmost = leafOffsets[leafOffsets.length - 1];
2041
- return {
2042
- side,
2043
- offset,
2044
- edgeLeft: leftmost.edgeLeft,
2045
- edgeRight: rightmost.edgeRight,
2046
- isEdge: leftmost.edgeLeft || rightmost.edgeRight,
2047
- stack: Math.max(...leafOffsets.map((item) => item.stack))
2048
- };
2049
- }
2050
- function flattenHeaderLeaves(column) {
2051
- if (!column.columns || column.columns.length === 0) return [column];
2052
- return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2053
- }
2054
-
2055
- // src/components/ui/table/features/inline-search/inlineSearch.ts
2056
- var INLINE_SEARCH_MAX_RESULTS = 1e3;
2057
- var INLINE_SEARCH_TARGET_TICK_MS = 10;
2058
- var INLINE_SEARCH_INITIAL_STRIDE = 10;
2059
- function escapeSearchRegex(value) {
2060
- return value.replace(/([$()*+.?[\\\]^{|}-])/g, "\\$1");
2061
- }
2062
- function createSearchRegex(query) {
2063
- const trimmed = query.trim();
2064
- if (!trimmed) return null;
2065
- return new RegExp(escapeSearchRegex(trimmed), "i");
2066
- }
2067
- function cellValueToSearchText(value) {
2068
- if (value == null) return void 0;
2069
- if (typeof value === "string") return value;
2070
- if (typeof value === "number" || typeof value === "boolean") {
2071
- return String(value);
2072
- }
2073
- if (Array.isArray(value)) {
2074
- return value.map((item) => cellValueToSearchText(item) ?? "").join(" ");
2075
- }
2076
- if (typeof value === "object") {
2077
- try {
2078
- return JSON.stringify(value);
2079
- } catch {
2080
- return String(value);
2081
- }
2082
- }
2083
- return String(value);
2084
- }
2085
- function formatSearchResultLabel(status) {
2086
- const countLabel = status.results >= INLINE_SEARCH_MAX_RESULTS ? `over ${INLINE_SEARCH_MAX_RESULTS}` : `${status.results} result${status.results !== 1 ? "s" : ""}`;
2087
- if (status.selectedIndex >= 0 && status.results > 0) {
2088
- return `${status.selectedIndex + 1} of ${countLabel}`;
2089
- }
2090
- return countLabel;
2091
- }
2092
- function nextSearchIndex(selectedIndex, results) {
2093
- if (results <= 0) return -1;
2094
- if (selectedIndex < 0) return 0;
2095
- return (selectedIndex + 1) % results;
2096
- }
2097
- function previousSearchIndex(selectedIndex, results) {
2098
- if (results <= 0) return -1;
2099
- if (selectedIndex < 0) return results - 1;
2100
- let next = (selectedIndex - 1) % results;
2101
- if (next < 0) next += results;
2102
- return next;
2103
- }
2104
- function buildSearchMatchKey(colIndex, rowIndex) {
2105
- return `${colIndex}:${rowIndex}`;
2106
- }
2107
- function buildSearchMatchKeys(results) {
2108
- const keys = /* @__PURE__ */ new Set();
2109
- for (const [colIndex, rowIndex] of results) {
2110
- keys.add(buildSearchMatchKey(colIndex, rowIndex));
2111
- }
2112
- return keys;
2113
- }
2114
- function collectSearchMatchesInRange(options) {
2115
- const {
2116
- query,
2117
- startRow,
2118
- rowCount,
2119
- columnCount,
2120
- getCellValue,
2121
- maxResults = INLINE_SEARCH_MAX_RESULTS
2122
- } = options;
2123
- const regex = createSearchRegex(query);
2124
- if (!regex || rowCount <= 0 || columnCount <= 0) return [];
2125
- const matches = [];
2126
- for (let rowOffset = 0; rowOffset < rowCount; rowOffset += 1) {
2127
- const rowIndex = startRow + rowOffset;
2128
- for (let colIndex = 0; colIndex < columnCount; colIndex += 1) {
2129
- const text = cellValueToSearchText(getCellValue(rowIndex, colIndex));
2130
- if (text !== void 0 && regex.test(text)) {
2131
- matches.push([colIndex, rowIndex]);
2132
- if (matches.length >= maxResults) {
2133
- return matches;
2134
- }
2135
- }
2136
- }
2137
- }
2138
- return matches;
2139
- }
2140
- function nextSearchStride(currentStride, elapsedMs, targetMs = INLINE_SEARCH_TARGET_TICK_MS) {
2141
- const rounded = Math.max(elapsedMs, 1);
2142
- const scalar = targetMs / rounded;
2143
- return Math.max(1, Math.ceil(currentStride * scalar));
2144
- }
2145
- function buildFlatSearchCorpus(rows, getRowId) {
2146
- return rows.map((data, index) => ({
2147
- id: getRowId(data, index),
2148
- data,
2149
- ancestorToggleKeys: []
2150
- }));
2151
- }
2152
- function buildTreeSearchCorpus(visibleRows, options) {
2153
- const { toggleField, getRowId } = options;
2154
- const corpus = [];
2155
- const seen = /* @__PURE__ */ new Set();
2156
- const walk = (node, ancestorToggleKeys) => {
2157
- const id = getRowId(node, corpus.length);
2158
- if (seen.has(id)) return;
2159
- seen.add(id);
2160
- corpus.push({
2161
- id,
2162
- data: node,
2163
- ancestorToggleKeys
2164
- });
2165
- const children = node.children;
2166
- if (!Array.isArray(children) || children.length === 0) return;
2167
- const toggleValue = node[toggleField];
2168
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
2169
- for (const child of children) {
2170
- if (child && typeof child === "object") {
2171
- walk(child, childAncestors);
2172
- }
2173
- }
2174
- };
2175
- for (const row of visibleRows) {
2176
- const level = row.level;
2177
- if (level === 0 || level === void 0) {
2178
- walk(row, []);
2179
- }
2180
- }
2181
- for (const row of visibleRows) {
2182
- const id = getRowId(row, corpus.length);
2183
- if (seen.has(id)) continue;
2184
- walk(row, []);
2599
+ offset: rightOffset,
2600
+ isEdge: false,
2601
+ edgeLeft: false,
2602
+ edgeRight: false,
2603
+ stack: 0
2604
+ });
2605
+ rightOffset += column.size;
2185
2606
  }
2186
- return corpus;
2607
+ rightIds.forEach((id, index) => {
2608
+ const entry = result.get(id);
2609
+ if (!entry) return;
2610
+ entry.stack = rightIds.length - index;
2611
+ });
2612
+ columns.forEach((column, index) => {
2613
+ if (!column.side) return;
2614
+ const entry = result.get(column.id);
2615
+ if (!entry) return;
2616
+ const prevSide = index > 0 ? columns[index - 1]?.side : void 0;
2617
+ const nextSide = index < columns.length - 1 ? columns[index + 1]?.side : void 0;
2618
+ entry.edgeLeft = prevSide !== column.side;
2619
+ entry.edgeRight = nextSide !== column.side;
2620
+ if (index === 0) entry.edgeLeft = false;
2621
+ if (index === columns.length - 1) entry.edgeRight = false;
2622
+ entry.isEdge = entry.edgeLeft || entry.edgeRight;
2623
+ });
2624
+ return result;
2187
2625
  }
2188
- function mapSearchResultsToVisibleKeys(results, corpus, visibleRowIndexById) {
2189
- const keys = /* @__PURE__ */ new Set();
2190
- for (const [colIndex, corpusRowIndex] of results) {
2191
- const corpusRow = corpus[corpusRowIndex];
2192
- if (!corpusRow) continue;
2193
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2194
- if (visibleRowIndex === void 0) continue;
2195
- keys.add(buildSearchMatchKey(colIndex, visibleRowIndex));
2196
- }
2197
- return keys;
2626
+ function getColumnFreezeStyle(offset, options) {
2627
+ if (!offset) return void 0;
2628
+ const zBase = options?.isHeader ? HEADER_Z_BASE : BODY_Z_BASE;
2629
+ return {
2630
+ position: "sticky",
2631
+ ...offset.side === "left" ? { left: offset.offset } : { right: offset.offset },
2632
+ zIndex: zBase + offset.stack
2633
+ };
2198
2634
  }
2199
- function mapSearchResultToVisibleItem(item, corpus, visibleRowIndexById) {
2200
- const [colIndex, corpusRowIndex] = item;
2201
- const corpusRow = corpus[corpusRowIndex];
2202
- if (!corpusRow) return null;
2203
- const visibleRowIndex = visibleRowIndexById.get(corpusRow.id);
2204
- if (visibleRowIndex === void 0) return null;
2205
- return [colIndex, visibleRowIndex];
2635
+ function resolveHeaderFreezeOffset(column, freezeOffsets) {
2636
+ const direct = freezeOffsets.get(column.id);
2637
+ if (direct) return direct;
2638
+ const leaves = typeof column.getLeafColumns === "function" ? column.getLeafColumns() : column.columns && column.columns.length > 0 ? flattenHeaderLeaves(column) : [];
2639
+ if (leaves.length === 0) return void 0;
2640
+ const leafOffsets = [];
2641
+ for (const leaf of leaves) {
2642
+ const offset2 = freezeOffsets.get(leaf.id);
2643
+ if (!offset2) return void 0;
2644
+ leafOffsets.push(offset2);
2645
+ }
2646
+ const side = leafOffsets[0]?.side;
2647
+ if (!side || leafOffsets.some((offset2) => offset2.side !== side)) {
2648
+ return void 0;
2649
+ }
2650
+ const offset = Math.min(...leafOffsets.map((item) => item.offset));
2651
+ const leftmost = leafOffsets[0];
2652
+ const rightmost = leafOffsets[leafOffsets.length - 1];
2653
+ return {
2654
+ side,
2655
+ offset,
2656
+ edgeLeft: leftmost.edgeLeft,
2657
+ edgeRight: rightmost.edgeRight,
2658
+ isEdge: leftmost.edgeLeft || rightmost.edgeRight,
2659
+ stack: Math.max(...leafOffsets.map((item) => item.stack))
2660
+ };
2206
2661
  }
2207
- function collectAncestorKeysToExpand(corpusRow, expandedRows) {
2208
- return corpusRow.ancestorToggleKeys.filter((key) => !expandedRows.has(key));
2662
+ function flattenHeaderLeaves(column) {
2663
+ if (!column.columns || column.columns.length === 0) return [column];
2664
+ return column.columns.flatMap((child) => flattenHeaderLeaves(child));
2209
2665
  }
2210
2666
 
2211
2667
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
2212
2668
  var import_react4 = require("react");
2213
2669
  var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
2670
+ var searchInstanceCount = 0;
2671
+ var lastPointerTarget = null;
2672
+ function trackPointerTarget(event) {
2673
+ lastPointerTarget = event.target;
2674
+ }
2675
+ function registerSearchInstance() {
2676
+ if (searchInstanceCount === 0) {
2677
+ document.addEventListener("pointerdown", trackPointerTarget, true);
2678
+ }
2679
+ searchInstanceCount += 1;
2680
+ return () => {
2681
+ searchInstanceCount -= 1;
2682
+ if (searchInstanceCount === 0) {
2683
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
2684
+ lastPointerTarget = null;
2685
+ }
2686
+ };
2687
+ }
2214
2688
  function useInlineSearch({
2215
2689
  enabled = false,
2216
2690
  rowCount,
2217
2691
  columnCount,
2218
2692
  getCellValue,
2693
+ contentKey,
2219
2694
  initialStartRow = 0,
2220
2695
  showSearch: controlledShowSearch,
2221
2696
  searchValue: controlledSearchValue,
@@ -2424,6 +2899,7 @@ function useInlineSearch({
2424
2899
  }
2425
2900
  beginSearch(searchValue);
2426
2901
  }, [
2902
+ contentKey,
2427
2903
  beginSearch,
2428
2904
  cancelSearch,
2429
2905
  controlledSearchResults,
@@ -2444,6 +2920,9 @@ function useInlineSearch({
2444
2920
  if (!focusInside && active !== document.body) {
2445
2921
  return;
2446
2922
  }
2923
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
2924
+ return;
2925
+ }
2447
2926
  }
2448
2927
  event.preventDefault();
2449
2928
  event.stopPropagation();
@@ -2457,7 +2936,11 @@ function useInlineSearch({
2457
2936
  }
2458
2937
  };
2459
2938
  window.addEventListener("keydown", handleKeyDown, true);
2460
- return () => window.removeEventListener("keydown", handleKeyDown, true);
2939
+ const releaseInstance = registerSearchInstance();
2940
+ return () => {
2941
+ window.removeEventListener("keydown", handleKeyDown, true);
2942
+ releaseInstance();
2943
+ };
2461
2944
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
2462
2945
  (0, import_react4.useEffect)(() => () => cancelSearch(), [cancelSearch]);
2463
2946
  const searchMatchKeys = (0, import_react4.useMemo)(
@@ -2513,8 +2996,12 @@ function getFieldValue(row, key) {
2513
2996
  }
2514
2997
  function canExpandRow(row) {
2515
2998
  const children = row.children;
2516
- const level = row.level;
2517
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
2999
+ return Array.isArray(children) && children.length > 0;
3000
+ }
3001
+ function toTreeToggleKey(value) {
3002
+ if (value === null || value === void 0) return null;
3003
+ const key = String(value);
3004
+ return key.length > 0 ? key : null;
2518
3005
  }
2519
3006
  function toggleExpandedRowId(rowId, previous) {
2520
3007
  const next = new Set(previous);
@@ -2535,7 +3022,8 @@ var useConvertTreeData = ({
2535
3022
  preventExpand = false,
2536
3023
  startIndex = 1,
2537
3024
  expandedRows,
2538
- onExpandedRowsChange
3025
+ onExpandedRowsChange,
3026
+ autoExpandOnLoad = true
2539
3027
  }) => {
2540
3028
  const onExpandedRowsChangeRef = (0, import_react5.useRef)(onExpandedRowsChange);
2541
3029
  const hasInitializedRef = (0, import_react5.useRef)(false);
@@ -2548,16 +3036,33 @@ var useConvertTreeData = ({
2548
3036
  return;
2549
3037
  }
2550
3038
  if (!enabled || hasInitializedRef.current) return;
2551
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
2552
- onExpandedRowsChangeRef.current?.(new Set(ids));
2553
3039
  hasInitializedRef.current = true;
2554
- }, [enabled, data, toggleField]);
3040
+ if (!autoExpandOnLoad) return;
3041
+ const ids = /* @__PURE__ */ new Set();
3042
+ const collect = (items) => {
3043
+ for (const item of items) {
3044
+ if (!item || typeof item !== "object") continue;
3045
+ const record = item;
3046
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
3047
+ if (key) ids.add(key);
3048
+ const nested = record[flattenField];
3049
+ if (Array.isArray(nested)) collect(nested);
3050
+ }
3051
+ };
3052
+ collect(data);
3053
+ onExpandedRowsChangeRef.current?.(ids);
3054
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
2555
3055
  const processedData = (0, import_react5.useMemo)(() => {
2556
3056
  if (!enabled || !data || data.length === 0) return [];
2557
3057
  const flattenedData = [];
2558
- const flattenItems = (items) => {
2559
- items.forEach((item) => {
2560
- const newItem = { ...item };
3058
+ const flattenItems = (items, parentPath) => {
3059
+ items.forEach((item, itemIndex) => {
3060
+ if (!item || typeof item !== "object") return;
3061
+ const source = {
3062
+ path: [...parentPath, itemIndex],
3063
+ childrenField: flattenField
3064
+ };
3065
+ const newItem = { ...item, [TREE_SOURCE]: source };
2561
3066
  const nested = newItem[flattenField];
2562
3067
  if (Array.isArray(nested)) {
2563
3068
  const children = nested.map(
@@ -2571,89 +3076,68 @@ var useConvertTreeData = ({
2571
3076
  child[childField] = newItem[toggleField];
2572
3077
  }
2573
3078
  });
2574
- flattenItems(children);
3079
+ flattenItems(children, source.path);
2575
3080
  } else {
2576
3081
  flattenedData.push(newItem);
2577
3082
  }
2578
3083
  });
2579
3084
  };
2580
- flattenItems(data);
3085
+ flattenItems(data, []);
2581
3086
  const dataWithLevels = flattenedData.map((item) => ({
2582
3087
  ...item,
2583
3088
  level: 0,
2584
3089
  children: [],
2585
3090
  processed: false
2586
3091
  }));
2587
- const findNearestPrecedingParent = (index, parentKey) => {
2588
- for (let i = index - 1; i >= 0; i -= 1) {
2589
- const candidate = dataWithLevels[i];
2590
- if (!candidate) continue;
2591
- if (getFieldValue(candidate, toggleField) === parentKey) {
2592
- return candidate;
2593
- }
2594
- }
2595
- return void 0;
2596
- };
2597
3092
  const rootItems = [];
3093
+ const latestByKey = /* @__PURE__ */ new Map();
2598
3094
  dataWithLevels.forEach((item) => {
2599
- if (!getFieldValue(item, childField)) {
2600
- rootItems.push(item);
2601
- item.processed = true;
2602
- }
2603
- });
2604
- dataWithLevels.forEach((item, index) => {
2605
3095
  const parentKey = getFieldValue(item, childField);
2606
- if (!parentKey || item.processed) return;
2607
- const parent = findNearestPrecedingParent(index, parentKey);
3096
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
2608
3097
  if (parent) {
2609
3098
  item.level = parent.level + 1;
2610
3099
  parent.children.push(item);
2611
- item.processed = true;
2612
- return;
3100
+ } else {
3101
+ rootItems.push(item);
2613
3102
  }
2614
- rootItems.push(item);
2615
3103
  item.processed = true;
3104
+ latestByKey.set(getFieldValue(item, toggleField), item);
2616
3105
  });
2617
3106
  return rootItems;
2618
3107
  }, [enabled, data, toggleField, childField, flattenField]);
2619
3108
  const flattenTree = (0, import_react5.useMemo)(() => {
2620
3109
  if (!enabled) return [];
2621
- const flatten = (nodes, result = [], level = 0) => {
3110
+ const flatten = (nodes, result, parentTreeNo) => {
2622
3111
  nodes.forEach((node, index) => {
2623
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
3112
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
2624
3113
  const toggleValue = getFieldValue(node, toggleField);
2625
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
3114
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
2626
3115
  result.push({
2627
3116
  ...node,
2628
3117
  treeNo: currentIndex,
2629
3118
  uniqueId,
2630
3119
  processed: true
2631
3120
  });
2632
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
3121
+ const toggleKey = toTreeToggleKey(toggleValue);
3122
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
2633
3123
  if (shouldExpandChildren) {
2634
- flatten(node.children, result, index + startIndex);
3124
+ flatten(node.children, result, currentIndex);
2635
3125
  }
2636
3126
  });
2637
3127
  return result;
2638
3128
  };
2639
- const flattenedData = flatten(processedData, [], 0);
2640
- flattenedData.forEach((item, index) => {
3129
+ const flattenedData = flatten(processedData, [], null);
3130
+ const latestByKey = /* @__PURE__ */ new Map();
3131
+ flattenedData.forEach((item) => {
2641
3132
  const parentKey = getFieldValue(item, childField);
2642
3133
  if (!parentKey) {
2643
3134
  item.parentCount = 1;
2644
- return;
2645
- }
2646
- let parentItem;
2647
- for (let i = index - 1; i >= 0; i -= 1) {
2648
- const candidate = flattenedData[i];
2649
- if (!candidate) continue;
2650
- if (getFieldValue(candidate, toggleField) === parentKey) {
2651
- parentItem = candidate;
2652
- break;
2653
- }
3135
+ } else {
3136
+ const parentItem = latestByKey.get(parentKey);
3137
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
3138
+ item.parentCount = parentAmount || 1;
2654
3139
  }
2655
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
2656
- item.parentCount = parentAmount || 1;
3140
+ latestByKey.set(getFieldValue(item, toggleField), item);
2657
3141
  });
2658
3142
  return flattenedData;
2659
3143
  }, [
@@ -2670,18 +3154,7 @@ var useConvertTreeData = ({
2670
3154
  if (!enabled) {
2671
3155
  return data ?? [];
2672
3156
  }
2673
- return [...flattenTree].sort((a, b) => {
2674
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
2675
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
2676
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
2677
- const aVal = aParts[i] || 0;
2678
- const bVal = bParts[i] || 0;
2679
- if (aVal !== bVal) {
2680
- return aVal - bVal;
2681
- }
2682
- }
2683
- return 0;
2684
- });
3157
+ return flattenTree;
2685
3158
  }, [enabled, data, flattenTree]);
2686
3159
  return sortedData;
2687
3160
  };
@@ -2739,13 +3212,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
2739
3212
  for (let index = 0; index < data.length; index++) {
2740
3213
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
2741
3214
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
2742
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
3215
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
2743
3216
  result.push({ rowSpan: 0, isFirstInGroup: false });
2744
3217
  continue;
2745
3218
  }
2746
3219
  let span = 1;
2747
3220
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
2748
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
3221
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
2749
3222
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
2750
3223
  span++;
2751
3224
  }
@@ -2838,6 +3311,9 @@ function collectRowSpanColumns(columns) {
2838
3311
  }
2839
3312
 
2840
3313
  // src/core/useGlideTable.ts
3314
+ function isProductionBuild() {
3315
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
3316
+ }
2841
3317
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
2842
3318
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
2843
3319
  function useGlideTable(options) {
@@ -2859,18 +3335,24 @@ function useGlideTable(options) {
2859
3335
  selectOnRowClick = true,
2860
3336
  enableCellSelection = true,
2861
3337
  onDataChange,
2862
- onCellChange,
2863
- onBatchChange,
3338
+ onCellChange: onCellChangeProp,
3339
+ onBatchChange: onBatchChangeProp,
2864
3340
  cellRenderers,
2865
3341
  preserveRowSelection = false,
2866
- toggleField,
2867
- childField,
2868
- flattenField,
3342
+ toggleField: toggleFieldProp,
3343
+ idField,
3344
+ childField: childFieldProp,
3345
+ parentIdField,
3346
+ flattenField: flattenFieldProp,
3347
+ childrenField,
2869
3348
  qtyField,
3349
+ expandColumn,
2870
3350
  expandedRows: controlledExpandedRows,
2871
3351
  onExpandedRowsChange,
2872
3352
  preventExpand = false,
3353
+ autoExpandOnLoad = true,
2873
3354
  enableSubtreeCopy,
3355
+ escapeCopyFormulas = false,
2874
3356
  onCopyActionsReady,
2875
3357
  onRowsPaste,
2876
3358
  enableInsertPaste,
@@ -2891,8 +3373,27 @@ function useGlideTable(options) {
2891
3373
  onSearchValueChange,
2892
3374
  onSearchClose,
2893
3375
  searchResults,
2894
- onSearchResultsChanged
3376
+ onSearchResultsChanged,
3377
+ enableWasdNavigation = true
2895
3378
  } = options;
3379
+ const toggleField = toggleFieldProp ?? idField;
3380
+ const childField = childFieldProp ?? parentIdField;
3381
+ const flattenField = flattenFieldProp ?? childrenField;
3382
+ const onCellChange = (0, import_react6.useMemo)(() => {
3383
+ if (onCellChangeProp) return onCellChangeProp;
3384
+ if (!onBatchChangeProp) return void 0;
3385
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
3386
+ }, [onBatchChangeProp, onCellChangeProp]);
3387
+ const onBatchChange = (0, import_react6.useMemo)(() => {
3388
+ if (onBatchChangeProp) return onBatchChangeProp;
3389
+ if (!onCellChangeProp) return void 0;
3390
+ return (changes) => {
3391
+ for (const change of changes) {
3392
+ onCellChangeProp(change.rowId, change.columnId, change.value);
3393
+ }
3394
+ };
3395
+ }, [onBatchChangeProp, onCellChangeProp]);
3396
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
2896
3397
  const labels = (0, import_react6.useMemo)(() => {
2897
3398
  const resolved = resolveDataTableLabels(labelsProp);
2898
3399
  return {
@@ -2910,7 +3411,7 @@ function useGlideTable(options) {
2910
3411
  const [internalExpandedRows, setInternalExpandedRows] = (0, import_react6.useState)(
2911
3412
  () => /* @__PURE__ */ new Set()
2912
3413
  );
2913
- const [hoveredRowIndex, setHoveredRowIndex] = (0, import_react6.useState)(null);
3414
+ const [hoverStore] = (0, import_react6.useState)(createRowHoverStore);
2914
3415
  const scrollRef = (0, import_react6.useRef)(null);
2915
3416
  const rootRef = (0, import_react6.useRef)(null);
2916
3417
  const escapeDismissOwnerRef = (0, import_react6.useRef)(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
@@ -2967,8 +3468,10 @@ function useGlideTable(options) {
2967
3468
  qtyField,
2968
3469
  expandedRows,
2969
3470
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
2970
- preventExpand
3471
+ preventExpand,
3472
+ autoExpandOnLoad
2971
3473
  });
3474
+ const sourceData = (0, import_react6.useMemo)(() => data ?? [], [data]);
2972
3475
  const table = (0, import_react_table.useReactTable)({
2973
3476
  data: tableData,
2974
3477
  columns: tableColumns,
@@ -3007,7 +3510,11 @@ function useGlideTable(options) {
3007
3510
  );
3008
3511
  },
3009
3512
  getCoreRowModel: (0, import_react_table.getCoreRowModel)(),
3010
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
3513
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
3514
+ // Tree rows: their path in the original data, which (unlike the
3515
+ // flattened index) survives expanding/collapsing rows above.
3516
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
3517
+ )
3011
3518
  });
3012
3519
  const rowSpanColumnKeys = (0, import_react6.useMemo)(() => {
3013
3520
  if (!enableRowSpan) return [];
@@ -3024,6 +3531,20 @@ function useGlideTable(options) {
3024
3531
  const rows = table.getRowModel().rows;
3025
3532
  const columnCount = table.getAllLeafColumns().length || 1;
3026
3533
  const visibleLeafColumns = table.getVisibleLeafColumns();
3534
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
3535
+ const warnedBooleanColumnsRef = (0, import_react6.useRef)(/* @__PURE__ */ new Set());
3536
+ (0, import_react6.useEffect)(() => {
3537
+ if (!hasWriteCallback || isProductionBuild()) return;
3538
+ for (const column of visibleLeafColumns) {
3539
+ const meta = column.columnDef.meta;
3540
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
3541
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
3542
+ warnedBooleanColumnsRef.current.add(column.id);
3543
+ console.warn(
3544
+ `[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.`
3545
+ );
3546
+ }
3547
+ }, [hasWriteCallback, visibleLeafColumns]);
3027
3548
  const columnFreezeOffsets = (0, import_react6.useMemo)(() => {
3028
3549
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
3029
3550
  return buildColumnFreezeOffsets(
@@ -3066,7 +3587,7 @@ function useGlideTable(options) {
3066
3587
  const cell = scrollElement.querySelector(
3067
3588
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
3068
3589
  );
3069
- if (cell instanceof HTMLElement) {
3590
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
3070
3591
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
3071
3592
  }
3072
3593
  };
@@ -3084,6 +3605,10 @@ function useGlideTable(options) {
3084
3605
  },
3085
3606
  [scrollCellIntoView]
3086
3607
  );
3608
+ const editKeyRef = (0, import_react6.useRef)(() => {
3609
+ });
3610
+ const clearKeyRef = (0, import_react6.useRef)(() => {
3611
+ });
3087
3612
  const {
3088
3613
  dragState,
3089
3614
  activeSelectionBounds,
@@ -3091,20 +3616,27 @@ function useGlideTable(options) {
3091
3616
  handleCellMouseEnter,
3092
3617
  handleFillHandleMouseDown,
3093
3618
  clearSelection: clearCellSelection,
3094
- copySelection
3619
+ copySelection,
3620
+ selectCell,
3621
+ focusSelection
3095
3622
  } = useCellSelection({
3096
- data: tableData,
3623
+ data: sourceData,
3097
3624
  rows,
3098
3625
  enabled: enableCellSelection,
3099
3626
  columnCount: visibleLeafColumns.length,
3627
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
3100
3628
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
3629
+ escapeCopyFormulas,
3101
3630
  enableInsertPaste: enableInsertPaste ?? true,
3102
3631
  onDataChange,
3103
3632
  onBatchChange,
3104
3633
  onRowsPaste,
3105
3634
  onCellNavigate: handleCellNavigate,
3106
3635
  cellRendererRegistry,
3107
- rootRef
3636
+ rootRef,
3637
+ enableWasdNavigation,
3638
+ onEditKey: (position) => editKeyRef.current(position),
3639
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
3108
3640
  });
3109
3641
  const clearRowSelection = (0, import_react6.useCallback)(() => {
3110
3642
  if (rowSelectionMode === "none") return;
@@ -3125,22 +3657,79 @@ function useGlideTable(options) {
3125
3657
  const {
3126
3658
  editingCell,
3127
3659
  draftValue,
3660
+ draftInvalid,
3661
+ setDraftInvalid,
3128
3662
  setDraftValue,
3129
3663
  startEdit,
3130
3664
  commitEdit,
3131
3665
  cancelEdit
3132
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
3666
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
3667
+ editKeyRef.current = (position) => {
3668
+ startEdit(position.row, position.col);
3669
+ };
3670
+ clearKeyRef.current = (bounds) => {
3671
+ const changes = [];
3672
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
3673
+ const row = rows[rowIndex];
3674
+ if (!row) continue;
3675
+ const cells = row.getVisibleCells();
3676
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
3677
+ const cell = cells[colIndex];
3678
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
3679
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
3680
+ }
3681
+ }
3682
+ if (changes.length === 0) return;
3683
+ if (onBatchChange) {
3684
+ onBatchChange(changes);
3685
+ return;
3686
+ }
3687
+ if (!onDataChange) return;
3688
+ let next = sourceData;
3689
+ for (const change of changes) {
3690
+ const row = rows.find((item) => item.id === change.rowId);
3691
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
3692
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
3693
+ if (!row || !accessorKey) continue;
3694
+ next = applyCellChangesToData(next, [
3695
+ { original: row.original, index: row.index, accessorKey, value: null }
3696
+ ]);
3697
+ }
3698
+ if (next !== sourceData) onDataChange(next);
3699
+ };
3700
+ const commitEditAndMove = (0, import_react6.useCallback)(
3701
+ (raw, delta) => {
3702
+ const current = editingCell;
3703
+ if (!commitEdit(raw)) return false;
3704
+ if (current) {
3705
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
3706
+ }
3707
+ rootRef.current?.focus({ preventScroll: true });
3708
+ return true;
3709
+ },
3710
+ [commitEdit, editingCell, selectCell]
3711
+ );
3712
+ const cancelEditAndRefocus = (0, import_react6.useCallback)(() => {
3713
+ cancelEdit();
3714
+ rootRef.current?.focus({ preventScroll: true });
3715
+ }, [cancelEdit]);
3133
3716
  const commitRenderedCellValue = (0, import_react6.useCallback)(
3134
- (rowId, columnId, value) => commitCellValue({
3135
- data: tableData,
3136
- rows,
3137
- rowId,
3138
- columnId,
3139
- value,
3140
- onCellChange,
3141
- onDataChange
3142
- }),
3143
- [onCellChange, onDataChange, rows, tableData]
3717
+ (rowId, columnId, value) => {
3718
+ const columnDef = table.getColumn(columnId)?.columnDef;
3719
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
3720
+ return false;
3721
+ }
3722
+ return commitCellValue({
3723
+ data: sourceData,
3724
+ rows,
3725
+ rowId,
3726
+ columnId,
3727
+ value,
3728
+ onCellChange,
3729
+ onDataChange
3730
+ });
3731
+ },
3732
+ [onCellChange, onDataChange, rows, sourceData, table]
3144
3733
  );
3145
3734
  const getCellContext = (0, import_react6.useCallback)(
3146
3735
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -3168,25 +3757,12 @@ function useGlideTable(options) {
3168
3757
  (row, index) => {
3169
3758
  if (getRowId) return getRowId(row, index);
3170
3759
  if (enableExpand) {
3171
- const record = row;
3172
- const idValue = record.id;
3173
- if (idValue != null && String(idValue).length > 0) {
3174
- return String(idValue);
3175
- }
3176
- const uniqueId = record.uniqueId;
3177
- if (uniqueId != null && String(uniqueId).length > 0) {
3178
- return String(uniqueId);
3179
- }
3180
- if (toggleField) {
3181
- const toggleValue = record[toggleField];
3182
- if (toggleValue != null && String(toggleValue).length > 0) {
3183
- return String(toggleValue);
3184
- }
3185
- }
3760
+ const treeKey = getTreeRowKey(row);
3761
+ if (treeKey) return treeKey;
3186
3762
  }
3187
3763
  return String(index);
3188
3764
  },
3189
- [enableExpand, getRowId, toggleField]
3765
+ [enableExpand, getRowId]
3190
3766
  );
3191
3767
  const searchCorpus = (0, import_react6.useMemo)(() => {
3192
3768
  if (!enableInlineSearch) return [];
@@ -3213,28 +3789,59 @@ function useGlideTable(options) {
3213
3789
  }
3214
3790
  return map;
3215
3791
  }, [resolveSearchRowId, rows]);
3216
- const getSearchCellValue = (0, import_react6.useCallback)(
3217
- (rowIndex, colIndex) => {
3218
- const corpusRow = searchCorpusRef.current[rowIndex];
3219
- const column = visibleLeafColumns[colIndex];
3220
- if (!corpusRow || !column) return void 0;
3792
+ const readSearchRawValue = (0, import_react6.useCallback)(
3793
+ (corpusRow, rowIndex, column) => {
3221
3794
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
3222
3795
  if (visibleIndex !== void 0) {
3223
3796
  const visibleRow = rows[visibleIndex];
3224
3797
  if (visibleRow) {
3225
- return visibleRow.getValue(column.id);
3798
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
3226
3799
  }
3227
3800
  }
3228
3801
  const columnDef = column.columnDef;
3229
3802
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
3230
- return columnDef.accessorFn(corpusRow.data, rowIndex);
3803
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
3231
3804
  }
3232
3805
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
3233
- return corpusRow.data[String(columnDef.accessorKey)];
3806
+ return {
3807
+ value: corpusRow.data[String(columnDef.accessorKey)],
3808
+ row: void 0
3809
+ };
3810
+ }
3811
+ return { value: corpusRow.data[column.id], row: void 0 };
3812
+ },
3813
+ [rows, visibleRowIndexById]
3814
+ );
3815
+ const getSearchCellValue = (0, import_react6.useCallback)(
3816
+ (rowIndex, colIndex) => {
3817
+ const corpusRow = searchCorpusRef.current[rowIndex];
3818
+ const column = visibleLeafColumns[colIndex];
3819
+ if (!corpusRow || !column) return void 0;
3820
+ if (isProtectedColumn(column.columnDef)) return void 0;
3821
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
3822
+ const meta = column.columnDef.meta;
3823
+ const searchValue2 = meta?.searchValue;
3824
+ if (!searchValue2 || searchValue2 === "value") return value;
3825
+ const ctx = {
3826
+ value,
3827
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
3828
+ index: row?.index ?? rowIndex,
3829
+ columnId: column.id,
3830
+ cellProps: meta?.cellProps,
3831
+ update: () => {
3832
+ }
3833
+ };
3834
+ try {
3835
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
3836
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
3837
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
3838
+ if (renderer) return reactNodeToText(renderer.render(ctx));
3839
+ } catch {
3840
+ return value;
3234
3841
  }
3235
- return corpusRow.data[column.id];
3842
+ return value;
3236
3843
  },
3237
- [rows, visibleLeafColumns, visibleRowIndexById]
3844
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
3238
3845
  );
3239
3846
  const pendingSearchNavRef = (0, import_react6.useRef)(null);
3240
3847
  const focusSearchResult = (0, import_react6.useCallback)(
@@ -3285,11 +3892,19 @@ function useGlideTable(options) {
3285
3892
  focusSearchResult(pending.colIndex, visibleRowIndex);
3286
3893
  }, [focusSearchResult, rows, visibleRowIndexById]);
3287
3894
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
3895
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
3896
+ const searchContentKey = (0, import_react6.useMemo)(
3897
+ () => ({ data: sourceData, columns: searchColumnSignature }),
3898
+ [sourceData, searchColumnSignature]
3899
+ );
3288
3900
  const inlineSearch = useInlineSearch({
3289
3901
  enabled: enableInlineSearch,
3290
3902
  rowCount: searchCorpus.length,
3291
3903
  columnCount: visibleLeafColumns.length,
3292
3904
  getCellValue: getSearchCellValue,
3905
+ // Re-scan when the rows' content/order or the column order changes
3906
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
3907
+ contentKey: searchContentKey,
3293
3908
  initialStartRow: initialSearchStartRow,
3294
3909
  showSearch,
3295
3910
  searchValue,
@@ -3327,11 +3942,14 @@ function useGlideTable(options) {
3327
3942
  visibleRowIndexById
3328
3943
  ]);
3329
3944
  const clearHover = (0, import_react6.useCallback)(() => {
3330
- setHoveredRowIndex(null);
3331
- }, []);
3332
- const handleRowHover = (0, import_react6.useCallback)((rowIndex, _rowData) => {
3333
- setHoveredRowIndex(rowIndex);
3334
- }, []);
3945
+ hoverStore.setHoveredRowIndex(null);
3946
+ }, [hoverStore]);
3947
+ const handleRowHover = (0, import_react6.useCallback)(
3948
+ (rowIndex, _rowData) => {
3949
+ hoverStore.setHoveredRowIndex(rowIndex);
3950
+ },
3951
+ [hoverStore]
3952
+ );
3335
3953
  const handleToggleSelect = (0, import_react6.useCallback)(
3336
3954
  (row) => {
3337
3955
  if (!row.getCanSelect()) return;
@@ -3356,7 +3974,7 @@ function useGlideTable(options) {
3356
3974
  primaryRowSpanKey,
3357
3975
  primaryRowSpanColumnId,
3358
3976
  columnRowSpanMap,
3359
- hoveredRowIndex,
3977
+ hoverStore,
3360
3978
  selectedRowIndices,
3361
3979
  onRowHover: handleRowHover
3362
3980
  },
@@ -3370,6 +3988,7 @@ function useGlideTable(options) {
3370
3988
  enableCellSelection,
3371
3989
  activeSelectionBounds,
3372
3990
  dragState,
3991
+ canFill,
3373
3992
  onCellMouseDown: handleCellMouseDownWithCommit,
3374
3993
  onCellMouseEnter: handleCellMouseEnter,
3375
3994
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -3377,18 +3996,23 @@ function useGlideTable(options) {
3377
3996
  cellEdit: {
3378
3997
  editingCell,
3379
3998
  draftValue,
3999
+ draftInvalid,
4000
+ onDraftInvalidChange: setDraftInvalid,
3380
4001
  onDraftValueChange: setDraftValue,
3381
4002
  onStartEdit: startEdit,
3382
4003
  onCommitEdit: commitEdit,
3383
- onCancelEdit: cancelEdit
4004
+ onCommitEditAndMove: commitEditAndMove,
4005
+ onCancelEdit: cancelEditAndRefocus
3384
4006
  },
3385
4007
  cellRender: {
3386
4008
  registry: cellRendererRegistry,
3387
- commitValue: commitRenderedCellValue
4009
+ commitValue: commitRenderedCellValue,
4010
+ protectedLabel: labels.protectedCell
3388
4011
  },
3389
4012
  expand: {
3390
4013
  enableExpand,
3391
4014
  toggleField,
4015
+ expandColumn,
3392
4016
  expandedRows,
3393
4017
  preventExpand,
3394
4018
  onToggleExpand: handleToggleExpand,
@@ -3413,7 +4037,7 @@ function useGlideTable(options) {
3413
4037
  primaryRowSpanKey,
3414
4038
  primaryRowSpanColumnId,
3415
4039
  columnRowSpanMap,
3416
- hoveredRowIndex,
4040
+ hoverStore,
3417
4041
  selectedRowIndices,
3418
4042
  handleRowHover,
3419
4043
  rowSelectionMode,
@@ -3423,19 +4047,25 @@ function useGlideTable(options) {
3423
4047
  enableCellSelection,
3424
4048
  activeSelectionBounds,
3425
4049
  dragState,
4050
+ canFill,
3426
4051
  handleCellMouseDownWithCommit,
3427
4052
  handleCellMouseEnter,
3428
4053
  handleFillHandleMouseDown,
3429
4054
  editingCell,
3430
4055
  draftValue,
4056
+ draftInvalid,
4057
+ setDraftInvalid,
3431
4058
  setDraftValue,
3432
4059
  startEdit,
3433
4060
  commitEdit,
3434
- cancelEdit,
4061
+ commitEditAndMove,
4062
+ cancelEditAndRefocus,
3435
4063
  cellRendererRegistry,
3436
4064
  commitRenderedCellValue,
4065
+ labels.protectedCell,
3437
4066
  enableExpand,
3438
4067
  toggleField,
4068
+ expandColumn,
3439
4069
  expandedRows,
3440
4070
  preventExpand,
3441
4071
  handleToggleExpand,
@@ -3483,6 +4113,7 @@ function useGlideTable(options) {
3483
4113
  handleToggleSelect,
3484
4114
  clearHover,
3485
4115
  setColumnOrder,
4116
+ handleRootFocus: focusSelection,
3486
4117
  copySelection: stableCopySelection,
3487
4118
  inlineSearch: {
3488
4119
  showSearch: inlineSearch.showSearch,
@@ -3539,12 +4170,16 @@ function ResolvedTableCell({
3539
4170
  },
3540
4171
  [cellRender, columnId, row.id]
3541
4172
  );
4173
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
4174
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
4175
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
4176
+ }
3542
4177
  const ctx = {
3543
4178
  value,
3544
4179
  row,
3545
4180
  index: row.index,
3546
4181
  columnId,
3547
- cellProps: meta?.cellProps,
4182
+ cellProps,
3548
4183
  update
3549
4184
  };
3550
4185
  if (meta?.cellRender) {
@@ -4076,7 +4711,11 @@ function blurActiveElementOutside(container) {
4076
4711
  if (container instanceof Node && container.contains(active)) return;
4077
4712
  active.blur();
4078
4713
  }
4079
- function resolveExpandCellIndex(cells, toggleField) {
4714
+ function resolveExpandCellIndex(cells, toggleField, expandColumn) {
4715
+ if (expandColumn) {
4716
+ const explicitIndex = cells.findIndex((cell) => cell.column.id === expandColumn);
4717
+ if (explicitIndex >= 0) return explicitIndex;
4718
+ }
4080
4719
  if (!toggleField) return 0;
4081
4720
  const matchedIndex = cells.findIndex(
4082
4721
  (cell) => cell.column.id === toggleField
@@ -4119,7 +4758,7 @@ function DataTableRow({
4119
4758
  enableRowSpan,
4120
4759
  primaryRowSpanColumnId,
4121
4760
  columnRowSpanMap,
4122
- hoveredRowIndex,
4761
+ hoverStore,
4123
4762
  selectedRowIndices,
4124
4763
  onRowHover
4125
4764
  } = rowSpan;
@@ -4128,6 +4767,7 @@ function DataTableRow({
4128
4767
  enableCellSelection,
4129
4768
  activeSelectionBounds,
4130
4769
  dragState,
4770
+ canFill = true,
4131
4771
  onCellMouseDown,
4132
4772
  onCellMouseEnter,
4133
4773
  onFillHandleMouseDown
@@ -4135,9 +4775,12 @@ function DataTableRow({
4135
4775
  const {
4136
4776
  editingCell,
4137
4777
  draftValue,
4778
+ draftInvalid = false,
4779
+ onDraftInvalidChange,
4138
4780
  onDraftValueChange,
4139
4781
  onStartEdit,
4140
4782
  onCommitEdit,
4783
+ onCommitEditAndMove,
4141
4784
  onCancelEdit
4142
4785
  } = cellEdit;
4143
4786
  const renderCell = (tableCell) => (0, import_react_table2.flexRender)(
@@ -4147,6 +4790,7 @@ function DataTableRow({
4147
4790
  const {
4148
4791
  enableExpand,
4149
4792
  toggleField,
4793
+ expandColumn,
4150
4794
  expandedRows,
4151
4795
  preventExpand,
4152
4796
  onToggleExpand,
@@ -4155,13 +4799,50 @@ function DataTableRow({
4155
4799
  } = expand;
4156
4800
  const rowIndex = row.index;
4157
4801
  const rowData = row.original;
4158
- const isRowHovered = hoveredRowIndex === rowIndex;
4159
4802
  const isRowSelected = row.getIsSelected();
4160
4803
  const { startRow: primaryGroupStart, rowSpan: primaryGroupSpan } = resolveRowSpanAt(
4161
4804
  primaryRowSpanColumnId ? columnRowSpanMap.get(primaryRowSpanColumnId) : void 0,
4162
4805
  rowIndex
4163
4806
  );
4164
- const isGroupHovered = enableRowSpan && hoveredRowIndex !== null && hoveredRowIndex >= primaryGroupStart && hoveredRowIndex <= primaryGroupStart + primaryGroupSpan - 1;
4807
+ const isRowHovered2 = (0, import_react10.useSyncExternalStore)(
4808
+ hoverStore.subscribe,
4809
+ () => isRowHovered(hoverStore.getHoveredRowIndex(), rowIndex),
4810
+ () => false
4811
+ );
4812
+ const isGroupHovered = (0, import_react10.useSyncExternalStore)(
4813
+ hoverStore.subscribe,
4814
+ () => isRowGroupHovered(
4815
+ hoverStore.getHoveredRowIndex(),
4816
+ enableRowSpan,
4817
+ primaryGroupStart,
4818
+ primaryGroupSpan
4819
+ ),
4820
+ () => false
4821
+ );
4822
+ const rowSpanColumnIds = enableRowSpan ? [...columnRowSpanMap.keys()].filter((id) => id !== primaryRowSpanColumnId) : [];
4823
+ const nestedRowSpanRanges = rowSpanColumnIds.map((columnId) => {
4824
+ const { startRow, rowSpan: span } = resolveRowSpanAt(
4825
+ columnRowSpanMap.get(columnId),
4826
+ rowIndex
4827
+ );
4828
+ return { columnId, startRow, span };
4829
+ });
4830
+ const nestedHoverSignature = (0, import_react10.useSyncExternalStore)(
4831
+ hoverStore.subscribe,
4832
+ () => {
4833
+ const hovered = hoverStore.getHoveredRowIndex();
4834
+ return nestedRowSpanRanges.map(
4835
+ ({ startRow, span }) => isRowGroupHovered(hovered, true, startRow, span) ? "1" : "0"
4836
+ ).join("");
4837
+ },
4838
+ () => rowSpanColumnIds.map(() => "0").join("")
4839
+ );
4840
+ const nestedHoverByColumn = new Map(
4841
+ rowSpanColumnIds.map((columnId, index) => [
4842
+ columnId,
4843
+ nestedHoverSignature[index] === "1"
4844
+ ])
4845
+ );
4165
4846
  const visibleCells = row.getVisibleCells();
4166
4847
  const columnIdsByIndex = visibleCells.map((cell) => cell.column.id);
4167
4848
  row.getIsCellDragSelected = (columnId) => {
@@ -4207,12 +4888,13 @@ function DataTableRow({
4207
4888
  span
4208
4889
  );
4209
4890
  } : void 0;
4210
- const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField) : -1;
4891
+ const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField, expandColumn) : -1;
4211
4892
  const canExpand = enableExpand && !preventExpand && canExpandRow(rowData);
4212
4893
  const expandKey = toggleField && rowData[toggleField] !== null && rowData[toggleField] !== void 0 ? String(rowData[toggleField]) : null;
4213
4894
  const isExpanded = expandKey !== null && Boolean(expandedRows?.has(expandKey));
4214
4895
  const rowLevel = typeof rowData.level === "number" ? rowData.level : 0;
4215
4896
  const editInputRef = (0, import_react10.useRef)(null);
4897
+ const cellPressRef = (0, import_react10.useRef)(false);
4216
4898
  const isRowEditing = editingCell?.rowIndex === rowIndex;
4217
4899
  (0, import_react10.useEffect)(() => {
4218
4900
  if (!isRowEditing) return;
@@ -4225,23 +4907,29 @@ function DataTableRow({
4225
4907
  ref: measureElement,
4226
4908
  "data-index": virtualIndex,
4227
4909
  "data-selected": isRowSelected ? "" : void 0,
4228
- "data-hovered": isRowHovered || isGroupHovered ? "" : void 0,
4910
+ "data-hovered": isRowHovered2 || isGroupHovered ? "" : void 0,
4229
4911
  "data-expandable": enableExpand && canExpand ? "" : void 0,
4230
4912
  "data-expanded": isExpanded ? "" : void 0,
4913
+ "data-level": enableExpand ? rowLevel : void 0,
4231
4914
  className: cn(
4232
4915
  "DataTableRowJSX",
4233
4916
  !enableRowSpan && ROW_HOVER_CLASS,
4234
- enableRowSpan && isRowHovered && !isRowSelected && ROW_HOVERED_BG_CLASS,
4917
+ enableRowSpan && isRowHovered2 && !isRowSelected && ROW_HOVERED_BG_CLASS,
4235
4918
  isRowSelected && "is-selected",
4236
4919
  enableExpand && canExpand && "is-expandable",
4237
4920
  classNames?.row,
4238
4921
  getRowClassName?.(rowData, rowIndex)
4239
4922
  ),
4240
4923
  onMouseEnter: () => onRowHover(rowIndex, rowData),
4924
+ onMouseDownCapture: () => {
4925
+ cellPressRef.current = false;
4926
+ },
4241
4927
  onClick: () => {
4928
+ const startedCellSelection = cellPressRef.current;
4929
+ cellPressRef.current = false;
4242
4930
  if (isRowEditing) return;
4243
4931
  onRowClick?.(rowData, rowIndex);
4244
- if (rowSelectionMode !== "none" && selectOnRowClick) {
4932
+ if (rowSelectionMode !== "none" && selectOnRowClick && !startedCellSelection) {
4245
4933
  onToggleSelect();
4246
4934
  }
4247
4935
  },
@@ -4264,8 +4952,8 @@ function DataTableRow({
4264
4952
  }
4265
4953
  const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === cellIndex;
4266
4954
  const cellRowSpan = rowSpanInfo?.rowSpan ?? 1;
4267
- const isMergedCellHovered = hoveredRowIndex !== null && hoveredRowIndex >= rowIndex && hoveredRowIndex <= rowIndex + cellRowSpan - 1;
4268
- const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered;
4955
+ const isMergedCellHovered = columnId === primaryRowSpanColumnId ? isGroupHovered : nestedHoverByColumn.get(columnId) ?? false;
4956
+ const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered2;
4269
4957
  let isMergedCellSelected = false;
4270
4958
  if (isRowSpanColumn) {
4271
4959
  for (let r = rowIndex; r < rowIndex + cellRowSpan; r += 1) {
@@ -4287,7 +4975,7 @@ function DataTableRow({
4287
4975
  activeSelectionBounds,
4288
4976
  cellRowSpan
4289
4977
  );
4290
- const isBottomRightCell = !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4978
+ const isBottomRightCell = canFill && !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
4291
4979
  const spanRowHeights = enableCellSelection && activeSelectionBounds && isCellDragSelected && cellRowSpan > 1 ? measureMergedSpanRowHeights(rowIndex, cellRowSpan) : void 0;
4292
4980
  const selectionEdgeStyle = getCellSelectionEdgeStyle(
4293
4981
  rowIndex,
@@ -4345,6 +5033,7 @@ function DataTableRow({
4345
5033
  if (isInteractiveMouseTarget(event.target)) return;
4346
5034
  event.preventDefault();
4347
5035
  blurActiveElementOutside(event.currentTarget);
5036
+ cellPressRef.current = true;
4348
5037
  onCellMouseDown(
4349
5038
  resolveCellRowIndex(event.clientY, event.currentTarget),
4350
5039
  cellIndex,
@@ -4398,6 +5087,8 @@ function DataTableRow({
4398
5087
  ref: editInputRef,
4399
5088
  type: editType === "number" ? "number" : "text",
4400
5089
  defaultValue: draftValue,
5090
+ "aria-invalid": draftInvalid ? true : void 0,
5091
+ "data-invalid": draftInvalid ? "" : void 0,
4401
5092
  className: cn(
4402
5093
  "cell-edit-input",
4403
5094
  CELL_ALIGN_CLASS[align],
@@ -4406,6 +5097,7 @@ function DataTableRow({
4406
5097
  ),
4407
5098
  onChange: (event) => {
4408
5099
  editInputProps?.onChange?.(event);
5100
+ onDraftInvalidChange?.(Boolean(event.target.validity?.badInput));
4409
5101
  onDraftValueChange(event.target.value);
4410
5102
  },
4411
5103
  onMouseDown: (event) => {
@@ -4419,9 +5111,22 @@ function DataTableRow({
4419
5111
  onKeyDown: (event) => {
4420
5112
  editInputProps?.onKeyDown?.(event);
4421
5113
  if (event.defaultPrevented) return;
4422
- if (event.key === "Enter") {
5114
+ if (event.nativeEvent.isComposing || event.keyCode === 229) {
5115
+ return;
5116
+ }
5117
+ if (event.key === "Enter" || event.key === "Tab") {
4423
5118
  event.preventDefault();
4424
- onCommitEdit(event.currentTarget.value);
5119
+ if (event.currentTarget.validity?.badInput) {
5120
+ onDraftInvalidChange?.(true);
5121
+ return;
5122
+ }
5123
+ const delta = event.key === "Enter" ? { row: event.shiftKey ? -1 : 1, col: 0 } : { row: 0, col: event.shiftKey ? -1 : 1 };
5124
+ if (onCommitEditAndMove) {
5125
+ onCommitEditAndMove(event.currentTarget.value, delta);
5126
+ } else {
5127
+ onCommitEdit(event.currentTarget.value);
5128
+ }
5129
+ return;
4425
5130
  }
4426
5131
  if (event.key === "Escape") {
4427
5132
  event.preventDefault();
@@ -4431,6 +5136,10 @@ function DataTableRow({
4431
5136
  onBlur: (event) => {
4432
5137
  editInputProps?.onBlur?.(event);
4433
5138
  if (event.defaultPrevented) return;
5139
+ if (event.currentTarget.validity?.badInput) {
5140
+ onDraftInvalidChange?.(true);
5141
+ return;
5142
+ }
4434
5143
  onCommitEdit(event.currentTarget.value);
4435
5144
  }
4436
5145
  }
@@ -4442,6 +5151,7 @@ function DataTableRow({
4442
5151
  "expand-cell-content",
4443
5152
  classNames?.expandCellContent
4444
5153
  ),
5154
+ style: { "--table-row-level": rowLevel },
4445
5155
  children: [
4446
5156
  rowLevel > 0 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
4447
5157
  "span",
@@ -4471,6 +5181,7 @@ function DataTableRow({
4471
5181
  {
4472
5182
  type: "button",
4473
5183
  "aria-label": isExpanded ? collapseRowLabel : expandRowLabel,
5184
+ "aria-expanded": isExpanded,
4474
5185
  className: cn(
4475
5186
  "expand-toggle-button",
4476
5187
  classNames?.expandToggle
@@ -4557,6 +5268,7 @@ function DataTableSearch({
4557
5268
  previousLabel,
4558
5269
  nextLabel,
4559
5270
  closeLabel,
5271
+ formatResult = formatSearchResultLabel,
4560
5272
  rowsTotal,
4561
5273
  classNames,
4562
5274
  onSearchValueChange,
@@ -4565,9 +5277,10 @@ function DataTableSearch({
4565
5277
  onPrevious
4566
5278
  }) {
4567
5279
  if (!showSearch) return null;
4568
- const resultString = searchStatus ? formatSearchResultLabel(searchStatus) : resultHint;
5280
+ const resultString = searchStatus ? formatResult(searchStatus) : resultHint;
4569
5281
  const progress = rowsTotal > 0 ? Math.floor((searchStatus?.rowsSearched ?? 0) / rowsTotal * 100) : 0;
4570
5282
  const handleKeyDown = (event) => {
5283
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
4571
5284
  if ((event.ctrlKey || event.metaKey) && event.code === "KeyF" || event.key === "Escape") {
4572
5285
  event.preventDefault();
4573
5286
  event.stopPropagation();
@@ -4691,6 +5404,7 @@ function DataTableToolbar({
4691
5404
  summary,
4692
5405
  selectedCount,
4693
5406
  selectionLabel,
5407
+ countLabel,
4694
5408
  toolbar,
4695
5409
  className,
4696
5410
  classNames
@@ -4704,7 +5418,7 @@ function DataTableToolbar({
4704
5418
  if (!hasLeftContent && !hasToolbar && !hasSelectionContent) return null;
4705
5419
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: cn("DataTableToolbarJSX", classNames?.toolbar, className), children: [
4706
5420
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: cn("toolbar-left", classNames?.toolbarLeft), children: [
4707
- hasCount && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
5421
+ hasCount && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: countLabel ? countLabel(displayFiltered, totalCount) : displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
4708
5422
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "toolbar-count-primary", children: displayFiltered }),
4709
5423
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("span", { className: "toolbar-count-placeholder", children: [
4710
5424
  " / ",
@@ -4831,7 +5545,8 @@ function DataTable({
4831
5545
  handleToggleSelect,
4832
5546
  clearHover,
4833
5547
  setColumnOrder,
4834
- inlineSearch
5548
+ inlineSearch,
5549
+ handleRootFocus
4835
5550
  } = useGlideTable(glideOptions);
4836
5551
  const ToolbarSlot = slots?.Toolbar ?? DataTableToolbar;
4837
5552
  const ScrollSlot = slots?.Scroll ?? DefaultScroll;
@@ -4875,13 +5590,33 @@ function DataTable({
4875
5590
  }));
4876
5591
  return resolveColumnLayoutWidths(containerWidth, columns);
4877
5592
  }, [enableColumnResize, containerWidth, table, columnLayoutMetaSignature]);
5593
+ const [measuredWidths, setMeasuredWidths] = (0, import_react11.useState)(
5594
+ () => /* @__PURE__ */ new Map()
5595
+ );
5596
+ (0, import_react11.useLayoutEffect)(() => {
5597
+ if (!enableColumnFreeze || enableColumnResize) return;
5598
+ const element = scrollRef.current;
5599
+ if (!element) return;
5600
+ const next = /* @__PURE__ */ new Map();
5601
+ element.querySelectorAll("th[data-leaf-column-id]").forEach((th) => {
5602
+ const id = th.getAttribute("data-leaf-column-id");
5603
+ const width = th.getBoundingClientRect().width;
5604
+ if (id && width > 0) next.set(id, width);
5605
+ });
5606
+ setMeasuredWidths((previous) => {
5607
+ if (previous.size === next.size && [...next].every(([id, width]) => previous.get(id) === width)) {
5608
+ return previous;
5609
+ }
5610
+ return next;
5611
+ });
5612
+ });
4878
5613
  const freezeOffsets = (0, import_react11.useMemo)(() => {
4879
5614
  if (!enableColumnFreeze || enableColumnResize || !layoutWidths) {
4880
5615
  return rowContextValue.columnFreeze.offsets;
4881
5616
  }
4882
5617
  const columns = table.getVisibleLeafColumns().map((column) => ({
4883
5618
  id: column.id,
4884
- size: layoutWidths.get(column.id) ?? column.getSize(),
5619
+ size: measuredWidths.get(column.id) ?? layoutWidths.get(column.id) ?? column.getSize(),
4885
5620
  side: resolveColumnFreezeSide(column.columnDef.meta?.frozen)
4886
5621
  }));
4887
5622
  return buildColumnFreezeOffsets(columns);
@@ -4889,6 +5624,7 @@ function DataTable({
4889
5624
  enableColumnFreeze,
4890
5625
  enableColumnResize,
4891
5626
  layoutWidths,
5627
+ measuredWidths,
4892
5628
  rowContextValue.columnFreeze.offsets,
4893
5629
  table
4894
5630
  ]);
@@ -4921,6 +5657,10 @@ function DataTable({
4921
5657
  "div",
4922
5658
  {
4923
5659
  ref: rootRef,
5660
+ tabIndex: enableCellSelection ? 0 : void 0,
5661
+ onFocus: enableCellSelection ? (event) => {
5662
+ if (event.target === event.currentTarget) handleRootFocus();
5663
+ } : void 0,
4924
5664
  className: cn(
4925
5665
  "DataTableJSX",
4926
5666
  !enableCellSelection && "DataTableJSX--no-cell-selection",
@@ -4941,6 +5681,7 @@ function DataTable({
4941
5681
  summary,
4942
5682
  selectedCount,
4943
5683
  selectionLabel,
5684
+ countLabel: labels.count,
4944
5685
  toolbar,
4945
5686
  classNames
4946
5687
  }
@@ -4959,6 +5700,7 @@ function DataTable({
4959
5700
  previousLabel: labels.searchPrevious,
4960
5701
  nextLabel: labels.searchNext,
4961
5702
  closeLabel: labels.searchClose,
5703
+ formatResult: labels.searchResultCount,
4962
5704
  rowsTotal: inlineSearch.searchRowCount,
4963
5705
  classNames,
4964
5706
  onSearchValueChange: inlineSearch.setSearchValue,
@@ -5008,6 +5750,8 @@ function DataTable({
5008
5750
  (leafColumn) => isColumnReorderable(leafColumn.columnDef.meta)
5009
5751
  );
5010
5752
  const isDragging = draggingColumnId === header.column.id;
5753
+ const sortDirection = isPlaceholder ? void 0 : header.column.columnDef.meta?.sortDirection;
5754
+ const ariaSort = sortDirection === void 0 ? void 0 : sortDirection === "asc" ? "ascending" : sortDirection === "desc" ? "descending" : "none";
5011
5755
  const dropEdge = !isPlaceholder && dropTarget?.columnId === header.column.id ? dropTarget.edge : void 0;
5012
5756
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
5013
5757
  "th",
@@ -5023,7 +5767,8 @@ function DataTable({
5023
5767
  "data-resizing": header.column.getIsResizing() ? "" : void 0,
5024
5768
  "data-frozen": freezeOffset?.side,
5025
5769
  "data-freeze-edge": getColumnFreezeEdgeAttr(freezeOffset),
5026
- "aria-grabbed": isDragging ? true : void 0,
5770
+ "data-leaf-column-id": isLeafHeader ? header.column.id : void 0,
5771
+ "aria-sort": ariaSort,
5027
5772
  title: canDrag ? labels.reorderColumn : void 0,
5028
5773
  onPointerDown: enableColumnReorder ? (event) => onHeaderPointerDown(event, {
5029
5774
  columnId: header.column.id,
@@ -5050,7 +5795,31 @@ function DataTable({
5050
5795
  role: "separator",
5051
5796
  "aria-orientation": "vertical",
5052
5797
  "aria-label": labels.resizeColumn,
5798
+ "aria-valuenow": header.getSize(),
5799
+ tabIndex: 0,
5053
5800
  "data-table-disable-cell-selection": "",
5801
+ onKeyDown: (event) => {
5802
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {
5803
+ return;
5804
+ }
5805
+ event.preventDefault();
5806
+ event.stopPropagation();
5807
+ const step = event.shiftKey ? 50 : 10;
5808
+ const columnDef = header.column.columnDef;
5809
+ const min = columnDef.minSize ?? DATA_TABLE_COLUMN_MIN_SIZE;
5810
+ const max = columnDef.maxSize ?? DATA_TABLE_COLUMN_MAX_SIZE;
5811
+ const nextSize = Math.min(
5812
+ max,
5813
+ Math.max(
5814
+ min,
5815
+ header.getSize() + (event.key === "ArrowRight" ? step : -step)
5816
+ )
5817
+ );
5818
+ table.setColumnSizing((previous) => ({
5819
+ ...previous,
5820
+ [header.column.id]: nextSize
5821
+ }));
5822
+ },
5054
5823
  className: cn(
5055
5824
  "data-table-resize-handle",
5056
5825
  classNames?.resizeHandle
@@ -5158,16 +5927,21 @@ function DataTable({
5158
5927
  }
5159
5928
 
5160
5929
  // src/components/ui/table/components/Table/Table.tsx
5161
- var import_react14 = require("react");
5930
+ var import_react15 = require("react");
5162
5931
 
5163
5932
  // src/components/ui/table/components/Table/buildColumnDef.tsx
5933
+ var import_react12 = require("react");
5164
5934
  var import_jsx_runtime8 = require("react/jsx-runtime");
5935
+ var TableSortContext = (0, import_react12.createContext)(null);
5165
5936
  function SortableHeader({
5166
5937
  label,
5167
5938
  field,
5168
- sort,
5169
- onSort
5939
+ sort: sortProp,
5940
+ onSort: onSortProp
5170
5941
  }) {
5942
+ const context = (0, import_react12.use)(TableSortContext);
5943
+ const sort = context ? context.sort : sortProp;
5944
+ const onSort = context ? context.onSort : onSortProp;
5171
5945
  const isActive = sort?.field === field;
5172
5946
  const Icon = isActive ? sort.direction === "asc" ? ArrowUp : ArrowDown : ArrowUpDown;
5173
5947
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
@@ -5186,7 +5960,7 @@ function SortableHeader({
5186
5960
  }
5187
5961
  );
5188
5962
  }
5189
- function buildColumnDef(props, sort, onSort) {
5963
+ function buildColumnDef(props, sort, onSort, headerCache) {
5190
5964
  const {
5191
5965
  field,
5192
5966
  virtual = false,
@@ -5212,8 +5986,29 @@ function buildColumnDef(props, sort, onSort) {
5212
5986
  className,
5213
5987
  headerClassName,
5214
5988
  render,
5215
- copyValue
5989
+ copyValue,
5990
+ searchValue
5216
5991
  } = props;
5992
+ const createHeader = () => sortable ? () => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5993
+ SortableHeader,
5994
+ {
5995
+ label: children,
5996
+ field,
5997
+ sort,
5998
+ onSort
5999
+ }
6000
+ ) : (
6001
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
6002
+ () => children
6003
+ );
6004
+ const cached = headerCache?.get(field);
6005
+ let header;
6006
+ if (cached && cached.label === children && cached.sortable === sortable) {
6007
+ header = cached.render;
6008
+ } else {
6009
+ header = createHeader();
6010
+ headerCache?.set(field, { label: children, sortable, render: header });
6011
+ }
5217
6012
  return {
5218
6013
  id: field,
5219
6014
  ...!virtual ? { accessorKey: field } : {},
@@ -5221,18 +6016,7 @@ function buildColumnDef(props, sort, onSort) {
5221
6016
  ...minResizeWidth != null ? { minSize: minResizeWidth } : {},
5222
6017
  ...maxResizeWidth != null ? { maxSize: maxResizeWidth } : {},
5223
6018
  ...resizable === false ? { enableResizing: false } : {},
5224
- header: sortable ? () => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5225
- SortableHeader,
5226
- {
5227
- label: children,
5228
- field,
5229
- sort,
5230
- onSort
5231
- }
5232
- ) : (
5233
- // eslint-disable-next-line @typescript-eslint/promise-function-async
5234
- () => children
5235
- ),
6019
+ header,
5236
6020
  // eslint-disable-next-line @typescript-eslint/promise-function-async
5237
6021
  cell: (info) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(ResolvedTableCell, { info }),
5238
6022
  meta: {
@@ -5247,6 +6031,8 @@ function buildColumnDef(props, sort, onSort) {
5247
6031
  cellProps,
5248
6032
  cellRender: render,
5249
6033
  copyValue,
6034
+ searchValue,
6035
+ sortDirection: sortable ? sort?.field === field ? sort.direction : false : void 0,
5250
6036
  frozen,
5251
6037
  reorderable,
5252
6038
  width,
@@ -5264,12 +6050,12 @@ function resolveGroupId(props, index) {
5264
6050
  }
5265
6051
  return `group:${index}`;
5266
6052
  }
5267
- function buildColumnDefsFromTree(nodes, sort, onSort) {
6053
+ function buildColumnDefsFromTree(nodes, sort, onSort, headerCache) {
5268
6054
  return nodes.map((node, index) => {
5269
6055
  if (node.type === "leaf") {
5270
- return buildColumnDef(node.props, sort, onSort);
6056
+ return buildColumnDef(node.props, sort, onSort, headerCache);
5271
6057
  }
5272
- const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort);
6058
+ const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort, headerCache);
5273
6059
  const { header, align, headerClassName } = node.props;
5274
6060
  return {
5275
6061
  id: resolveGroupId(node.props, index),
@@ -5297,10 +6083,10 @@ function countLeafColumns(nodes) {
5297
6083
  }
5298
6084
 
5299
6085
  // src/components/ui/table/components/Table/parseTableChildren.ts
5300
- var import_react13 = require("react");
6086
+ var import_react14 = require("react");
5301
6087
 
5302
6088
  // src/components/ui/table/components/Table/tableChildTypes.ts
5303
- var import_react12 = require("react");
6089
+ var import_react13 = require("react");
5304
6090
  var TABLE_HEADER_DISPLAY_NAME = "Table.Header";
5305
6091
  var TABLE_BODY_DISPLAY_NAME = "Table.Body";
5306
6092
  var TABLE_COLUMN_DISPLAY_NAME = "Table.Column";
@@ -5313,19 +6099,19 @@ function getComponentDisplayName(type) {
5313
6099
  return void 0;
5314
6100
  }
5315
6101
  function isTableHeaderElement(child) {
5316
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_HEADER_DISPLAY_NAME;
6102
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_HEADER_DISPLAY_NAME;
5317
6103
  }
5318
6104
  function isTableBodyElement(child) {
5319
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_BODY_DISPLAY_NAME;
6105
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_BODY_DISPLAY_NAME;
5320
6106
  }
5321
6107
  function isTableColumnElement(child) {
5322
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_DISPLAY_NAME;
6108
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_DISPLAY_NAME;
5323
6109
  }
5324
6110
  function isTableColumnGroupElement(child) {
5325
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_GROUP_DISPLAY_NAME;
6111
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_GROUP_DISPLAY_NAME;
5326
6112
  }
5327
6113
  function isTablePaginationElement(child) {
5328
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_PAGINATION_DISPLAY_NAME;
6114
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_PAGINATION_DISPLAY_NAME;
5329
6115
  }
5330
6116
 
5331
6117
  // src/components/ui/table/components/Table/parseTableChildren.ts
@@ -5335,7 +6121,7 @@ function parseTableChildren(children) {
5335
6121
  body: null,
5336
6122
  pagination: null
5337
6123
  };
5338
- for (const child of import_react13.Children.toArray(children)) {
6124
+ for (const child of import_react14.Children.toArray(children)) {
5339
6125
  if (isTableHeaderElement(child)) {
5340
6126
  slots.header = child;
5341
6127
  continue;
@@ -5352,7 +6138,7 @@ function parseTableChildren(children) {
5352
6138
  }
5353
6139
  function walkColumnTreeNodes(children) {
5354
6140
  const result = [];
5355
- for (const child of import_react13.Children.toArray(children)) {
6141
+ for (const child of import_react14.Children.toArray(children)) {
5356
6142
  if (isTableColumnElement(child)) {
5357
6143
  result.push({
5358
6144
  type: "leaf",
@@ -5369,7 +6155,7 @@ function walkColumnTreeNodes(children) {
5369
6155
  });
5370
6156
  continue;
5371
6157
  }
5372
- if ((0, import_react13.isValidElement)(child)) {
6158
+ if ((0, import_react14.isValidElement)(child)) {
5373
6159
  const nested = child.props.children;
5374
6160
  if (nested != null) {
5375
6161
  result.push(...walkColumnTreeNodes(nested));
@@ -5405,13 +6191,22 @@ function TableColumnGroup(props) {
5405
6191
  TableColumnGroup.displayName = TABLE_COLUMN_GROUP_DISPLAY_NAME;
5406
6192
 
5407
6193
  // src/components/ui/table/components/Table/tableDataPipeline.ts
5408
- function sortTableData(data, sort) {
6194
+ function readField(row, field) {
6195
+ if (field in row || !field.includes(".")) return row[field];
6196
+ return field.split(".").reduce((current, key) => {
6197
+ if (current === null || current === void 0 || typeof current !== "object") {
6198
+ return void 0;
6199
+ }
6200
+ return current[key];
6201
+ }, row);
6202
+ }
6203
+ function sortTableData(data, sort, locale = "ko") {
5409
6204
  if (!sort) return data;
5410
6205
  const { field, direction } = sort;
5411
6206
  const multiplier = direction === "asc" ? 1 : -1;
5412
6207
  return [...data].sort((left, right) => {
5413
- const leftValue = left[field];
5414
- const rightValue = right[field];
6208
+ const leftValue = readField(left, field);
6209
+ const rightValue = readField(right, field);
5415
6210
  if ((leftValue === null || leftValue === void 0) && (rightValue === null || rightValue === void 0)) {
5416
6211
  return 0;
5417
6212
  }
@@ -5420,11 +6215,12 @@ function sortTableData(data, sort) {
5420
6215
  if (typeof leftValue === "number" && typeof rightValue === "number") {
5421
6216
  return (leftValue - rightValue) * multiplier;
5422
6217
  }
5423
- return String(leftValue).localeCompare(String(rightValue), "ko") * multiplier;
6218
+ return String(leftValue).localeCompare(String(rightValue), locale, { numeric: true }) * multiplier;
5424
6219
  });
5425
6220
  }
5426
6221
  function paginateTableData(data, page, pageSize) {
5427
- const safePage = Math.max(1, page);
6222
+ const lastPage = getTotalPages(data.length, pageSize);
6223
+ const safePage = Math.min(Math.max(1, page), lastPage);
5428
6224
  const start = (safePage - 1) * pageSize;
5429
6225
  return data.slice(start, start + pageSize);
5430
6226
  }
@@ -5432,6 +6228,36 @@ function getTotalPages(totalCount, pageSize) {
5432
6228
  if (pageSize <= 0) return 1;
5433
6229
  return Math.max(1, Math.ceil(totalCount / pageSize));
5434
6230
  }
6231
+ function buildTreeRootBlocks(data, fields, sort, locale) {
6232
+ const childrenByRow = /* @__PURE__ */ new Map();
6233
+ const roots = [];
6234
+ const latestById = /* @__PURE__ */ new Map();
6235
+ for (const row of data) {
6236
+ const parentKey = row[fields.parentIdField];
6237
+ const parent = parentKey !== null && parentKey !== void 0 && parentKey !== "" ? latestById.get(parentKey) : void 0;
6238
+ if (parent) {
6239
+ const siblings = childrenByRow.get(parent);
6240
+ if (siblings) siblings.push(row);
6241
+ else childrenByRow.set(parent, [row]);
6242
+ } else {
6243
+ roots.push(row);
6244
+ }
6245
+ latestById.set(row[fields.idField], row);
6246
+ }
6247
+ const appendSubtree = (row, out) => {
6248
+ out.push(row);
6249
+ const children = childrenByRow.get(row);
6250
+ if (!children) return;
6251
+ for (const child of sortTableData(children, sort, locale)) {
6252
+ appendSubtree(child, out);
6253
+ }
6254
+ };
6255
+ return sortTableData(roots, sort, locale).map((root) => {
6256
+ const block = [];
6257
+ appendSubtree(root, block);
6258
+ return block;
6259
+ });
6260
+ }
5435
6261
 
5436
6262
  // src/components/ui/table/components/Table/TableHeader.tsx
5437
6263
  function TableHeader(props) {
@@ -5447,7 +6273,9 @@ function TablePagination({
5447
6273
  pageSize = 10,
5448
6274
  totalCount = 0,
5449
6275
  onChange,
5450
- className
6276
+ className,
6277
+ previousLabel = "Previous page",
6278
+ nextLabel = "Next page"
5451
6279
  }) {
5452
6280
  const totalPages = getTotalPages(totalCount, pageSize);
5453
6281
  const safePage = Math.min(Math.max(1, page), totalPages);
@@ -5461,7 +6289,7 @@ function TablePagination({
5461
6289
  className: "pagination-button",
5462
6290
  disabled: !canGoPrev,
5463
6291
  onClick: () => onChange(safePage - 1),
5464
- "aria-label": "Previous page",
6292
+ "aria-label": previousLabel,
5465
6293
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronLeft, { className: "pagination-button-icon" })
5466
6294
  }
5467
6295
  ),
@@ -5477,7 +6305,7 @@ function TablePagination({
5477
6305
  className: "pagination-button",
5478
6306
  disabled: !canGoNext,
5479
6307
  onClick: () => onChange(safePage + 1),
5480
- "aria-label": "Next page",
6308
+ "aria-label": nextLabel,
5481
6309
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronRight, { className: "pagination-button-icon" })
5482
6310
  }
5483
6311
  )
@@ -5491,63 +6319,124 @@ function TableRoot({
5491
6319
  data,
5492
6320
  children,
5493
6321
  className,
6322
+ classNames,
5494
6323
  totalCount,
5495
6324
  filteredCount,
6325
+ onDataChange,
6326
+ getRowId,
6327
+ sort: controlledSort,
6328
+ defaultSort = null,
6329
+ onSortChange,
6330
+ sortLocale,
5496
6331
  ...dataTableProps
5497
6332
  }) {
5498
- const { header, pagination: paginationElement } = (0, import_react14.useMemo)(
6333
+ const { header, pagination: paginationElement } = (0, import_react15.useMemo)(
5499
6334
  () => parseTableChildren(children),
5500
6335
  [children]
5501
6336
  );
5502
- const [sort, setSort] = (0, import_react14.useState)(null);
5503
- const handleSort = (0, import_react14.useCallback)((field) => {
5504
- setSort((previous) => {
5505
- if (previous?.field !== field) {
5506
- return { field, direction: "asc" };
5507
- }
5508
- if (previous.direction === "asc") {
5509
- return { field, direction: "desc" };
6337
+ const [internalSort, setInternalSort] = (0, import_react15.useState)(defaultSort);
6338
+ const sort = controlledSort !== void 0 ? controlledSort : internalSort;
6339
+ const handleSort = (0, import_react15.useCallback)(
6340
+ (field) => {
6341
+ let next;
6342
+ if (sort?.field !== field) {
6343
+ next = { field, direction: "asc" };
6344
+ } else if (sort.direction === "asc") {
6345
+ next = { field, direction: "desc" };
6346
+ } else {
6347
+ next = null;
5510
6348
  }
5511
- return null;
5512
- });
5513
- }, []);
5514
- const columnTree = (0, import_react14.useMemo)(() => extractColumnTree(header), [header]);
5515
- const columns = (0, import_react14.useMemo)(
5516
- () => buildColumnDefsFromTree(columnTree, sort, handleSort),
6349
+ if (controlledSort === void 0) setInternalSort(next);
6350
+ onSortChange?.(next);
6351
+ },
6352
+ [controlledSort, onSortChange, sort]
6353
+ );
6354
+ const columnTree = (0, import_react15.useMemo)(() => extractColumnTree(header), [header]);
6355
+ const headerCacheRef = (0, import_react15.useRef)(/* @__PURE__ */ new Map());
6356
+ const columns = (0, import_react15.useMemo)(
6357
+ () => buildColumnDefsFromTree(columnTree, sort, handleSort, headerCacheRef.current),
5517
6358
  [columnTree, sort, handleSort]
5518
6359
  );
6360
+ const sortContextValue = (0, import_react15.useMemo)(() => ({ sort, onSort: handleSort }), [sort, handleSort]);
5519
6361
  const paginationProps = paginationElement?.props;
5520
6362
  const pageSize = paginationProps?.pageSize ?? 10;
5521
6363
  const page = paginationProps?.page ?? 1;
5522
6364
  const resolvedTotalCount = paginationProps?.totalCount ?? totalCount ?? data.length;
5523
- const tableData = (0, import_react14.useMemo)(() => {
5524
- const sortedData = sortTableData(data, sort);
5525
- if (!paginationProps) return sortedData;
6365
+ const isManualPagination = Boolean(paginationProps?.manual);
6366
+ const treeIdField = dataTableProps.toggleField ?? dataTableProps.idField;
6367
+ const isTree = Boolean(treeIdField);
6368
+ const treeParentIdField = dataTableProps.childField ?? dataTableProps.parentIdField ?? DEFAULT_TREE_PARENT_ID_FIELD;
6369
+ const treeBlocks = (0, import_react15.useMemo)(() => {
6370
+ if (!isTree || !treeIdField) return null;
6371
+ if (!sort && (!paginationProps || isManualPagination)) return null;
6372
+ return buildTreeRootBlocks(
6373
+ data,
6374
+ { idField: treeIdField, parentIdField: treeParentIdField },
6375
+ sort,
6376
+ sortLocale
6377
+ );
6378
+ }, [data, isManualPagination, isTree, paginationProps, sort, sortLocale, treeIdField, treeParentIdField]);
6379
+ const pageTotalCount = paginationProps?.totalCount ?? totalCount ?? (treeBlocks ? treeBlocks.length : data.length);
6380
+ const tableData = (0, import_react15.useMemo)(() => {
6381
+ if (treeBlocks) {
6382
+ const blocks = !paginationProps || isManualPagination ? treeBlocks : paginateTableData(treeBlocks, page, pageSize);
6383
+ return blocks.flat();
6384
+ }
6385
+ const sortedData = sortTableData(data, sort, sortLocale);
6386
+ if (!paginationProps || isManualPagination) return sortedData;
5526
6387
  return paginateTableData(sortedData, page, pageSize);
5527
- }, [data, sort, paginationProps, page, pageSize]);
6388
+ }, [treeBlocks, data, sort, sortLocale, paginationProps, isManualPagination, page, pageSize]);
6389
+ const originalIndexByRow = (0, import_react15.useMemo)(() => {
6390
+ const map = /* @__PURE__ */ new Map();
6391
+ data.forEach((row, index) => map.set(row, index));
6392
+ return map;
6393
+ }, [data]);
6394
+ const resolvedGetRowId = (0, import_react15.useMemo)(() => {
6395
+ if (getRowId) return getRowId;
6396
+ if (isTree) return void 0;
6397
+ return (row, index) => String(originalIndexByRow.get(row) ?? index);
6398
+ }, [isTree, getRowId, originalIndexByRow]);
6399
+ const handleDataChange = (0, import_react15.useMemo)(() => {
6400
+ if (!onDataChange) return void 0;
6401
+ return (next) => {
6402
+ const merged = data.slice();
6403
+ tableData.forEach((row, index) => {
6404
+ const nextRow = next[index];
6405
+ if (nextRow === void 0 || nextRow === row) return;
6406
+ const originalIndex = originalIndexByRow.get(row);
6407
+ if (originalIndex !== void 0) merged[originalIndex] = nextRow;
6408
+ });
6409
+ onDataChange(merged);
6410
+ };
6411
+ }, [data, onDataChange, originalIndexByRow, tableData]);
5528
6412
  if (countLeafColumns(columnTree) === 0) {
5529
6413
  console.warn("[Table] Declare at least one Table.Column inside Table.Header.");
5530
6414
  }
5531
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "TableJSX", children: [
5532
- /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
6415
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: cn("TableJSX", classNames?.tableRoot), children: [
6416
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(TableSortContext, { value: sortContextValue, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5533
6417
  DataTable,
5534
6418
  {
5535
6419
  ...dataTableProps,
6420
+ classNames,
6421
+ getRowId: resolvedGetRowId,
6422
+ onDataChange: handleDataChange,
5536
6423
  data: tableData,
5537
6424
  columns,
5538
6425
  totalCount: paginationProps ? resolvedTotalCount : totalCount,
5539
6426
  filteredCount: filteredCount ?? data.length,
5540
6427
  className: cn(className, paginationProps && "DataTableJSX--with-pagination")
5541
6428
  }
5542
- ),
6429
+ ) }),
5543
6430
  paginationProps && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5544
6431
  TablePagination,
5545
6432
  {
5546
6433
  page,
5547
6434
  pageSize,
5548
- totalCount: resolvedTotalCount,
6435
+ totalCount: pageTotalCount,
5549
6436
  onChange: paginationProps.onChange,
5550
- className: paginationProps.className
6437
+ className: cn(classNames?.pagination, paginationProps.className),
6438
+ previousLabel: paginationProps.previousLabel ?? dataTableProps.labels?.paginationPrevious,
6439
+ nextLabel: paginationProps.nextLabel ?? dataTableProps.labels?.paginationNext
5551
6440
  }
5552
6441
  )
5553
6442
  ] });
@@ -5621,6 +6510,7 @@ var Table = Object.assign(TableRoot, {
5621
6510
  createSearchRegex,
5622
6511
  createTable,
5623
6512
  escapeSearchRegex,
6513
+ escapeSpreadsheetFormula,
5624
6514
  flattenSubtreeRows,
5625
6515
  formatCellValue,
5626
6516
  formatDefaultCellValue,