react-glide-table 2.3.5 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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");
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+$/, "");
2669
2944
  }
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
- };
2945
+ function rememberSubtreeCopy(text) {
2946
+ lastSubtreeCopy = normalize(text);
2678
2947
  }
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
- }
2687
- }
2688
- function isActiveCellSelectionOwner(owner) {
2689
- return activeOwner === owner;
2690
- }
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");
@@ -3066,6 +3312,7 @@ function writeTextWithExecCommand(text) {
3066
3312
  async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible", options) {
3067
3313
  const text = serializeSelectionToTSV(visibleRows, bounds, mode, options);
3068
3314
  if (!text) return false;
3315
+ if (mode === "subtree") rememberSubtreeCopy(text);
3069
3316
  if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
3070
3317
  return writeTextWithExecCommand(text);
3071
3318
  }
@@ -3077,6 +3324,42 @@ async function writeSelectionToClipboard(visibleRows, bounds, mode = "visible",
3077
3324
  }
3078
3325
  }
3079
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
+ }
3361
+ }
3362
+
3080
3363
  // src/components/ui/table/features/cell-selection/fillData.ts
3081
3364
  function getColumnAccessorKey2(columnDef) {
3082
3365
  if ("accessorKey" in columnDef && columnDef.accessorKey) {
@@ -3099,6 +3382,8 @@ function collectFillTargets(rows, sourceBounds, fillBounds) {
3099
3382
  const targetCell = targetRow?.getVisibleCells()[colIndex];
3100
3383
  const sourceCell = rows[sourceRowIndex]?.getVisibleCells()[sourceColIndex];
3101
3384
  if (!targetRow || !targetCell || !sourceCell) continue;
3385
+ if (!isColumnEditable(targetCell.column.columnDef)) continue;
3386
+ if (isProtectedColumn(sourceCell.column.columnDef)) continue;
3102
3387
  const accessorKey = getColumnAccessorKey2(
3103
3388
  targetCell.column.columnDef
3104
3389
  );
@@ -3120,13 +3405,22 @@ function collectFillChanges(rows, sourceBounds, fillBounds) {
3120
3405
  );
3121
3406
  }
3122
3407
  function applyFillData(data, rows, sourceBounds, fillBounds) {
3123
- const newData = data.map((row) => ({ ...row }));
3124
3408
  const targets = collectFillTargets(rows, sourceBounds, fillBounds);
3125
- for (const target of targets) {
3126
- if (!newData[target.rowIndex]) continue;
3127
- newData[target.rowIndex][target.accessorKey] = target.value;
3128
- }
3129
- 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
+ );
3130
3424
  }
3131
3425
  function hasFillExtension(sourceBounds, fillBounds) {
3132
3426
  if (!sourceBounds) return false;
@@ -3147,14 +3441,59 @@ function looksLikeSubtreeIndentation(leadingEmptyCounts) {
3147
3441
  if (firstDepth !== 0) return false;
3148
3442
  return leadingEmptyCounts.some((depth) => depth > 0);
3149
3443
  }
3150
- 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) {
3151
3490
  if (!text) return { values: [], depths: [] };
3152
3491
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3153
3492
  const withoutTrailing = normalized.replace(/\n+$/, "");
3154
3493
  if (!withoutTrailing) return { values: [], depths: [] };
3155
- const rows = withoutTrailing.split("\n").map((line) => line.split(" "));
3494
+ const rows = splitTSV(withoutTrailing);
3156
3495
  const leadingEmptyCounts = rows.map(countLeadingEmptyCells);
3157
- const treatAsDepth = looksLikeSubtreeIndentation(leadingEmptyCounts);
3496
+ const treatAsDepth = options?.treeDepth !== "none" && looksLikeSubtreeIndentation(leadingEmptyCounts);
3158
3497
  const values = [];
3159
3498
  const depths = [];
3160
3499
  for (let index = 0; index < rows.length; index += 1) {
@@ -3181,8 +3520,8 @@ function resolvePasteColumnIds(rows, startCol, width) {
3181
3520
  }
3182
3521
  return columnIds;
3183
3522
  }
3184
- function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow) {
3185
- const { values, depths } = parseClipboardTSVWithDepths(text);
3523
+ function buildRowsPastePayload(rows, startRow, startCol, text, mode, endRow = startRow, options) {
3524
+ const { values, depths } = parseClipboardTSVWithDepths(text, options);
3186
3525
  if (values.length === 0) return null;
3187
3526
  const width = Math.max(...values.map((row) => row.length), 0);
3188
3527
  if (width === 0) return null;
@@ -3215,6 +3554,19 @@ function isEditablePasteTarget(target) {
3215
3554
  }
3216
3555
 
3217
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
+ }
3218
3570
  function isFocusOutsideRoot(rootRef) {
3219
3571
  const root = rootRef?.current;
3220
3572
  if (!root) return false;
@@ -3227,29 +3579,50 @@ function useCellSelection({
3227
3579
  rows,
3228
3580
  enabled = true,
3229
3581
  columnCount = 0,
3582
+ columnSignature,
3230
3583
  enableSubtreeCopy = false,
3584
+ escapeCopyFormulas = false,
3231
3585
  enableInsertPaste = true,
3232
3586
  onDataChange,
3233
3587
  onBatchChange,
3234
3588
  onRowsPaste,
3235
3589
  onCellNavigate,
3236
3590
  cellRendererRegistry,
3237
- rootRef
3591
+ rootRef,
3592
+ enableWasdNavigation = true,
3593
+ onEditKey,
3594
+ onClearKey
3238
3595
  }) {
3239
3596
  const ownerRef = (0, import_react7.useRef)(createCellSelectionOwner());
3240
3597
  const [dragState, setDragState] = (0, import_react7.useState)(INITIAL_DRAG_STATE);
3241
3598
  const pendingPasteModeRef = (0, import_react7.useRef)(null);
3242
3599
  const dragStateRef = (0, import_react7.useRef)(dragState);
3243
3600
  const onCellNavigateRef = (0, import_react7.useRef)(onCellNavigate);
3601
+ const onEditKeyRef = (0, import_react7.useRef)(onEditKey);
3602
+ const onClearKeyRef = (0, import_react7.useRef)(onClearKey);
3244
3603
  dragStateRef.current = dragState;
3245
3604
  onCellNavigateRef.current = onCellNavigate;
3246
- const cellSelectionBounds = getCellSelectionBounds(dragState.start, dragState.end);
3247
- 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]);
3248
3621
  const handleCellMouseDown = (0, import_react7.useCallback)(
3249
3622
  (rowIndex, colIndex, options) => {
3250
3623
  if (!enabled) return;
3251
3624
  claimCellSelectionOwner(ownerRef.current);
3252
- setDragState((prev) => {
3625
+ updateDragState((prev) => {
3253
3626
  if (options?.shiftKey && prev.start) {
3254
3627
  return {
3255
3628
  ...prev,
@@ -3270,28 +3643,30 @@ function useCellSelection({
3270
3643
  };
3271
3644
  });
3272
3645
  },
3273
- [enabled]
3646
+ [enabled, updateDragState]
3274
3647
  );
3275
3648
  const handleCellMouseEnter = (0, import_react7.useCallback)(
3276
3649
  (rowIndex, colIndex) => {
3277
3650
  if (!enabled) return;
3278
- setDragState((prev) => {
3651
+ updateDragState((prev) => {
3279
3652
  if (prev.isSelecting) {
3653
+ if (prev.end?.row === rowIndex && prev.end.col === colIndex) return prev;
3280
3654
  return { ...prev, end: { row: rowIndex, col: colIndex } };
3281
3655
  }
3282
3656
  if (prev.isFillDragging) {
3657
+ if (prev.fillEnd?.row === rowIndex && prev.fillEnd.col === colIndex) return prev;
3283
3658
  return { ...prev, fillEnd: { row: rowIndex, col: colIndex } };
3284
3659
  }
3285
3660
  return prev;
3286
3661
  });
3287
3662
  },
3288
- [enabled]
3663
+ [enabled, updateDragState]
3289
3664
  );
3290
3665
  const handleFillHandleMouseDown = (0, import_react7.useCallback)(
3291
3666
  (rowIndex, colIndex) => {
3292
3667
  if (!enabled) return;
3293
3668
  claimCellSelectionOwner(ownerRef.current);
3294
- setDragState((prev) => {
3669
+ updateDragState((prev) => {
3295
3670
  const bounds = getCellSelectionBounds(prev.start, prev.end);
3296
3671
  if (!bounds) return prev;
3297
3672
  return {
@@ -3303,7 +3678,7 @@ function useCellSelection({
3303
3678
  };
3304
3679
  });
3305
3680
  },
3306
- [enabled]
3681
+ [enabled, updateDragState]
3307
3682
  );
3308
3683
  const clearSelection = (0, import_react7.useCallback)(() => {
3309
3684
  const prev = dragStateRef.current;
@@ -3322,6 +3697,130 @@ function useCellSelection({
3322
3697
  (0, import_react7.useEffect)(() => {
3323
3698
  return registerCellSelectionOwner(ownerRef.current, clearSelection);
3324
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]);
3325
3824
  (0, import_react7.useEffect)(() => {
3326
3825
  if (!enabled) return;
3327
3826
  const handleKeyDown = (e) => {
@@ -3331,6 +3830,7 @@ function useCellSelection({
3331
3830
  return;
3332
3831
  }
3333
3832
  if (isFocusOutsideRoot(rootRef)) return;
3833
+ if (!enableWasdNavigation && e.key.length === 1) return;
3334
3834
  const delta = getCellNavigationDelta(e.key);
3335
3835
  if (!delta) return;
3336
3836
  const prev = dragStateRef.current;
@@ -3370,14 +3870,15 @@ function useCellSelection({
3370
3870
  };
3371
3871
  window.addEventListener("keydown", handleKeyDown);
3372
3872
  return () => window.removeEventListener("keydown", handleKeyDown);
3373
- }, [columnCount, enabled, rows]);
3873
+ }, [columnCount, enableWasdNavigation, enabled, rows]);
3374
3874
  const copySelection = (0, import_react7.useCallback)(
3375
3875
  async (options) => {
3376
3876
  if (!enabled || !activeSelectionBounds) return false;
3377
3877
  const mode = options?.includeDescendants && enableSubtreeCopy ? "subtree" : "visible";
3378
3878
  return writeSelectionToClipboard(rows, activeSelectionBounds, mode, {
3379
3879
  registry: cellRendererRegistry,
3380
- root: rootRef?.current
3880
+ root: rootRef?.current,
3881
+ escapeFormulas: escapeCopyFormulas
3381
3882
  });
3382
3883
  },
3383
3884
  [
@@ -3385,6 +3886,7 @@ function useCellSelection({
3385
3886
  cellRendererRegistry,
3386
3887
  enableSubtreeCopy,
3387
3888
  enabled,
3889
+ escapeCopyFormulas,
3388
3890
  rootRef,
3389
3891
  rows
3390
3892
  ]
@@ -3402,6 +3904,7 @@ function useCellSelection({
3402
3904
  const isSubtreeShortcut = enableSubtreeCopy && e.shiftKey && e.key.toLowerCase() === "c";
3403
3905
  const isVisibleCopyShortcut = !e.shiftKey && e.key.toLowerCase() === "c";
3404
3906
  if (!isSubtreeShortcut && !isVisibleCopyShortcut) return;
3907
+ if (hasPageTextSelectionOutside(rootRef?.current)) return;
3405
3908
  e.preventDefault();
3406
3909
  void copySelection({ includeDescendants: isSubtreeShortcut });
3407
3910
  };
@@ -3417,9 +3920,17 @@ function useCellSelection({
3417
3920
  activeSelectionBounds.startCol,
3418
3921
  text,
3419
3922
  mode,
3420
- 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" }
3421
3927
  );
3422
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
+ });
3423
3934
  onRowsPaste(payload);
3424
3935
  return true;
3425
3936
  },
@@ -3450,7 +3961,10 @@ function useCellSelection({
3450
3961
  void (async () => {
3451
3962
  try {
3452
3963
  const text = await navigator.clipboard.readText();
3453
- if (pasteHandledRef.current) return;
3964
+ if (pasteHandledRef.current) {
3965
+ pasteHandledRef.current = false;
3966
+ return;
3967
+ }
3454
3968
  if (pendingPasteModeRef.current !== mode) return;
3455
3969
  if (!isActiveCellSelectionOwner(ownerRef.current)) return;
3456
3970
  if (!text) return;
@@ -3475,6 +3989,7 @@ function useCellSelection({
3475
3989
  }
3476
3990
  const mode = pendingPasteModeRef.current ?? "overwrite";
3477
3991
  if (pasteHandledRef.current) {
3992
+ pasteHandledRef.current = false;
3478
3993
  e.preventDefault();
3479
3994
  return;
3480
3995
  }
@@ -3501,39 +4016,41 @@ function useCellSelection({
3501
4016
  (0, import_react7.useEffect)(() => {
3502
4017
  if (!enabled) return;
3503
4018
  const handleMouseUp = () => {
3504
- setDragState((prev) => {
3505
- if (prev.isFillDragging && prev.fillAnchor && prev.fillEnd) {
3506
- const sourceBounds = getCellSelectionBounds(prev.start, prev.end);
3507
- const newBounds = getCellSelectionBounds(prev.fillAnchor, prev.fillEnd);
3508
- if (newBounds) {
3509
- if (hasFillExtension(sourceBounds, newBounds) && sourceBounds) {
3510
- if (onBatchChange) {
3511
- const changes = collectFillChanges(rows, sourceBounds, newBounds);
3512
- if (changes.length > 0) {
3513
- onBatchChange(changes);
3514
- }
3515
- } else if (onDataChange) {
3516
- 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);
3517
4030
  }
4031
+ } else if (onDataChange) {
4032
+ onDataChange(applyFillData(data, rows, sourceBounds, newBounds));
3518
4033
  }
3519
- return {
3520
- isSelecting: false,
3521
- isFillDragging: false,
3522
- start: { row: newBounds.startRow, col: newBounds.startCol },
3523
- end: { row: newBounds.endRow, col: newBounds.endCol },
3524
- fillAnchor: null,
3525
- fillEnd: null
3526
- };
3527
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 };
3528
4045
  }
3529
- if (prev.isSelecting) {
3530
- return { ...prev, isSelecting: false };
3531
- }
3532
- if (prev.isFillDragging) {
3533
- return { ...prev, isFillDragging: false, fillAnchor: null, fillEnd: null };
3534
- }
3535
- return prev;
3536
- });
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);
3537
4054
  };
3538
4055
  window.addEventListener("mouseup", handleMouseUp);
3539
4056
  return () => window.removeEventListener("mouseup", handleMouseUp);
@@ -3545,7 +4062,9 @@ function useCellSelection({
3545
4062
  handleCellMouseEnter,
3546
4063
  handleFillHandleMouseDown,
3547
4064
  clearSelection,
3548
- copySelection
4065
+ copySelection,
4066
+ selectCell,
4067
+ focusSelection
3549
4068
  };
3550
4069
  }
3551
4070
 
@@ -3606,11 +4125,30 @@ function registerEscapeDismiss(owner, clearAllSelections) {
3606
4125
  // src/components/ui/table/features/inline-search/useInlineSearch.ts
3607
4126
  var import_react8 = require("react");
3608
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
+ }
3609
4146
  function useInlineSearch({
3610
4147
  enabled = false,
3611
4148
  rowCount,
3612
4149
  columnCount,
3613
4150
  getCellValue,
4151
+ contentKey,
3614
4152
  initialStartRow = 0,
3615
4153
  showSearch: controlledShowSearch,
3616
4154
  searchValue: controlledSearchValue,
@@ -3819,6 +4357,7 @@ function useInlineSearch({
3819
4357
  }
3820
4358
  beginSearch(searchValue);
3821
4359
  }, [
4360
+ contentKey,
3822
4361
  beginSearch,
3823
4362
  cancelSearch,
3824
4363
  controlledSearchResults,
@@ -3839,6 +4378,9 @@ function useInlineSearch({
3839
4378
  if (!focusInside && active !== document.body) {
3840
4379
  return;
3841
4380
  }
4381
+ if (!focusInside && !(lastPointerTarget instanceof Node && root.contains(lastPointerTarget))) {
4382
+ return;
4383
+ }
3842
4384
  }
3843
4385
  event.preventDefault();
3844
4386
  event.stopPropagation();
@@ -3852,7 +4394,11 @@ function useInlineSearch({
3852
4394
  }
3853
4395
  };
3854
4396
  window.addEventListener("keydown", handleKeyDown, true);
3855
- return () => window.removeEventListener("keydown", handleKeyDown, true);
4397
+ const releaseInstance = registerSearchInstance();
4398
+ return () => {
4399
+ window.removeEventListener("keydown", handleKeyDown, true);
4400
+ releaseInstance();
4401
+ };
3856
4402
  }, [controlledShowSearch, enabled, rootRef, showSearch]);
3857
4403
  (0, import_react8.useEffect)(() => () => cancelSearch(), [cancelSearch]);
3858
4404
  const searchMatchKeys = (0, import_react8.useMemo)(
@@ -3929,7 +4475,11 @@ var DEFAULT_DATA_TABLE_LABELS = {
3929
4475
  searchResultHint: "Type to search",
3930
4476
  searchPrevious: "Previous result",
3931
4477
  searchNext: "Next result",
3932
- searchClose: "Close search"
4478
+ searchClose: "Close search",
4479
+ searchResultCount: formatSearchResultLabel,
4480
+ protectedCell: "protected",
4481
+ paginationPrevious: "Previous page",
4482
+ paginationNext: "Next page"
3933
4483
  };
3934
4484
  function resolveDataTableLabels(partial) {
3935
4485
  return {
@@ -3939,6 +4489,9 @@ function resolveDataTableLabels(partial) {
3939
4489
  }
3940
4490
 
3941
4491
  // src/core/useGlideTable.ts
4492
+ function isProductionBuild() {
4493
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
4494
+ }
3942
4495
  var EMPTY_COLUMN_FREEZE_OFFSETS = /* @__PURE__ */ new Map();
3943
4496
  var EMPTY_SEARCH_MATCH_KEYS = /* @__PURE__ */ new Set();
3944
4497
  function useGlideTable(options) {
@@ -3960,18 +4513,24 @@ function useGlideTable(options) {
3960
4513
  selectOnRowClick = true,
3961
4514
  enableCellSelection = true,
3962
4515
  onDataChange,
3963
- onCellChange,
3964
- onBatchChange,
4516
+ onCellChange: onCellChangeProp,
4517
+ onBatchChange: onBatchChangeProp,
3965
4518
  cellRenderers,
3966
4519
  preserveRowSelection = false,
3967
- toggleField,
3968
- childField,
3969
- flattenField,
4520
+ toggleField: toggleFieldProp,
4521
+ idField,
4522
+ childField: childFieldProp,
4523
+ parentIdField,
4524
+ flattenField: flattenFieldProp,
4525
+ childrenField,
3970
4526
  qtyField,
4527
+ expandColumn,
3971
4528
  expandedRows: controlledExpandedRows,
3972
4529
  onExpandedRowsChange,
3973
4530
  preventExpand = false,
4531
+ autoExpandOnLoad = true,
3974
4532
  enableSubtreeCopy,
4533
+ escapeCopyFormulas = false,
3975
4534
  onCopyActionsReady,
3976
4535
  onRowsPaste,
3977
4536
  enableInsertPaste,
@@ -3992,8 +4551,27 @@ function useGlideTable(options) {
3992
4551
  onSearchValueChange,
3993
4552
  onSearchClose,
3994
4553
  searchResults,
3995
- onSearchResultsChanged
4554
+ onSearchResultsChanged,
4555
+ enableWasdNavigation = true
3996
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);
3997
4575
  const labels = (0, import_react9.useMemo)(() => {
3998
4576
  const resolved = resolveDataTableLabels(labelsProp);
3999
4577
  return {
@@ -4011,7 +4589,7 @@ function useGlideTable(options) {
4011
4589
  const [internalExpandedRows, setInternalExpandedRows] = (0, import_react9.useState)(
4012
4590
  () => /* @__PURE__ */ new Set()
4013
4591
  );
4014
- const [hoveredRowIndex, setHoveredRowIndex] = (0, import_react9.useState)(null);
4592
+ const [hoverStore] = (0, import_react9.useState)(createRowHoverStore);
4015
4593
  const scrollRef = (0, import_react9.useRef)(null);
4016
4594
  const rootRef = (0, import_react9.useRef)(null);
4017
4595
  const escapeDismissOwnerRef = (0, import_react9.useRef)(/* @__PURE__ */ Symbol("escape-dismiss-owner"));
@@ -4068,8 +4646,10 @@ function useGlideTable(options) {
4068
4646
  qtyField,
4069
4647
  expandedRows,
4070
4648
  onExpandedRowsChange: enableExpand ? handleExpandedRowsChange : void 0,
4071
- preventExpand
4649
+ preventExpand,
4650
+ autoExpandOnLoad
4072
4651
  });
4652
+ const sourceData = (0, import_react9.useMemo)(() => data ?? [], [data]);
4073
4653
  const table = (0, import_react_table2.useReactTable)({
4074
4654
  data: tableData,
4075
4655
  columns: tableColumns,
@@ -4108,7 +4688,11 @@ function useGlideTable(options) {
4108
4688
  );
4109
4689
  },
4110
4690
  getCoreRowModel: (0, import_react_table2.getCoreRowModel)(),
4111
- 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
+ )
4112
4696
  });
4113
4697
  const rowSpanColumnKeys = (0, import_react9.useMemo)(() => {
4114
4698
  if (!enableRowSpan) return [];
@@ -4125,6 +4709,20 @@ function useGlideTable(options) {
4125
4709
  const rows = table.getRowModel().rows;
4126
4710
  const columnCount = table.getAllLeafColumns().length || 1;
4127
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]);
4128
4726
  const columnFreezeOffsets = (0, import_react9.useMemo)(() => {
4129
4727
  if (!enableColumnFreeze) return EMPTY_COLUMN_FREEZE_OFFSETS;
4130
4728
  return buildColumnFreezeOffsets(
@@ -4167,7 +4765,7 @@ function useGlideTable(options) {
4167
4765
  const cell = scrollElement.querySelector(
4168
4766
  `[data-row-index="${rowIndex}"][data-col-index="${colIndex}"]`
4169
4767
  );
4170
- if (cell instanceof HTMLElement) {
4768
+ if (cell instanceof HTMLElement && typeof cell.scrollIntoView === "function") {
4171
4769
  cell.scrollIntoView({ block: blockAlign, inline: "nearest" });
4172
4770
  }
4173
4771
  };
@@ -4185,6 +4783,10 @@ function useGlideTable(options) {
4185
4783
  },
4186
4784
  [scrollCellIntoView]
4187
4785
  );
4786
+ const editKeyRef = (0, import_react9.useRef)(() => {
4787
+ });
4788
+ const clearKeyRef = (0, import_react9.useRef)(() => {
4789
+ });
4188
4790
  const {
4189
4791
  dragState,
4190
4792
  activeSelectionBounds,
@@ -4192,20 +4794,27 @@ function useGlideTable(options) {
4192
4794
  handleCellMouseEnter,
4193
4795
  handleFillHandleMouseDown,
4194
4796
  clearSelection: clearCellSelection,
4195
- copySelection
4797
+ copySelection,
4798
+ selectCell,
4799
+ focusSelection
4196
4800
  } = useCellSelection({
4197
- data: tableData,
4801
+ data: sourceData,
4198
4802
  rows,
4199
4803
  enabled: enableCellSelection,
4200
4804
  columnCount: visibleLeafColumns.length,
4805
+ columnSignature: visibleLeafColumns.map((column) => column.id).join("\0"),
4201
4806
  enableSubtreeCopy: resolvedEnableSubtreeCopy,
4807
+ escapeCopyFormulas,
4202
4808
  enableInsertPaste: enableInsertPaste ?? true,
4203
4809
  onDataChange,
4204
4810
  onBatchChange,
4205
4811
  onRowsPaste,
4206
4812
  onCellNavigate: handleCellNavigate,
4207
4813
  cellRendererRegistry,
4208
- rootRef
4814
+ rootRef,
4815
+ enableWasdNavigation,
4816
+ onEditKey: (position) => editKeyRef.current(position),
4817
+ onClearKey: (bounds) => clearKeyRef.current(bounds)
4209
4818
  });
4210
4819
  const clearRowSelection = (0, import_react9.useCallback)(() => {
4211
4820
  if (rowSelectionMode === "none") return;
@@ -4226,22 +4835,79 @@ function useGlideTable(options) {
4226
4835
  const {
4227
4836
  editingCell,
4228
4837
  draftValue,
4838
+ draftInvalid,
4839
+ setDraftInvalid,
4229
4840
  setDraftValue,
4230
4841
  startEdit,
4231
4842
  commitEdit,
4232
4843
  cancelEdit
4233
- } = 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]);
4234
4894
  const commitRenderedCellValue = (0, import_react9.useCallback)(
4235
- (rowId, columnId, value) => commitCellValue({
4236
- data: tableData,
4237
- rows,
4238
- rowId,
4239
- columnId,
4240
- value,
4241
- onCellChange,
4242
- onDataChange
4243
- }),
4244
- [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]
4245
4911
  );
4246
4912
  const getCellContext = (0, import_react9.useCallback)(
4247
4913
  (cell) => withCellUpdate(cell.getContext(), commitRenderedCellValue),
@@ -4269,25 +4935,12 @@ function useGlideTable(options) {
4269
4935
  (row, index) => {
4270
4936
  if (getRowId) return getRowId(row, index);
4271
4937
  if (enableExpand) {
4272
- const record = row;
4273
- const idValue = record.id;
4274
- if (idValue != null && String(idValue).length > 0) {
4275
- return String(idValue);
4276
- }
4277
- const uniqueId = record.uniqueId;
4278
- if (uniqueId != null && String(uniqueId).length > 0) {
4279
- return String(uniqueId);
4280
- }
4281
- if (toggleField) {
4282
- const toggleValue = record[toggleField];
4283
- if (toggleValue != null && String(toggleValue).length > 0) {
4284
- return String(toggleValue);
4285
- }
4286
- }
4938
+ const treeKey = getTreeRowKey(row);
4939
+ if (treeKey) return treeKey;
4287
4940
  }
4288
4941
  return String(index);
4289
4942
  },
4290
- [enableExpand, getRowId, toggleField]
4943
+ [enableExpand, getRowId]
4291
4944
  );
4292
4945
  const searchCorpus = (0, import_react9.useMemo)(() => {
4293
4946
  if (!enableInlineSearch) return [];
@@ -4314,28 +4967,59 @@ function useGlideTable(options) {
4314
4967
  }
4315
4968
  return map;
4316
4969
  }, [resolveSearchRowId, rows]);
4317
- const getSearchCellValue = (0, import_react9.useCallback)(
4318
- (rowIndex, colIndex) => {
4319
- const corpusRow = searchCorpusRef.current[rowIndex];
4320
- const column = visibleLeafColumns[colIndex];
4321
- if (!corpusRow || !column) return void 0;
4970
+ const readSearchRawValue = (0, import_react9.useCallback)(
4971
+ (corpusRow, rowIndex, column) => {
4322
4972
  const visibleIndex = visibleRowIndexById.get(corpusRow.id);
4323
4973
  if (visibleIndex !== void 0) {
4324
4974
  const visibleRow = rows[visibleIndex];
4325
4975
  if (visibleRow) {
4326
- return visibleRow.getValue(column.id);
4976
+ return { value: visibleRow.getValue(column.id), row: visibleRow };
4327
4977
  }
4328
4978
  }
4329
4979
  const columnDef = column.columnDef;
4330
4980
  if ("accessorFn" in columnDef && typeof columnDef.accessorFn === "function") {
4331
- return columnDef.accessorFn(corpusRow.data, rowIndex);
4981
+ return { value: columnDef.accessorFn(corpusRow.data, rowIndex), row: void 0 };
4332
4982
  }
4333
4983
  if ("accessorKey" in columnDef && columnDef.accessorKey != null && columnDef.accessorKey !== "") {
4334
- return corpusRow.data[String(columnDef.accessorKey)];
4984
+ return {
4985
+ value: corpusRow.data[String(columnDef.accessorKey)],
4986
+ row: void 0
4987
+ };
4335
4988
  }
4336
- return corpusRow.data[column.id];
4989
+ return { value: corpusRow.data[column.id], row: void 0 };
4337
4990
  },
4338
- [rows, visibleLeafColumns, visibleRowIndexById]
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;
5019
+ }
5020
+ return value;
5021
+ },
5022
+ [cellRendererRegistry, readSearchRawValue, visibleLeafColumns]
4339
5023
  );
4340
5024
  const pendingSearchNavRef = (0, import_react9.useRef)(null);
4341
5025
  const focusSearchResult = (0, import_react9.useCallback)(
@@ -4386,11 +5070,19 @@ function useGlideTable(options) {
4386
5070
  focusSearchResult(pending.colIndex, visibleRowIndex);
4387
5071
  }, [focusSearchResult, rows, visibleRowIndexById]);
4388
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
+ );
4389
5078
  const inlineSearch = useInlineSearch({
4390
5079
  enabled: enableInlineSearch,
4391
5080
  rowCount: searchCorpus.length,
4392
5081
  columnCount: visibleLeafColumns.length,
4393
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,
4394
5086
  initialStartRow: initialSearchStartRow,
4395
5087
  showSearch,
4396
5088
  searchValue,
@@ -4428,11 +5120,14 @@ function useGlideTable(options) {
4428
5120
  visibleRowIndexById
4429
5121
  ]);
4430
5122
  const clearHover = (0, import_react9.useCallback)(() => {
4431
- setHoveredRowIndex(null);
4432
- }, []);
4433
- const handleRowHover = (0, import_react9.useCallback)((rowIndex, _rowData) => {
4434
- setHoveredRowIndex(rowIndex);
4435
- }, []);
5123
+ hoverStore.setHoveredRowIndex(null);
5124
+ }, [hoverStore]);
5125
+ const handleRowHover = (0, import_react9.useCallback)(
5126
+ (rowIndex, _rowData) => {
5127
+ hoverStore.setHoveredRowIndex(rowIndex);
5128
+ },
5129
+ [hoverStore]
5130
+ );
4436
5131
  const handleToggleSelect = (0, import_react9.useCallback)(
4437
5132
  (row) => {
4438
5133
  if (!row.getCanSelect()) return;
@@ -4457,7 +5152,7 @@ function useGlideTable(options) {
4457
5152
  primaryRowSpanKey,
4458
5153
  primaryRowSpanColumnId,
4459
5154
  columnRowSpanMap,
4460
- hoveredRowIndex,
5155
+ hoverStore,
4461
5156
  selectedRowIndices,
4462
5157
  onRowHover: handleRowHover
4463
5158
  },
@@ -4471,6 +5166,7 @@ function useGlideTable(options) {
4471
5166
  enableCellSelection,
4472
5167
  activeSelectionBounds,
4473
5168
  dragState,
5169
+ canFill,
4474
5170
  onCellMouseDown: handleCellMouseDownWithCommit,
4475
5171
  onCellMouseEnter: handleCellMouseEnter,
4476
5172
  onFillHandleMouseDown: handleFillHandleMouseDown
@@ -4478,18 +5174,23 @@ function useGlideTable(options) {
4478
5174
  cellEdit: {
4479
5175
  editingCell,
4480
5176
  draftValue,
5177
+ draftInvalid,
5178
+ onDraftInvalidChange: setDraftInvalid,
4481
5179
  onDraftValueChange: setDraftValue,
4482
5180
  onStartEdit: startEdit,
4483
5181
  onCommitEdit: commitEdit,
4484
- onCancelEdit: cancelEdit
5182
+ onCommitEditAndMove: commitEditAndMove,
5183
+ onCancelEdit: cancelEditAndRefocus
4485
5184
  },
4486
5185
  cellRender: {
4487
5186
  registry: cellRendererRegistry,
4488
- commitValue: commitRenderedCellValue
5187
+ commitValue: commitRenderedCellValue,
5188
+ protectedLabel: labels.protectedCell
4489
5189
  },
4490
5190
  expand: {
4491
5191
  enableExpand,
4492
5192
  toggleField,
5193
+ expandColumn,
4493
5194
  expandedRows,
4494
5195
  preventExpand,
4495
5196
  onToggleExpand: handleToggleExpand,
@@ -4514,7 +5215,7 @@ function useGlideTable(options) {
4514
5215
  primaryRowSpanKey,
4515
5216
  primaryRowSpanColumnId,
4516
5217
  columnRowSpanMap,
4517
- hoveredRowIndex,
5218
+ hoverStore,
4518
5219
  selectedRowIndices,
4519
5220
  handleRowHover,
4520
5221
  rowSelectionMode,
@@ -4524,19 +5225,25 @@ function useGlideTable(options) {
4524
5225
  enableCellSelection,
4525
5226
  activeSelectionBounds,
4526
5227
  dragState,
5228
+ canFill,
4527
5229
  handleCellMouseDownWithCommit,
4528
5230
  handleCellMouseEnter,
4529
5231
  handleFillHandleMouseDown,
4530
5232
  editingCell,
4531
5233
  draftValue,
5234
+ draftInvalid,
5235
+ setDraftInvalid,
4532
5236
  setDraftValue,
4533
5237
  startEdit,
4534
5238
  commitEdit,
4535
- cancelEdit,
5239
+ commitEditAndMove,
5240
+ cancelEditAndRefocus,
4536
5241
  cellRendererRegistry,
4537
5242
  commitRenderedCellValue,
5243
+ labels.protectedCell,
4538
5244
  enableExpand,
4539
5245
  toggleField,
5246
+ expandColumn,
4540
5247
  expandedRows,
4541
5248
  preventExpand,
4542
5249
  handleToggleExpand,
@@ -4584,6 +5291,7 @@ function useGlideTable(options) {
4584
5291
  handleToggleSelect,
4585
5292
  clearHover,
4586
5293
  setColumnOrder,
5294
+ handleRootFocus: focusSelection,
4587
5295
  copySelection: stableCopySelection,
4588
5296
  inlineSearch: {
4589
5297
  showSearch: inlineSearch.showSearch,
@@ -4681,7 +5389,8 @@ function DataTable({
4681
5389
  handleToggleSelect,
4682
5390
  clearHover,
4683
5391
  setColumnOrder,
4684
- inlineSearch
5392
+ inlineSearch,
5393
+ handleRootFocus
4685
5394
  } = useGlideTable(glideOptions);
4686
5395
  const ToolbarSlot = slots?.Toolbar ?? DataTableToolbar;
4687
5396
  const ScrollSlot = slots?.Scroll ?? DefaultScroll;
@@ -4725,13 +5434,33 @@ function DataTable({
4725
5434
  }));
4726
5435
  return resolveColumnLayoutWidths(containerWidth, columns);
4727
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
+ });
4728
5457
  const freezeOffsets = (0, import_react10.useMemo)(() => {
4729
5458
  if (!enableColumnFreeze || enableColumnResize || !layoutWidths) {
4730
5459
  return rowContextValue.columnFreeze.offsets;
4731
5460
  }
4732
5461
  const columns = table.getVisibleLeafColumns().map((column) => ({
4733
5462
  id: column.id,
4734
- size: layoutWidths.get(column.id) ?? column.getSize(),
5463
+ size: measuredWidths.get(column.id) ?? layoutWidths.get(column.id) ?? column.getSize(),
4735
5464
  side: resolveColumnFreezeSide(column.columnDef.meta?.frozen)
4736
5465
  }));
4737
5466
  return buildColumnFreezeOffsets(columns);
@@ -4739,6 +5468,7 @@ function DataTable({
4739
5468
  enableColumnFreeze,
4740
5469
  enableColumnResize,
4741
5470
  layoutWidths,
5471
+ measuredWidths,
4742
5472
  rowContextValue.columnFreeze.offsets,
4743
5473
  table
4744
5474
  ]);
@@ -4771,6 +5501,10 @@ function DataTable({
4771
5501
  "div",
4772
5502
  {
4773
5503
  ref: rootRef,
5504
+ tabIndex: enableCellSelection ? 0 : void 0,
5505
+ onFocus: enableCellSelection ? (event) => {
5506
+ if (event.target === event.currentTarget) handleRootFocus();
5507
+ } : void 0,
4774
5508
  className: cn(
4775
5509
  "DataTableJSX",
4776
5510
  !enableCellSelection && "DataTableJSX--no-cell-selection",
@@ -4791,6 +5525,7 @@ function DataTable({
4791
5525
  summary,
4792
5526
  selectedCount,
4793
5527
  selectionLabel,
5528
+ countLabel: labels.count,
4794
5529
  toolbar,
4795
5530
  classNames
4796
5531
  }
@@ -4809,6 +5544,7 @@ function DataTable({
4809
5544
  previousLabel: labels.searchPrevious,
4810
5545
  nextLabel: labels.searchNext,
4811
5546
  closeLabel: labels.searchClose,
5547
+ formatResult: labels.searchResultCount,
4812
5548
  rowsTotal: inlineSearch.searchRowCount,
4813
5549
  classNames,
4814
5550
  onSearchValueChange: inlineSearch.setSearchValue,
@@ -4858,6 +5594,8 @@ function DataTable({
4858
5594
  (leafColumn) => isColumnReorderable(leafColumn.columnDef.meta)
4859
5595
  );
4860
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";
4861
5599
  const dropEdge = !isPlaceholder && dropTarget?.columnId === header.column.id ? dropTarget.edge : void 0;
4862
5600
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
4863
5601
  "th",
@@ -4873,7 +5611,8 @@ function DataTable({
4873
5611
  "data-resizing": header.column.getIsResizing() ? "" : void 0,
4874
5612
  "data-frozen": freezeOffset?.side,
4875
5613
  "data-freeze-edge": getColumnFreezeEdgeAttr(freezeOffset),
4876
- "aria-grabbed": isDragging ? true : void 0,
5614
+ "data-leaf-column-id": isLeafHeader ? header.column.id : void 0,
5615
+ "aria-sort": ariaSort,
4877
5616
  title: canDrag ? labels.reorderColumn : void 0,
4878
5617
  onPointerDown: enableColumnReorder ? (event) => onHeaderPointerDown(event, {
4879
5618
  columnId: header.column.id,
@@ -4900,7 +5639,31 @@ function DataTable({
4900
5639
  role: "separator",
4901
5640
  "aria-orientation": "vertical",
4902
5641
  "aria-label": labels.resizeColumn,
5642
+ "aria-valuenow": header.getSize(),
5643
+ tabIndex: 0,
4903
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
+ },
4904
5667
  className: cn(
4905
5668
  "data-table-resize-handle",
4906
5669
  classNames?.resizeHandle
@@ -5008,7 +5771,10 @@ function DataTable({
5008
5771
  }
5009
5772
 
5010
5773
  // src/components/ui/table/components/Table/Table.tsx
5011
- 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");
5012
5778
 
5013
5779
  // src/components/ui/table/features/cell-render/ResolvedTableCell.tsx
5014
5780
  var import_react11 = require("react");
@@ -5026,12 +5792,16 @@ function ResolvedTableCell({
5026
5792
  },
5027
5793
  [cellRender, columnId, row.id]
5028
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
+ }
5029
5799
  const ctx = {
5030
5800
  value,
5031
5801
  row,
5032
5802
  index: row.index,
5033
5803
  columnId,
5034
- cellProps: meta?.cellProps,
5804
+ cellProps,
5035
5805
  update
5036
5806
  };
5037
5807
  if (meta?.cellRender) {
@@ -5046,12 +5816,16 @@ function ResolvedTableCell({
5046
5816
 
5047
5817
  // src/components/ui/table/components/Table/buildColumnDef.tsx
5048
5818
  var import_jsx_runtime8 = require("react/jsx-runtime");
5819
+ var TableSortContext = (0, import_react12.createContext)(null);
5049
5820
  function SortableHeader({
5050
5821
  label,
5051
5822
  field,
5052
- sort,
5053
- onSort
5823
+ sort: sortProp,
5824
+ onSort: onSortProp
5054
5825
  }) {
5826
+ const context = (0, import_react12.use)(TableSortContext);
5827
+ const sort = context ? context.sort : sortProp;
5828
+ const onSort = context ? context.onSort : onSortProp;
5055
5829
  const isActive = sort?.field === field;
5056
5830
  const Icon = isActive ? sort.direction === "asc" ? ArrowUp : ArrowDown : ArrowUpDown;
5057
5831
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
@@ -5070,7 +5844,7 @@ function SortableHeader({
5070
5844
  }
5071
5845
  );
5072
5846
  }
5073
- function buildColumnDef(props, sort, onSort) {
5847
+ function buildColumnDef(props, sort, onSort, headerCache) {
5074
5848
  const {
5075
5849
  field,
5076
5850
  virtual = false,
@@ -5096,8 +5870,29 @@ function buildColumnDef(props, sort, onSort) {
5096
5870
  className,
5097
5871
  headerClassName,
5098
5872
  render,
5099
- copyValue
5873
+ copyValue,
5874
+ searchValue
5100
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
+ }
5101
5896
  return {
5102
5897
  id: field,
5103
5898
  ...!virtual ? { accessorKey: field } : {},
@@ -5105,18 +5900,7 @@ function buildColumnDef(props, sort, onSort) {
5105
5900
  ...minResizeWidth != null ? { minSize: minResizeWidth } : {},
5106
5901
  ...maxResizeWidth != null ? { maxSize: maxResizeWidth } : {},
5107
5902
  ...resizable === false ? { enableResizing: false } : {},
5108
- header: sortable ? () => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5109
- SortableHeader,
5110
- {
5111
- label: children,
5112
- field,
5113
- sort,
5114
- onSort
5115
- }
5116
- ) : (
5117
- // eslint-disable-next-line @typescript-eslint/promise-function-async
5118
- () => children
5119
- ),
5903
+ header,
5120
5904
  // eslint-disable-next-line @typescript-eslint/promise-function-async
5121
5905
  cell: (info) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(ResolvedTableCell, { info }),
5122
5906
  meta: {
@@ -5131,6 +5915,8 @@ function buildColumnDef(props, sort, onSort) {
5131
5915
  cellProps,
5132
5916
  cellRender: render,
5133
5917
  copyValue,
5918
+ searchValue,
5919
+ sortDirection: sortable ? sort?.field === field ? sort.direction : false : void 0,
5134
5920
  frozen,
5135
5921
  reorderable,
5136
5922
  width,
@@ -5148,12 +5934,12 @@ function resolveGroupId(props, index) {
5148
5934
  }
5149
5935
  return `group:${index}`;
5150
5936
  }
5151
- function buildColumnDefsFromTree(nodes, sort, onSort) {
5937
+ function buildColumnDefsFromTree(nodes, sort, onSort, headerCache) {
5152
5938
  return nodes.map((node, index) => {
5153
5939
  if (node.type === "leaf") {
5154
- return buildColumnDef(node.props, sort, onSort);
5940
+ return buildColumnDef(node.props, sort, onSort, headerCache);
5155
5941
  }
5156
- const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort);
5942
+ const childDefs = buildColumnDefsFromTree(node.columns, sort, onSort, headerCache);
5157
5943
  const { header, align, headerClassName } = node.props;
5158
5944
  return {
5159
5945
  id: resolveGroupId(node.props, index),
@@ -5181,10 +5967,10 @@ function countLeafColumns(nodes) {
5181
5967
  }
5182
5968
 
5183
5969
  // src/components/ui/table/components/Table/parseTableChildren.ts
5184
- var import_react13 = require("react");
5970
+ var import_react14 = require("react");
5185
5971
 
5186
5972
  // src/components/ui/table/components/Table/tableChildTypes.ts
5187
- var import_react12 = require("react");
5973
+ var import_react13 = require("react");
5188
5974
  var TABLE_HEADER_DISPLAY_NAME = "Table.Header";
5189
5975
  var TABLE_BODY_DISPLAY_NAME = "Table.Body";
5190
5976
  var TABLE_COLUMN_DISPLAY_NAME = "Table.Column";
@@ -5197,19 +5983,19 @@ function getComponentDisplayName(type) {
5197
5983
  return void 0;
5198
5984
  }
5199
5985
  function isTableHeaderElement(child) {
5200
- 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;
5201
5987
  }
5202
5988
  function isTableBodyElement(child) {
5203
- 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;
5204
5990
  }
5205
5991
  function isTableColumnElement(child) {
5206
- 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;
5207
5993
  }
5208
5994
  function isTableColumnGroupElement(child) {
5209
- 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;
5210
5996
  }
5211
5997
  function isTablePaginationElement(child) {
5212
- 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;
5213
5999
  }
5214
6000
 
5215
6001
  // src/components/ui/table/components/Table/parseTableChildren.ts
@@ -5219,7 +6005,7 @@ function parseTableChildren(children) {
5219
6005
  body: null,
5220
6006
  pagination: null
5221
6007
  };
5222
- for (const child of import_react13.Children.toArray(children)) {
6008
+ for (const child of import_react14.Children.toArray(children)) {
5223
6009
  if (isTableHeaderElement(child)) {
5224
6010
  slots.header = child;
5225
6011
  continue;
@@ -5236,7 +6022,7 @@ function parseTableChildren(children) {
5236
6022
  }
5237
6023
  function walkColumnTreeNodes(children) {
5238
6024
  const result = [];
5239
- for (const child of import_react13.Children.toArray(children)) {
6025
+ for (const child of import_react14.Children.toArray(children)) {
5240
6026
  if (isTableColumnElement(child)) {
5241
6027
  result.push({
5242
6028
  type: "leaf",
@@ -5253,7 +6039,7 @@ function walkColumnTreeNodes(children) {
5253
6039
  });
5254
6040
  continue;
5255
6041
  }
5256
- if ((0, import_react13.isValidElement)(child)) {
6042
+ if ((0, import_react14.isValidElement)(child)) {
5257
6043
  const nested = child.props.children;
5258
6044
  if (nested != null) {
5259
6045
  result.push(...walkColumnTreeNodes(nested));
@@ -5289,13 +6075,22 @@ function TableColumnGroup(props) {
5289
6075
  TableColumnGroup.displayName = TABLE_COLUMN_GROUP_DISPLAY_NAME;
5290
6076
 
5291
6077
  // src/components/ui/table/components/Table/tableDataPipeline.ts
5292
- 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") {
5293
6088
  if (!sort) return data;
5294
6089
  const { field, direction } = sort;
5295
6090
  const multiplier = direction === "asc" ? 1 : -1;
5296
6091
  return [...data].sort((left, right) => {
5297
- const leftValue = left[field];
5298
- const rightValue = right[field];
6092
+ const leftValue = readField(left, field);
6093
+ const rightValue = readField(right, field);
5299
6094
  if ((leftValue === null || leftValue === void 0) && (rightValue === null || rightValue === void 0)) {
5300
6095
  return 0;
5301
6096
  }
@@ -5304,11 +6099,12 @@ function sortTableData(data, sort) {
5304
6099
  if (typeof leftValue === "number" && typeof rightValue === "number") {
5305
6100
  return (leftValue - rightValue) * multiplier;
5306
6101
  }
5307
- return String(leftValue).localeCompare(String(rightValue), "ko") * multiplier;
6102
+ return String(leftValue).localeCompare(String(rightValue), locale, { numeric: true }) * multiplier;
5308
6103
  });
5309
6104
  }
5310
6105
  function paginateTableData(data, page, pageSize) {
5311
- const safePage = Math.max(1, page);
6106
+ const lastPage = getTotalPages(data.length, pageSize);
6107
+ const safePage = Math.min(Math.max(1, page), lastPage);
5312
6108
  const start = (safePage - 1) * pageSize;
5313
6109
  return data.slice(start, start + pageSize);
5314
6110
  }
@@ -5316,6 +6112,36 @@ function getTotalPages(totalCount, pageSize) {
5316
6112
  if (pageSize <= 0) return 1;
5317
6113
  return Math.max(1, Math.ceil(totalCount / pageSize));
5318
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
+ }
5319
6145
 
5320
6146
  // src/components/ui/table/components/Table/TableHeader.tsx
5321
6147
  function TableHeader(props) {
@@ -5331,7 +6157,9 @@ function TablePagination({
5331
6157
  pageSize = 10,
5332
6158
  totalCount = 0,
5333
6159
  onChange,
5334
- className
6160
+ className,
6161
+ previousLabel = "Previous page",
6162
+ nextLabel = "Next page"
5335
6163
  }) {
5336
6164
  const totalPages = getTotalPages(totalCount, pageSize);
5337
6165
  const safePage = Math.min(Math.max(1, page), totalPages);
@@ -5345,7 +6173,7 @@ function TablePagination({
5345
6173
  className: "pagination-button",
5346
6174
  disabled: !canGoPrev,
5347
6175
  onClick: () => onChange(safePage - 1),
5348
- "aria-label": "Previous page",
6176
+ "aria-label": previousLabel,
5349
6177
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronLeft, { className: "pagination-button-icon" })
5350
6178
  }
5351
6179
  ),
@@ -5361,7 +6189,7 @@ function TablePagination({
5361
6189
  className: "pagination-button",
5362
6190
  disabled: !canGoNext,
5363
6191
  onClick: () => onChange(safePage + 1),
5364
- "aria-label": "Next page",
6192
+ "aria-label": nextLabel,
5365
6193
  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ChevronRight, { className: "pagination-button-icon" })
5366
6194
  }
5367
6195
  )
@@ -5375,63 +6203,124 @@ function TableRoot({
5375
6203
  data,
5376
6204
  children,
5377
6205
  className,
6206
+ classNames,
5378
6207
  totalCount,
5379
6208
  filteredCount,
6209
+ onDataChange,
6210
+ getRowId,
6211
+ sort: controlledSort,
6212
+ defaultSort = null,
6213
+ onSortChange,
6214
+ sortLocale,
5380
6215
  ...dataTableProps
5381
6216
  }) {
5382
- const { header, pagination: paginationElement } = (0, import_react14.useMemo)(
6217
+ const { header, pagination: paginationElement } = (0, import_react15.useMemo)(
5383
6218
  () => parseTableChildren(children),
5384
6219
  [children]
5385
6220
  );
5386
- const [sort, setSort] = (0, import_react14.useState)(null);
5387
- const handleSort = (0, import_react14.useCallback)((field) => {
5388
- setSort((previous) => {
5389
- if (previous?.field !== field) {
5390
- return { field, direction: "asc" };
5391
- }
5392
- if (previous.direction === "asc") {
5393
- 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;
5394
6232
  }
5395
- return null;
5396
- });
5397
- }, []);
5398
- const columnTree = (0, import_react14.useMemo)(() => extractColumnTree(header), [header]);
5399
- const columns = (0, import_react14.useMemo)(
5400
- () => 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),
5401
6242
  [columnTree, sort, handleSort]
5402
6243
  );
6244
+ const sortContextValue = (0, import_react15.useMemo)(() => ({ sort, onSort: handleSort }), [sort, handleSort]);
5403
6245
  const paginationProps = paginationElement?.props;
5404
6246
  const pageSize = paginationProps?.pageSize ?? 10;
5405
6247
  const page = paginationProps?.page ?? 1;
5406
6248
  const resolvedTotalCount = paginationProps?.totalCount ?? totalCount ?? data.length;
5407
- const tableData = (0, import_react14.useMemo)(() => {
5408
- const sortedData = sortTableData(data, sort);
5409
- 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;
5410
6271
  return paginateTableData(sortedData, page, pageSize);
5411
- }, [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]);
5412
6296
  if (countLeafColumns(columnTree) === 0) {
5413
6297
  console.warn("[Table] Declare at least one Table.Column inside Table.Header.");
5414
6298
  }
5415
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "TableJSX", children: [
5416
- /* @__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)(
5417
6301
  DataTable,
5418
6302
  {
5419
6303
  ...dataTableProps,
6304
+ classNames,
6305
+ getRowId: resolvedGetRowId,
6306
+ onDataChange: handleDataChange,
5420
6307
  data: tableData,
5421
6308
  columns,
5422
6309
  totalCount: paginationProps ? resolvedTotalCount : totalCount,
5423
6310
  filteredCount: filteredCount ?? data.length,
5424
6311
  className: cn(className, paginationProps && "DataTableJSX--with-pagination")
5425
6312
  }
5426
- ),
6313
+ ) }),
5427
6314
  paginationProps && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5428
6315
  TablePagination,
5429
6316
  {
5430
6317
  page,
5431
6318
  pageSize,
5432
- totalCount: resolvedTotalCount,
6319
+ totalCount: pageTotalCount,
5433
6320
  onChange: paginationProps.onChange,
5434
- className: paginationProps.className
6321
+ className: cn(classNames?.pagination, paginationProps.className),
6322
+ previousLabel: paginationProps.previousLabel ?? dataTableProps.labels?.paginationPrevious,
6323
+ nextLabel: paginationProps.nextLabel ?? dataTableProps.labels?.paginationNext
5435
6324
  }
5436
6325
  )
5437
6326
  ] });