react-glide-table 2.3.4 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/compound.cjs CHANGED
@@ -71,6 +71,61 @@ function DataTableContextProvider({
71
71
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DataTableContext, { value, children });
72
72
  }
73
73
 
74
+ // src/components/ui/table/features/data-patch/dataPatch.ts
75
+ var TREE_SOURCE = /* @__PURE__ */ Symbol("react-glide-table.treeSource");
76
+ function getTreeSource(row) {
77
+ if (!row || typeof row !== "object") return void 0;
78
+ return row[TREE_SOURCE];
79
+ }
80
+ function getTreeRowKey(row) {
81
+ const source = getTreeSource(row);
82
+ if (!source) return void 0;
83
+ return `tree:${source.path.join(".")}`;
84
+ }
85
+ function setValueAtAccessor(record, accessorKey, value) {
86
+ if (!accessorKey.includes(".") || accessorKey in record) {
87
+ return { ...record, [accessorKey]: value };
88
+ }
89
+ const [head, ...rest] = accessorKey.split(".");
90
+ const current = record[head];
91
+ const child = current && typeof current === "object" && !Array.isArray(current) ? current : {};
92
+ return {
93
+ ...record,
94
+ [head]: setValueAtAccessor(child, rest.join("."), value)
95
+ };
96
+ }
97
+ function patchAtPath(nodes, path, childrenField, accessorKey, value) {
98
+ const [head, ...rest] = path;
99
+ if (head === void 0 || head < 0 || head >= nodes.length) return null;
100
+ const node = nodes[head];
101
+ if (!node || typeof node !== "object") return null;
102
+ const record = node;
103
+ let nextNode;
104
+ if (rest.length === 0) {
105
+ nextNode = setValueAtAccessor(record, accessorKey, value);
106
+ } else {
107
+ const children = record[childrenField];
108
+ if (!Array.isArray(children)) return null;
109
+ const nextChildren = patchAtPath(children, rest, childrenField, accessorKey, value);
110
+ if (!nextChildren) return null;
111
+ nextNode = { ...record, [childrenField]: nextChildren };
112
+ }
113
+ const next = nodes.slice();
114
+ next[head] = nextNode;
115
+ return next;
116
+ }
117
+ function applyCellChangesToData(data, changes) {
118
+ let next = data;
119
+ for (const change of changes) {
120
+ const source = getTreeSource(change.original);
121
+ const path = source ? source.path : [change.index];
122
+ const childrenField = source?.childrenField ?? "";
123
+ const patched = patchAtPath(next, path, childrenField, change.accessorKey, change.value);
124
+ if (patched) next = patched;
125
+ }
126
+ return next === data ? data.slice() : next;
127
+ }
128
+
74
129
  // src/components/ui/table/features/cell-edit/cellEdit.ts
75
130
  function getColumnAccessorKey(columnDef) {
76
131
  if (columnDef.accessorKey !== void 0 && columnDef.accessorKey !== null) {
@@ -78,7 +133,11 @@ function getColumnAccessorKey(columnDef) {
78
133
  }
79
134
  return columnDef.id;
80
135
  }
136
+ function isProtectedColumn(columnDef) {
137
+ return columnDef.meta?.kind === "protected";
138
+ }
81
139
  function isColumnEditable(columnDef) {
140
+ if (isProtectedColumn(columnDef)) return false;
82
141
  return Boolean(columnDef.meta?.editable);
83
142
  }
84
143
  function getColumnEditType(columnDef) {
@@ -203,9 +262,22 @@ function isCellInSelection(rowIndex, colIndex, bounds, rowSpan = 1) {
203
262
  const cellEndRow = rowIndex + rowSpan - 1;
204
263
  return cellEndRow >= bounds.startRow && rowIndex <= bounds.endRow && colIndex >= bounds.startCol && colIndex <= bounds.endCol;
205
264
  }
265
+ function resolveFillBounds(source, pointer) {
266
+ const below = pointer.row - source.endRow;
267
+ const above = source.startRow - pointer.row;
268
+ const right = pointer.col - source.endCol;
269
+ const left = source.startCol - pointer.col;
270
+ const vertical = Math.max(below, above, 0);
271
+ const horizontal = Math.max(right, left, 0);
272
+ if (vertical === 0 && horizontal === 0) return { ...source };
273
+ if (vertical >= horizontal) {
274
+ return below > 0 ? { ...source, endRow: pointer.row } : { ...source, startRow: pointer.row };
275
+ }
276
+ return right > 0 ? { ...source, endCol: pointer.col } : { ...source, startCol: pointer.col };
277
+ }
206
278
  function getActiveSelectionBounds(dragState, selectionBounds) {
207
- if (dragState.isFillDragging && dragState.fillAnchor && dragState.fillEnd) {
208
- return getCellSelectionBounds(dragState.fillAnchor, dragState.fillEnd);
279
+ if (dragState.isFillDragging && dragState.fillEnd && selectionBounds) {
280
+ return resolveFillBounds(selectionBounds, dragState.fillEnd);
209
281
  }
210
282
  return selectionBounds;
211
283
  }
@@ -781,7 +853,8 @@ function buildTreeSearchCorpus(visibleRows, options) {
781
853
  const children = node.children;
782
854
  if (!Array.isArray(children) || children.length === 0) return;
783
855
  const toggleValue = node[toggleField];
784
- const childAncestors = typeof toggleValue === "string" && toggleValue.length > 0 ? [...ancestorToggleKeys, toggleValue] : ancestorToggleKeys;
856
+ const toggleKey = toggleValue === null || toggleValue === void 0 ? "" : String(toggleValue);
857
+ const childAncestors = toggleKey.length > 0 ? [...ancestorToggleKeys, toggleKey] : ancestorToggleKeys;
785
858
  for (const child of children) {
786
859
  if (child && typeof child === "object") {
787
860
  walk(child, childAncestors);
@@ -839,8 +912,12 @@ function getFieldValue(row, key) {
839
912
  }
840
913
  function canExpandRow(row) {
841
914
  const children = row.children;
842
- const level = row.level;
843
- return Array.isArray(children) && children.length > 0 && (level === 0 || level === void 0);
915
+ return Array.isArray(children) && children.length > 0;
916
+ }
917
+ function toTreeToggleKey(value) {
918
+ if (value === null || value === void 0) return null;
919
+ const key = String(value);
920
+ return key.length > 0 ? key : null;
844
921
  }
845
922
  function toggleExpandedRowId(rowId, previous) {
846
923
  const next = new Set(previous);
@@ -861,7 +938,8 @@ var useConvertTreeData = ({
861
938
  preventExpand = false,
862
939
  startIndex = 1,
863
940
  expandedRows,
864
- onExpandedRowsChange
941
+ onExpandedRowsChange,
942
+ autoExpandOnLoad = true
865
943
  }) => {
866
944
  const onExpandedRowsChangeRef = (0, import_react2.useRef)(onExpandedRowsChange);
867
945
  const hasInitializedRef = (0, import_react2.useRef)(false);
@@ -874,16 +952,33 @@ var useConvertTreeData = ({
874
952
  return;
875
953
  }
876
954
  if (!enabled || hasInitializedRef.current) return;
877
- const ids = data.map((item) => getFieldValue(item, toggleField)).filter((value) => typeof value === "string" && value.length > 0);
878
- onExpandedRowsChangeRef.current?.(new Set(ids));
879
955
  hasInitializedRef.current = true;
880
- }, [enabled, data, toggleField]);
956
+ if (!autoExpandOnLoad) return;
957
+ const ids = /* @__PURE__ */ new Set();
958
+ const collect = (items) => {
959
+ for (const item of items) {
960
+ if (!item || typeof item !== "object") continue;
961
+ const record = item;
962
+ const key = toTreeToggleKey(getFieldValue(record, toggleField));
963
+ if (key) ids.add(key);
964
+ const nested = record[flattenField];
965
+ if (Array.isArray(nested)) collect(nested);
966
+ }
967
+ };
968
+ collect(data);
969
+ onExpandedRowsChangeRef.current?.(ids);
970
+ }, [enabled, data, toggleField, flattenField, autoExpandOnLoad]);
881
971
  const processedData = (0, import_react2.useMemo)(() => {
882
972
  if (!enabled || !data || data.length === 0) return [];
883
973
  const flattenedData = [];
884
- const flattenItems = (items) => {
885
- items.forEach((item) => {
886
- const newItem = { ...item };
974
+ const flattenItems = (items, parentPath) => {
975
+ items.forEach((item, itemIndex) => {
976
+ if (!item || typeof item !== "object") return;
977
+ const source = {
978
+ path: [...parentPath, itemIndex],
979
+ childrenField: flattenField
980
+ };
981
+ const newItem = { ...item, [TREE_SOURCE]: source };
887
982
  const nested = newItem[flattenField];
888
983
  if (Array.isArray(nested)) {
889
984
  const children = nested.map(
@@ -897,89 +992,68 @@ var useConvertTreeData = ({
897
992
  child[childField] = newItem[toggleField];
898
993
  }
899
994
  });
900
- flattenItems(children);
995
+ flattenItems(children, source.path);
901
996
  } else {
902
997
  flattenedData.push(newItem);
903
998
  }
904
999
  });
905
1000
  };
906
- flattenItems(data);
1001
+ flattenItems(data, []);
907
1002
  const dataWithLevels = flattenedData.map((item) => ({
908
1003
  ...item,
909
1004
  level: 0,
910
1005
  children: [],
911
1006
  processed: false
912
1007
  }));
913
- const findNearestPrecedingParent = (index, parentKey) => {
914
- for (let i = index - 1; i >= 0; i -= 1) {
915
- const candidate = dataWithLevels[i];
916
- if (!candidate) continue;
917
- if (getFieldValue(candidate, toggleField) === parentKey) {
918
- return candidate;
919
- }
920
- }
921
- return void 0;
922
- };
923
1008
  const rootItems = [];
1009
+ const latestByKey = /* @__PURE__ */ new Map();
924
1010
  dataWithLevels.forEach((item) => {
925
- if (!getFieldValue(item, childField)) {
926
- rootItems.push(item);
927
- item.processed = true;
928
- }
929
- });
930
- dataWithLevels.forEach((item, index) => {
931
1011
  const parentKey = getFieldValue(item, childField);
932
- if (!parentKey || item.processed) return;
933
- const parent = findNearestPrecedingParent(index, parentKey);
1012
+ const parent = parentKey ? latestByKey.get(parentKey) : void 0;
934
1013
  if (parent) {
935
1014
  item.level = parent.level + 1;
936
1015
  parent.children.push(item);
937
- item.processed = true;
938
- return;
1016
+ } else {
1017
+ rootItems.push(item);
939
1018
  }
940
- rootItems.push(item);
941
1019
  item.processed = true;
1020
+ latestByKey.set(getFieldValue(item, toggleField), item);
942
1021
  });
943
1022
  return rootItems;
944
1023
  }, [enabled, data, toggleField, childField, flattenField]);
945
1024
  const flattenTree = (0, import_react2.useMemo)(() => {
946
1025
  if (!enabled) return [];
947
- const flatten = (nodes, result = [], level = 0) => {
1026
+ const flatten = (nodes, result, parentTreeNo) => {
948
1027
  nodes.forEach((node, index) => {
949
- const currentIndex = level === 0 ? `${index + startIndex}` : `${level}-${index + 1}`;
1028
+ const currentIndex = parentTreeNo === null ? `${index + startIndex}` : `${parentTreeNo}-${index + 1}`;
950
1029
  const toggleValue = getFieldValue(node, toggleField);
951
- const uniqueId = `${index}-${String(toggleValue ?? "")}`;
1030
+ const uniqueId = `${currentIndex}-${String(toggleValue ?? "")}`;
952
1031
  result.push({
953
1032
  ...node,
954
1033
  treeNo: currentIndex,
955
1034
  uniqueId,
956
1035
  processed: true
957
1036
  });
958
- const shouldExpandChildren = node.children.length > 0 && (preventExpand || typeof toggleValue === "string" && expandedRows?.has(toggleValue));
1037
+ const toggleKey = toTreeToggleKey(toggleValue);
1038
+ const shouldExpandChildren = node.children.length > 0 && (preventExpand || toggleKey !== null && Boolean(expandedRows?.has(toggleKey)));
959
1039
  if (shouldExpandChildren) {
960
- flatten(node.children, result, index + startIndex);
1040
+ flatten(node.children, result, currentIndex);
961
1041
  }
962
1042
  });
963
1043
  return result;
964
1044
  };
965
- const flattenedData = flatten(processedData, [], 0);
966
- flattenedData.forEach((item, index) => {
1045
+ const flattenedData = flatten(processedData, [], null);
1046
+ const latestByKey = /* @__PURE__ */ new Map();
1047
+ flattenedData.forEach((item) => {
967
1048
  const parentKey = getFieldValue(item, childField);
968
1049
  if (!parentKey) {
969
1050
  item.parentCount = 1;
970
- return;
971
- }
972
- let parentItem;
973
- for (let i = index - 1; i >= 0; i -= 1) {
974
- const candidate = flattenedData[i];
975
- if (!candidate) continue;
976
- if (getFieldValue(candidate, toggleField) === parentKey) {
977
- parentItem = candidate;
978
- break;
979
- }
1051
+ } else {
1052
+ const parentItem = latestByKey.get(parentKey);
1053
+ const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
1054
+ item.parentCount = parentAmount || 1;
980
1055
  }
981
- const parentAmount = parentItem ? Number(getFieldValue(parentItem, qtyField) ?? 1) : 1;
982
- item.parentCount = parentAmount || 1;
1056
+ latestByKey.set(getFieldValue(item, toggleField), item);
983
1057
  });
984
1058
  return flattenedData;
985
1059
  }, [
@@ -996,22 +1070,36 @@ var useConvertTreeData = ({
996
1070
  if (!enabled) {
997
1071
  return data ?? [];
998
1072
  }
999
- return [...flattenTree].sort((a, b) => {
1000
- const aParts = String(a.treeNo ?? "").split("-").map(Number);
1001
- const bParts = String(b.treeNo ?? "").split("-").map(Number);
1002
- for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
1003
- const aVal = aParts[i] || 0;
1004
- const bVal = bParts[i] || 0;
1005
- if (aVal !== bVal) {
1006
- return aVal - bVal;
1007
- }
1008
- }
1009
- return 0;
1010
- });
1073
+ return flattenTree;
1011
1074
  }, [enabled, data, flattenTree]);
1012
1075
  return sortedData;
1013
1076
  };
1014
1077
 
1078
+ // src/components/ui/table/features/row-hover/rowHover.ts
1079
+ function createRowHoverStore() {
1080
+ let hoveredRowIndex = null;
1081
+ const listeners = /* @__PURE__ */ new Set();
1082
+ return {
1083
+ getHoveredRowIndex: () => hoveredRowIndex,
1084
+ setHoveredRowIndex: (nextRowIndex) => {
1085
+ if (nextRowIndex === hoveredRowIndex) return;
1086
+ hoveredRowIndex = nextRowIndex;
1087
+ listeners.forEach((listener) => listener());
1088
+ },
1089
+ subscribe: (listener) => {
1090
+ listeners.add(listener);
1091
+ return () => listeners.delete(listener);
1092
+ }
1093
+ };
1094
+ }
1095
+ function isRowHovered(hoveredRowIndex, rowIndex) {
1096
+ return hoveredRowIndex === rowIndex;
1097
+ }
1098
+ function isRowGroupHovered(hoveredRowIndex, enableRowSpan, groupStart, groupSpan) {
1099
+ if (!enableRowSpan || hoveredRowIndex === null) return false;
1100
+ return hoveredRowIndex >= groupStart && hoveredRowIndex <= groupStart + groupSpan - 1;
1101
+ }
1102
+
1015
1103
  // src/components/ui/table/features/row-span/rowSpan.ts
1016
1104
  function getRowFieldValue(row, key) {
1017
1105
  return row[key];
@@ -1050,13 +1138,13 @@ function computeRowSpans(data, rowSpanKey, parentSpans) {
1050
1138
  for (let index = 0; index < data.length; index++) {
1051
1139
  const currentValue = getRowFieldValue(data[index], rowSpanKey);
1052
1140
  const previousValue = index > 0 ? getRowFieldValue(data[index - 1], rowSpanKey) : void 0;
1053
- if (index > 0 && currentValue === previousValue && sharesParentGroup(parentStartRows, index)) {
1141
+ if (index > 0 && Object.is(currentValue, previousValue) && sharesParentGroup(parentStartRows, index)) {
1054
1142
  result.push({ rowSpan: 0, isFirstInGroup: false });
1055
1143
  continue;
1056
1144
  }
1057
1145
  let span = 1;
1058
1146
  for (let nextIndex = index + 1; nextIndex < data.length; nextIndex++) {
1059
- if (getRowFieldValue(data[nextIndex], rowSpanKey) !== currentValue) break;
1147
+ if (!Object.is(getRowFieldValue(data[nextIndex], rowSpanKey), currentValue)) break;
1060
1148
  if (!sharesParentGroup(parentStartRows, nextIndex)) break;
1061
1149
  span++;
1062
1150
  }
@@ -1314,7 +1402,11 @@ function blurActiveElementOutside(container) {
1314
1402
  if (container instanceof Node && container.contains(active)) return;
1315
1403
  active.blur();
1316
1404
  }
1317
- function resolveExpandCellIndex(cells, toggleField) {
1405
+ function resolveExpandCellIndex(cells, toggleField, expandColumn) {
1406
+ if (expandColumn) {
1407
+ const explicitIndex = cells.findIndex((cell) => cell.column.id === expandColumn);
1408
+ if (explicitIndex >= 0) return explicitIndex;
1409
+ }
1318
1410
  if (!toggleField) return 0;
1319
1411
  const matchedIndex = cells.findIndex(
1320
1412
  (cell) => cell.column.id === toggleField
@@ -1357,7 +1449,7 @@ function DataTableRow({
1357
1449
  enableRowSpan,
1358
1450
  primaryRowSpanColumnId,
1359
1451
  columnRowSpanMap,
1360
- hoveredRowIndex,
1452
+ hoverStore,
1361
1453
  selectedRowIndices,
1362
1454
  onRowHover
1363
1455
  } = rowSpan;
@@ -1366,6 +1458,7 @@ function DataTableRow({
1366
1458
  enableCellSelection,
1367
1459
  activeSelectionBounds,
1368
1460
  dragState,
1461
+ canFill = true,
1369
1462
  onCellMouseDown,
1370
1463
  onCellMouseEnter,
1371
1464
  onFillHandleMouseDown
@@ -1373,9 +1466,12 @@ function DataTableRow({
1373
1466
  const {
1374
1467
  editingCell,
1375
1468
  draftValue,
1469
+ draftInvalid = false,
1470
+ onDraftInvalidChange,
1376
1471
  onDraftValueChange,
1377
1472
  onStartEdit,
1378
1473
  onCommitEdit,
1474
+ onCommitEditAndMove,
1379
1475
  onCancelEdit
1380
1476
  } = cellEdit;
1381
1477
  const renderCell = (tableCell) => (0, import_react_table.flexRender)(
@@ -1385,6 +1481,7 @@ function DataTableRow({
1385
1481
  const {
1386
1482
  enableExpand,
1387
1483
  toggleField,
1484
+ expandColumn,
1388
1485
  expandedRows,
1389
1486
  preventExpand,
1390
1487
  onToggleExpand,
@@ -1393,13 +1490,50 @@ function DataTableRow({
1393
1490
  } = expand;
1394
1491
  const rowIndex = row.index;
1395
1492
  const rowData = row.original;
1396
- const isRowHovered = hoveredRowIndex === rowIndex;
1397
1493
  const isRowSelected = row.getIsSelected();
1398
1494
  const { startRow: primaryGroupStart, rowSpan: primaryGroupSpan } = resolveRowSpanAt(
1399
1495
  primaryRowSpanColumnId ? columnRowSpanMap.get(primaryRowSpanColumnId) : void 0,
1400
1496
  rowIndex
1401
1497
  );
1402
- const isGroupHovered = enableRowSpan && hoveredRowIndex !== null && hoveredRowIndex >= primaryGroupStart && hoveredRowIndex <= primaryGroupStart + primaryGroupSpan - 1;
1498
+ const isRowHovered2 = (0, import_react3.useSyncExternalStore)(
1499
+ hoverStore.subscribe,
1500
+ () => isRowHovered(hoverStore.getHoveredRowIndex(), rowIndex),
1501
+ () => false
1502
+ );
1503
+ const isGroupHovered = (0, import_react3.useSyncExternalStore)(
1504
+ hoverStore.subscribe,
1505
+ () => isRowGroupHovered(
1506
+ hoverStore.getHoveredRowIndex(),
1507
+ enableRowSpan,
1508
+ primaryGroupStart,
1509
+ primaryGroupSpan
1510
+ ),
1511
+ () => false
1512
+ );
1513
+ const rowSpanColumnIds = enableRowSpan ? [...columnRowSpanMap.keys()].filter((id) => id !== primaryRowSpanColumnId) : [];
1514
+ const nestedRowSpanRanges = rowSpanColumnIds.map((columnId) => {
1515
+ const { startRow, rowSpan: span } = resolveRowSpanAt(
1516
+ columnRowSpanMap.get(columnId),
1517
+ rowIndex
1518
+ );
1519
+ return { columnId, startRow, span };
1520
+ });
1521
+ const nestedHoverSignature = (0, import_react3.useSyncExternalStore)(
1522
+ hoverStore.subscribe,
1523
+ () => {
1524
+ const hovered = hoverStore.getHoveredRowIndex();
1525
+ return nestedRowSpanRanges.map(
1526
+ ({ startRow, span }) => isRowGroupHovered(hovered, true, startRow, span) ? "1" : "0"
1527
+ ).join("");
1528
+ },
1529
+ () => rowSpanColumnIds.map(() => "0").join("")
1530
+ );
1531
+ const nestedHoverByColumn = new Map(
1532
+ rowSpanColumnIds.map((columnId, index) => [
1533
+ columnId,
1534
+ nestedHoverSignature[index] === "1"
1535
+ ])
1536
+ );
1403
1537
  const visibleCells = row.getVisibleCells();
1404
1538
  const columnIdsByIndex = visibleCells.map((cell) => cell.column.id);
1405
1539
  row.getIsCellDragSelected = (columnId) => {
@@ -1445,12 +1579,13 @@ function DataTableRow({
1445
1579
  span
1446
1580
  );
1447
1581
  } : void 0;
1448
- const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField) : -1;
1582
+ const expandCellIndex = enableExpand ? resolveExpandCellIndex(visibleCells, toggleField, expandColumn) : -1;
1449
1583
  const canExpand = enableExpand && !preventExpand && canExpandRow(rowData);
1450
1584
  const expandKey = toggleField && rowData[toggleField] !== null && rowData[toggleField] !== void 0 ? String(rowData[toggleField]) : null;
1451
1585
  const isExpanded = expandKey !== null && Boolean(expandedRows?.has(expandKey));
1452
1586
  const rowLevel = typeof rowData.level === "number" ? rowData.level : 0;
1453
1587
  const editInputRef = (0, import_react3.useRef)(null);
1588
+ const cellPressRef = (0, import_react3.useRef)(false);
1454
1589
  const isRowEditing = editingCell?.rowIndex === rowIndex;
1455
1590
  (0, import_react3.useEffect)(() => {
1456
1591
  if (!isRowEditing) return;
@@ -1463,23 +1598,29 @@ function DataTableRow({
1463
1598
  ref: measureElement,
1464
1599
  "data-index": virtualIndex,
1465
1600
  "data-selected": isRowSelected ? "" : void 0,
1466
- "data-hovered": isRowHovered || isGroupHovered ? "" : void 0,
1601
+ "data-hovered": isRowHovered2 || isGroupHovered ? "" : void 0,
1467
1602
  "data-expandable": enableExpand && canExpand ? "" : void 0,
1468
1603
  "data-expanded": isExpanded ? "" : void 0,
1604
+ "data-level": enableExpand ? rowLevel : void 0,
1469
1605
  className: cn(
1470
1606
  "DataTableRowJSX",
1471
1607
  !enableRowSpan && ROW_HOVER_CLASS,
1472
- enableRowSpan && isRowHovered && !isRowSelected && ROW_HOVERED_BG_CLASS,
1608
+ enableRowSpan && isRowHovered2 && !isRowSelected && ROW_HOVERED_BG_CLASS,
1473
1609
  isRowSelected && "is-selected",
1474
1610
  enableExpand && canExpand && "is-expandable",
1475
1611
  classNames?.row,
1476
1612
  getRowClassName?.(rowData, rowIndex)
1477
1613
  ),
1478
1614
  onMouseEnter: () => onRowHover(rowIndex, rowData),
1615
+ onMouseDownCapture: () => {
1616
+ cellPressRef.current = false;
1617
+ },
1479
1618
  onClick: () => {
1619
+ const startedCellSelection = cellPressRef.current;
1620
+ cellPressRef.current = false;
1480
1621
  if (isRowEditing) return;
1481
1622
  onRowClick?.(rowData, rowIndex);
1482
- if (rowSelectionMode !== "none" && selectOnRowClick) {
1623
+ if (rowSelectionMode !== "none" && selectOnRowClick && !startedCellSelection) {
1483
1624
  onToggleSelect();
1484
1625
  }
1485
1626
  },
@@ -1502,8 +1643,8 @@ function DataTableRow({
1502
1643
  }
1503
1644
  const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === cellIndex;
1504
1645
  const cellRowSpan = rowSpanInfo?.rowSpan ?? 1;
1505
- const isMergedCellHovered = hoveredRowIndex !== null && hoveredRowIndex >= rowIndex && hoveredRowIndex <= rowIndex + cellRowSpan - 1;
1506
- const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered;
1646
+ const isMergedCellHovered = columnId === primaryRowSpanColumnId ? isGroupHovered : nestedHoverByColumn.get(columnId) ?? false;
1647
+ const showCellHover = isRowSpanColumn ? isMergedCellHovered : isRowHovered2;
1507
1648
  let isMergedCellSelected = false;
1508
1649
  if (isRowSpanColumn) {
1509
1650
  for (let r = rowIndex; r < rowIndex + cellRowSpan; r += 1) {
@@ -1525,7 +1666,7 @@ function DataTableRow({
1525
1666
  activeSelectionBounds,
1526
1667
  cellRowSpan
1527
1668
  );
1528
- const isBottomRightCell = !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
1669
+ const isBottomRightCell = canFill && !isEditing && activeSelectionBounds && !dragState.isSelecting && activeSelectionBounds.endRow >= rowIndex && activeSelectionBounds.endRow <= rowIndex + cellRowSpan - 1 && cellIndex === activeSelectionBounds.endCol;
1529
1670
  const spanRowHeights = enableCellSelection && activeSelectionBounds && isCellDragSelected && cellRowSpan > 1 ? measureMergedSpanRowHeights(rowIndex, cellRowSpan) : void 0;
1530
1671
  const selectionEdgeStyle = getCellSelectionEdgeStyle(
1531
1672
  rowIndex,
@@ -1583,6 +1724,7 @@ function DataTableRow({
1583
1724
  if (isInteractiveMouseTarget(event.target)) return;
1584
1725
  event.preventDefault();
1585
1726
  blurActiveElementOutside(event.currentTarget);
1727
+ cellPressRef.current = true;
1586
1728
  onCellMouseDown(
1587
1729
  resolveCellRowIndex(event.clientY, event.currentTarget),
1588
1730
  cellIndex,
@@ -1636,6 +1778,8 @@ function DataTableRow({
1636
1778
  ref: editInputRef,
1637
1779
  type: editType === "number" ? "number" : "text",
1638
1780
  defaultValue: draftValue,
1781
+ "aria-invalid": draftInvalid ? true : void 0,
1782
+ "data-invalid": draftInvalid ? "" : void 0,
1639
1783
  className: cn(
1640
1784
  "cell-edit-input",
1641
1785
  CELL_ALIGN_CLASS[align],
@@ -1644,6 +1788,7 @@ function DataTableRow({
1644
1788
  ),
1645
1789
  onChange: (event) => {
1646
1790
  editInputProps?.onChange?.(event);
1791
+ onDraftInvalidChange?.(Boolean(event.target.validity?.badInput));
1647
1792
  onDraftValueChange(event.target.value);
1648
1793
  },
1649
1794
  onMouseDown: (event) => {
@@ -1657,9 +1802,22 @@ function DataTableRow({
1657
1802
  onKeyDown: (event) => {
1658
1803
  editInputProps?.onKeyDown?.(event);
1659
1804
  if (event.defaultPrevented) return;
1660
- if (event.key === "Enter") {
1805
+ if (event.nativeEvent.isComposing || event.keyCode === 229) {
1806
+ return;
1807
+ }
1808
+ if (event.key === "Enter" || event.key === "Tab") {
1661
1809
  event.preventDefault();
1662
- onCommitEdit(event.currentTarget.value);
1810
+ if (event.currentTarget.validity?.badInput) {
1811
+ onDraftInvalidChange?.(true);
1812
+ return;
1813
+ }
1814
+ const delta = event.key === "Enter" ? { row: event.shiftKey ? -1 : 1, col: 0 } : { row: 0, col: event.shiftKey ? -1 : 1 };
1815
+ if (onCommitEditAndMove) {
1816
+ onCommitEditAndMove(event.currentTarget.value, delta);
1817
+ } else {
1818
+ onCommitEdit(event.currentTarget.value);
1819
+ }
1820
+ return;
1663
1821
  }
1664
1822
  if (event.key === "Escape") {
1665
1823
  event.preventDefault();
@@ -1669,6 +1827,10 @@ function DataTableRow({
1669
1827
  onBlur: (event) => {
1670
1828
  editInputProps?.onBlur?.(event);
1671
1829
  if (event.defaultPrevented) return;
1830
+ if (event.currentTarget.validity?.badInput) {
1831
+ onDraftInvalidChange?.(true);
1832
+ return;
1833
+ }
1672
1834
  onCommitEdit(event.currentTarget.value);
1673
1835
  }
1674
1836
  }
@@ -1680,6 +1842,7 @@ function DataTableRow({
1680
1842
  "expand-cell-content",
1681
1843
  classNames?.expandCellContent
1682
1844
  ),
1845
+ style: { "--table-row-level": rowLevel },
1683
1846
  children: [
1684
1847
  rowLevel > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1685
1848
  "span",
@@ -1709,6 +1872,7 @@ function DataTableRow({
1709
1872
  {
1710
1873
  type: "button",
1711
1874
  "aria-label": isExpanded ? collapseRowLabel : expandRowLabel,
1875
+ "aria-expanded": isExpanded,
1712
1876
  className: cn(
1713
1877
  "expand-toggle-button",
1714
1878
  classNames?.expandToggle
@@ -1795,6 +1959,7 @@ function DataTableSearch({
1795
1959
  previousLabel,
1796
1960
  nextLabel,
1797
1961
  closeLabel,
1962
+ formatResult = formatSearchResultLabel,
1798
1963
  rowsTotal,
1799
1964
  classNames,
1800
1965
  onSearchValueChange,
@@ -1803,9 +1968,10 @@ function DataTableSearch({
1803
1968
  onPrevious
1804
1969
  }) {
1805
1970
  if (!showSearch) return null;
1806
- const resultString = searchStatus ? formatSearchResultLabel(searchStatus) : resultHint;
1971
+ const resultString = searchStatus ? formatResult(searchStatus) : resultHint;
1807
1972
  const progress = rowsTotal > 0 ? Math.floor((searchStatus?.rowsSearched ?? 0) / rowsTotal * 100) : 0;
1808
1973
  const handleKeyDown = (event) => {
1974
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
1809
1975
  if ((event.ctrlKey || event.metaKey) && event.code === "KeyF" || event.key === "Escape") {
1810
1976
  event.preventDefault();
1811
1977
  event.stopPropagation();
@@ -1929,6 +2095,7 @@ function DataTableToolbar({
1929
2095
  summary,
1930
2096
  selectedCount,
1931
2097
  selectionLabel,
2098
+ countLabel,
1932
2099
  toolbar,
1933
2100
  className,
1934
2101
  classNames
@@ -1942,7 +2109,7 @@ function DataTableToolbar({
1942
2109
  if (!hasLeftContent && !hasToolbar && !hasSelectionContent) return null;
1943
2110
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: cn("DataTableToolbarJSX", classNames?.toolbar, className), children: [
1944
2111
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: cn("toolbar-left", classNames?.toolbarLeft), children: [
1945
- hasCount && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
2112
+ hasCount && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: cn("toolbar-count", classNames?.toolbarCount), children: countLabel ? countLabel(displayFiltered, totalCount) : displayFiltered !== void 0 && totalCount !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
1946
2113
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "toolbar-count-primary", children: displayFiltered }),
1947
2114
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "toolbar-count-placeholder", children: [
1948
2115
  " / ",
@@ -2356,12 +2523,12 @@ function commitCellValue({
2356
2523
  if (!cell) return false;
2357
2524
  const accessorKey = getColumnAccessorKey(cell.column.columnDef);
2358
2525
  if (!accessorKey) return false;
2359
- const dataIndex = row.index;
2360
- if (dataIndex < 0 || dataIndex >= data.length) return false;
2361
- const next = data.map((item) => ({ ...item }));
2362
- const target = next[dataIndex];
2363
- if (!target) return false;
2364
- target[accessorKey] = value;
2526
+ const next = applyCellChangesToData(data, [
2527
+ { original: row.original, index: row.index, accessorKey, value }
2528
+ ]);
2529
+ if (next === data || next.every((item, index) => item === data[index])) {
2530
+ return false;
2531
+ }
2365
2532
  onDataChange?.(next);
2366
2533
  return true;
2367
2534
  }
@@ -2373,19 +2540,36 @@ function useCellEdit({
2373
2540
  onDataChange,
2374
2541
  onCellChange
2375
2542
  }) {
2376
- const [editingCell, setEditingCell] = (0, import_react5.useState)(null);
2543
+ const [editingKey, setEditingKey] = (0, import_react5.useState)(null);
2377
2544
  const [draftValue, setDraftValue] = (0, import_react5.useState)("");
2378
2545
  const draftValueRef = (0, import_react5.useRef)(draftValue);
2379
- const editingCellRef = (0, import_react5.useRef)(editingCell);
2546
+ const [draftInvalid, setDraftInvalidState] = (0, import_react5.useState)(false);
2547
+ const draftInvalidRef = (0, import_react5.useRef)(false);
2548
+ const setDraftInvalid = (0, import_react5.useCallback)((invalid) => {
2549
+ draftInvalidRef.current = invalid;
2550
+ setDraftInvalidState(invalid);
2551
+ }, []);
2380
2552
  (0, import_react5.useEffect)(() => {
2381
2553
  draftValueRef.current = draftValue;
2382
2554
  }, [draftValue]);
2555
+ const editingCell = (0, import_react5.useMemo)(
2556
+ () => resolveEditingCell(rows, editingKey),
2557
+ [rows, editingKey]
2558
+ );
2559
+ const editingCellRef = (0, import_react5.useRef)(editingCell);
2560
+ editingCellRef.current = editingCell;
2383
2561
  (0, import_react5.useEffect)(() => {
2384
- editingCellRef.current = editingCell;
2385
- }, [editingCell]);
2562
+ if (editingKey && !editingCell) {
2563
+ setEditingKey(null);
2564
+ setDraftValue("");
2565
+ }
2566
+ }, [editingCell, editingKey]);
2386
2567
  const cancelEdit = (0, import_react5.useCallback)(() => {
2387
- setEditingCell(null);
2568
+ editingCellRef.current = null;
2569
+ setEditingKey(null);
2388
2570
  setDraftValue("");
2571
+ draftInvalidRef.current = false;
2572
+ setDraftInvalidState(false);
2389
2573
  }, []);
2390
2574
  const commitEdit = (0, import_react5.useCallback)(
2391
2575
  (raw) => {
@@ -2405,6 +2589,7 @@ function useCellEdit({
2405
2589
  cancelEdit();
2406
2590
  return true;
2407
2591
  }
2592
+ if (draftInvalidRef.current) return false;
2408
2593
  const value = raw ?? draftValueRef.current;
2409
2594
  const parsed = parseCellEditValue(value, getColumnEditType(cell.column.columnDef));
2410
2595
  if (!parsed.ok) return false;
@@ -2425,13 +2610,15 @@ function useCellEdit({
2425
2610
  );
2426
2611
  const startEdit = (0, import_react5.useCallback)(
2427
2612
  (rowIndex, colIndex) => {
2428
- const cell = rows[rowIndex]?.getVisibleCells()[colIndex];
2429
- if (!cell || !isColumnEditable(cell.column.columnDef)) return;
2613
+ const row = rows[rowIndex];
2614
+ const cell = row?.getVisibleCells()[colIndex];
2615
+ if (!row || !cell || !isColumnEditable(cell.column.columnDef)) return;
2616
+ if (!isTextEditableValue(cell.getValue())) return;
2430
2617
  const current = editingCellRef.current;
2431
2618
  if (current && (current.rowIndex !== rowIndex || current.colIndex !== colIndex) && !commitEdit()) {
2432
2619
  return;
2433
2620
  }
2434
- setEditingCell({ rowIndex, colIndex });
2621
+ setEditingKey({ rowId: row.id, columnId: cell.column.id });
2435
2622
  setDraftValue(getCellEditDraftValue(cell.getValue()));
2436
2623
  },
2437
2624
  [commitEdit, rows]
@@ -2439,12 +2626,55 @@ function useCellEdit({
2439
2626
  return {
2440
2627
  editingCell,
2441
2628
  draftValue,
2629
+ draftInvalid,
2630
+ setDraftInvalid,
2442
2631
  setDraftValue,
2443
2632
  startEdit,
2444
2633
  commitEdit,
2445
2634
  cancelEdit
2446
2635
  };
2447
2636
  }
2637
+ function resolveEditingCell(rows, key) {
2638
+ if (!key) return null;
2639
+ const rowIndex = rows.findIndex((row) => row.id === key.rowId);
2640
+ if (rowIndex < 0) return null;
2641
+ const colIndex = rows[rowIndex].getVisibleCells().findIndex((cell) => cell.column.id === key.columnId);
2642
+ if (colIndex < 0) return null;
2643
+ return { rowIndex, colIndex };
2644
+ }
2645
+ function isTextEditableValue(value) {
2646
+ return value === null || value === void 0 || typeof value !== "object";
2647
+ }
2648
+
2649
+ // src/components/ui/table/features/cell-selection/formatCellValue.ts
2650
+ function formatObjectValue(value) {
2651
+ const text = value.text ?? value.label ?? value.name ?? value.title;
2652
+ if (text != null && text !== "") {
2653
+ return formatCellValue(text);
2654
+ }
2655
+ try {
2656
+ return JSON.stringify(value);
2657
+ } catch {
2658
+ return "";
2659
+ }
2660
+ }
2661
+ function formatCellValue(value) {
2662
+ if (value === null || value === void 0) return "";
2663
+ if (value instanceof Date) {
2664
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
2665
+ }
2666
+ if (Array.isArray(value)) {
2667
+ return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
2668
+ }
2669
+ if (typeof value === "object") {
2670
+ return formatObjectValue(value);
2671
+ }
2672
+ if (typeof value === "string") return value;
2673
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
2674
+ return String(value);
2675
+ }
2676
+ return "";
2677
+ }
2448
2678
 
2449
2679
  // src/components/ui/table/features/cell-render/builtins.tsx
2450
2680
  var import_jsx_runtime6 = require("react/jsx-runtime");
@@ -2468,8 +2698,9 @@ function asDrilldownItems(value) {
2468
2698
  const record = item;
2469
2699
  const text = asString(record.text ?? record.label ?? "");
2470
2700
  if (!text) return [];
2471
- const img = record.img ?? record.image;
2472
- return [{ text, ...typeof img === "string" ? { img } : {} }];
2701
+ const rawImg = record.img ?? record.image;
2702
+ const img = typeof rawImg === "string" ? sanitizeImageSrc(rawImg) : null;
2703
+ return [{ text, ...img ? { img } : {} }];
2473
2704
  }
2474
2705
  return [{ text: asString(item) }];
2475
2706
  });
@@ -2530,6 +2761,22 @@ function sanitizeUriHref(raw) {
2530
2761
  return href;
2531
2762
  }
2532
2763
  }
2764
+ function sanitizeImageSrc(raw) {
2765
+ const src = raw.trim();
2766
+ if (!src) return null;
2767
+ try {
2768
+ const parsed = new URL(src);
2769
+ const protocol = parsed.protocol.toLowerCase();
2770
+ if (protocol === "http:" || protocol === "https:" || protocol === "blob:") {
2771
+ return src;
2772
+ }
2773
+ if (protocol === "data:" && /^data:image\//i.test(src)) return src;
2774
+ return null;
2775
+ } catch {
2776
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return null;
2777
+ return src;
2778
+ }
2779
+ }
2533
2780
  function UriCell({ value }) {
2534
2781
  const raw = asString(value);
2535
2782
  if (!raw) return null;
@@ -2551,7 +2798,10 @@ function UriCell({ value }) {
2551
2798
  );
2552
2799
  }
2553
2800
  function ImageCell({ value }) {
2554
- const urls = asStringList(value);
2801
+ const urls = asStringList(value).flatMap((url) => {
2802
+ const src = sanitizeImageSrc(url);
2803
+ return src ? [src] : [];
2804
+ });
2555
2805
  if (urls.length === 0) return null;
2556
2806
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "data-table-cell-image", children: urls.map((url, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2557
2807
  "img",
@@ -2604,8 +2854,33 @@ function DrilldownCell({ value }) {
2604
2854
  function LoadingCell() {
2605
2855
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "data-table-cell-loading", "aria-busy": "true" });
2606
2856
  }
2607
- function ProtectedCell() {
2608
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "data-table-cell-protected", "aria-label": "protected", children: "****" });
2857
+ function ProtectedCell({ cellProps }) {
2858
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "protected";
2859
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "data-table-cell-protected", "aria-label": label, children: "****" });
2860
+ }
2861
+ function RowSelectCell({ row, cellProps }) {
2862
+ const canSelect = typeof row.getCanSelect === "function" ? row.getCanSelect() : false;
2863
+ const checked = typeof row.getIsSelected === "function" ? row.getIsSelected() : false;
2864
+ const label = typeof cellProps?.ariaLabel === "string" ? cellProps.ariaLabel : "Select row";
2865
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2866
+ "input",
2867
+ {
2868
+ type: "checkbox",
2869
+ className: "data-table-cell-row-select",
2870
+ checked,
2871
+ disabled: !canSelect,
2872
+ "aria-label": label,
2873
+ onChange: () => {
2874
+ if (canSelect) row.toggleSelected();
2875
+ },
2876
+ onClick: (event) => {
2877
+ event.stopPropagation();
2878
+ },
2879
+ onMouseDown: (event) => {
2880
+ event.stopPropagation();
2881
+ }
2882
+ }
2883
+ );
2609
2884
  }
2610
2885
  function RowIdCell({ value }) {
2611
2886
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "data-table-cell-row-id", children: asString(value) });
@@ -2621,7 +2896,8 @@ var BUILTIN_RENDER_MAP = {
2621
2896
  drilldown: DrilldownCell,
2622
2897
  loading: LoadingCell,
2623
2898
  protected: ProtectedCell,
2624
- "row-id": RowIdCell
2899
+ "row-id": RowIdCell,
2900
+ "row-select": RowSelectCell
2625
2901
  };
2626
2902
  var BUILTIN_CELL_RENDERERS = Object.keys(BUILTIN_RENDER_MAP).map((kind) => ({
2627
2903
  kind,
@@ -2655,47 +2931,32 @@ function formatDefaultCellValue(value) {
2655
2931
  return String(value);
2656
2932
  }
2657
2933
  if (typeof value === "bigint") return value.toString();
2658
- return String(value);
2934
+ return formatCellValue(value);
2659
2935
  }
2660
2936
 
2661
- // src/components/ui/table/features/cell-selection/useCellSelection.ts
2662
- var import_react7 = require("react");
2937
+ // src/components/ui/table/features/cell-selection/copyData.ts
2938
+ var import_react6 = require("react");
2663
2939
 
2664
- // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
2665
- var activeOwner = null;
2666
- var clearByOwner = /* @__PURE__ */ new Map();
2667
- function createCellSelectionOwner() {
2668
- return /* @__PURE__ */ Symbol("cell-selection-owner");
2669
- }
2670
- function registerCellSelectionOwner(owner, clearSelection) {
2671
- clearByOwner.set(owner, clearSelection);
2672
- return () => {
2673
- clearByOwner.delete(owner);
2674
- if (activeOwner === owner) {
2675
- activeOwner = null;
2676
- }
2677
- };
2678
- }
2679
- function claimCellSelectionOwner(owner) {
2680
- if (activeOwner === owner) return;
2681
- activeOwner = owner;
2682
- for (const [id, clearSelection] of clearByOwner) {
2683
- if (id !== owner) {
2684
- clearSelection();
2685
- }
2686
- }
2940
+ // src/components/ui/table/features/cell-selection/subtreeClipboard.ts
2941
+ var lastSubtreeCopy = null;
2942
+ function normalize(text) {
2943
+ return text.replace(/\r\n?/g, "\n").replace(/\n+$/, "");
2687
2944
  }
2688
- function isActiveCellSelectionOwner(owner) {
2689
- return activeOwner === owner;
2945
+ function rememberSubtreeCopy(text) {
2946
+ lastSubtreeCopy = normalize(text);
2690
2947
  }
2691
- function releaseCellSelectionOwner(owner) {
2692
- if (activeOwner === owner) {
2693
- activeOwner = null;
2694
- }
2948
+ function isOwnSubtreeCopy(text) {
2949
+ return lastSubtreeCopy !== null && normalize(text) === lastSubtreeCopy;
2695
2950
  }
2696
2951
 
2697
2952
  // src/components/ui/table/features/cell-selection/copyData.ts
2698
- var import_react6 = require("react");
2953
+ var SPREADSHEET_FORMULA_PREFIX = /^[=+\-@\t\r]/;
2954
+ var PLAIN_SIGNED_NUMBER = /^[+-]\d+(?:\.\d+)?$/;
2955
+ function escapeSpreadsheetFormula(text) {
2956
+ if (!SPREADSHEET_FORMULA_PREFIX.test(text)) return text;
2957
+ if (PLAIN_SIGNED_NUMBER.test(text)) return text;
2958
+ return `'${text}`;
2959
+ }
2699
2960
  function isReactNodeIterable(node) {
2700
2961
  return typeof node === "object" && node !== null && !(0, import_react6.isValidElement)(node) && Symbol.iterator in node;
2701
2962
  }
@@ -2821,6 +3082,10 @@ function reactNodeToText(node) {
2821
3082
  }
2822
3083
  return "";
2823
3084
  }
3085
+ function quoteTsvCell(text) {
3086
+ if (!/[\t\n\r]/.test(text) && !text.startsWith('"')) return text;
3087
+ return `"${text.replace(/"/g, '""')}"`;
3088
+ }
2824
3089
  function sanitizeClipboardCell(text) {
2825
3090
  return text.replace(/\s+/g, " ").trim();
2826
3091
  }
@@ -2896,7 +3161,7 @@ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIn
2896
3161
  return formatCellValue(value);
2897
3162
  }
2898
3163
  }
2899
- if (options?.registry && meta?.kind && isPrimitiveCopyValue(value)) {
3164
+ if (options?.registry && meta?.kind && (isPrimitiveCopyValue(value) || meta.kind === "protected")) {
2900
3165
  try {
2901
3166
  const renderer = resolveCellRenderer(options.registry, meta.kind, ctx);
2902
3167
  if (renderer) {
@@ -2910,35 +3175,6 @@ function formatCopyCellText(rowData, columnDef, columnId, visibleRow, fallbackIn
2910
3175
  }
2911
3176
  return formatCellValue(value);
2912
3177
  }
2913
- function formatPrimitive(value) {
2914
- if (value === null || value === void 0) return "";
2915
- if (typeof value === "string") return value;
2916
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
2917
- return String(value);
2918
- }
2919
- return "";
2920
- }
2921
- function formatObjectValue(value) {
2922
- const text = value.text ?? value.label ?? value.name ?? value.title;
2923
- if (text != null && text !== "") {
2924
- return formatCellValue(text);
2925
- }
2926
- try {
2927
- return JSON.stringify(value);
2928
- } catch {
2929
- return "";
2930
- }
2931
- }
2932
- function formatCellValue(value) {
2933
- if (value === null || value === void 0) return "";
2934
- if (Array.isArray(value)) {
2935
- return value.map((item) => formatCellValue(item)).filter((item) => item.length > 0).join(", ");
2936
- }
2937
- if (typeof value === "object") {
2938
- return formatObjectValue(value);
2939
- }
2940
- return formatPrimitive(value);
2941
- }
2942
3178
  function getNestedValue(row, path) {
2943
3179
  if (!path.includes(".")) return row[path];
2944
3180
  return path.split(".").reduce((current, key) => {
@@ -2970,15 +3206,23 @@ function getRowDepth(original) {
2970
3206
  function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
2971
3207
  const { startRow, endRow } = bounds;
2972
3208
  const result = [];
2973
- const includedOriginalIds = /* @__PURE__ */ new Set();
3209
+ if (mode !== "subtree") {
3210
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
3211
+ const row = visibleRows[rowIndex];
3212
+ if (row) result.push({ row: row.original, depth: 0 });
3213
+ }
3214
+ return result;
3215
+ }
3216
+ const included = /* @__PURE__ */ new Set();
3217
+ const keyOf = (node) => getTreeRowKey(node) ?? (getOriginalRowId(node) || node);
2974
3218
  const appendSubtree = (node, depth) => {
2975
3219
  const children = node.children;
2976
3220
  if (!Array.isArray(children) || children.length === 0) return;
2977
3221
  for (const child of children) {
2978
- const childId = getOriginalRowId(child);
2979
- if (!(childId && includedOriginalIds.has(childId))) {
3222
+ const key = keyOf(child);
3223
+ if (!included.has(key)) {
2980
3224
  result.push({ row: child, depth });
2981
- if (childId) includedOriginalIds.add(childId);
3225
+ included.add(key);
2982
3226
  }
2983
3227
  appendSubtree(child, depth + 1);
2984
3228
  }
@@ -2986,12 +3230,12 @@ function collectCopyRowEntries(visibleRows, bounds, mode = "visible") {
2986
3230
  for (let rowIndex = startRow; rowIndex <= endRow; rowIndex += 1) {
2987
3231
  const row = visibleRows[rowIndex];
2988
3232
  if (!row) continue;
2989
- const originalId = getOriginalRowId(row.original);
2990
- if (originalId && includedOriginalIds.has(originalId)) continue;
3233
+ const key = keyOf(row.original);
3234
+ if (included.has(key)) continue;
2991
3235
  const depth = getRowDepth(row.original);
2992
3236
  result.push({ row: row.original, depth });
2993
- if (originalId) includedOriginalIds.add(originalId);
2994
- if (mode !== "subtree" || !hasSubtree(row.original)) continue;
3237
+ included.add(key);
3238
+ if (!hasSubtree(row.original)) continue;
2995
3239
  appendSubtree(row.original, depth + 1);
2996
3240
  }
2997
3241
  return result;
@@ -3016,7 +3260,7 @@ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options)
3016
3260
  const line = copyableColumns.map(({ templateCell, colOffset }) => {
3017
3261
  const sourceCell = matchingCells?.[colOffset];
3018
3262
  const column = sourceCell?.column ?? templateCell.column;
3019
- return formatCopyCellText(
3263
+ const text = formatCopyCellText(
3020
3264
  rowData,
3021
3265
  column.columnDef,
3022
3266
  resolveCopyColumnId(sourceCell ?? templateCell),
@@ -3026,6 +3270,8 @@ function serializeCopyRowsToTSV(copyRows, visibleRows, bounds, depths, options)
3026
3270
  visibleRow != null ? { rowIndex: visibleRow.index, colIndex: startCol + colOffset } : void 0,
3027
3271
  options
3028
3272
  );
3273
+ const escaped = options?.escapeFormulas ? escapeSpreadsheetFormula(text) : text;
3274
+ return quoteTsvCell(escaped);
3029
3275
  }).join(" ");
3030
3276
  return `${" ".repeat(relativeDepth)}${line}`;
3031
3277
  }).join("\n");
@@ -3040,15 +3286,78 @@ function serializeSelectionToTSV(visibleRows, bounds, mode = "visible", options)
3040
3286
  options
3041
3287
  );
3042
3288
  }
3289
+ function writeTextWithExecCommand(text) {
3290
+ if (typeof document === "undefined") return false;
3291
+ const textarea = document.createElement("textarea");
3292
+ textarea.value = text;
3293
+ textarea.setAttribute("readonly", "");
3294
+ textarea.style.position = "fixed";
3295
+ textarea.style.top = "0";
3296
+ textarea.style.left = "0";
3297
+ textarea.style.opacity = "0";
3298
+ textarea.style.pointerEvents = "none";
3299
+ document.body.appendChild(textarea);
3300
+ const previouslyFocused = document.activeElement;
3301
+ try {
3302
+ textarea.focus();
3303
+ textarea.select();
3304
+ return document.execCommand("copy");
3305
+ } catch {
3306
+ return false;
3307
+ } finally {
3308
+ document.body.removeChild(textarea);
3309
+ previouslyFocused?.focus?.();
3310
+ }
3311
+ }
3043
3312
  async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
3044
3313
  const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
3045
3314
  if (!text) return false;
3315
+ if (mode === "subtree") rememberSubtreeCopy(text);
3316
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
3317
+ return writeTextWithExecCommand(text);
3318
+ }
3046
3319
  try {
3047
3320
  await navigator.clipboard.writeText(text);
3321
+ return true;
3048
3322
  } catch {
3049
3323
  return false;
3050
3324
  }
3051
- return true;
3325
+ }
3326
+
3327
+ // src/components/ui/table/features/cell-selection/useCellSelection.ts
3328
+ var import_react7 = require("react");
3329
+
3330
+ // src/components/ui/table/features/cell-selection/activeCellSelectionOwner.ts
3331
+ var activeOwner = null;
3332
+ var clearByOwner = /* @__PURE__ */ new Map();
3333
+ function createCellSelectionOwner() {
3334
+ return /* @__PURE__ */ Symbol("cell-selection-owner");
3335
+ }
3336
+ function registerCellSelectionOwner(owner, clearSelection) {
3337
+ clearByOwner.set(owner, clearSelection);
3338
+ return () => {
3339
+ clearByOwner.delete(owner);
3340
+ if (activeOwner === owner) {
3341
+ activeOwner = null;
3342
+ }
3343
+ };
3344
+ }
3345
+ function claimCellSelectionOwner(owner) {
3346
+ if (activeOwner === owner) return;
3347
+ activeOwner = owner;
3348
+ for (const [id, clearSelection] of clearByOwner) {
3349
+ if (id !== owner) {
3350
+ clearSelection();
3351
+ }
3352
+ }
3353
+ }
3354
+ function isActiveCellSelectionOwner(owner) {
3355
+ return activeOwner === owner;
3356
+ }
3357
+ function releaseCellSelectionOwner(owner) {
3358
+ if (activeOwner === owner) {
3359
+ activeOwner = null;
3360
+ }
3052
3361
  }
3053
3362
 
3054
3363
  // src/components/ui/table/features/cell-selection/fillData.ts
@@ -3073,6 +3382,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
3073
3382
  const targetCell = targetRow?.getVisibleCells()[colIndex];
3074
3383
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
3075
3384
  if (!targetRow || !targetCell || !sourceCell) continue;
3385
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
3386
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
3076
3387
  const accessorKey = getColumnAccessorKey2(
3077
3388
  targetCell.column.columnDef
3078
3389
  );
@@ -3094,13 +3405,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
3094
3405
  );
3095
3406
  }
3096
3407
  function applyFillData(data, rows, sourceBounds, fillBounds) {
3097
- const newData = data.map((row) => ({ ...row }));
3098
3408
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
3099
- for (const target of targets) {
3100
- if (!newData[target.rowIndex]) continue;
3101
- newData[target.rowIndex][target.accessorKey] = target.value;
3102
- }
3103
- return newData;
3409
+ return applyCellChangesToData(
3410
+ data,
3411
+ targets.flatMap((target) => {
3412
+ const row = rows[target.rowIndex];
3413
+ if (!row) return [];
3414
+ return [
3415
+ {
3416
+ original: row.original,
3417
+ index: row.index,
3418
+ accessorKey: target.accessorKey,
3419
+ value: target.value
3420
+ }
3421
+ ];
3422
+ })
3423
+ );
3104
3424
  }
3105
3425
  function hasFillExtension(sourceBounds, fillBounds) {
3106
3426
  if (!sourceBounds) return false;
@@ -3121,14 +3441,59 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
3121
3441
  if (firstDepth !== 0) return false;
3122
3442
  return leadingEmptyCounts.some((depth) => depth > 0);
3123
3443
  }
3124
- function parseClipboardTSVWithDepths(text) {
3444
+ function splitTSV(text) {
3445
+ const rows = [];
3446
+ let row = [];
3447
+ let index = 0;
3448
+ while (index <= text.length) {
3449
+ let cell = "";
3450
+ if (text[index] === '"') {
3451
+ index += 1;
3452
+ while (index < text.length) {
3453
+ const char = text[index];
3454
+ if (char === '"') {
3455
+ if (text[index + 1] === '"') {
3456
+ cell += '"';
3457
+ index += 2;
3458
+ continue;
3459
+ }
3460
+ index += 1;
3461
+ break;
3462
+ }
3463
+ cell += char;
3464
+ index += 1;
3465
+ }
3466
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
3467
+ cell += text[index];
3468
+ index += 1;
3469
+ }
3470
+ } else {
3471
+ while (index < text.length && text[index] !== " " && text[index] !== "\n") {
3472
+ cell += text[index];
3473
+ index += 1;
3474
+ }
3475
+ }
3476
+ row.push(cell);
3477
+ if (index >= text.length) {
3478
+ rows.push(row);
3479
+ break;
3480
+ }
3481
+ if (text[index] === "\n") {
3482
+ rows.push(row);
3483
+ row = [];
3484
+ }
3485
+ index += 1;
3486
+ }
3487
+ return rows;
3488
+ }
3489
+ function parseClipboardTSVWithDepths(text, options) {
3125
3490
  if (!text) return { values: [], depths: [] };
3126
3491
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3127
3492
  const withoutTrailing = normalized.replace(/\n+$/, "");
3128
3493
  if (!withoutTrailing) return { values: [], depths: [] };
3129
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
3494
+ const rows = splitTSV(withoutTrailing);
3130
3495
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
3131
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
3496
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
3132
3497
  const values = [];
3133
3498
  const depths = [];
3134
3499
  for (let index = 0; index < rows.length; index += 1) {
@@ -3155,8 +3520,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
3155
3520
  }
3156
3521
  return columnIds;
3157
3522
  }
3158
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
3159
- const { values, depths } = parseClipboardTSVWithDepths(text);
3523
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
3524
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
3160
3525
  if (values.length === 0) return null;
3161
3526
  const width = Math.max(...values.map((row) => row.length), 0);
3162
3527
  if (width === 0) return null;
@@ -3189,6 +3554,19 @@ function isEditablePasteTarget(target) {
3189
3554
  }
3190
3555
 
3191
3556
  // src/components/ui/table/features/cell-selection/useCellSelection.ts
3557
+ var INTERACTIVE_FOCUS_SELECTOR = "button, a[href], input, textarea, select, [contenteditable]:not([contenteditable='false'])";
3558
+ function isInteractiveFocus() {
3559
+ const active = document.activeElement;
3560
+ return active instanceof Element && active.matches(INTERACTIVE_FOCUS_SELECTOR);
3561
+ }
3562
+ function hasPageTextSelectionOutside(root) {
3563
+ if (typeof window.getSelection !== "function") return false;
3564
+ const selection = window.getSelection();
3565
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return false;
3566
+ if (!selection.toString()) return false;
3567
+ const anchor = selection.anchorNode;
3568
+ return !(root && anchor && root.contains(anchor));
3569
+ }
3192
3570
  function isFocusOutsideRoot(rootRef) {
3193
3571
  const root = rootRef?.current;
3194
3572
  if (!root) return false;
@@ -3201,29 +3579,50 @@ function useCellSelection({
3201
3579
  rows,
3202
3580
  enabled = true,
3203
3581
  columnCount = 0,
3582
+ columnSignature,
3204
3583
  enableSubtreeCopy = false,
3584
+ escapeCopyFormulas = false,
3205
3585
  enableInsertPaste = true,
3206
3586
  onDataChange,
3207
3587
  onBatchChange,
3208
3588
  onRowsPaste,
3209
3589
  onCellNavigate,
3210
3590
  cellRendererRegistry,
3211
- rootRef
3591
+ rootRef,
3592
+ enableWasdNavigation = true,
3593
+ onEditKey,
3594
+ onClearKey
3212
3595
  }) {
3213
3596
  const ownerRef = (0, import_react7.useRef)(createCellSelectionOwner());
3214
3597
  const [dragState, setDragState] = (0, import_react7.useState)(INITIAL_DRAG_STATE);
3215
3598
  const pendingPasteModeRef = (0, import_react7.useRef)(null);
3216
3599
  const dragStateRef = (0, import_react7.useRef)(dragState);
3217
3600
  const onCellNavigateRef = (0, import_react7.useRef)(onCellNavigate);
3601
+ const onEditKeyRef = (0, import_react7.useRef)(onEditKey);
3602
+ const onClearKeyRef = (0, import_react7.useRef)(onClearKey);
3218
3603
  dragStateRef.current = dragState;
3219
3604
  onCellNavigateRef.current = onCellNavigate;
3220
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
3221
- const activeSelectionBounds = enabled ? getActiveSelectionBounds(dragState, cellSelectionBounds) : null;
3605
+ onEditKeyRef.current = onEditKey;
3606
+ onClearKeyRef.current = onClearKey;
3607
+ const updateDragState = (0, import_react7.useCallback)((update) => {
3608
+ const prev = dragStateRef.current;
3609
+ const next = update(prev);
3610
+ if (next === prev) return;
3611
+ dragStateRef.current = next;
3612
+ setDragState(next);
3613
+ }, []);
3614
+ const activeSelectionBounds = (0, import_react7.useMemo)(() => {
3615
+ if (!enabled) return null;
3616
+ return getActiveSelectionBounds(
3617
+ dragState,
3618
+ getCellSelectionBounds(dragState.start, dragState.end)
3619
+ );
3620
+ }, [dragState, enabled]);
3222
3621
  const handleCellMouseDown = (0, import_react7.useCallback)(
3223
3622
  (rowIndex, colIndex, options) => {
3224
3623
  if (!enabled) return;
3225
3624
  claimCellSelectionOwner(ownerRef.current);
3226
- setDragState((prev) => {
3625
+ updateDragState((prev) => {
3227
3626
  if (options?.shiftKey && prev.start) {
3228
3627
  return {
3229
3628
  ...prev,
@@ -3244,28 +3643,30 @@ function useCellSelection({
3244
3643
  };
3245
3644
  });
3246
3645
  },
3247
- [enabled]
3646
+ [enabled, updateDragState]
3248
3647
  );
3249
3648
  const handleCellMouseEnter = (0, import_react7.useCallback)(
3250
3649
  (rowIndex, colIndex) => {
3251
3650
  if (!enabled) return;
3252
- setDragState((prev) => {
3651
+ updateDragState((prev) => {
3253
3652
  if (prev.isSelecting) {
3653
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
3254
3654
  return { ...prev, end: { row: rowIndex, col: colIndex } };
3255
3655
  }
3256
3656
  if (prev.isFillDragging) {
3657
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
3257
3658
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
3258
3659
  }
3259
3660
  return prev;
3260
3661
  });
3261
3662
  },
3262
- [enabled]
3663
+ [enabled, updateDragState]
3263
3664
  );
3264
3665
  const handleFillHandleMouseDown = (0, import_react7.useCallback)(
3265
3666
  (rowIndex, colIndex) => {
3266
3667
  if (!enabled) return;
3267
3668
  claimCellSelectionOwner(ownerRef.current);
3268
- setDragState((prev) => {
3669
+ updateDragState((prev) => {
3269
3670
  const bounds = getCellSelectionBounds(prev.start, prev.end);
3270
3671
  if (!bounds) return prev;
3271
3672
  return {
@@ -3277,7 +3678,7 @@ function useCellSelection({
3277
3678
  };
3278
3679
  });
3279
3680
  },
3280
- [enabled]
3681
+ [enabled, updateDragState]
3281
3682
  );
3282
3683
  const clearSelection = (0, import_react7.useCallback)(() => {
3283
3684
  const prev = dragStateRef.current;
@@ -3296,6 +3697,130 @@ function useCellSelection({
3296
3697
  (0, import_react7.useEffect)(() => {
3297
3698
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
3298
3699
  }, [clearSelection]);
3700
+ const previousColumnSignatureRef = (0, import_react7.useRef)(columnSignature);
3701
+ (0, import_react7.useEffect)(() => {
3702
+ const columnsChanged = columnSignature !== void 0 && previousColumnSignatureRef.current !== void 0 && previousColumnSignatureRef.current !== columnSignature;
3703
+ previousColumnSignatureRef.current = columnSignature;
3704
+ const prev = dragStateRef.current;
3705
+ if (!prev.start || !prev.end) return;
3706
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
3707
+ const resolvedColumnCount = columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0;
3708
+ const outOfRange = bounds !== null && (bounds.endRow >= rows.length || resolvedColumnCount > 0 && bounds.endCol >= resolvedColumnCount);
3709
+ if (columnsChanged || outOfRange) {
3710
+ clearSelection();
3711
+ }
3712
+ }, [clearSelection, columnCount, columnSignature, rows]);
3713
+ (0, import_react7.useEffect)(() => {
3714
+ if (!enabled) return;
3715
+ const handlePointerDown = (event) => {
3716
+ const root = rootRef?.current;
3717
+ if (!root || !isActiveCellSelectionOwner(ownerRef.current)) return;
3718
+ if (event.target instanceof Node && root.contains(event.target)) return;
3719
+ releaseCellSelectionOwner(ownerRef.current);
3720
+ };
3721
+ document.addEventListener("pointerdown", handlePointerDown, true);
3722
+ document.addEventListener("mousedown", handlePointerDown, true);
3723
+ return () => {
3724
+ document.removeEventListener("pointerdown", handlePointerDown, true);
3725
+ document.removeEventListener("mousedown", handlePointerDown, true);
3726
+ };
3727
+ }, [enabled, rootRef]);
3728
+ const getColumnCount = (0, import_react7.useCallback)(
3729
+ () => columnCount > 0 ? columnCount : rows[0]?.getVisibleCells().length ?? 0,
3730
+ [columnCount, rows]
3731
+ );
3732
+ const selectCell = (0, import_react7.useCallback)(
3733
+ (row, col) => {
3734
+ if (!enabled) return;
3735
+ const resolvedColumnCount = getColumnCount();
3736
+ if (rows.length <= 0 || resolvedColumnCount <= 0) return;
3737
+ const position = clampCellPosition({ row, col }, rows.length, resolvedColumnCount);
3738
+ claimCellSelectionOwner(ownerRef.current);
3739
+ const nextState = {
3740
+ isSelecting: false,
3741
+ isFillDragging: false,
3742
+ start: position,
3743
+ end: position,
3744
+ fillAnchor: null,
3745
+ fillEnd: null
3746
+ };
3747
+ dragStateRef.current = nextState;
3748
+ setDragState(nextState);
3749
+ onCellNavigateRef.current?.(position);
3750
+ },
3751
+ [enabled, getColumnCount, rows.length]
3752
+ );
3753
+ const focusSelection = (0, import_react7.useCallback)(() => {
3754
+ if (!enabled) return;
3755
+ const prev = dragStateRef.current;
3756
+ if (prev.start && prev.end) {
3757
+ claimCellSelectionOwner(ownerRef.current);
3758
+ return;
3759
+ }
3760
+ selectCell(0, 0);
3761
+ }, [enabled, selectCell]);
3762
+ (0, import_react7.useEffect)(() => {
3763
+ if (!enabled) return;
3764
+ const handleKeyDown = (e) => {
3765
+ if (!isActiveCellSelectionOwner(ownerRef.current)) return;
3766
+ if (e.altKey) return;
3767
+ if (isEditablePasteTarget(e.target) || isEditablePasteTarget(document.activeElement)) {
3768
+ return;
3769
+ }
3770
+ if (isFocusOutsideRoot(rootRef)) return;
3771
+ const prev = dragStateRef.current;
3772
+ if (!prev.start || !prev.end) return;
3773
+ if (prev.isSelecting || prev.isFillDragging) return;
3774
+ const rowCount = rows.length;
3775
+ const resolvedColumnCount = getColumnCount();
3776
+ if (rowCount <= 0 || resolvedColumnCount <= 0) return;
3777
+ const withModifier = e.ctrlKey || e.metaKey;
3778
+ if (withModifier && !e.shiftKey && e.key.toLowerCase() === "a") {
3779
+ e.preventDefault();
3780
+ claimCellSelectionOwner(ownerRef.current);
3781
+ const nextState = {
3782
+ isSelecting: false,
3783
+ isFillDragging: false,
3784
+ start: { row: 0, col: 0 },
3785
+ end: { row: rowCount - 1, col: resolvedColumnCount - 1 },
3786
+ fillAnchor: null,
3787
+ fillEnd: null
3788
+ };
3789
+ dragStateRef.current = nextState;
3790
+ setDragState(nextState);
3791
+ return;
3792
+ }
3793
+ if (e.key === "Home" || e.key === "End") {
3794
+ e.preventDefault();
3795
+ const toEnd = e.key === "End";
3796
+ const target = withModifier ? toEnd ? { row: rowCount - 1, col: resolvedColumnCount - 1 } : { row: 0, col: 0 } : { row: prev.end.row, col: toEnd ? resolvedColumnCount - 1 : 0 };
3797
+ if (e.shiftKey) {
3798
+ const nextState = { ...prev, end: target, fillAnchor: null, fillEnd: null };
3799
+ dragStateRef.current = nextState;
3800
+ setDragState(nextState);
3801
+ onCellNavigateRef.current?.(target);
3802
+ } else {
3803
+ selectCell(target.row, target.col);
3804
+ }
3805
+ return;
3806
+ }
3807
+ if (withModifier || isInteractiveFocus()) return;
3808
+ if (e.key === "Enter" || e.key === "F2") {
3809
+ if (!onEditKeyRef.current) return;
3810
+ e.preventDefault();
3811
+ onEditKeyRef.current(prev.end);
3812
+ return;
3813
+ }
3814
+ if (e.key === "Delete" || e.key === "Backspace") {
3815
+ const bounds = getCellSelectionBounds(prev.start, prev.end);
3816
+ if (!bounds || !onClearKeyRef.current) return;
3817
+ e.preventDefault();
3818
+ onClearKeyRef.current(bounds);
3819
+ }
3820
+ };
3821
+ window.addEventListener("keydown", handleKeyDown);
3822
+ return () => window.removeEventListener("keydown", handleKeyDown);
3823
+ }, [enabled, getColumnCount, rootRef, rows.length, selectCell]);
3299
3824
  (0, import_react7.useEffect)(() => {
3300
3825
  if (!enabled) return;
3301
3826
  const handleKeyDown = (e) => {
@@ -3305,6 +3830,7 @@ function useCellSelection({
3305
3830
  return;
3306
3831
  }
3307
3832
  if (isFocusOutsideRoot(rootRef)) return;
3833
+ if (!enableWasdNavigation && e.key.length === 1) return;
3308
3834
  const delta = getCellNavigationDelta(e.key);
3309
3835
  if (!delta) return;
3310
3836
  const prev = dragStateRef.current;
@@ -3344,14 +3870,15 @@ function useCellSelection({
3344
3870
  };
3345
3871
  window.addEventListener("keydown", handleKeyDown);
3346
3872
  return () => window.removeEventListener("keydown", handleKeyDown);
3347
- }, [columnCount, enabled, rows]);
3873
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
3348
3874
  const copySelection = (0, import_react7.useCallback)(
3349
3875
  async (options) => {
3350
3876
  if (!enabled || !activeSelectionBounds) return false;
3351
3877
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
3352
3878
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
3353
3879
  registry: cellRendererRegistry,
3354
- root: rootRef?.current
3880
+ root: rootRef?.current,
3881
+ escapeFormulas: escapeCopyFormulas
3355
3882
  });
3356
3883
  },
3357
3884
  [
@@ -3359,6 +3886,7 @@ function useCellSelection({
3359
3886
  cellRendererRegistry,
3360
3887
  enableSubtreeCopy,
3361
3888
  enabled,
3889
+ escapeCopyFormulas,
3362
3890
  rootRef,
3363
3891
  rows
3364
3892
  ]
@@ -3376,6 +3904,7 @@ function useCellSelection({
3376
3904
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
3377
3905
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
3378
3906
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
3907
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
3379
3908
  e.preventDefault();
3380
3909
  void copySelection({ includeDescendants: isSubtreeShortcut });
3381
3910
  };
@@ -3391,9 +3920,17 @@ function useCellSelection({
3391
3920
  activeSelectionBounds.startCol,
3392
3921
  text,
3393
3922
  mode,
3394
- activeSelectionBounds.endRow
3923
+ activeSelectionBounds.endRow,
3924
+ // Leading blank cells are tree depth only in this table's own subtree
3925
+ // copy; from a spreadsheet they are real (empty) cells.
3926
+ { treeDepth: isOwnSubtreeCopy(text) ? "auto" : "none" }
3395
3927
  );
3396
3928
  if (!payload) return false;
3929
+ const cells = rows[activeSelectionBounds.startRow]?.getVisibleCells() ?? [];
3930
+ payload.editableColumnIds = payload.columnIds.filter((columnId) => {
3931
+ const cell = cells.find((item) => item.column.id === columnId);
3932
+ return cell ? isColumnEditable(cell.column.columnDef) : false;
3933
+ });
3397
3934
  onRowsPaste(payload);
3398
3935
  return true;
3399
3936
  },
@@ -3424,7 +3961,10 @@ function useCellSelection({
3424
3961
  void (async () => {
3425
3962
  try {
3426
3963
  const text = await navigator.clipboard.readText();
3427
- if (pasteHandledRef.current) return;
3964
+ if (pasteHandledRef.current) {
3965
+ pasteHandledRef.current = false;
3966
+ return;
3967
+ }
3428
3968
  if (pendingPasteModeRef.current !== mode) return;
3429
3969
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
3430
3970
  if (!text) return;
@@ -3449,6 +3989,7 @@ function useCellSelection({
3449
3989
  }
3450
3990
  const mode = pendingPasteModeRef.current ?? "overwrite";
3451
3991
  if (pasteHandledRef.current) {
3992
+ pasteHandledRef.current = false;
3452
3993
  e.preventDefault();
3453
3994
  return;
3454
3995
  }
@@ -3475,39 +4016,41 @@ function useCellSelection({
3475
4016
  (0, import_react7.useEffect)(() => {
3476
4017
  if (!enabled) return;
3477
4018
  const handleMouseUp = () => {
3478
- setDragState((prev) => {
3479
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
3480
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
3481
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
3482
- if (newBounds) {
3483
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
3484
- if (onBatchChange) {
3485
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
3486
- if (changes.length > 0) {
3487
- onBatchChange(changes);
3488
- }
3489
- } else if (onDataChange) {
3490
- onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
4019
+ const prev = dragStateRef.current;
4020
+ let next = prev;
4021
+ if (prev.isFillDragging && prev.fillEnd) {
4022
+ const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
4023
+ if (sourceBounds) {
4024
+ const newBounds = resolveFillBounds(sourceBounds, prev.fillEnd);
4025
+ if (hasFillExtension(sourceBounds, newBounds)) {
4026
+ if (onBatchChange) {
4027
+ const changes = collectFillChanges(rows, sourceBounds, newBounds);
4028
+ if (changes.length > 0) {
4029
+ onBatchChange(changes);
3491
4030
  }
4031
+ } else if (onDataChange) {
4032
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
3492
4033
  }
3493
- return {
3494
- isSelecting: false,
3495
- isFillDragging: false,
3496
- start: { row: newBounds.startRow, col: newBounds.startCol },
3497
- end: { row: newBounds.endRow, col: newBounds.endCol },
3498
- fillAnchor: null,
3499
- fillEnd: null
3500
- };
3501
4034
  }
4035
+ next = {
4036
+ isSelecting: false,
4037
+ isFillDragging: false,
4038
+ start: { row: newBounds.startRow, col: newBounds.startCol },
4039
+ end: { row: newBounds.endRow, col: newBounds.endCol },
4040
+ fillAnchor: null,
4041
+ fillEnd: null
4042
+ };
4043
+ } else {
4044
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
3502
4045
  }
3503
- if (prev.isSelecting) {
3504
- return { ...prev, isSelecting: false };
3505
- }
3506
- if (prev.isFillDragging) {
3507
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
3508
- }
3509
- return prev;
3510
- });
4046
+ } else if (prev.isSelecting) {
4047
+ next = { ...prev, isSelecting: false };
4048
+ } else if (prev.isFillDragging) {
4049
+ next = { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
4050
+ }
4051
+ if (next === prev) return;
4052
+ dragStateRef.current = next;
4053
+ setDragState(next);
3511
4054
  };
3512
4055
  window.addEventListener("mouseup", handleMouseUp);
3513
4056
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -3519,7 +4062,9 @@ function useCellSelection({
3519
4062
  handleCellMouseEnter,
3520
4063
  handleFillHandleMouseDown,
3521
4064
  clearSelection,
3522
- copySelection
4065
+ copySelection,
4066
+ selectCell,
4067
+ focusSelection
3523
4068
  };
3524
4069
  }
3525
4070
 
@@ -3554,8 +4099,12 @@ function handleEscape(event) {
3554
4099
  if (isOverlayDismissIgnoreTarget(event.target) || isOverlayDismissIgnoreTarget(document.activeElement)) {
3555
4100
  return;
3556
4101
  }
3557
- for (const clearAllSelections of clearAllByOwner.values()) {
3558
- clearAllSelections();
4102
+ for (const clearAllSelections of [...clearAllByOwner.values()]) {
4103
+ try {
4104
+ clearAllSelections();
4105
+ } catch (error) {
4106
+ console.error("[react-glide-table] escape-dismiss callback failed", error);
4107
+ }
3559
4108
  }
3560
4109
  }
3561
4110
  function registerEscapeDismiss(owner, clearAllSelections) {
@@ -3576,11 +4125,30 @@ function registerEscapeDismiss(owner, clearAllSelections) {
3576
4125
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
3577
4126
  var import_react8 = require("react");
3578
4127
  var EMPTY_MATCH_KEYS = /* @__PURE__ */ new Set();
4128
+ var searchInstanceCount = 0;
4129
+ var lastPointerTarget = null;
4130
+ function trackPointerTarget(event) {
4131
+ lastPointerTarget = event.target;
4132
+ }
4133
+ function registerSearchInstance() {
4134
+ if (searchInstanceCount === 0) {
4135
+ document.addEventListener("pointerdown", trackPointerTarget, true);
4136
+ }
4137
+ searchInstanceCount += 1;
4138
+ return () => {
4139
+ searchInstanceCount -= 1;
4140
+ if (searchInstanceCount === 0) {
4141
+ document.removeEventListener("pointerdown", trackPointerTarget, true);
4142
+ lastPointerTarget = null;
4143
+ }
4144
+ };
4145
+ }
3579
4146
  function useInlineSearch({
3580
4147
  enabled = false,
3581
4148
  rowCount,
3582
4149
  columnCount,
3583
4150
  getCellValue,
4151
+ contentKey,
3584
4152
  initialStartRow = 0,
3585
4153
  showSearch: controlledShowSearch,
3586
4154
  searchValue: controlledSearchValue,
@@ -3789,6 +4357,7 @@ function useInlineSearch({
3789
4357
  }
3790
4358
  beginSearch(searchValue);
3791
4359
  }, [
4360
+ contentKey,
3792
4361
  beginSearch,
3793
4362
  cancelSearch,
3794
4363
  controlledSearchResults,
@@ -3809,6 +4378,9 @@ function useInlineSearch({
3809
4378
  if (!focusInside && active !== document.body) {
3810
4379
  return;
3811
4380
  }
4381
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
4382
+ return;
4383
+ }
3812
4384
  }
3813
4385
  event.preventDefault();
3814
4386
  event.stopPropagation();
@@ -3822,7 +4394,11 @@ function useInlineSearch({
3822
4394
  }
3823
4395
  };
3824
4396
  window.addEventListener("keydown", handleKeyDown, true);
3825
- return () => window.removeEventListener("keydown", handleKeyDown, true);
4397
+ const releaseInstance = registerSearchInstance();
4398
+ return () => {
4399
+ window.removeEventListener("keydown", handleKeyDown, true);
4400
+ releaseInstance();
4401
+ };
3826
4402
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
3827
4403
  (0, import_react8.useEffect)(() => () => cancelSearch(), [cancelSearch]);
3828
4404
  const searchMatchKeys = (0, import_react8.useMemo)(
@@ -3899,7 +4475,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
3899
4475
  searchResultHint: "Type to search",
3900
4476
  searchPrevious: "Previous result",
3901
4477
  searchNext: "Next result",
3902
- searchClose: "Close search"
4478
+ searchClose: "Close search",
4479
+ searchResultCount: formatSearchResultLabel,
4480
+ protectedCell: "protected",
4481
+ paginationPrevious: "Previous page",
4482
+ paginationNext: "Next page"
3903
4483
  };
3904
4484
  function resolveDataTableLabels(partial) {
3905
4485
  return {
@@ -3909,6 +4489,9 @@ function resolveDataTableLabels(partial) {
3909
4489
  }
3910
4490
 
3911
4491
  // src/core/useGlideTable.ts
4492
+ function isProductionBuild() {
4493
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
4494
+ }
3912
4495
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
3913
4496
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
3914
4497
  function useGlideTable(options) {
@@ -3930,18 +4513,24 @@ function useGlideTable(options) {
3930
4513
  selectOnRowClick = true,
3931
4514
  enableCellSelection = true,
3932
4515
  onDataChange,
3933
- onCellChange,
3934
- onBatchChange,
4516
+ onCellChange: onCellChangeProp,
4517
+ onBatchChange: onBatchChangeProp,
3935
4518
  cellRenderers,
3936
4519
  preserveRowSelection = false,
3937
- toggleField,
3938
- childField,
3939
- flattenField,
4520
+ toggleField: toggleFieldProp,
4521
+ idField,
4522
+ childField: childFieldProp,
4523
+ parentIdField,
4524
+ flattenField: flattenFieldProp,
4525
+ childrenField,
3940
4526
  qtyField,
4527
+ expandColumn,
3941
4528
  expandedRows: controlledExpandedRows,
3942
4529
  onExpandedRowsChange,
3943
4530
  preventExpand = false,
4531
+ autoExpandOnLoad = true,
3944
4532
  enableSubtreeCopy,
4533
+ escapeCopyFormulas = false,
3945
4534
  onCopyActionsReady,
3946
4535
  onRowsPaste,
3947
4536
  enableInsertPaste,
@@ -3962,8 +4551,27 @@ function useGlideTable(options) {
3962
4551
  onSearchValueChange,
3963
4552
  onSearchClose,
3964
4553
  searchResults,
3965
- onSearchResultsChanged
4554
+ onSearchResultsChanged,
4555
+ enableWasdNavigation = true
3966
4556
  } = options;
4557
+ const toggleField = toggleFieldProp ?? idField;
4558
+ const childField = childFieldProp ?? parentIdField;
4559
+ const flattenField = flattenFieldProp ?? childrenField;
4560
+ const onCellChange = (0, import_react9.useMemo)(() => {
4561
+ if (onCellChangeProp) return onCellChangeProp;
4562
+ if (!onBatchChangeProp) return void 0;
4563
+ return (rowId, columnId, value) => onBatchChangeProp([{ rowId, columnId, value }]);
4564
+ }, [onBatchChangeProp, onCellChangeProp]);
4565
+ const onBatchChange = (0, import_react9.useMemo)(() => {
4566
+ if (onBatchChangeProp) return onBatchChangeProp;
4567
+ if (!onCellChangeProp) return void 0;
4568
+ return (changes) => {
4569
+ for (const change of changes) {
4570
+ onCellChangeProp(change.rowId, change.columnId, change.value);
4571
+ }
4572
+ };
4573
+ }, [onBatchChangeProp, onCellChangeProp]);
4574
+ const hasWriteCallback = Boolean(onCellChange || onBatchChange || onDataChange);
3967
4575
  const labels = (0, import_react9.useMemo)(() => {
3968
4576
  const resolved = resolveDataTableLabels(labelsProp);
3969
4577
  return {
@@ -3981,7 +4589,7 @@ function useGlideTable(options) {
3981
4589
  const [internalExpandedRows, setInternalExpandedRows] = (0, import_react9.useState)(
3982
4590
  () => /* @__PURE__ */ new Set()
3983
4591
  );
3984
- const [hoveredRowIndex, setHoveredRowIndex] = (0, import_react9.useState)(null);
4592
+ const [hoverStore] = (0, import_react9.useState)(createRowHoverStore);
3985
4593
  const scrollRef = (0, import_react9.useRef)(null);
3986
4594
  const rootRef = (0, import_react9.useRef)(null);
3987
4595
  const escapeDismissOwnerRef = (0, import_react9.useRef)(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
@@ -4038,8 +4646,10 @@ function useGlideTable(options) {
4038
4646
  qtyField,
4039
4647
  expandedRows,
4040
4648
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
4041
- preventExpand
4649
+ preventExpand,
4650
+ autoExpandOnLoad
4042
4651
  });
4652
+ const sourceData = (0, import_react9.useMemo)(() => data ?? [], [data]);
4043
4653
  const table = (0, import_react_table2.useReactTable)({
4044
4654
  data: tableData,
4045
4655
  columns: tableColumns,
@@ -4078,7 +4688,11 @@ function useGlideTable(options) {
4078
4688
  );
4079
4689
  },
4080
4690
  getCoreRowModel: (0, import_react_table2.getCoreRowModel)(),
4081
- getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (_originalRow, index) => String(index)
4691
+ getRowId: getRowId ? (originalRow, index) => getRowId(originalRow, index) : (
4692
+ // Tree rows: their path in the original data, which (unlike the
4693
+ // flattened index) survives expanding/collapsing rows above.
4694
+ (originalRow, index) => getTreeRowKey(originalRow) ?? String(index)
4695
+ )
4082
4696
  });
4083
4697
  const rowSpanColumnKeys = (0, import_react9.useMemo)(() => {
4084
4698
  if (!enableRowSpan) return [];
@@ -4095,6 +4709,20 @@ function useGlideTable(options) {
4095
4709
  const rows = table.getRowModel().rows;
4096
4710
  const columnCount = table.getAllLeafColumns().length || 1;
4097
4711
  const visibleLeafColumns = table.getVisibleLeafColumns();
4712
+ const canFill = enableCellSelection && hasWriteCallback && visibleLeafColumns.some((column) => isColumnEditable(column.columnDef));
4713
+ const warnedBooleanColumnsRef = (0, import_react9.useRef)(/* @__PURE__ */ new Set());
4714
+ (0, import_react9.useEffect)(() => {
4715
+ if (!hasWriteCallback || isProductionBuild()) return;
4716
+ for (const column of visibleLeafColumns) {
4717
+ const meta = column.columnDef.meta;
4718
+ if (meta?.kind !== "boolean" || meta.editable !== void 0 || meta.cellRender) continue;
4719
+ if (warnedBooleanColumnsRef.current.has(column.id)) continue;
4720
+ warnedBooleanColumnsRef.current.add(column.id);
4721
+ console.warn(
4722
+ `[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.`
4723
+ );
4724
+ }
4725
+ }, [hasWriteCallback, visibleLeafColumns]);
4098
4726
  const columnFreezeOffsets = (0, import_react9.useMemo)(() => {
4099
4727
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
4100
4728
  return buildColumnFreezeOffsets(
@@ -4137,7 +4765,7 @@ function useGlideTable(options) {
4137
4765
  const cell = scrollElement.querySelector(
4138
4766
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
4139
4767
  );
4140
- if (cell instanceof HTMLElement) {
4768
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
4141
4769
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
4142
4770
  }
4143
4771
  };
@@ -4155,6 +4783,10 @@ function useGlideTable(options) {
4155
4783
  },
4156
4784
  [scrollCellIntoView]
4157
4785
  );
4786
+ const editKeyRef = (0, import_react9.useRef)(() => {
4787
+ });
4788
+ const clearKeyRef = (0, import_react9.useRef)(() => {
4789
+ });
4158
4790
  const {
4159
4791
  dragState,
4160
4792
  activeSelectionBounds,
@@ -4162,20 +4794,27 @@ function useGlideTable(options) {
4162
4794
  handleCellMouseEnter,
4163
4795
  handleFillHandleMouseDown,
4164
4796
  clearSelection: clearCellSelection,
4165
- copySelection
4797
+ copySelection,
4798
+ selectCell,
4799
+ focusSelection
4166
4800
  } = useCellSelection({
4167
- data: tableData,
4801
+ data: sourceData,
4168
4802
  rows,
4169
4803
  enabled: enableCellSelection,
4170
4804
  columnCount: visibleLeafColumns.length,
4805
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
4171
4806
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
4807
+ escapeCopyFormulas,
4172
4808
  enableInsertPaste: enableInsertPaste ?? true,
4173
4809
  onDataChange,
4174
4810
  onBatchChange,
4175
4811
  onRowsPaste,
4176
4812
  onCellNavigate: handleCellNavigate,
4177
4813
  cellRendererRegistry,
4178
- rootRef
4814
+ rootRef,
4815
+ enableWasdNavigation,
4816
+ onEditKey: (position) => editKeyRef.current(position),
4817
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
4179
4818
  });
4180
4819
  const clearRowSelection = (0, import_react9.useCallback)(() => {
4181
4820
  if (rowSelectionMode === "none") return;
@@ -4196,22 +4835,79 @@ function useGlideTable(options) {
4196
4835
  const {
4197
4836
  editingCell,
4198
4837
  draftValue,
4838
+ draftInvalid,
4839
+ setDraftInvalid,
4199
4840
  setDraftValue,
4200
4841
  startEdit,
4201
4842
  commitEdit,
4202
4843
  cancelEdit
4203
- } = useCellEdit({ data: tableData, rows, onDataChange, onCellChange });
4844
+ } = useCellEdit({ data: sourceData, rows, onDataChange, onCellChange });
4845
+ editKeyRef.current = (position) => {
4846
+ startEdit(position.row, position.col);
4847
+ };
4848
+ clearKeyRef.current = (bounds) => {
4849
+ const changes = [];
4850
+ for (let rowIndex = bounds.startRow; rowIndex <= bounds.endRow; rowIndex += 1) {
4851
+ const row = rows[rowIndex];
4852
+ if (!row) continue;
4853
+ const cells = row.getVisibleCells();
4854
+ for (let colIndex = bounds.startCol; colIndex <= bounds.endCol; colIndex += 1) {
4855
+ const cell = cells[colIndex];
4856
+ if (!cell || !isColumnEditable(cell.column.columnDef)) continue;
4857
+ changes.push({ rowId: row.id, columnId: cell.column.id, value: null });
4858
+ }
4859
+ }
4860
+ if (changes.length === 0) return;
4861
+ if (onBatchChange) {
4862
+ onBatchChange(changes);
4863
+ return;
4864
+ }
4865
+ if (!onDataChange) return;
4866
+ let next = sourceData;
4867
+ for (const change of changes) {
4868
+ const row = rows.find((item) => item.id === change.rowId);
4869
+ const cell = row?.getVisibleCells().find((item) => item.column.id === change.columnId);
4870
+ const accessorKey = cell ? getColumnAccessorKey(cell.column.columnDef) : void 0;
4871
+ if (!row || !accessorKey) continue;
4872
+ next = applyCellChangesToData(next, [
4873
+ { original: row.original, index: row.index, accessorKey, value: null }
4874
+ ]);
4875
+ }
4876
+ if (next !== sourceData) onDataChange(next);
4877
+ };
4878
+ const commitEditAndMove = (0, import_react9.useCallback)(
4879
+ (raw, delta) => {
4880
+ const current = editingCell;
4881
+ if (!commitEdit(raw)) return false;
4882
+ if (current) {
4883
+ selectCell(current.rowIndex + delta.row, current.colIndex + delta.col);
4884
+ }
4885
+ rootRef.current?.focus({ preventScroll: true });
4886
+ return true;
4887
+ },
4888
+ [commitEdit, editingCell, selectCell]
4889
+ );
4890
+ const cancelEditAndRefocus = (0, import_react9.useCallback)(() => {
4891
+ cancelEdit();
4892
+ rootRef.current?.focus({ preventScroll: true });
4893
+ }, [cancelEdit]);
4204
4894
  const commitRenderedCellValue = (0, import_react9.useCallback)(
4205
- (rowId, columnId, value) => commitCellValue({
4206
- data: tableData,
4207
- rows,
4208
- rowId,
4209
- columnId,
4210
- value,
4211
- onCellChange,
4212
- onDataChange
4213
- }),
4214
- [onCellChange, onDataChange, rows, tableData]
4895
+ (rowId, columnId, value) => {
4896
+ const columnDef = table.getColumn(columnId)?.columnDef;
4897
+ if (columnDef && (columnDef.meta?.editable === false || isProtectedColumn(columnDef))) {
4898
+ return false;
4899
+ }
4900
+ return commitCellValue({
4901
+ data: sourceData,
4902
+ rows,
4903
+ rowId,
4904
+ columnId,
4905
+ value,
4906
+ onCellChange,
4907
+ onDataChange
4908
+ });
4909
+ },
4910
+ [onCellChange, onDataChange, rows, sourceData, table]
4215
4911
  );
4216
4912
  const getCellContext = (0, import_react9.useCallback)(
4217
4913
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -4239,25 +4935,12 @@ function useGlideTable(options) {
4239
4935
  (row, index) => {
4240
4936
  if (getRowId) return getRowId(row, index);
4241
4937
  if (enableExpand) {
4242
- const record = row;
4243
- const idValue = record.id;
4244
- if (idValue != null && String(idValue).length > 0) {
4245
- return String(idValue);
4246
- }
4247
- const uniqueId = record.uniqueId;
4248
- if (uniqueId != null && String(uniqueId).length > 0) {
4249
- return String(uniqueId);
4250
- }
4251
- if (toggleField) {
4252
- const toggleValue = record[toggleField];
4253
- if (toggleValue != null && String(toggleValue).length > 0) {
4254
- return String(toggleValue);
4255
- }
4256
- }
4938
+ const treeKey = getTreeRowKey(row);
4939
+ if (treeKey) return treeKey;
4257
4940
  }
4258
4941
  return String(index);
4259
4942
  },
4260
- [enableExpand, getRowId, toggleField]
4943
+ [enableExpand, getRowId]
4261
4944
  );
4262
4945
  const searchCorpus = (0, import_react9.useMemo)(() => {
4263
4946
  if (!enableInlineSearch) return [];
@@ -4284,28 +4967,59 @@ function useGlideTable(options) {
4284
4967
  }
4285
4968
  return map;
4286
4969
  }, [resolveSearchRowId, rows]);
4287
- const getSearchCellValue = (0, import_react9.useCallback)(
4288
- (rowIndex, colIndex) => {
4289
- const corpusRow = searchCorpusRef.current[rowIndex];
4290
- const column = visibleLeafColumns[colIndex];
4291
- if (!corpusRow || !column) return void 0;
4970
+ const readSearchRawValue = (0, import_react9.useCallback)(
4971
+ (corpusRow, rowIndex, column) => {
4292
4972
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
4293
4973
  if (visibleIndex !== void 0) {
4294
4974
  const visibleRow = rows[visibleIndex];
4295
4975
  if (visibleRow) {
4296
- return visibleRow.getValue(column.id);
4976
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
4297
4977
  }
4298
4978
  }
4299
4979
  const columnDef = column.columnDef;
4300
4980
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
4301
- return columnDef.accessorFn(corpusRow.data, rowIndex);
4981
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
4302
4982
  }
4303
4983
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
4304
- return corpusRow.data[String(columnDef.accessorKey)];
4984
+ return {
4985
+ value: corpusRow.data[String(columnDef.accessorKey)],
4986
+ row: void 0
4987
+ };
4988
+ }
4989
+ return { value: corpusRow.data[column.id], row: void 0 };
4990
+ },
4991
+ [rows, visibleRowIndexById]
4992
+ );
4993
+ const getSearchCellValue = (0, import_react9.useCallback)(
4994
+ (rowIndex, colIndex) => {
4995
+ const corpusRow = searchCorpusRef.current[rowIndex];
4996
+ const column = visibleLeafColumns[colIndex];
4997
+ if (!corpusRow || !column) return void 0;
4998
+ if (isProtectedColumn(column.columnDef)) return void 0;
4999
+ const { value, row } = readSearchRawValue(corpusRow, rowIndex, column);
5000
+ const meta = column.columnDef.meta;
5001
+ const searchValue2 = meta?.searchValue;
5002
+ if (!searchValue2 || searchValue2 === "value") return value;
5003
+ const ctx = {
5004
+ value,
5005
+ row: row ?? { id: corpusRow.id, index: rowIndex, original: corpusRow.data },
5006
+ index: row?.index ?? rowIndex,
5007
+ columnId: column.id,
5008
+ cellProps: meta?.cellProps,
5009
+ update: () => {
5010
+ }
5011
+ };
5012
+ try {
5013
+ if (typeof searchValue2 === "function") return searchValue2(ctx);
5014
+ if (meta?.cellRender) return reactNodeToText(meta.cellRender(ctx));
5015
+ const renderer = resolveCellRenderer(cellRendererRegistry, meta?.kind, ctx);
5016
+ if (renderer) return reactNodeToText(renderer.render(ctx));
5017
+ } catch {
5018
+ return value;
4305
5019
  }
4306
- return corpusRow.data[column.id];
5020
+ return value;
4307
5021
  },
4308
- [rows, visibleLeafColumns, visibleRowIndexById]
5022
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
4309
5023
  );
4310
5024
  const pendingSearchNavRef = (0, import_react9.useRef)(null);
4311
5025
  const focusSearchResult = (0, import_react9.useCallback)(
@@ -4356,11 +5070,19 @@ function useGlideTable(options) {
4356
5070
  focusSearchResult(pending.colIndex, visibleRowIndex);
4357
5071
  }, [focusSearchResult, rows, visibleRowIndexById]);
4358
5072
  const initialSearchStartRow = virtualRows[0]?.index ?? 0;
5073
+ const searchColumnSignature = visibleLeafColumns.map((column) => column.id).join("\0");
5074
+ const searchContentKey = (0, import_react9.useMemo)(
5075
+ () => ({ data: sourceData, columns: searchColumnSignature }),
5076
+ [sourceData, searchColumnSignature]
5077
+ );
4359
5078
  const inlineSearch = useInlineSearch({
4360
5079
  enabled: enableInlineSearch,
4361
5080
  rowCount: searchCorpus.length,
4362
5081
  columnCount: visibleLeafColumns.length,
4363
5082
  getCellValue: getSearchCellValue,
5083
+ // Re-scan when the rows' content/order or the column order changes
5084
+ // (edits, re-sorts, reorders) — not on tree expand/collapse.
5085
+ contentKey: searchContentKey,
4364
5086
  initialStartRow: initialSearchStartRow,
4365
5087
  showSearch,
4366
5088
  searchValue,
@@ -4398,11 +5120,14 @@ function useGlideTable(options) {
4398
5120
  visibleRowIndexById
4399
5121
  ]);
4400
5122
  const clearHover = (0, import_react9.useCallback)(() => {
4401
- setHoveredRowIndex(null);
4402
- }, []);
4403
- const handleRowHover = (0, import_react9.useCallback)((rowIndex, _rowData) => {
4404
- setHoveredRowIndex(rowIndex);
4405
- }, []);
5123
+ hoverStore.setHoveredRowIndex(null);
5124
+ }, [hoverStore]);
5125
+ const handleRowHover = (0, import_react9.useCallback)(
5126
+ (rowIndex, _rowData) => {
5127
+ hoverStore.setHoveredRowIndex(rowIndex);
5128
+ },
5129
+ [hoverStore]
5130
+ );
4406
5131
  const handleToggleSelect = (0, import_react9.useCallback)(
4407
5132
  (row) => {
4408
5133
  if (!row.getCanSelect()) return;
@@ -4427,7 +5152,7 @@ function useGlideTable(options) {
4427
5152
  primaryRowSpanKey,
4428
5153
  primaryRowSpanColumnId,
4429
5154
  columnRowSpanMap,
4430
- hoveredRowIndex,
5155
+ hoverStore,
4431
5156
  selectedRowIndices,
4432
5157
  onRowHover: handleRowHover
4433
5158
  },
@@ -4441,6 +5166,7 @@ function useGlideTable(options) {
4441
5166
  enableCellSelection,
4442
5167
  activeSelectionBounds,
4443
5168
  dragState,
5169
+ canFill,
4444
5170
  onCellMouseDown: handleCellMouseDownWithCommit,
4445
5171
  onCellMouseEnter: handleCellMouseEnter,
4446
5172
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -4448,18 +5174,23 @@ function useGlideTable(options) {
4448
5174
  cellEdit: {
4449
5175
  editingCell,
4450
5176
  draftValue,
5177
+ draftInvalid,
5178
+ onDraftInvalidChange: setDraftInvalid,
4451
5179
  onDraftValueChange: setDraftValue,
4452
5180
  onStartEdit: startEdit,
4453
5181
  onCommitEdit: commitEdit,
4454
- onCancelEdit: cancelEdit
5182
+ onCommitEditAndMove: commitEditAndMove,
5183
+ onCancelEdit: cancelEditAndRefocus
4455
5184
  },
4456
5185
  cellRender: {
4457
5186
  registry: cellRendererRegistry,
4458
- commitValue: commitRenderedCellValue
5187
+ commitValue: commitRenderedCellValue,
5188
+ protectedLabel: labels.protectedCell
4459
5189
  },
4460
5190
  expand: {
4461
5191
  enableExpand,
4462
5192
  toggleField,
5193
+ expandColumn,
4463
5194
  expandedRows,
4464
5195
  preventExpand,
4465
5196
  onToggleExpand: handleToggleExpand,
@@ -4484,7 +5215,7 @@ function useGlideTable(options) {
4484
5215
  primaryRowSpanKey,
4485
5216
  primaryRowSpanColumnId,
4486
5217
  columnRowSpanMap,
4487
- hoveredRowIndex,
5218
+ hoverStore,
4488
5219
  selectedRowIndices,
4489
5220
  handleRowHover,
4490
5221
  rowSelectionMode,
@@ -4494,19 +5225,25 @@ function useGlideTable(options) {
4494
5225
  enableCellSelection,
4495
5226
  activeSelectionBounds,
4496
5227
  dragState,
5228
+ canFill,
4497
5229
  handleCellMouseDownWithCommit,
4498
5230
  handleCellMouseEnter,
4499
5231
  handleFillHandleMouseDown,
4500
5232
  editingCell,
4501
5233
  draftValue,
5234
+ draftInvalid,
5235
+ setDraftInvalid,
4502
5236
  setDraftValue,
4503
5237
  startEdit,
4504
5238
  commitEdit,
4505
- cancelEdit,
5239
+ commitEditAndMove,
5240
+ cancelEditAndRefocus,
4506
5241
  cellRendererRegistry,
4507
5242
  commitRenderedCellValue,
5243
+ labels.protectedCell,
4508
5244
  enableExpand,
4509
5245
  toggleField,
5246
+ expandColumn,
4510
5247
  expandedRows,
4511
5248
  preventExpand,
4512
5249
  handleToggleExpand,
@@ -4554,6 +5291,7 @@ function useGlideTable(options) {
4554
5291
  handleToggleSelect,
4555
5292
  clearHover,
4556
5293
  setColumnOrder,
5294
+ handleRootFocus: focusSelection,
4557
5295
  copySelection: stableCopySelection,
4558
5296
  inlineSearch: {
4559
5297
  showSearch: inlineSearch.showSearch,
@@ -4651,7 +5389,8 @@ function DataTable({
4651
5389
  handleToggleSelect,
4652
5390
  clearHover,
4653
5391
  setColumnOrder,
4654
- inlineSearch
5392
+ inlineSearch,
5393
+ handleRootFocus
4655
5394
  } = useGlideTable(glideOptions);
4656
5395
  const ToolbarSlot = slots?.Toolbar ?? DataTableToolbar;
4657
5396
  const ScrollSlot = slots?.Scroll ?? DefaultScroll;
@@ -4695,13 +5434,33 @@ function DataTable({
4695
5434
  }));
4696
5435
  return resolveColumnLayoutWidths(containerWidth, columns);
4697
5436
  }, [enableColumnResize, containerWidth, table, columnLayoutMetaSignature]);
5437
+ const [measuredWidths, setMeasuredWidths] = (0, import_react10.useState)(
5438
+ () => /* @__PURE__ */ new Map()
5439
+ );
5440
+ (0, import_react10.useLayoutEffect)(() => {
5441
+ if (!enableColumnFreeze || enableColumnResize) return;
5442
+ const element = scrollRef.current;
5443
+ if (!element) return;
5444
+ const next = /* @__PURE__ */ new Map();
5445
+ element.querySelectorAll("th[data-leaf-column-id]").forEach((th) => {
5446
+ const id = th.getAttribute("data-leaf-column-id");
5447
+ const width = th.getBoundingClientRect().width;
5448
+ if (id && width > 0) next.set(id, width);
5449
+ });
5450
+ setMeasuredWidths((previous) => {
5451
+ if (previous.size === next.size && [...next].every(([id, width]) => previous.get(id) === width)) {
5452
+ return previous;
5453
+ }
5454
+ return next;
5455
+ });
5456
+ });
4698
5457
  const freezeOffsets = (0, import_react10.useMemo)(() => {
4699
5458
  if (!enableColumnFreeze || enableColumnResize || !layoutWidths) {
4700
5459
  return rowContextValue.columnFreeze.offsets;
4701
5460
  }
4702
5461
  const columns = table.getVisibleLeafColumns().map((column) => ({
4703
5462
  id: column.id,
4704
- size: layoutWidths.get(column.id) ?? column.getSize(),
5463
+ size: measuredWidths.get(column.id) ?? layoutWidths.get(column.id) ?? column.getSize(),
4705
5464
  side: resolveColumnFreezeSide(column.columnDef.meta?.frozen)
4706
5465
  }));
4707
5466
  return buildColumnFreezeOffsets(columns);
@@ -4709,6 +5468,7 @@ function DataTable({
4709
5468
  enableColumnFreeze,
4710
5469
  enableColumnResize,
4711
5470
  layoutWidths,
5471
+ measuredWidths,
4712
5472
  rowContextValue.columnFreeze.offsets,
4713
5473
  table
4714
5474
  ]);
@@ -4741,6 +5501,10 @@ function DataTable({
4741
5501
  "div",
4742
5502
  {
4743
5503
  ref: rootRef,
5504
+ tabIndex: enableCellSelection ? 0 : void 0,
5505
+ onFocus: enableCellSelection ? (event) => {
5506
+ if (event.target === event.currentTarget) handleRootFocus();
5507
+ } : void 0,
4744
5508
  className: cn(
4745
5509
  "DataTableJSX",
4746
5510
  !enableCellSelection && "DataTableJSX--no-cell-selection",
@@ -4761,6 +5525,7 @@ function DataTable({
4761
5525
  summary,
4762
5526
  selectedCount,
4763
5527
  selectionLabel,
5528
+ countLabel: labels.count,
4764
5529
  toolbar,
4765
5530
  classNames
4766
5531
  }
@@ -4779,6 +5544,7 @@ function DataTable({
4779
5544
  previousLabel: labels.searchPrevious,
4780
5545
  nextLabel: labels.searchNext,
4781
5546
  closeLabel: labels.searchClose,
5547
+ formatResult: labels.searchResultCount,
4782
5548
  rowsTotal: inlineSearch.searchRowCount,
4783
5549
  classNames,
4784
5550
  onSearchValueChange: inlineSearch.setSearchValue,
@@ -4828,6 +5594,8 @@ function DataTable({
4828
5594
  (leafColumn) => isColumnReorderable(leafColumn.columnDef.meta)
4829
5595
  );
4830
5596
  const isDragging = draggingColumnId === header.column.id;
5597
+ const sortDirection = isPlaceholder ? void 0 : header.column.columnDef.meta?.sortDirection;
5598
+ const ariaSort = sortDirection === void 0 ? void 0 : sortDirection === "asc" ? "ascending" : sortDirection === "desc" ? "descending" : "none";
4831
5599
  const dropEdge = !isPlaceholder && dropTarget?.columnId === header.column.id ? dropTarget.edge : void 0;
4832
5600
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
4833
5601
  "th",
@@ -4843,7 +5611,8 @@ function DataTable({
4843
5611
  "data-resizing": header.column.getIsResizing() ? "" : void 0,
4844
5612
  "data-frozen": freezeOffset?.side,
4845
5613
  "data-freeze-edge": getColumnFreezeEdgeAttr(freezeOffset),
4846
- "aria-grabbed": isDragging ? true : void 0,
5614
+ "data-leaf-column-id": isLeafHeader ? header.column.id : void 0,
5615
+ "aria-sort": ariaSort,
4847
5616
  title: canDrag ? labels.reorderColumn : void 0,
4848
5617
  onPointerDown: enableColumnReorder ? (event) => onHeaderPointerDown(event, {
4849
5618
  columnId: header.column.id,
@@ -4870,7 +5639,31 @@ function DataTable({
4870
5639
  role: "separator",
4871
5640
  "aria-orientation": "vertical",
4872
5641
  "aria-label": labels.resizeColumn,
5642
+ "aria-valuenow": header.getSize(),
5643
+ tabIndex: 0,
4873
5644
  "data-table-disable-cell-selection": "",
5645
+ onKeyDown: (event) => {
5646
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {
5647
+ return;
5648
+ }
5649
+ event.preventDefault();
5650
+ event.stopPropagation();
5651
+ const step = event.shiftKey ? 50 : 10;
5652
+ const columnDef = header.column.columnDef;
5653
+ const min = columnDef.minSize ?? DATA_TABLE_COLUMN_MIN_SIZE;
5654
+ const max = columnDef.maxSize ?? DATA_TABLE_COLUMN_MAX_SIZE;
5655
+ const nextSize = Math.min(
5656
+ max,
5657
+ Math.max(
5658
+ min,
5659
+ header.getSize() + (event.key === "ArrowRight" ? step : -step)
5660
+ )
5661
+ );
5662
+ table.setColumnSizing((previous) => ({
5663
+ ...previous,
5664
+ [header.column.id]: nextSize
5665
+ }));
5666
+ },
4874
5667
  className: cn(
4875
5668
  "data-table-resize-handle",
4876
5669
  classNames?.resizeHandle
@@ -4978,7 +5771,10 @@ function DataTable({
4978
5771
  }
4979
5772
 
4980
5773
  // src/components/ui/table/components/Table/Table.tsx
4981
- var import_react14 = require("react");
5774
+ var import_react15 = require("react");
5775
+
5776
+ // src/components/ui/table/components/Table/buildColumnDef.tsx
5777
+ var import_react12 = require("react");
4982
5778
 
4983
5779
  // src/components/ui/table/features/cell-render/ResolvedTableCell.tsx
4984
5780
  var import_react11 = require("react");
@@ -4996,12 +5792,16 @@ function ResolvedTableCell({
4996
5792
  },
4997
5793
  [cellRender, columnId, row.id]
4998
5794
  );
5795
+ let cellProps = meta?.editable === false ? { ...meta.cellProps, readonly: true } : meta?.cellProps;
5796
+ if (meta?.kind === "protected" && cellRender.protectedLabel && cellProps?.ariaLabel === void 0) {
5797
+ cellProps = { ...cellProps, ariaLabel: cellRender.protectedLabel };
5798
+ }
4999
5799
  const ctx = {
5000
5800
  value,
5001
5801
  row,
5002
5802
  index: row.index,
5003
5803
  columnId,
5004
- cellProps: meta?.cellProps,
5804
+ cellProps,
5005
5805
  update
5006
5806
  };
5007
5807
  if (meta?.cellRender) {
@@ -5016,12 +5816,16 @@ function ResolvedTableCell({
5016
5816
 
5017
5817
  // src/components/ui/table/components/Table/buildColumnDef.tsx
5018
5818
  var import_jsx_runtime8 = require("react/jsx-runtime");
5819
+ var TableSortContext = (0, import_react12.createContext)(null);
5019
5820
  function SortableHeader({
5020
5821
  label,
5021
5822
  field,
5022
- sort,
5023
- onSort
5823
+ sort: sortProp,
5824
+ onSort: onSortProp
5024
5825
  }) {
5826
+ const context = (0, import_react12.use)(TableSortContext);
5827
+ const sort = context ? context.sort : sortProp;
5828
+ const onSort = context ? context.onSort : onSortProp;
5025
5829
  const isActive = sort?.field === field;
5026
5830
  const Icon = isActive ? sort.direction === "asc" ? ArrowUp : ArrowDown : ArrowUpDown;
5027
5831
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
@@ -5040,7 +5844,7 @@ function SortableHeader({
5040
5844
  }
5041
5845
  );
5042
5846
  }
5043
- function buildColumnDef(props, sort, onSort) {
5847
+ function buildColumnDef(props, sort, onSort, headerCache) {
5044
5848
  const {
5045
5849
  field,
5046
5850
  virtual = false,
@@ -5066,8 +5870,29 @@ function buildColumnDef(props, sort, onSort) {
5066
5870
  className,
5067
5871
  headerClassName,
5068
5872
  render,
5069
- copyValue
5873
+ copyValue,
5874
+ searchValue
5070
5875
  } = props;
5876
+ const createHeader = () => sortable ? () => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5877
+ SortableHeader,
5878
+ {
5879
+ label: children,
5880
+ field,
5881
+ sort,
5882
+ onSort
5883
+ }
5884
+ ) : (
5885
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
5886
+ () => children
5887
+ );
5888
+ const cached = headerCache?.get(field);
5889
+ let header;
5890
+ if (cached && cached.label === children && cached.sortable === sortable) {
5891
+ header = cached.render;
5892
+ } else {
5893
+ header = createHeader();
5894
+ headerCache?.set(field, { label: children, sortable, render: header });
5895
+ }
5071
5896
  return {
5072
5897
  id: field,
5073
5898
  ...!virtual ? { accessorKey: field } : {},
@@ -5075,18 +5900,7 @@ function buildColumnDef(props, sort, onSort) {
5075
5900
  ...minResizeWidth != null ? { minSize: minResizeWidth } : {},
5076
5901
  ...maxResizeWidth != null ? { maxSize: maxResizeWidth } : {},
5077
5902
  ...resizable === false ? { enableResizing: false } : {},
5078
- header: sortable ? () => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5079
- SortableHeader,
5080
- {
5081
- label: children,
5082
- field,
5083
- sort,
5084
- onSort
5085
- }
5086
- ) : (
5087
- // eslint-disable-next-line @typescript-eslint/promise-function-async
5088
- () => children
5089
- ),
5903
+ header,
5090
5904
  // eslint-disable-next-line @typescript-eslint/promise-function-async
5091
5905
  cell: (info) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(ResolvedTableCell, { info }),
5092
5906
  meta: {
@@ -5101,6 +5915,8 @@ function buildColumnDef(props, sort, onSort) {
5101
5915
  cellProps,
5102
5916
  cellRender: render,
5103
5917
  copyValue,
5918
+ searchValue,
5919
+ sortDirection: sortable ? sort?.field === field ? sort.direction : false : void 0,
5104
5920
  frozen,
5105
5921
  reorderable,
5106
5922
  width,
@@ -5118,12 +5934,12 @@ function resolveGroupId(props, index) {
5118
5934
  }
5119
5935
  return `group:${index}`;
5120
5936
  }
5121
- function buildColumnDefsFromTree(nodes, sort, onSort) {
5937
+ function buildColumnDefsFromTree(nodes, sort, onSort, headerCache) {
5122
5938
  return nodes.map((node, index) => {
5123
5939
  if (node.type === "leaf") {
5124
- return buildColumnDef(node.props, sort, onSort);
5940
+ return buildColumnDef(node.props, sort, onSort, headerCache);
5125
5941
  }
5126
- const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort);
5942
+ const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort, headerCache);
5127
5943
  const { header, align, headerClassName } = node.props;
5128
5944
  return {
5129
5945
  id: resolveGroupId(node.props, index),
@@ -5151,10 +5967,10 @@ function countLeafColumns(nodes) {
5151
5967
  }
5152
5968
 
5153
5969
  // src/components/ui/table/components/Table/parseTableChildren.ts
5154
- var import_react13 = require("react");
5970
+ var import_react14 = require("react");
5155
5971
 
5156
5972
  // src/components/ui/table/components/Table/tableChildTypes.ts
5157
- var import_react12 = require("react");
5973
+ var import_react13 = require("react");
5158
5974
  var TABLE_HEADER_DISPLAY_NAME = "Table.Header";
5159
5975
  var TABLE_BODY_DISPLAY_NAME = "Table.Body";
5160
5976
  var TABLE_COLUMN_DISPLAY_NAME = "Table.Column";
@@ -5167,19 +5983,19 @@ function getComponentDisplayName(type) {
5167
5983
  return void 0;
5168
5984
  }
5169
5985
  function isTableHeaderElement(child) {
5170
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_HEADER_DISPLAY_NAME;
5986
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_HEADER_DISPLAY_NAME;
5171
5987
  }
5172
5988
  function isTableBodyElement(child) {
5173
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_BODY_DISPLAY_NAME;
5989
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_BODY_DISPLAY_NAME;
5174
5990
  }
5175
5991
  function isTableColumnElement(child) {
5176
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_DISPLAY_NAME;
5992
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_DISPLAY_NAME;
5177
5993
  }
5178
5994
  function isTableColumnGroupElement(child) {
5179
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_GROUP_DISPLAY_NAME;
5995
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_COLUMN_GROUP_DISPLAY_NAME;
5180
5996
  }
5181
5997
  function isTablePaginationElement(child) {
5182
- return (0, import_react12.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_PAGINATION_DISPLAY_NAME;
5998
+ return (0, import_react13.isValidElement)(child) && getComponentDisplayName(child.type) === TABLE_PAGINATION_DISPLAY_NAME;
5183
5999
  }
5184
6000
 
5185
6001
  // src/components/ui/table/components/Table/parseTableChildren.ts
@@ -5189,7 +6005,7 @@ function parseTableChildren(children) {
5189
6005
  body: null,
5190
6006
  pagination: null
5191
6007
  };
5192
- for (const child of import_react13.Children.toArray(children)) {
6008
+ for (const child of import_react14.Children.toArray(children)) {
5193
6009
  if (isTableHeaderElement(child)) {
5194
6010
  slots.header = child;
5195
6011
  continue;
@@ -5206,7 +6022,7 @@ function parseTableChildren(children) {
5206
6022
  }
5207
6023
  function walkColumnTreeNodes(children) {
5208
6024
  const result = [];
5209
- for (const child of import_react13.Children.toArray(children)) {
6025
+ for (const child of import_react14.Children.toArray(children)) {
5210
6026
  if (isTableColumnElement(child)) {
5211
6027
  result.push({
5212
6028
  type: "leaf",
@@ -5223,7 +6039,7 @@ function walkColumnTreeNodes(children) {
5223
6039
  });
5224
6040
  continue;
5225
6041
  }
5226
- if ((0, import_react13.isValidElement)(child)) {
6042
+ if ((0, import_react14.isValidElement)(child)) {
5227
6043
  const nested = child.props.children;
5228
6044
  if (nested != null) {
5229
6045
  result.push(...walkColumnTreeNodes(nested));
@@ -5259,13 +6075,22 @@ function TableColumnGroup(props) {
5259
6075
  TableColumnGroup.displayName = TABLE_COLUMN_GROUP_DISPLAY_NAME;
5260
6076
 
5261
6077
  // src/components/ui/table/components/Table/tableDataPipeline.ts
5262
- function sortTableData(data, sort) {
6078
+ function readField(row, field) {
6079
+ if (field in row || !field.includes(".")) return row[field];
6080
+ return field.split(".").reduce((current, key) => {
6081
+ if (current === null || current === void 0 || typeof current !== "object") {
6082
+ return void 0;
6083
+ }
6084
+ return current[key];
6085
+ }, row);
6086
+ }
6087
+ function sortTableData(data, sort, locale = "ko") {
5263
6088
  if (!sort) return data;
5264
6089
  const { field, direction } = sort;
5265
6090
  const multiplier = direction === "asc" ? 1 : -1;
5266
6091
  return [...data].sort((left, right) => {
5267
- const leftValue = left[field];
5268
- const rightValue = right[field];
6092
+ const leftValue = readField(left, field);
6093
+ const rightValue = readField(right, field);
5269
6094
  if ((leftValue === null || leftValue === void 0) && (rightValue === null || rightValue === void 0)) {
5270
6095
  return 0;
5271
6096
  }
@@ -5274,11 +6099,12 @@ function sortTableData(data, sort) {
5274
6099
  if (typeof leftValue === "number" && typeof rightValue === "number") {
5275
6100
  return (leftValue - rightValue) * multiplier;
5276
6101
  }
5277
- return String(leftValue).localeCompare(String(rightValue), "ko") * multiplier;
6102
+ return String(leftValue).localeCompare(String(rightValue), locale, { numeric: true }) * multiplier;
5278
6103
  });
5279
6104
  }
5280
6105
  function paginateTableData(data, page, pageSize) {
5281
- const safePage = Math.max(1, page);
6106
+ const lastPage = getTotalPages(data.length, pageSize);
6107
+ const safePage = Math.min(Math.max(1, page), lastPage);
5282
6108
  const start = (safePage - 1) * pageSize;
5283
6109
  return data.slice(start, start + pageSize);
5284
6110
  }
@@ -5286,6 +6112,36 @@ function getTotalPages(totalCount, pageSize) {
5286
6112
  if (pageSize <= 0) return 1;
5287
6113
  return Math.max(1, Math.ceil(totalCount / pageSize));
5288
6114
  }
6115
+ function buildTreeRootBlocks(data, fields, sort, locale) {
6116
+ const childrenByRow = /* @__PURE__ */ new Map();
6117
+ const roots = [];
6118
+ const latestById = /* @__PURE__ */ new Map();
6119
+ for (const row of data) {
6120
+ const parentKey = row[fields.parentIdField];
6121
+ const parent = parentKey !== null && parentKey !== void 0 && parentKey !== "" ? latestById.get(parentKey) : void 0;
6122
+ if (parent) {
6123
+ const siblings = childrenByRow.get(parent);
6124
+ if (siblings) siblings.push(row);
6125
+ else childrenByRow.set(parent, [row]);
6126
+ } else {
6127
+ roots.push(row);
6128
+ }
6129
+ latestById.set(row[fields.idField], row);
6130
+ }
6131
+ const appendSubtree = (row, out) => {
6132
+ out.push(row);
6133
+ const children = childrenByRow.get(row);
6134
+ if (!children) return;
6135
+ for (const child of sortTableData(children, sort, locale)) {
6136
+ appendSubtree(child, out);
6137
+ }
6138
+ };
6139
+ return sortTableData(roots, sort, locale).map((root) => {
6140
+ const block = [];
6141
+ appendSubtree(root, block);
6142
+ return block;
6143
+ });
6144
+ }
5289
6145
 
5290
6146
  // src/components/ui/table/components/Table/TableHeader.tsx
5291
6147
  function TableHeader(props) {
@@ -5301,7 +6157,9 @@ function TablePagination({
5301
6157
  pageSize = 10,
5302
6158
  totalCount = 0,
5303
6159
  onChange,
5304
- className
6160
+ className,
6161
+ previousLabel = "Previous page",
6162
+ nextLabel = "Next page"
5305
6163
  }) {
5306
6164
  const totalPages = getTotalPages(totalCount, pageSize);
5307
6165
  const safePage = Math.min(Math.max(1, page), totalPages);
@@ -5315,7 +6173,7 @@ function TablePagination({
5315
6173
  className: "pagination-button",
5316
6174
  disabled: !canGoPrev,
5317
6175
  onClick: () => onChange(safePage - 1),
5318
- "aria-label": "Previous page",
6176
+ "aria-label": previousLabel,
5319
6177
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronLeft, { className: "pagination-button-icon" })
5320
6178
  }
5321
6179
  ),
@@ -5331,7 +6189,7 @@ function TablePagination({
5331
6189
  className: "pagination-button",
5332
6190
  disabled: !canGoNext,
5333
6191
  onClick: () => onChange(safePage + 1),
5334
- "aria-label": "Next page",
6192
+ "aria-label": nextLabel,
5335
6193
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronRight, { className: "pagination-button-icon" })
5336
6194
  }
5337
6195
  )
@@ -5345,63 +6203,124 @@ function TableRoot({
5345
6203
  data,
5346
6204
  children,
5347
6205
  className,
6206
+ classNames,
5348
6207
  totalCount,
5349
6208
  filteredCount,
6209
+ onDataChange,
6210
+ getRowId,
6211
+ sort: controlledSort,
6212
+ defaultSort = null,
6213
+ onSortChange,
6214
+ sortLocale,
5350
6215
  ...dataTableProps
5351
6216
  }) {
5352
- const { header, pagination: paginationElement } = (0, import_react14.useMemo)(
6217
+ const { header, pagination: paginationElement } = (0, import_react15.useMemo)(
5353
6218
  () => parseTableChildren(children),
5354
6219
  [children]
5355
6220
  );
5356
- const [sort, setSort] = (0, import_react14.useState)(null);
5357
- const handleSort = (0, import_react14.useCallback)((field) => {
5358
- setSort((previous) => {
5359
- if (previous?.field !== field) {
5360
- return { field, direction: "asc" };
5361
- }
5362
- if (previous.direction === "asc") {
5363
- return { field, direction: "desc" };
6221
+ const [internalSort, setInternalSort] = (0, import_react15.useState)(defaultSort);
6222
+ const sort = controlledSort !== void 0 ? controlledSort : internalSort;
6223
+ const handleSort = (0, import_react15.useCallback)(
6224
+ (field) => {
6225
+ let next;
6226
+ if (sort?.field !== field) {
6227
+ next = { field, direction: "asc" };
6228
+ } else if (sort.direction === "asc") {
6229
+ next = { field, direction: "desc" };
6230
+ } else {
6231
+ next = null;
5364
6232
  }
5365
- return null;
5366
- });
5367
- }, []);
5368
- const columnTree = (0, import_react14.useMemo)(() => extractColumnTree(header), [header]);
5369
- const columns = (0, import_react14.useMemo)(
5370
- () => buildColumnDefsFromTree(columnTree, sort, handleSort),
6233
+ if (controlledSort === void 0) setInternalSort(next);
6234
+ onSortChange?.(next);
6235
+ },
6236
+ [controlledSort, onSortChange, sort]
6237
+ );
6238
+ const columnTree = (0, import_react15.useMemo)(() => extractColumnTree(header), [header]);
6239
+ const headerCacheRef = (0, import_react15.useRef)(/* @__PURE__ */ new Map());
6240
+ const columns = (0, import_react15.useMemo)(
6241
+ () => buildColumnDefsFromTree(columnTree, sort, handleSort, headerCacheRef.current),
5371
6242
  [columnTree, sort, handleSort]
5372
6243
  );
6244
+ const sortContextValue = (0, import_react15.useMemo)(() => ({ sort, onSort: handleSort }), [sort, handleSort]);
5373
6245
  const paginationProps = paginationElement?.props;
5374
6246
  const pageSize = paginationProps?.pageSize ?? 10;
5375
6247
  const page = paginationProps?.page ?? 1;
5376
6248
  const resolvedTotalCount = paginationProps?.totalCount ?? totalCount ?? data.length;
5377
- const tableData = (0, import_react14.useMemo)(() => {
5378
- const sortedData = sortTableData(data, sort);
5379
- if (!paginationProps) return sortedData;
6249
+ const isManualPagination = Boolean(paginationProps?.manual);
6250
+ const treeIdField = dataTableProps.toggleField ?? dataTableProps.idField;
6251
+ const isTree = Boolean(treeIdField);
6252
+ const treeParentIdField = dataTableProps.childField ?? dataTableProps.parentIdField ?? DEFAULT_TREE_PARENT_ID_FIELD;
6253
+ const treeBlocks = (0, import_react15.useMemo)(() => {
6254
+ if (!isTree || !treeIdField) return null;
6255
+ if (!sort && (!paginationProps || isManualPagination)) return null;
6256
+ return buildTreeRootBlocks(
6257
+ data,
6258
+ { idField: treeIdField, parentIdField: treeParentIdField },
6259
+ sort,
6260
+ sortLocale
6261
+ );
6262
+ }, [data, isManualPagination, isTree, paginationProps, sort, sortLocale, treeIdField, treeParentIdField]);
6263
+ const pageTotalCount = paginationProps?.totalCount ?? totalCount ?? (treeBlocks ? treeBlocks.length : data.length);
6264
+ const tableData = (0, import_react15.useMemo)(() => {
6265
+ if (treeBlocks) {
6266
+ const blocks = !paginationProps || isManualPagination ? treeBlocks : paginateTableData(treeBlocks, page, pageSize);
6267
+ return blocks.flat();
6268
+ }
6269
+ const sortedData = sortTableData(data, sort, sortLocale);
6270
+ if (!paginationProps || isManualPagination) return sortedData;
5380
6271
  return paginateTableData(sortedData, page, pageSize);
5381
- }, [data, sort, paginationProps, page, pageSize]);
6272
+ }, [treeBlocks, data, sort, sortLocale, paginationProps, isManualPagination, page, pageSize]);
6273
+ const originalIndexByRow = (0, import_react15.useMemo)(() => {
6274
+ const map = /* @__PURE__ */ new Map();
6275
+ data.forEach((row, index) => map.set(row, index));
6276
+ return map;
6277
+ }, [data]);
6278
+ const resolvedGetRowId = (0, import_react15.useMemo)(() => {
6279
+ if (getRowId) return getRowId;
6280
+ if (isTree) return void 0;
6281
+ return (row, index) => String(originalIndexByRow.get(row) ?? index);
6282
+ }, [isTree, getRowId, originalIndexByRow]);
6283
+ const handleDataChange = (0, import_react15.useMemo)(() => {
6284
+ if (!onDataChange) return void 0;
6285
+ return (next) => {
6286
+ const merged = data.slice();
6287
+ tableData.forEach((row, index) => {
6288
+ const nextRow = next[index];
6289
+ if (nextRow === void 0 || nextRow === row) return;
6290
+ const originalIndex = originalIndexByRow.get(row);
6291
+ if (originalIndex !== void 0) merged[originalIndex] = nextRow;
6292
+ });
6293
+ onDataChange(merged);
6294
+ };
6295
+ }, [data, onDataChange, originalIndexByRow, tableData]);
5382
6296
  if (countLeafColumns(columnTree) === 0) {
5383
6297
  console.warn("[Table] Declare at least one Table.Column inside Table.Header.");
5384
6298
  }
5385
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "TableJSX", children: [
5386
- /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
6299
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: cn("TableJSX", classNames?.tableRoot), children: [
6300
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(TableSortContext, { value: sortContextValue, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5387
6301
  DataTable,
5388
6302
  {
5389
6303
  ...dataTableProps,
6304
+ classNames,
6305
+ getRowId: resolvedGetRowId,
6306
+ onDataChange: handleDataChange,
5390
6307
  data: tableData,
5391
6308
  columns,
5392
6309
  totalCount: paginationProps ? resolvedTotalCount : totalCount,
5393
6310
  filteredCount: filteredCount ?? data.length,
5394
6311
  className: cn(className, paginationProps && "DataTableJSX--with-pagination")
5395
6312
  }
5396
- ),
6313
+ ) }),
5397
6314
  paginationProps && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5398
6315
  TablePagination,
5399
6316
  {
5400
6317
  page,
5401
6318
  pageSize,
5402
- totalCount: resolvedTotalCount,
6319
+ totalCount: pageTotalCount,
5403
6320
  onChange: paginationProps.onChange,
5404
- className: paginationProps.className
6321
+ className: cn(classNames?.pagination, paginationProps.className),
6322
+ previousLabel: paginationProps.previousLabel ?? dataTableProps.labels?.paginationPrevious,
6323
+ nextLabel: paginationProps.nextLabel ?? dataTableProps.labels?.paginationNext
5405
6324
  }
5406
6325
  )
5407
6326
  ] });