@pretable/core 0.0.6 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -587,6 +587,34 @@ function matchesFilters(row, resolvedFilters) {
587
587
  return true;
588
588
  }
589
589
 
590
+ // ../grid-core/dist/group-column.js
591
+ var GROUP_COLUMN_ID = "__pretable_group__";
592
+ var DEFAULT_GROUP_COLUMN_WIDTH_PX = 200;
593
+ function resolveEffectiveColumns(input) {
594
+ const { columns, rowGroups, groupColumn, hideGroupedColumns } = input;
595
+ if (rowGroups.length === 0) {
596
+ return columns;
597
+ }
598
+ const grouped = new Set(rowGroups);
599
+ const kept = hideGroupedColumns === false ? columns : columns.filter((column) => !grouped.has(column.id));
600
+ return [makeGroupColumn(columns, rowGroups, groupColumn), ...kept];
601
+ }
602
+ function makeGroupColumn(columns, rowGroups, groupColumn) {
603
+ const firstLevel = columns.find((column2) => column2.id === rowGroups[0]);
604
+ const column = {
605
+ id: GROUP_COLUMN_ID,
606
+ header: groupColumn?.header ?? firstLevel?.header ?? "",
607
+ widthPx: groupColumn?.widthPx ?? DEFAULT_GROUP_COLUMN_WIDTH_PX,
608
+ // The group column shows a tree, not a value: sorting or filtering it has
609
+ // no meaning, and both would index into a column that has no `value`.
610
+ sortable: false,
611
+ filterable: false,
612
+ resizable: false,
613
+ reorderable: false
614
+ };
615
+ return groupColumn?.pinned === "left" ? { ...column, pinned: "left" } : column;
616
+ }
617
+
590
618
  // ../grid-core/dist/group-expansion.js
591
619
  var DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT = 1e4;
592
620
  function resolveGroupExpansionOverrideLimit(configured) {
@@ -615,31 +643,6 @@ var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
615
643
  function isDataRow(entry) {
616
644
  return entry.kind === "data";
617
645
  }
618
- function scanDataRows(rows, rowId) {
619
- let count2 = 0;
620
- let index = -1;
621
- for (const entry of rows) {
622
- if (!isDataRow(entry))
623
- continue;
624
- if (rowId !== null && entry.id === rowId)
625
- index = count2;
626
- count2 += 1;
627
- }
628
- return { count: count2, index };
629
- }
630
- function dataRowAt(rows, ordinal) {
631
- if (ordinal < 0)
632
- return void 0;
633
- let seen = 0;
634
- for (const entry of rows) {
635
- if (!isDataRow(entry))
636
- continue;
637
- if (seen === ordinal)
638
- return entry;
639
- seen += 1;
640
- }
641
- return void 0;
642
- }
643
646
  function clampColumnWidth(width, column) {
644
647
  const min2 = column.minWidthPx ?? 40;
645
648
  const max2 = column.maxWidthPx ?? Infinity;
@@ -669,7 +672,7 @@ function groupColumnsByPin(columns) {
669
672
  const right = [];
670
673
  for (const column of columns) {
671
674
  const region = column.pinned === "left" ? left : column.pinned === "right" ? right : unpinned;
672
- if (column.id === ROW_SELECT_COLUMN_ID) {
675
+ if (column.id === ROW_SELECT_COLUMN_ID || column.id === GROUP_COLUMN_ID) {
673
676
  region.unshift(column);
674
677
  } else {
675
678
  region.push(column);
@@ -696,6 +699,9 @@ function createGridCore(inputOptions) {
696
699
  let cachedDerivedOverrides = null;
697
700
  let cachedDerivedDefaultExpanded = null;
698
701
  let cachedDerivedAggregateFiltered = null;
702
+ let cachedEffectiveColumns = null;
703
+ let cachedEffectiveColumnsSource = null;
704
+ let cachedEffectiveColumnsRowGroups = null;
699
705
  let sort = [];
700
706
  let filters = {};
701
707
  let rowGroups = sanitizeRowGroups(options.columns.filter((column) => column.rowGroup === true).map((c) => c.id), options.columns);
@@ -723,6 +729,7 @@ function createGridCore(inputOptions) {
723
729
  };
724
730
  },
725
731
  getSnapshot,
732
+ getColumns,
726
733
  setSort(columnId, direction) {
727
734
  const candidate = columnId && direction ? [{ columnId, direction }] : [];
728
735
  const next = sanitizeSortEntries(candidate, options.columns);
@@ -742,26 +749,31 @@ function createGridCore(inputOptions) {
742
749
  },
743
750
  setColumnFilter(columnId, filter) {
744
751
  const current = filters[columnId];
752
+ let next;
745
753
  if (filter && isFilterActive(filter)) {
746
754
  if (current && columnFilterEqual(current, filter)) {
747
755
  return;
748
756
  }
749
- filters = { ...filters, [columnId]: filter };
757
+ next = { ...filters, [columnId]: filter };
750
758
  } else {
751
759
  if (current === void 0) {
752
760
  return;
753
761
  }
754
- const next = { ...filters };
762
+ next = { ...filters };
755
763
  delete next[columnId];
756
- filters = next;
757
764
  }
765
+ const before = captureVisibleRowsForFocusReconciliation();
766
+ filters = next;
767
+ reconcileFocusAfterVisibleModelChange(before);
758
768
  emit();
759
769
  },
760
770
  clearFilters() {
761
771
  if (Object.keys(filters).length === 0) {
762
772
  return;
763
773
  }
774
+ const before = captureVisibleRowsForFocusReconciliation();
764
775
  filters = {};
776
+ reconcileFocusAfterVisibleModelChange(before);
765
777
  emit();
766
778
  },
767
779
  replaceFilters(nextFilters) {
@@ -774,7 +786,9 @@ function createGridCore(inputOptions) {
774
786
  if (filtersEqual(filters, normalized)) {
775
787
  return;
776
788
  }
789
+ const before = captureVisibleRowsForFocusReconciliation();
777
790
  filters = normalized;
791
+ reconcileFocusAfterVisibleModelChange(before);
778
792
  emit();
779
793
  },
780
794
  distinctColumnValues(columnId) {
@@ -810,8 +824,9 @@ function createGridCore(inputOptions) {
810
824
  const dataRows = getSnapshot().visibleRows.filter(isDataRow);
811
825
  const firstRow = dataRows[0];
812
826
  const lastRow = dataRows[dataRows.length - 1];
813
- const firstColumn = options.columns[0];
814
- const lastColumn = options.columns[options.columns.length - 1];
827
+ const effectiveColumns = getColumns();
828
+ const firstColumn = effectiveColumns[0];
829
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
815
830
  if (!firstRow || !lastRow || !firstColumn || !lastColumn) {
816
831
  return;
817
832
  }
@@ -833,7 +848,10 @@ function createGridCore(inputOptions) {
833
848
  emit();
834
849
  },
835
850
  clearSelection() {
836
- const focusAddr = focus.rowId && focus.columnId ? { rowId: focus.rowId, columnId: focus.columnId } : null;
851
+ const focusedRowId = focus.rowId;
852
+ const focusedColumnId = focus.columnId;
853
+ const focusedRow = focusedRowId ? getSnapshot().visibleRows.find((row) => row.id === focusedRowId) : void 0;
854
+ const focusAddr = focusedRow?.kind === "group" || !focusedRowId || !focusedColumnId ? null : { rowId: focusedRowId, columnId: focusedColumnId };
837
855
  const next = focusAddr ? {
838
856
  ranges: [
839
857
  {
@@ -873,8 +891,13 @@ function createGridCore(inputOptions) {
873
891
  emit();
874
892
  },
875
893
  toggleRowSelection(rowId) {
876
- const firstColumn = options.columns[0];
877
- const lastColumn = options.columns[options.columns.length - 1];
894
+ const visibleRow = getSnapshot().visibleRows.find((row) => row.id === rowId);
895
+ if (visibleRow?.kind === "group") {
896
+ return;
897
+ }
898
+ const effectiveColumns = getColumns();
899
+ const firstColumn = effectiveColumns[0];
900
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
878
901
  if (!firstColumn || !lastColumn) {
879
902
  return;
880
903
  }
@@ -898,8 +921,9 @@ function createGridCore(inputOptions) {
898
921
  },
899
922
  setSelectAllVisible(checked) {
900
923
  const dataRows = getSnapshot().visibleRows.filter(isDataRow);
901
- const firstColumn = options.columns[0];
902
- const lastColumn = options.columns[options.columns.length - 1];
924
+ const effectiveColumns = getColumns();
925
+ const firstColumn = effectiveColumns[0];
926
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
903
927
  if (!firstColumn || !lastColumn) {
904
928
  return;
905
929
  }
@@ -937,13 +961,15 @@ function createGridCore(inputOptions) {
937
961
  },
938
962
  moveFocus(direction, moveOptions = {}) {
939
963
  const snapshot = getSnapshot();
940
- const { count: dataRowCount, index: currentRowIndex } = scanDataRows(snapshot.visibleRows, focus.rowId);
941
- const columnList = options.columns;
942
- if (dataRowCount === 0 || columnList.length === 0) {
964
+ const rowList = snapshot.visibleRows;
965
+ const rowCount = rowList.length;
966
+ const columnList = getColumns();
967
+ if (rowCount === 0 || columnList.length === 0) {
943
968
  focus = { rowId: null, columnId: null };
944
969
  emit();
945
970
  return;
946
971
  }
972
+ const currentRowIndex = focus.rowId === null ? -1 : rowList.findIndex((entry) => entry.id === focus.rowId);
947
973
  const currentColumnIndex = focus.columnId ? columnList.findIndex((c) => c.id === focus.columnId) : -1;
948
974
  const hasRowFocus = currentRowIndex !== -1;
949
975
  const hasColumnFocus = currentColumnIndex !== -1;
@@ -951,28 +977,28 @@ function createGridCore(inputOptions) {
951
977
  const baseColumnIndex = hasColumnFocus ? currentColumnIndex : 0;
952
978
  let nextRowIndex = baseRowIndex;
953
979
  let nextColumnIndex = baseColumnIndex;
954
- const pageStep = computePageStep(viewport, dataRowCount);
980
+ const pageStep = computePageStep(viewport, rowCount);
955
981
  switch (direction) {
956
982
  case "up":
957
983
  if (moveOptions.jumpToEdge) {
958
984
  nextRowIndex = 0;
959
985
  } else if (!hasRowFocus) {
960
- nextRowIndex = dataRowCount - 1;
986
+ nextRowIndex = rowCount - 1;
961
987
  } else if (moveOptions.byPage) {
962
- nextRowIndex = clamp(baseRowIndex - pageStep, 0, dataRowCount - 1);
988
+ nextRowIndex = clamp(baseRowIndex - pageStep, 0, rowCount - 1);
963
989
  } else {
964
- nextRowIndex = clamp(baseRowIndex - 1, 0, dataRowCount - 1);
990
+ nextRowIndex = clamp(baseRowIndex - 1, 0, rowCount - 1);
965
991
  }
966
992
  break;
967
993
  case "down":
968
994
  if (moveOptions.jumpToEdge) {
969
- nextRowIndex = dataRowCount - 1;
995
+ nextRowIndex = rowCount - 1;
970
996
  } else if (!hasRowFocus) {
971
997
  nextRowIndex = 0;
972
998
  } else if (moveOptions.byPage) {
973
- nextRowIndex = clamp(baseRowIndex + pageStep, 0, dataRowCount - 1);
999
+ nextRowIndex = clamp(baseRowIndex + pageStep, 0, rowCount - 1);
974
1000
  } else {
975
- nextRowIndex = clamp(baseRowIndex + 1, 0, dataRowCount - 1);
1001
+ nextRowIndex = clamp(baseRowIndex + 1, 0, rowCount - 1);
976
1002
  }
977
1003
  break;
978
1004
  case "left":
@@ -994,7 +1020,7 @@ function createGridCore(inputOptions) {
994
1020
  }
995
1021
  break;
996
1022
  }
997
- const nextRow = dataRowAt(snapshot.visibleRows, nextRowIndex);
1023
+ const nextRow = rowList[nextRowIndex];
998
1024
  const nextColumn = columnList[nextColumnIndex];
999
1025
  if (!nextRow || !nextColumn) {
1000
1026
  return;
@@ -1004,8 +1030,31 @@ function createGridCore(inputOptions) {
1004
1030
  columnId: nextColumn.id
1005
1031
  };
1006
1032
  focus = nextAddr;
1007
- if (moveOptions.extend) {
1008
- if (!selection.anchor) {
1033
+ if (isDataRow(nextRow)) {
1034
+ if (moveOptions.extend) {
1035
+ if (!selection.anchor) {
1036
+ selection = {
1037
+ ranges: [
1038
+ {
1039
+ startRowId: nextAddr.rowId,
1040
+ endRowId: nextAddr.rowId,
1041
+ startColumnId: nextAddr.columnId,
1042
+ endColumnId: nextAddr.columnId
1043
+ }
1044
+ ],
1045
+ anchor: nextAddr
1046
+ };
1047
+ } else {
1048
+ const newActive = {
1049
+ startRowId: selection.anchor.rowId,
1050
+ endRowId: nextAddr.rowId,
1051
+ startColumnId: selection.anchor.columnId,
1052
+ endColumnId: nextAddr.columnId
1053
+ };
1054
+ const ranges = selection.ranges.length === 0 ? [newActive] : [...selection.ranges.slice(0, -1), newActive];
1055
+ selection = { ranges, anchor: selection.anchor };
1056
+ }
1057
+ } else {
1009
1058
  selection = {
1010
1059
  ranges: [
1011
1060
  {
@@ -1017,28 +1066,7 @@ function createGridCore(inputOptions) {
1017
1066
  ],
1018
1067
  anchor: nextAddr
1019
1068
  };
1020
- } else {
1021
- const newActive = {
1022
- startRowId: selection.anchor.rowId,
1023
- endRowId: nextAddr.rowId,
1024
- startColumnId: selection.anchor.columnId,
1025
- endColumnId: nextAddr.columnId
1026
- };
1027
- const ranges = selection.ranges.length === 0 ? [newActive] : [...selection.ranges.slice(0, -1), newActive];
1028
- selection = { ranges, anchor: selection.anchor };
1029
1069
  }
1030
- } else {
1031
- selection = {
1032
- ranges: [
1033
- {
1034
- startRowId: nextAddr.rowId,
1035
- endRowId: nextAddr.rowId,
1036
- startColumnId: nextAddr.columnId,
1037
- endColumnId: nextAddr.columnId
1038
- }
1039
- ],
1040
- anchor: nextAddr
1041
- };
1042
1070
  }
1043
1071
  emit();
1044
1072
  },
@@ -1263,10 +1291,22 @@ function createGridCore(inputOptions) {
1263
1291
  return { ...newCol };
1264
1292
  });
1265
1293
  const grouped = groupColumnsByPin(merged);
1266
- const changed = !sameColumnLayout(options.columns, grouped);
1294
+ const layoutChanged = !sameColumnLayout(options.columns, grouped);
1295
+ const groupingSemanticsChanged = !sameColumnGroupingSemantics(options.columns, grouped);
1296
+ const before = groupingSemanticsChanged ? captureVisibleRowsForFocusReconciliation() : null;
1267
1297
  originalColumns = groupColumnsByPin(nextColumns).map((c) => ({ ...c }));
1268
1298
  options = { ...options, columns: grouped };
1269
- if (changed) {
1299
+ const nextRowGroups = sanitizeRowGroups(rowGroups, grouped);
1300
+ const sanitizedGroupingChanged = !stringListsEqual(rowGroups, nextRowGroups);
1301
+ if (sanitizedGroupingChanged) {
1302
+ rowGroups = nextRowGroups;
1303
+ groupExpansionOverrides = /* @__PURE__ */ new Set();
1304
+ }
1305
+ if (groupingSemanticsChanged) {
1306
+ cachedVisibleRows = null;
1307
+ reconcileFocusAfterVisibleModelChange(before);
1308
+ }
1309
+ if (layoutChanged || groupingSemanticsChanged || sanitizedGroupingChanged) {
1270
1310
  emit();
1271
1311
  }
1272
1312
  },
@@ -1275,6 +1315,7 @@ function createGridCore(inputOptions) {
1275
1315
  throw new Error("applyTransaction requires getRowId on PretableGridOptions");
1276
1316
  }
1277
1317
  const getRowId = options.getRowId;
1318
+ const before = captureVisibleRowsForFocusReconciliation();
1278
1319
  if (transaction.remove) {
1279
1320
  const removeSet = new Set(transaction.remove);
1280
1321
  sourceRows = sourceRows.filter((entry) => {
@@ -1318,9 +1359,11 @@ function createGridCore(inputOptions) {
1318
1359
  }
1319
1360
  }
1320
1361
  cachedVisibleRows = null;
1362
+ reconcileFocusAfterVisibleModelChange(before);
1321
1363
  emit();
1322
1364
  },
1323
1365
  setRows(nextRows) {
1366
+ const before = captureVisibleRowsForFocusReconciliation();
1324
1367
  options = { ...options, rows: nextRows };
1325
1368
  sourceRows = createSourceRows(options);
1326
1369
  sourceRowIndex.clear();
@@ -1336,9 +1379,6 @@ function createGridCore(inputOptions) {
1336
1379
  anchor: anchorValid ? selection.anchor : null
1337
1380
  };
1338
1381
  }
1339
- if (focus.rowId !== null && !hasRow(focus.rowId)) {
1340
- focus = { rowId: null, columnId: null };
1341
- }
1342
1382
  if (editing && !hasRow(editing.rowId)) {
1343
1383
  editing = null;
1344
1384
  }
@@ -1363,6 +1403,7 @@ function createGridCore(inputOptions) {
1363
1403
  };
1364
1404
  }
1365
1405
  cachedVisibleRows = null;
1406
+ reconcileFocusAfterVisibleModelChange(before);
1366
1407
  emit();
1367
1408
  },
1368
1409
  setRowGroups(columnIds) {
@@ -1370,8 +1411,10 @@ function createGridCore(inputOptions) {
1370
1411
  if (stringListsEqual(rowGroups, next)) {
1371
1412
  return;
1372
1413
  }
1414
+ const before = captureVisibleRowsForFocusReconciliation();
1373
1415
  rowGroups = next;
1374
1416
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1417
+ reconcileFocusAfterVisibleModelChange(before);
1375
1418
  emit();
1376
1419
  },
1377
1420
  toggleGroup(groupId) {
@@ -1381,6 +1424,7 @@ function createGridCore(inputOptions) {
1381
1424
  if (isGroupExpanded(groupId) === expanded) {
1382
1425
  return;
1383
1426
  }
1427
+ const before = captureVisibleRowsForFocusReconciliation();
1384
1428
  if (expanded === groupsDefaultExpanded) {
1385
1429
  const next = new Set(groupExpansionOverrides);
1386
1430
  next.delete(groupId);
@@ -1388,6 +1432,9 @@ function createGridCore(inputOptions) {
1388
1432
  } else {
1389
1433
  groupExpansionOverrides = addGroupExpansionOverride(groupExpansionOverrides, groupId, groupExpansionOverrideLimit);
1390
1434
  }
1435
+ reconcileFocusAfterVisibleModelChange(before, {
1436
+ preferAncestor: !expanded
1437
+ });
1391
1438
  emit();
1392
1439
  },
1393
1440
  expandAll() {
@@ -1462,10 +1509,53 @@ function createGridCore(inputOptions) {
1462
1509
  if (groupsDefaultExpanded === expanded && groupExpansionOverrides.size === 0) {
1463
1510
  return;
1464
1511
  }
1512
+ const before = captureVisibleRowsForFocusReconciliation();
1465
1513
  groupsDefaultExpanded = expanded;
1466
1514
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1515
+ reconcileFocusAfterVisibleModelChange(before, {
1516
+ preferAncestor: !expanded
1517
+ });
1467
1518
  emit();
1468
1519
  }
1520
+ function captureVisibleRowsForFocusReconciliation() {
1521
+ return focus.rowId === null && focus.columnId === null ? null : getSnapshot().visibleRows;
1522
+ }
1523
+ function reconcileFocusAfterVisibleModelChange(before, options2 = {}) {
1524
+ if (before === null || focus.rowId === null && focus.columnId === null) {
1525
+ return;
1526
+ }
1527
+ const oldRowId = focus.rowId;
1528
+ const oldIndex = oldRowId === null ? -1 : before.findIndex((entry) => entry.id === oldRowId);
1529
+ cachedSnapshot = null;
1530
+ const afterRows = getSnapshot().visibleRows;
1531
+ const afterColumns = getColumns();
1532
+ if (afterRows.length === 0 || afterColumns.length === 0) {
1533
+ focus = { rowId: null, columnId: null };
1534
+ cachedSnapshot = null;
1535
+ return;
1536
+ }
1537
+ const survivingRowIds = new Set(afterRows.map((entry) => entry.id));
1538
+ let nextRowId = oldRowId !== null && survivingRowIds.has(oldRowId) ? oldRowId : null;
1539
+ if (nextRowId === null && options2.preferAncestor === true && oldIndex !== -1) {
1540
+ const oldDepth = before[oldIndex].depth;
1541
+ for (let i = oldIndex - 1; i >= 0; i -= 1) {
1542
+ const candidate = before[i];
1543
+ if (candidate.kind === "group" && candidate.depth < oldDepth && survivingRowIds.has(candidate.id)) {
1544
+ nextRowId = candidate.id;
1545
+ break;
1546
+ }
1547
+ }
1548
+ }
1549
+ if (nextRowId === null) {
1550
+ const nextIndex = oldIndex === -1 ? 0 : clamp(oldIndex, 0, afterRows.length - 1);
1551
+ nextRowId = afterRows[nextIndex].id;
1552
+ }
1553
+ const focusedColumnSurvives = focus.columnId !== null && afterColumns.some((column) => column.id === focus.columnId);
1554
+ const groupColumn = rowGroups.length > 0 ? afterColumns.find((column) => column.id === GROUP_COLUMN_ID) : void 0;
1555
+ const nextColumnId = focusedColumnSurvives ? focus.columnId : groupColumn?.id ?? afterColumns[0].id;
1556
+ focus = { rowId: nextRowId, columnId: nextColumnId };
1557
+ cachedSnapshot = null;
1558
+ }
1469
1559
  function preserveAggregateIdentity(rows) {
1470
1560
  const next = /* @__PURE__ */ new Map();
1471
1561
  let result = rows;
@@ -1486,6 +1576,22 @@ function createGridCore(inputOptions) {
1486
1576
  previousAggregates = next;
1487
1577
  return result;
1488
1578
  }
1579
+ function getColumns() {
1580
+ if (cachedEffectiveColumns !== null && cachedEffectiveColumnsSource === options.columns && cachedEffectiveColumnsRowGroups === rowGroups) {
1581
+ return cachedEffectiveColumns;
1582
+ }
1583
+ const resolved = resolveEffectiveColumns({
1584
+ columns: options.columns,
1585
+ rowGroups,
1586
+ groupColumn: options.groupColumn,
1587
+ hideGroupedColumns: options.hideGroupedColumns
1588
+ });
1589
+ const effective = resolved === options.columns ? resolved : groupColumnsByPin(resolved);
1590
+ cachedEffectiveColumns = effective;
1591
+ cachedEffectiveColumnsSource = options.columns;
1592
+ cachedEffectiveColumnsRowGroups = rowGroups;
1593
+ return effective;
1594
+ }
1489
1595
  function getSnapshot() {
1490
1596
  if (cachedSnapshot) {
1491
1597
  return cachedSnapshot;
@@ -1550,12 +1656,21 @@ function sameColumnLayout(a, b) {
1550
1656
  return left.id === right.id && left.header === right.header && left.widthPx === right.widthPx && left.minWidthPx === right.minWidthPx && left.maxWidthPx === right.maxWidthPx && left.pinned === right.pinned && left.sortable === right.sortable && left.filterable === right.filterable && left.resizable === right.resizable && left.reorderable === right.reorderable && left.wrap === right.wrap;
1551
1657
  });
1552
1658
  }
1553
- function computePageStep(viewport, dataRowCount) {
1554
- if (viewport.height <= 0 || dataRowCount === 0) {
1659
+ function sameColumnGroupingSemantics(a, b) {
1660
+ if (a.length !== b.length) {
1661
+ return false;
1662
+ }
1663
+ return a.every((left, index) => {
1664
+ const right = b[index];
1665
+ return left.id === right.id && left.value === right.value && left.aggregate === right.aggregate;
1666
+ });
1667
+ }
1668
+ function computePageStep(viewport, rowCount) {
1669
+ if (viewport.height <= 0 || rowCount === 0) {
1555
1670
  return 1;
1556
1671
  }
1557
1672
  const estimatedRowsPerPage = Math.max(1, Math.floor(viewport.height * 0.8 / 32));
1558
- return Math.min(estimatedRowsPerPage, dataRowCount);
1673
+ return Math.min(estimatedRowsPerPage, rowCount);
1559
1674
  }
1560
1675
  function isFullRowRange(range, rowId, firstColumnId, lastColumnId) {
1561
1676
  return range.startRowId === rowId && range.endRowId === rowId && range.startColumnId === firstColumnId && range.endColumnId === lastColumnId;
@@ -1657,6 +1772,7 @@ function createGrid(options) {
1657
1772
  },
1658
1773
  subscribe: engine.subscribe,
1659
1774
  getSnapshot: engine.getSnapshot,
1775
+ getColumns: engine.getColumns,
1660
1776
  setSort: engine.setSort,
1661
1777
  replaceSort: engine.replaceSort,
1662
1778
  setColumnFilter: engine.setColumnFilter,
@@ -1700,4 +1816,5 @@ function createGrid(options) {
1700
1816
  };
1701
1817
  }
1702
1818
 
1819
+ exports.GROUP_COLUMN_ID = GROUP_COLUMN_ID;
1703
1820
  exports.createGrid = createGrid;
package/dist/index.d.cts CHANGED
@@ -20,6 +20,37 @@ interface AutosizeOptions {
20
20
  cellPaddingPx?: number;
21
21
  }
22
22
 
23
+ /**
24
+ * Id of the synthetic column that carries the group label, twisty and child
25
+ * count for every grouping level.
26
+ *
27
+ * It is *derived*, never stored: `options.columns` remains the consumer's
28
+ * truth, and {@link resolveEffectiveColumns} rebuilds this column on read
29
+ * whenever `rowGroups` is non-empty. The alternative — pushing it into
30
+ * `options.columns` — cannot work, because `mergeColumnsFromProps` rebuilds
31
+ * that array by mapping over the consumer's own array and would delete any
32
+ * column props never mentioned.
33
+ *
34
+ * @public
35
+ */
36
+ declare const GROUP_COLUMN_ID = "__pretable_group__";
37
+ /**
38
+ * Configuration for the derived group column.
39
+ *
40
+ * @public
41
+ */
42
+ interface PretableGroupColumnOptions {
43
+ /** Header text. Defaults to the header of the first grouped column. */
44
+ header?: string;
45
+ /** Column width. Defaults to 200. */
46
+ widthPx?: number;
47
+ /**
48
+ * Pin the group column to the left. Unpinned by default — pinning it would
49
+ * silently consume the pinned-left region a consumer may already be using.
50
+ */
51
+ pinned?: "left";
52
+ }
53
+
23
54
  /**
24
55
  * Base row constraint — every row is at minimum a string-keyed record.
25
56
  *
@@ -100,6 +131,15 @@ interface PretableColumn<TRow extends PretableRow = PretableRow> {
100
131
  options?: ColumnOption[];
101
132
  value?: (row: TRow) => unknown;
102
133
  format?: (input: PretableFormatInput<TRow>) => string;
134
+ /**
135
+ * Render this column's aggregate on a group row.
136
+ *
137
+ * Deliberately not `format`: `PretableFormatInput.row` is non-optional, so
138
+ * every consumer formatter is entitled to dereference it, and a group row has
139
+ * no row. Columns without `formatAggregate` fall back to the same default
140
+ * stringification a plain cell uses.
141
+ */
142
+ formatAggregate?: (input: PretableAggregateFormatInput<TRow>) => string;
103
143
  minWidthPx?: number;
104
144
  maxWidthPx?: number;
105
145
  /**
@@ -132,6 +172,17 @@ interface PretableFormatInput<TRow extends PretableRow = PretableRow> {
132
172
  row: TRow;
133
173
  column: PretableColumn<TRow>;
134
174
  }
175
+ /**
176
+ * Input passed to a column's `formatAggregate` function. Carries the group row
177
+ * in place of a data row — an aggregate has no row behind it.
178
+ *
179
+ * @public
180
+ */
181
+ interface PretableAggregateFormatInput<TRow extends PretableRow = PretableRow> {
182
+ value: unknown;
183
+ column: PretableColumn<TRow>;
184
+ group: PretableGroupRow;
185
+ }
135
186
  /**
136
187
  * Options accepted by `createGrid`.
137
188
  *
@@ -172,6 +223,18 @@ interface PretableGridOptions<TRow extends PretableRow = PretableRow> {
172
223
  * matter how many groups exist.
173
224
  */
174
225
  groupExpansionOverrideLimit?: number;
226
+ /**
227
+ * Configure the derived group column — the synthetic column that carries the
228
+ * label, twisty and child count for every grouping level. Present in
229
+ * `getColumns()` exactly while `rowGroups` is non-empty.
230
+ */
231
+ groupColumn?: PretableGroupColumnOptions;
232
+ /**
233
+ * Drop the grouped columns from the data area while grouping is active.
234
+ * Default `true`, uniformly — whether the grouping came from `rowGroup: true`
235
+ * on a column or from a later `setRowGroups` call.
236
+ */
237
+ hideGroupedColumns?: boolean;
175
238
  }
176
239
  /**
177
240
  * One entry in the ordered sort list; index in the list = priority.
@@ -376,6 +439,13 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
376
439
  subscribe(listener: () => void): () => void;
377
440
  /** Read the current snapshot. Stable reference until the next mutation. */
378
441
  getSnapshot(): PretableGridSnapshot<TRow>;
442
+ /**
443
+ * The columns to draw: `options.columns` plus the derived group column, minus
444
+ * the grouped columns, while grouping is active. Identical to
445
+ * `options.columns` — by identity — when ungrouped. Stable reference until
446
+ * the columns or the grouping levels change.
447
+ */
448
+ getColumns(): readonly PretableColumn<TRow>[];
379
449
  setSort(columnId: string | null, direction: PretableSortDirection): void;
380
450
  /** Atomically replace the ordered sort list. Unknown and `sortable: false` columns are dropped. */
381
451
  replaceSort(entries: PretableSortEntry[]): void;
@@ -463,4 +533,4 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
463
533
  */
464
534
  declare function createGrid<TRow extends PretableRow = PretableRow>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
465
535
 
466
- export { type AutosizeOptions, type ColumnFilter, type ColumnOption, type ColumnType, type FilterOperator, type FilterValue, type PretableAggregateSpec, type PretableAggregator, type PretableCellAddress, type PretableCellRange, type PretableColumn, type PretableDataRow, type PretableEditInput, type PretableEditState, type PretableEditStatus, type PretableFocusDirection, type PretableFocusState, type PretableFormatInput, type PretableGrid, type PretableGridOptions, type PretableGridSnapshot, type PretableGroupRow, type PretableMoveFocusOptions, type PretableRow, type PretableRowRange, type PretableRowSelectionTriState, type PretableSelectionState, type PretableSortDirection, type PretableSortEntry, type PretableTransaction, type PretableViewportState, type PretableVisibleRow, createGrid };
536
+ export { type AutosizeOptions, type ColumnFilter, type ColumnOption, type ColumnType, type FilterOperator, type FilterValue, GROUP_COLUMN_ID, type PretableAggregateFormatInput, type PretableAggregateSpec, type PretableAggregator, type PretableCellAddress, type PretableCellRange, type PretableColumn, type PretableDataRow, type PretableEditInput, type PretableEditState, type PretableEditStatus, type PretableFocusDirection, type PretableFocusState, type PretableFormatInput, type PretableGrid, type PretableGridOptions, type PretableGridSnapshot, type PretableGroupColumnOptions, type PretableGroupRow, type PretableMoveFocusOptions, type PretableRow, type PretableRowRange, type PretableRowSelectionTriState, type PretableSelectionState, type PretableSortDirection, type PretableSortEntry, type PretableTransaction, type PretableViewportState, type PretableVisibleRow, createGrid };
package/dist/index.d.ts CHANGED
@@ -20,6 +20,37 @@ interface AutosizeOptions {
20
20
  cellPaddingPx?: number;
21
21
  }
22
22
 
23
+ /**
24
+ * Id of the synthetic column that carries the group label, twisty and child
25
+ * count for every grouping level.
26
+ *
27
+ * It is *derived*, never stored: `options.columns` remains the consumer's
28
+ * truth, and {@link resolveEffectiveColumns} rebuilds this column on read
29
+ * whenever `rowGroups` is non-empty. The alternative — pushing it into
30
+ * `options.columns` — cannot work, because `mergeColumnsFromProps` rebuilds
31
+ * that array by mapping over the consumer's own array and would delete any
32
+ * column props never mentioned.
33
+ *
34
+ * @public
35
+ */
36
+ declare const GROUP_COLUMN_ID = "__pretable_group__";
37
+ /**
38
+ * Configuration for the derived group column.
39
+ *
40
+ * @public
41
+ */
42
+ interface PretableGroupColumnOptions {
43
+ /** Header text. Defaults to the header of the first grouped column. */
44
+ header?: string;
45
+ /** Column width. Defaults to 200. */
46
+ widthPx?: number;
47
+ /**
48
+ * Pin the group column to the left. Unpinned by default — pinning it would
49
+ * silently consume the pinned-left region a consumer may already be using.
50
+ */
51
+ pinned?: "left";
52
+ }
53
+
23
54
  /**
24
55
  * Base row constraint — every row is at minimum a string-keyed record.
25
56
  *
@@ -100,6 +131,15 @@ interface PretableColumn<TRow extends PretableRow = PretableRow> {
100
131
  options?: ColumnOption[];
101
132
  value?: (row: TRow) => unknown;
102
133
  format?: (input: PretableFormatInput<TRow>) => string;
134
+ /**
135
+ * Render this column's aggregate on a group row.
136
+ *
137
+ * Deliberately not `format`: `PretableFormatInput.row` is non-optional, so
138
+ * every consumer formatter is entitled to dereference it, and a group row has
139
+ * no row. Columns without `formatAggregate` fall back to the same default
140
+ * stringification a plain cell uses.
141
+ */
142
+ formatAggregate?: (input: PretableAggregateFormatInput<TRow>) => string;
103
143
  minWidthPx?: number;
104
144
  maxWidthPx?: number;
105
145
  /**
@@ -132,6 +172,17 @@ interface PretableFormatInput<TRow extends PretableRow = PretableRow> {
132
172
  row: TRow;
133
173
  column: PretableColumn<TRow>;
134
174
  }
175
+ /**
176
+ * Input passed to a column's `formatAggregate` function. Carries the group row
177
+ * in place of a data row — an aggregate has no row behind it.
178
+ *
179
+ * @public
180
+ */
181
+ interface PretableAggregateFormatInput<TRow extends PretableRow = PretableRow> {
182
+ value: unknown;
183
+ column: PretableColumn<TRow>;
184
+ group: PretableGroupRow;
185
+ }
135
186
  /**
136
187
  * Options accepted by `createGrid`.
137
188
  *
@@ -172,6 +223,18 @@ interface PretableGridOptions<TRow extends PretableRow = PretableRow> {
172
223
  * matter how many groups exist.
173
224
  */
174
225
  groupExpansionOverrideLimit?: number;
226
+ /**
227
+ * Configure the derived group column — the synthetic column that carries the
228
+ * label, twisty and child count for every grouping level. Present in
229
+ * `getColumns()` exactly while `rowGroups` is non-empty.
230
+ */
231
+ groupColumn?: PretableGroupColumnOptions;
232
+ /**
233
+ * Drop the grouped columns from the data area while grouping is active.
234
+ * Default `true`, uniformly — whether the grouping came from `rowGroup: true`
235
+ * on a column or from a later `setRowGroups` call.
236
+ */
237
+ hideGroupedColumns?: boolean;
175
238
  }
176
239
  /**
177
240
  * One entry in the ordered sort list; index in the list = priority.
@@ -376,6 +439,13 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
376
439
  subscribe(listener: () => void): () => void;
377
440
  /** Read the current snapshot. Stable reference until the next mutation. */
378
441
  getSnapshot(): PretableGridSnapshot<TRow>;
442
+ /**
443
+ * The columns to draw: `options.columns` plus the derived group column, minus
444
+ * the grouped columns, while grouping is active. Identical to
445
+ * `options.columns` — by identity — when ungrouped. Stable reference until
446
+ * the columns or the grouping levels change.
447
+ */
448
+ getColumns(): readonly PretableColumn<TRow>[];
379
449
  setSort(columnId: string | null, direction: PretableSortDirection): void;
380
450
  /** Atomically replace the ordered sort list. Unknown and `sortable: false` columns are dropped. */
381
451
  replaceSort(entries: PretableSortEntry[]): void;
@@ -463,4 +533,4 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
463
533
  */
464
534
  declare function createGrid<TRow extends PretableRow = PretableRow>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
465
535
 
466
- export { type AutosizeOptions, type ColumnFilter, type ColumnOption, type ColumnType, type FilterOperator, type FilterValue, type PretableAggregateSpec, type PretableAggregator, type PretableCellAddress, type PretableCellRange, type PretableColumn, type PretableDataRow, type PretableEditInput, type PretableEditState, type PretableEditStatus, type PretableFocusDirection, type PretableFocusState, type PretableFormatInput, type PretableGrid, type PretableGridOptions, type PretableGridSnapshot, type PretableGroupRow, type PretableMoveFocusOptions, type PretableRow, type PretableRowRange, type PretableRowSelectionTriState, type PretableSelectionState, type PretableSortDirection, type PretableSortEntry, type PretableTransaction, type PretableViewportState, type PretableVisibleRow, createGrid };
536
+ export { type AutosizeOptions, type ColumnFilter, type ColumnOption, type ColumnType, type FilterOperator, type FilterValue, GROUP_COLUMN_ID, type PretableAggregateFormatInput, type PretableAggregateSpec, type PretableAggregator, type PretableCellAddress, type PretableCellRange, type PretableColumn, type PretableDataRow, type PretableEditInput, type PretableEditState, type PretableEditStatus, type PretableFocusDirection, type PretableFocusState, type PretableFormatInput, type PretableGrid, type PretableGridOptions, type PretableGridSnapshot, type PretableGroupColumnOptions, type PretableGroupRow, type PretableMoveFocusOptions, type PretableRow, type PretableRowRange, type PretableRowSelectionTriState, type PretableSelectionState, type PretableSortDirection, type PretableSortEntry, type PretableTransaction, type PretableViewportState, type PretableVisibleRow, createGrid };
package/dist/index.mjs CHANGED
@@ -585,6 +585,34 @@ function matchesFilters(row, resolvedFilters) {
585
585
  return true;
586
586
  }
587
587
 
588
+ // ../grid-core/dist/group-column.js
589
+ var GROUP_COLUMN_ID = "__pretable_group__";
590
+ var DEFAULT_GROUP_COLUMN_WIDTH_PX = 200;
591
+ function resolveEffectiveColumns(input) {
592
+ const { columns, rowGroups, groupColumn, hideGroupedColumns } = input;
593
+ if (rowGroups.length === 0) {
594
+ return columns;
595
+ }
596
+ const grouped = new Set(rowGroups);
597
+ const kept = hideGroupedColumns === false ? columns : columns.filter((column) => !grouped.has(column.id));
598
+ return [makeGroupColumn(columns, rowGroups, groupColumn), ...kept];
599
+ }
600
+ function makeGroupColumn(columns, rowGroups, groupColumn) {
601
+ const firstLevel = columns.find((column2) => column2.id === rowGroups[0]);
602
+ const column = {
603
+ id: GROUP_COLUMN_ID,
604
+ header: groupColumn?.header ?? firstLevel?.header ?? "",
605
+ widthPx: groupColumn?.widthPx ?? DEFAULT_GROUP_COLUMN_WIDTH_PX,
606
+ // The group column shows a tree, not a value: sorting or filtering it has
607
+ // no meaning, and both would index into a column that has no `value`.
608
+ sortable: false,
609
+ filterable: false,
610
+ resizable: false,
611
+ reorderable: false
612
+ };
613
+ return groupColumn?.pinned === "left" ? { ...column, pinned: "left" } : column;
614
+ }
615
+
588
616
  // ../grid-core/dist/group-expansion.js
589
617
  var DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT = 1e4;
590
618
  function resolveGroupExpansionOverrideLimit(configured) {
@@ -613,31 +641,6 @@ var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
613
641
  function isDataRow(entry) {
614
642
  return entry.kind === "data";
615
643
  }
616
- function scanDataRows(rows, rowId) {
617
- let count2 = 0;
618
- let index = -1;
619
- for (const entry of rows) {
620
- if (!isDataRow(entry))
621
- continue;
622
- if (rowId !== null && entry.id === rowId)
623
- index = count2;
624
- count2 += 1;
625
- }
626
- return { count: count2, index };
627
- }
628
- function dataRowAt(rows, ordinal) {
629
- if (ordinal < 0)
630
- return void 0;
631
- let seen = 0;
632
- for (const entry of rows) {
633
- if (!isDataRow(entry))
634
- continue;
635
- if (seen === ordinal)
636
- return entry;
637
- seen += 1;
638
- }
639
- return void 0;
640
- }
641
644
  function clampColumnWidth(width, column) {
642
645
  const min2 = column.minWidthPx ?? 40;
643
646
  const max2 = column.maxWidthPx ?? Infinity;
@@ -667,7 +670,7 @@ function groupColumnsByPin(columns) {
667
670
  const right = [];
668
671
  for (const column of columns) {
669
672
  const region = column.pinned === "left" ? left : column.pinned === "right" ? right : unpinned;
670
- if (column.id === ROW_SELECT_COLUMN_ID) {
673
+ if (column.id === ROW_SELECT_COLUMN_ID || column.id === GROUP_COLUMN_ID) {
671
674
  region.unshift(column);
672
675
  } else {
673
676
  region.push(column);
@@ -694,6 +697,9 @@ function createGridCore(inputOptions) {
694
697
  let cachedDerivedOverrides = null;
695
698
  let cachedDerivedDefaultExpanded = null;
696
699
  let cachedDerivedAggregateFiltered = null;
700
+ let cachedEffectiveColumns = null;
701
+ let cachedEffectiveColumnsSource = null;
702
+ let cachedEffectiveColumnsRowGroups = null;
697
703
  let sort = [];
698
704
  let filters = {};
699
705
  let rowGroups = sanitizeRowGroups(options.columns.filter((column) => column.rowGroup === true).map((c) => c.id), options.columns);
@@ -721,6 +727,7 @@ function createGridCore(inputOptions) {
721
727
  };
722
728
  },
723
729
  getSnapshot,
730
+ getColumns,
724
731
  setSort(columnId, direction) {
725
732
  const candidate = columnId && direction ? [{ columnId, direction }] : [];
726
733
  const next = sanitizeSortEntries(candidate, options.columns);
@@ -740,26 +747,31 @@ function createGridCore(inputOptions) {
740
747
  },
741
748
  setColumnFilter(columnId, filter) {
742
749
  const current = filters[columnId];
750
+ let next;
743
751
  if (filter && isFilterActive(filter)) {
744
752
  if (current && columnFilterEqual(current, filter)) {
745
753
  return;
746
754
  }
747
- filters = { ...filters, [columnId]: filter };
755
+ next = { ...filters, [columnId]: filter };
748
756
  } else {
749
757
  if (current === void 0) {
750
758
  return;
751
759
  }
752
- const next = { ...filters };
760
+ next = { ...filters };
753
761
  delete next[columnId];
754
- filters = next;
755
762
  }
763
+ const before = captureVisibleRowsForFocusReconciliation();
764
+ filters = next;
765
+ reconcileFocusAfterVisibleModelChange(before);
756
766
  emit();
757
767
  },
758
768
  clearFilters() {
759
769
  if (Object.keys(filters).length === 0) {
760
770
  return;
761
771
  }
772
+ const before = captureVisibleRowsForFocusReconciliation();
762
773
  filters = {};
774
+ reconcileFocusAfterVisibleModelChange(before);
763
775
  emit();
764
776
  },
765
777
  replaceFilters(nextFilters) {
@@ -772,7 +784,9 @@ function createGridCore(inputOptions) {
772
784
  if (filtersEqual(filters, normalized)) {
773
785
  return;
774
786
  }
787
+ const before = captureVisibleRowsForFocusReconciliation();
775
788
  filters = normalized;
789
+ reconcileFocusAfterVisibleModelChange(before);
776
790
  emit();
777
791
  },
778
792
  distinctColumnValues(columnId) {
@@ -808,8 +822,9 @@ function createGridCore(inputOptions) {
808
822
  const dataRows = getSnapshot().visibleRows.filter(isDataRow);
809
823
  const firstRow = dataRows[0];
810
824
  const lastRow = dataRows[dataRows.length - 1];
811
- const firstColumn = options.columns[0];
812
- const lastColumn = options.columns[options.columns.length - 1];
825
+ const effectiveColumns = getColumns();
826
+ const firstColumn = effectiveColumns[0];
827
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
813
828
  if (!firstRow || !lastRow || !firstColumn || !lastColumn) {
814
829
  return;
815
830
  }
@@ -831,7 +846,10 @@ function createGridCore(inputOptions) {
831
846
  emit();
832
847
  },
833
848
  clearSelection() {
834
- const focusAddr = focus.rowId && focus.columnId ? { rowId: focus.rowId, columnId: focus.columnId } : null;
849
+ const focusedRowId = focus.rowId;
850
+ const focusedColumnId = focus.columnId;
851
+ const focusedRow = focusedRowId ? getSnapshot().visibleRows.find((row) => row.id === focusedRowId) : void 0;
852
+ const focusAddr = focusedRow?.kind === "group" || !focusedRowId || !focusedColumnId ? null : { rowId: focusedRowId, columnId: focusedColumnId };
835
853
  const next = focusAddr ? {
836
854
  ranges: [
837
855
  {
@@ -871,8 +889,13 @@ function createGridCore(inputOptions) {
871
889
  emit();
872
890
  },
873
891
  toggleRowSelection(rowId) {
874
- const firstColumn = options.columns[0];
875
- const lastColumn = options.columns[options.columns.length - 1];
892
+ const visibleRow = getSnapshot().visibleRows.find((row) => row.id === rowId);
893
+ if (visibleRow?.kind === "group") {
894
+ return;
895
+ }
896
+ const effectiveColumns = getColumns();
897
+ const firstColumn = effectiveColumns[0];
898
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
876
899
  if (!firstColumn || !lastColumn) {
877
900
  return;
878
901
  }
@@ -896,8 +919,9 @@ function createGridCore(inputOptions) {
896
919
  },
897
920
  setSelectAllVisible(checked) {
898
921
  const dataRows = getSnapshot().visibleRows.filter(isDataRow);
899
- const firstColumn = options.columns[0];
900
- const lastColumn = options.columns[options.columns.length - 1];
922
+ const effectiveColumns = getColumns();
923
+ const firstColumn = effectiveColumns[0];
924
+ const lastColumn = effectiveColumns[effectiveColumns.length - 1];
901
925
  if (!firstColumn || !lastColumn) {
902
926
  return;
903
927
  }
@@ -935,13 +959,15 @@ function createGridCore(inputOptions) {
935
959
  },
936
960
  moveFocus(direction, moveOptions = {}) {
937
961
  const snapshot = getSnapshot();
938
- const { count: dataRowCount, index: currentRowIndex } = scanDataRows(snapshot.visibleRows, focus.rowId);
939
- const columnList = options.columns;
940
- if (dataRowCount === 0 || columnList.length === 0) {
962
+ const rowList = snapshot.visibleRows;
963
+ const rowCount = rowList.length;
964
+ const columnList = getColumns();
965
+ if (rowCount === 0 || columnList.length === 0) {
941
966
  focus = { rowId: null, columnId: null };
942
967
  emit();
943
968
  return;
944
969
  }
970
+ const currentRowIndex = focus.rowId === null ? -1 : rowList.findIndex((entry) => entry.id === focus.rowId);
945
971
  const currentColumnIndex = focus.columnId ? columnList.findIndex((c) => c.id === focus.columnId) : -1;
946
972
  const hasRowFocus = currentRowIndex !== -1;
947
973
  const hasColumnFocus = currentColumnIndex !== -1;
@@ -949,28 +975,28 @@ function createGridCore(inputOptions) {
949
975
  const baseColumnIndex = hasColumnFocus ? currentColumnIndex : 0;
950
976
  let nextRowIndex = baseRowIndex;
951
977
  let nextColumnIndex = baseColumnIndex;
952
- const pageStep = computePageStep(viewport, dataRowCount);
978
+ const pageStep = computePageStep(viewport, rowCount);
953
979
  switch (direction) {
954
980
  case "up":
955
981
  if (moveOptions.jumpToEdge) {
956
982
  nextRowIndex = 0;
957
983
  } else if (!hasRowFocus) {
958
- nextRowIndex = dataRowCount - 1;
984
+ nextRowIndex = rowCount - 1;
959
985
  } else if (moveOptions.byPage) {
960
- nextRowIndex = clamp(baseRowIndex - pageStep, 0, dataRowCount - 1);
986
+ nextRowIndex = clamp(baseRowIndex - pageStep, 0, rowCount - 1);
961
987
  } else {
962
- nextRowIndex = clamp(baseRowIndex - 1, 0, dataRowCount - 1);
988
+ nextRowIndex = clamp(baseRowIndex - 1, 0, rowCount - 1);
963
989
  }
964
990
  break;
965
991
  case "down":
966
992
  if (moveOptions.jumpToEdge) {
967
- nextRowIndex = dataRowCount - 1;
993
+ nextRowIndex = rowCount - 1;
968
994
  } else if (!hasRowFocus) {
969
995
  nextRowIndex = 0;
970
996
  } else if (moveOptions.byPage) {
971
- nextRowIndex = clamp(baseRowIndex + pageStep, 0, dataRowCount - 1);
997
+ nextRowIndex = clamp(baseRowIndex + pageStep, 0, rowCount - 1);
972
998
  } else {
973
- nextRowIndex = clamp(baseRowIndex + 1, 0, dataRowCount - 1);
999
+ nextRowIndex = clamp(baseRowIndex + 1, 0, rowCount - 1);
974
1000
  }
975
1001
  break;
976
1002
  case "left":
@@ -992,7 +1018,7 @@ function createGridCore(inputOptions) {
992
1018
  }
993
1019
  break;
994
1020
  }
995
- const nextRow = dataRowAt(snapshot.visibleRows, nextRowIndex);
1021
+ const nextRow = rowList[nextRowIndex];
996
1022
  const nextColumn = columnList[nextColumnIndex];
997
1023
  if (!nextRow || !nextColumn) {
998
1024
  return;
@@ -1002,8 +1028,31 @@ function createGridCore(inputOptions) {
1002
1028
  columnId: nextColumn.id
1003
1029
  };
1004
1030
  focus = nextAddr;
1005
- if (moveOptions.extend) {
1006
- if (!selection.anchor) {
1031
+ if (isDataRow(nextRow)) {
1032
+ if (moveOptions.extend) {
1033
+ if (!selection.anchor) {
1034
+ selection = {
1035
+ ranges: [
1036
+ {
1037
+ startRowId: nextAddr.rowId,
1038
+ endRowId: nextAddr.rowId,
1039
+ startColumnId: nextAddr.columnId,
1040
+ endColumnId: nextAddr.columnId
1041
+ }
1042
+ ],
1043
+ anchor: nextAddr
1044
+ };
1045
+ } else {
1046
+ const newActive = {
1047
+ startRowId: selection.anchor.rowId,
1048
+ endRowId: nextAddr.rowId,
1049
+ startColumnId: selection.anchor.columnId,
1050
+ endColumnId: nextAddr.columnId
1051
+ };
1052
+ const ranges = selection.ranges.length === 0 ? [newActive] : [...selection.ranges.slice(0, -1), newActive];
1053
+ selection = { ranges, anchor: selection.anchor };
1054
+ }
1055
+ } else {
1007
1056
  selection = {
1008
1057
  ranges: [
1009
1058
  {
@@ -1015,28 +1064,7 @@ function createGridCore(inputOptions) {
1015
1064
  ],
1016
1065
  anchor: nextAddr
1017
1066
  };
1018
- } else {
1019
- const newActive = {
1020
- startRowId: selection.anchor.rowId,
1021
- endRowId: nextAddr.rowId,
1022
- startColumnId: selection.anchor.columnId,
1023
- endColumnId: nextAddr.columnId
1024
- };
1025
- const ranges = selection.ranges.length === 0 ? [newActive] : [...selection.ranges.slice(0, -1), newActive];
1026
- selection = { ranges, anchor: selection.anchor };
1027
1067
  }
1028
- } else {
1029
- selection = {
1030
- ranges: [
1031
- {
1032
- startRowId: nextAddr.rowId,
1033
- endRowId: nextAddr.rowId,
1034
- startColumnId: nextAddr.columnId,
1035
- endColumnId: nextAddr.columnId
1036
- }
1037
- ],
1038
- anchor: nextAddr
1039
- };
1040
1068
  }
1041
1069
  emit();
1042
1070
  },
@@ -1261,10 +1289,22 @@ function createGridCore(inputOptions) {
1261
1289
  return { ...newCol };
1262
1290
  });
1263
1291
  const grouped = groupColumnsByPin(merged);
1264
- const changed = !sameColumnLayout(options.columns, grouped);
1292
+ const layoutChanged = !sameColumnLayout(options.columns, grouped);
1293
+ const groupingSemanticsChanged = !sameColumnGroupingSemantics(options.columns, grouped);
1294
+ const before = groupingSemanticsChanged ? captureVisibleRowsForFocusReconciliation() : null;
1265
1295
  originalColumns = groupColumnsByPin(nextColumns).map((c) => ({ ...c }));
1266
1296
  options = { ...options, columns: grouped };
1267
- if (changed) {
1297
+ const nextRowGroups = sanitizeRowGroups(rowGroups, grouped);
1298
+ const sanitizedGroupingChanged = !stringListsEqual(rowGroups, nextRowGroups);
1299
+ if (sanitizedGroupingChanged) {
1300
+ rowGroups = nextRowGroups;
1301
+ groupExpansionOverrides = /* @__PURE__ */ new Set();
1302
+ }
1303
+ if (groupingSemanticsChanged) {
1304
+ cachedVisibleRows = null;
1305
+ reconcileFocusAfterVisibleModelChange(before);
1306
+ }
1307
+ if (layoutChanged || groupingSemanticsChanged || sanitizedGroupingChanged) {
1268
1308
  emit();
1269
1309
  }
1270
1310
  },
@@ -1273,6 +1313,7 @@ function createGridCore(inputOptions) {
1273
1313
  throw new Error("applyTransaction requires getRowId on PretableGridOptions");
1274
1314
  }
1275
1315
  const getRowId = options.getRowId;
1316
+ const before = captureVisibleRowsForFocusReconciliation();
1276
1317
  if (transaction.remove) {
1277
1318
  const removeSet = new Set(transaction.remove);
1278
1319
  sourceRows = sourceRows.filter((entry) => {
@@ -1316,9 +1357,11 @@ function createGridCore(inputOptions) {
1316
1357
  }
1317
1358
  }
1318
1359
  cachedVisibleRows = null;
1360
+ reconcileFocusAfterVisibleModelChange(before);
1319
1361
  emit();
1320
1362
  },
1321
1363
  setRows(nextRows) {
1364
+ const before = captureVisibleRowsForFocusReconciliation();
1322
1365
  options = { ...options, rows: nextRows };
1323
1366
  sourceRows = createSourceRows(options);
1324
1367
  sourceRowIndex.clear();
@@ -1334,9 +1377,6 @@ function createGridCore(inputOptions) {
1334
1377
  anchor: anchorValid ? selection.anchor : null
1335
1378
  };
1336
1379
  }
1337
- if (focus.rowId !== null && !hasRow(focus.rowId)) {
1338
- focus = { rowId: null, columnId: null };
1339
- }
1340
1380
  if (editing && !hasRow(editing.rowId)) {
1341
1381
  editing = null;
1342
1382
  }
@@ -1361,6 +1401,7 @@ function createGridCore(inputOptions) {
1361
1401
  };
1362
1402
  }
1363
1403
  cachedVisibleRows = null;
1404
+ reconcileFocusAfterVisibleModelChange(before);
1364
1405
  emit();
1365
1406
  },
1366
1407
  setRowGroups(columnIds) {
@@ -1368,8 +1409,10 @@ function createGridCore(inputOptions) {
1368
1409
  if (stringListsEqual(rowGroups, next)) {
1369
1410
  return;
1370
1411
  }
1412
+ const before = captureVisibleRowsForFocusReconciliation();
1371
1413
  rowGroups = next;
1372
1414
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1415
+ reconcileFocusAfterVisibleModelChange(before);
1373
1416
  emit();
1374
1417
  },
1375
1418
  toggleGroup(groupId) {
@@ -1379,6 +1422,7 @@ function createGridCore(inputOptions) {
1379
1422
  if (isGroupExpanded(groupId) === expanded) {
1380
1423
  return;
1381
1424
  }
1425
+ const before = captureVisibleRowsForFocusReconciliation();
1382
1426
  if (expanded === groupsDefaultExpanded) {
1383
1427
  const next = new Set(groupExpansionOverrides);
1384
1428
  next.delete(groupId);
@@ -1386,6 +1430,9 @@ function createGridCore(inputOptions) {
1386
1430
  } else {
1387
1431
  groupExpansionOverrides = addGroupExpansionOverride(groupExpansionOverrides, groupId, groupExpansionOverrideLimit);
1388
1432
  }
1433
+ reconcileFocusAfterVisibleModelChange(before, {
1434
+ preferAncestor: !expanded
1435
+ });
1389
1436
  emit();
1390
1437
  },
1391
1438
  expandAll() {
@@ -1460,10 +1507,53 @@ function createGridCore(inputOptions) {
1460
1507
  if (groupsDefaultExpanded === expanded && groupExpansionOverrides.size === 0) {
1461
1508
  return;
1462
1509
  }
1510
+ const before = captureVisibleRowsForFocusReconciliation();
1463
1511
  groupsDefaultExpanded = expanded;
1464
1512
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1513
+ reconcileFocusAfterVisibleModelChange(before, {
1514
+ preferAncestor: !expanded
1515
+ });
1465
1516
  emit();
1466
1517
  }
1518
+ function captureVisibleRowsForFocusReconciliation() {
1519
+ return focus.rowId === null && focus.columnId === null ? null : getSnapshot().visibleRows;
1520
+ }
1521
+ function reconcileFocusAfterVisibleModelChange(before, options2 = {}) {
1522
+ if (before === null || focus.rowId === null && focus.columnId === null) {
1523
+ return;
1524
+ }
1525
+ const oldRowId = focus.rowId;
1526
+ const oldIndex = oldRowId === null ? -1 : before.findIndex((entry) => entry.id === oldRowId);
1527
+ cachedSnapshot = null;
1528
+ const afterRows = getSnapshot().visibleRows;
1529
+ const afterColumns = getColumns();
1530
+ if (afterRows.length === 0 || afterColumns.length === 0) {
1531
+ focus = { rowId: null, columnId: null };
1532
+ cachedSnapshot = null;
1533
+ return;
1534
+ }
1535
+ const survivingRowIds = new Set(afterRows.map((entry) => entry.id));
1536
+ let nextRowId = oldRowId !== null && survivingRowIds.has(oldRowId) ? oldRowId : null;
1537
+ if (nextRowId === null && options2.preferAncestor === true && oldIndex !== -1) {
1538
+ const oldDepth = before[oldIndex].depth;
1539
+ for (let i = oldIndex - 1; i >= 0; i -= 1) {
1540
+ const candidate = before[i];
1541
+ if (candidate.kind === "group" && candidate.depth < oldDepth && survivingRowIds.has(candidate.id)) {
1542
+ nextRowId = candidate.id;
1543
+ break;
1544
+ }
1545
+ }
1546
+ }
1547
+ if (nextRowId === null) {
1548
+ const nextIndex = oldIndex === -1 ? 0 : clamp(oldIndex, 0, afterRows.length - 1);
1549
+ nextRowId = afterRows[nextIndex].id;
1550
+ }
1551
+ const focusedColumnSurvives = focus.columnId !== null && afterColumns.some((column) => column.id === focus.columnId);
1552
+ const groupColumn = rowGroups.length > 0 ? afterColumns.find((column) => column.id === GROUP_COLUMN_ID) : void 0;
1553
+ const nextColumnId = focusedColumnSurvives ? focus.columnId : groupColumn?.id ?? afterColumns[0].id;
1554
+ focus = { rowId: nextRowId, columnId: nextColumnId };
1555
+ cachedSnapshot = null;
1556
+ }
1467
1557
  function preserveAggregateIdentity(rows) {
1468
1558
  const next = /* @__PURE__ */ new Map();
1469
1559
  let result = rows;
@@ -1484,6 +1574,22 @@ function createGridCore(inputOptions) {
1484
1574
  previousAggregates = next;
1485
1575
  return result;
1486
1576
  }
1577
+ function getColumns() {
1578
+ if (cachedEffectiveColumns !== null && cachedEffectiveColumnsSource === options.columns && cachedEffectiveColumnsRowGroups === rowGroups) {
1579
+ return cachedEffectiveColumns;
1580
+ }
1581
+ const resolved = resolveEffectiveColumns({
1582
+ columns: options.columns,
1583
+ rowGroups,
1584
+ groupColumn: options.groupColumn,
1585
+ hideGroupedColumns: options.hideGroupedColumns
1586
+ });
1587
+ const effective = resolved === options.columns ? resolved : groupColumnsByPin(resolved);
1588
+ cachedEffectiveColumns = effective;
1589
+ cachedEffectiveColumnsSource = options.columns;
1590
+ cachedEffectiveColumnsRowGroups = rowGroups;
1591
+ return effective;
1592
+ }
1487
1593
  function getSnapshot() {
1488
1594
  if (cachedSnapshot) {
1489
1595
  return cachedSnapshot;
@@ -1548,12 +1654,21 @@ function sameColumnLayout(a, b) {
1548
1654
  return left.id === right.id && left.header === right.header && left.widthPx === right.widthPx && left.minWidthPx === right.minWidthPx && left.maxWidthPx === right.maxWidthPx && left.pinned === right.pinned && left.sortable === right.sortable && left.filterable === right.filterable && left.resizable === right.resizable && left.reorderable === right.reorderable && left.wrap === right.wrap;
1549
1655
  });
1550
1656
  }
1551
- function computePageStep(viewport, dataRowCount) {
1552
- if (viewport.height <= 0 || dataRowCount === 0) {
1657
+ function sameColumnGroupingSemantics(a, b) {
1658
+ if (a.length !== b.length) {
1659
+ return false;
1660
+ }
1661
+ return a.every((left, index) => {
1662
+ const right = b[index];
1663
+ return left.id === right.id && left.value === right.value && left.aggregate === right.aggregate;
1664
+ });
1665
+ }
1666
+ function computePageStep(viewport, rowCount) {
1667
+ if (viewport.height <= 0 || rowCount === 0) {
1553
1668
  return 1;
1554
1669
  }
1555
1670
  const estimatedRowsPerPage = Math.max(1, Math.floor(viewport.height * 0.8 / 32));
1556
- return Math.min(estimatedRowsPerPage, dataRowCount);
1671
+ return Math.min(estimatedRowsPerPage, rowCount);
1557
1672
  }
1558
1673
  function isFullRowRange(range, rowId, firstColumnId, lastColumnId) {
1559
1674
  return range.startRowId === rowId && range.endRowId === rowId && range.startColumnId === firstColumnId && range.endColumnId === lastColumnId;
@@ -1655,6 +1770,7 @@ function createGrid(options) {
1655
1770
  },
1656
1771
  subscribe: engine.subscribe,
1657
1772
  getSnapshot: engine.getSnapshot,
1773
+ getColumns: engine.getColumns,
1658
1774
  setSort: engine.setSort,
1659
1775
  replaceSort: engine.replaceSort,
1660
1776
  setColumnFilter: engine.setColumnFilter,
@@ -1698,4 +1814,4 @@ function createGrid(options) {
1698
1814
  };
1699
1815
  }
1700
1816
 
1701
- export { createGrid };
1817
+ export { GROUP_COLUMN_ID, createGrid };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pretable/core",
3
- "version": "0.0.6",
3
+ "version": "0.0.9",
4
4
  "description": "Framework-agnostic grid state primitives for Pretable.",
5
5
  "license": "MIT",
6
6
  "repository": {