@pretable/core 0.0.5 → 0.0.8

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,35 +587,59 @@ function matchesFilters(row, resolvedFilters) {
587
587
  return true;
588
588
  }
589
589
 
590
- // ../grid-core/dist/create-grid-core.js
591
- var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
592
- function isDataRow(entry) {
593
- return entry.kind === "data";
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];
594
601
  }
595
- function scanDataRows(rows, rowId) {
596
- let count2 = 0;
597
- let index = -1;
598
- for (const entry of rows) {
599
- if (!isDataRow(entry))
600
- continue;
601
- if (rowId !== null && entry.id === rowId)
602
- index = count2;
603
- count2 += 1;
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
+ };
613
+ return groupColumn?.pinned === "left" ? { ...column, pinned: "left" } : column;
614
+ }
615
+
616
+ // ../grid-core/dist/group-expansion.js
617
+ var DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT = 1e4;
618
+ function resolveGroupExpansionOverrideLimit(configured) {
619
+ if (configured === void 0)
620
+ return DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT;
621
+ if (configured === Number.POSITIVE_INFINITY)
622
+ return configured;
623
+ if (!Number.isFinite(configured)) {
624
+ return DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT;
604
625
  }
605
- return { count: count2, index };
626
+ return Math.max(1, Math.floor(configured));
606
627
  }
607
- function dataRowAt(rows, ordinal) {
608
- if (ordinal < 0)
609
- return void 0;
610
- let seen = 0;
611
- for (const entry of rows) {
612
- if (!isDataRow(entry))
613
- continue;
614
- if (seen === ordinal)
615
- return entry;
616
- seen += 1;
628
+ function addGroupExpansionOverride(current, groupId, limit) {
629
+ const next = new Set(current);
630
+ next.delete(groupId);
631
+ next.add(groupId);
632
+ while (next.size > limit) {
633
+ const oldest = next.values().next().value;
634
+ next.delete(oldest);
617
635
  }
618
- return void 0;
636
+ return next;
637
+ }
638
+
639
+ // ../grid-core/dist/create-grid-core.js
640
+ var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
641
+ function isDataRow(entry) {
642
+ return entry.kind === "data";
619
643
  }
620
644
  function clampColumnWidth(width, column) {
621
645
  const min2 = column.minWidthPx ?? 40;
@@ -646,7 +670,7 @@ function groupColumnsByPin(columns) {
646
670
  const right = [];
647
671
  for (const column of columns) {
648
672
  const region = column.pinned === "left" ? left : column.pinned === "right" ? right : unpinned;
649
- if (column.id === ROW_SELECT_COLUMN_ID) {
673
+ if (column.id === ROW_SELECT_COLUMN_ID || column.id === GROUP_COLUMN_ID) {
650
674
  region.unshift(column);
651
675
  } else {
652
676
  region.push(column);
@@ -673,10 +697,14 @@ function createGridCore(inputOptions) {
673
697
  let cachedDerivedOverrides = null;
674
698
  let cachedDerivedDefaultExpanded = null;
675
699
  let cachedDerivedAggregateFiltered = null;
700
+ let cachedEffectiveColumns = null;
701
+ let cachedEffectiveColumnsSource = null;
702
+ let cachedEffectiveColumnsRowGroups = null;
676
703
  let sort = [];
677
704
  let filters = {};
678
705
  let rowGroups = sanitizeRowGroups(options.columns.filter((column) => column.rowGroup === true).map((c) => c.id), options.columns);
679
706
  let groupExpansionOverrides = /* @__PURE__ */ new Set();
707
+ const groupExpansionOverrideLimit = resolveGroupExpansionOverrideLimit(options.groupExpansionOverrideLimit);
680
708
  let groupsDefaultExpanded = options.groupsDefaultExpanded ?? true;
681
709
  let previousAggregates = /* @__PURE__ */ new Map();
682
710
  let selection = { ranges: [], anchor: null };
@@ -699,6 +727,7 @@ function createGridCore(inputOptions) {
699
727
  };
700
728
  },
701
729
  getSnapshot,
730
+ getColumns,
702
731
  setSort(columnId, direction) {
703
732
  const candidate = columnId && direction ? [{ columnId, direction }] : [];
704
733
  const next = sanitizeSortEntries(candidate, options.columns);
@@ -913,13 +942,15 @@ function createGridCore(inputOptions) {
913
942
  },
914
943
  moveFocus(direction, moveOptions = {}) {
915
944
  const snapshot = getSnapshot();
916
- const { count: dataRowCount, index: currentRowIndex } = scanDataRows(snapshot.visibleRows, focus.rowId);
917
- const columnList = options.columns;
918
- if (dataRowCount === 0 || columnList.length === 0) {
945
+ const rowList = snapshot.visibleRows;
946
+ const rowCount = rowList.length;
947
+ const columnList = getColumns();
948
+ if (rowCount === 0 || columnList.length === 0) {
919
949
  focus = { rowId: null, columnId: null };
920
950
  emit();
921
951
  return;
922
952
  }
953
+ const currentRowIndex = focus.rowId === null ? -1 : rowList.findIndex((entry) => entry.id === focus.rowId);
923
954
  const currentColumnIndex = focus.columnId ? columnList.findIndex((c) => c.id === focus.columnId) : -1;
924
955
  const hasRowFocus = currentRowIndex !== -1;
925
956
  const hasColumnFocus = currentColumnIndex !== -1;
@@ -927,28 +958,28 @@ function createGridCore(inputOptions) {
927
958
  const baseColumnIndex = hasColumnFocus ? currentColumnIndex : 0;
928
959
  let nextRowIndex = baseRowIndex;
929
960
  let nextColumnIndex = baseColumnIndex;
930
- const pageStep = computePageStep(viewport, dataRowCount);
961
+ const pageStep = computePageStep(viewport, rowCount);
931
962
  switch (direction) {
932
963
  case "up":
933
964
  if (moveOptions.jumpToEdge) {
934
965
  nextRowIndex = 0;
935
966
  } else if (!hasRowFocus) {
936
- nextRowIndex = dataRowCount - 1;
967
+ nextRowIndex = rowCount - 1;
937
968
  } else if (moveOptions.byPage) {
938
- nextRowIndex = clamp(baseRowIndex - pageStep, 0, dataRowCount - 1);
969
+ nextRowIndex = clamp(baseRowIndex - pageStep, 0, rowCount - 1);
939
970
  } else {
940
- nextRowIndex = clamp(baseRowIndex - 1, 0, dataRowCount - 1);
971
+ nextRowIndex = clamp(baseRowIndex - 1, 0, rowCount - 1);
941
972
  }
942
973
  break;
943
974
  case "down":
944
975
  if (moveOptions.jumpToEdge) {
945
- nextRowIndex = dataRowCount - 1;
976
+ nextRowIndex = rowCount - 1;
946
977
  } else if (!hasRowFocus) {
947
978
  nextRowIndex = 0;
948
979
  } else if (moveOptions.byPage) {
949
- nextRowIndex = clamp(baseRowIndex + pageStep, 0, dataRowCount - 1);
980
+ nextRowIndex = clamp(baseRowIndex + pageStep, 0, rowCount - 1);
950
981
  } else {
951
- nextRowIndex = clamp(baseRowIndex + 1, 0, dataRowCount - 1);
982
+ nextRowIndex = clamp(baseRowIndex + 1, 0, rowCount - 1);
952
983
  }
953
984
  break;
954
985
  case "left":
@@ -970,7 +1001,7 @@ function createGridCore(inputOptions) {
970
1001
  }
971
1002
  break;
972
1003
  }
973
- const nextRow = dataRowAt(snapshot.visibleRows, nextRowIndex);
1004
+ const nextRow = rowList[nextRowIndex];
974
1005
  const nextColumn = columnList[nextColumnIndex];
975
1006
  if (!nextRow || !nextColumn) {
976
1007
  return;
@@ -1357,13 +1388,15 @@ function createGridCore(inputOptions) {
1357
1388
  if (isGroupExpanded(groupId) === expanded) {
1358
1389
  return;
1359
1390
  }
1360
- const next = new Set(groupExpansionOverrides);
1391
+ const before = getSnapshot().visibleRows;
1361
1392
  if (expanded === groupsDefaultExpanded) {
1393
+ const next = new Set(groupExpansionOverrides);
1362
1394
  next.delete(groupId);
1395
+ groupExpansionOverrides = next;
1363
1396
  } else {
1364
- next.add(groupId);
1397
+ groupExpansionOverrides = addGroupExpansionOverride(groupExpansionOverrides, groupId, groupExpansionOverrideLimit);
1365
1398
  }
1366
- groupExpansionOverrides = next;
1399
+ reanchorFocusAfterCollapse(before);
1367
1400
  emit();
1368
1401
  },
1369
1402
  expandAll() {
@@ -1438,10 +1471,34 @@ function createGridCore(inputOptions) {
1438
1471
  if (groupsDefaultExpanded === expanded && groupExpansionOverrides.size === 0) {
1439
1472
  return;
1440
1473
  }
1474
+ const before = getSnapshot().visibleRows;
1441
1475
  groupsDefaultExpanded = expanded;
1442
1476
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1477
+ reanchorFocusAfterCollapse(before);
1443
1478
  emit();
1444
1479
  }
1480
+ function reanchorFocusAfterCollapse(before) {
1481
+ if (focus.rowId === null)
1482
+ return;
1483
+ const fromIndex = before.findIndex((entry) => entry.id === focus.rowId);
1484
+ if (fromIndex === -1)
1485
+ return;
1486
+ cachedSnapshot = null;
1487
+ const after = getSnapshot().visibleRows;
1488
+ if (after.some((entry) => entry.id === focus.rowId))
1489
+ return;
1490
+ const surviving = new Set(after.map((entry) => entry.id));
1491
+ let nextRowId = null;
1492
+ for (let i = fromIndex - 1; i >= 0; i -= 1) {
1493
+ const candidate = before[i];
1494
+ if (candidate.kind === "group" && surviving.has(candidate.id)) {
1495
+ nextRowId = candidate.id;
1496
+ break;
1497
+ }
1498
+ }
1499
+ focus = nextRowId === null ? { rowId: null, columnId: null } : { rowId: nextRowId, columnId: focus.columnId };
1500
+ cachedSnapshot = null;
1501
+ }
1445
1502
  function preserveAggregateIdentity(rows) {
1446
1503
  const next = /* @__PURE__ */ new Map();
1447
1504
  let result = rows;
@@ -1462,6 +1519,22 @@ function createGridCore(inputOptions) {
1462
1519
  previousAggregates = next;
1463
1520
  return result;
1464
1521
  }
1522
+ function getColumns() {
1523
+ if (cachedEffectiveColumns !== null && cachedEffectiveColumnsSource === options.columns && cachedEffectiveColumnsRowGroups === rowGroups) {
1524
+ return cachedEffectiveColumns;
1525
+ }
1526
+ const resolved = resolveEffectiveColumns({
1527
+ columns: options.columns,
1528
+ rowGroups,
1529
+ groupColumn: options.groupColumn,
1530
+ hideGroupedColumns: options.hideGroupedColumns
1531
+ });
1532
+ const effective = resolved === options.columns ? resolved : groupColumnsByPin(resolved);
1533
+ cachedEffectiveColumns = effective;
1534
+ cachedEffectiveColumnsSource = options.columns;
1535
+ cachedEffectiveColumnsRowGroups = rowGroups;
1536
+ return effective;
1537
+ }
1465
1538
  function getSnapshot() {
1466
1539
  if (cachedSnapshot) {
1467
1540
  return cachedSnapshot;
@@ -1526,12 +1599,12 @@ function sameColumnLayout(a, b) {
1526
1599
  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;
1527
1600
  });
1528
1601
  }
1529
- function computePageStep(viewport, dataRowCount) {
1530
- if (viewport.height <= 0 || dataRowCount === 0) {
1602
+ function computePageStep(viewport, rowCount) {
1603
+ if (viewport.height <= 0 || rowCount === 0) {
1531
1604
  return 1;
1532
1605
  }
1533
1606
  const estimatedRowsPerPage = Math.max(1, Math.floor(viewport.height * 0.8 / 32));
1534
- return Math.min(estimatedRowsPerPage, dataRowCount);
1607
+ return Math.min(estimatedRowsPerPage, rowCount);
1535
1608
  }
1536
1609
  function isFullRowRange(range, rowId, firstColumnId, lastColumnId) {
1537
1610
  return range.startRowId === rowId && range.endRowId === rowId && range.startColumnId === firstColumnId && range.endColumnId === lastColumnId;
@@ -1633,6 +1706,7 @@ function createGrid(options) {
1633
1706
  },
1634
1707
  subscribe: engine.subscribe,
1635
1708
  getSnapshot: engine.getSnapshot,
1709
+ getColumns: engine.getColumns,
1636
1710
  setSort: engine.setSort,
1637
1711
  replaceSort: engine.replaceSort,
1638
1712
  setColumnFilter: engine.setColumnFilter,
@@ -1676,4 +1750,5 @@ function createGrid(options) {
1676
1750
  };
1677
1751
  }
1678
1752
 
1753
+ exports.GROUP_COLUMN_ID = GROUP_COLUMN_ID;
1679
1754
  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,8 +131,26 @@ 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;
145
+ /**
146
+ * Share of the width the fixed columns leave over, so the row ends exactly at
147
+ * the viewport edge instead of underfilling or overflowing it. Weights are
148
+ * relative: two columns at `flex: 1` split the remainder evenly, `1` and `3`
149
+ * split it a quarter to three quarters. `minWidthPx`/`maxWidthPx` still
150
+ * apply, and a column that has been resized (which sets `widthPx`) stops
151
+ * flexing — an explicit width outranks a computed one.
152
+ */
153
+ flex?: number;
105
154
  resizable?: boolean;
106
155
  reorderable?: boolean;
107
156
  /** Group rows by this column by default; levels follow column order. */
@@ -123,6 +172,17 @@ interface PretableFormatInput<TRow extends PretableRow = PretableRow> {
123
172
  row: TRow;
124
173
  column: PretableColumn<TRow>;
125
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
+ }
126
186
  /**
127
187
  * Options accepted by `createGrid`.
128
188
  *
@@ -144,6 +204,37 @@ interface PretableGridOptions<TRow extends PretableRow = PretableRow> {
144
204
  * Default `true`. Groups appearing mid-stream inherit it with no bookkeeping.
145
205
  */
146
206
  groupsDefaultExpanded?: boolean;
207
+ /**
208
+ * How many per-group expand/collapse decisions the grid remembers. Default
209
+ * `10_000`. Past the limit the least-recently-decided group is forgotten and
210
+ * reverts to `groupsDefaultExpanded`.
211
+ *
212
+ * **Why a limit exists.** Expansion state is keyed by a path-derived group id
213
+ * rather than owned by a node, which is what lets a group survive emptying and
214
+ * returning mid-stream. The price is that ids for groups which never return
215
+ * would otherwise accumulate forever under a stream whose grouping keys churn.
216
+ *
217
+ * Values below 1 clamp to 1; a non-finite value other than `Infinity` falls
218
+ * back to the default. Pass `Infinity` to opt out of the cap entirely and
219
+ * accept unbounded growth.
220
+ *
221
+ * `expandAll()` / `collapseAll()` are unaffected — they flip the default and
222
+ * clear the set, so "collapse everything" costs one entry-free operation no
223
+ * matter how many groups exist.
224
+ */
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;
147
238
  }
148
239
  /**
149
240
  * One entry in the ordered sort list; index in the list = priority.
@@ -348,6 +439,13 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
348
439
  subscribe(listener: () => void): () => void;
349
440
  /** Read the current snapshot. Stable reference until the next mutation. */
350
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>[];
351
449
  setSort(columnId: string | null, direction: PretableSortDirection): void;
352
450
  /** Atomically replace the ordered sort list. Unknown and `sortable: false` columns are dropped. */
353
451
  replaceSort(entries: PretableSortEntry[]): void;
@@ -435,4 +533,4 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
435
533
  */
436
534
  declare function createGrid<TRow extends PretableRow = PretableRow>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
437
535
 
438
- 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,8 +131,26 @@ 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;
145
+ /**
146
+ * Share of the width the fixed columns leave over, so the row ends exactly at
147
+ * the viewport edge instead of underfilling or overflowing it. Weights are
148
+ * relative: two columns at `flex: 1` split the remainder evenly, `1` and `3`
149
+ * split it a quarter to three quarters. `minWidthPx`/`maxWidthPx` still
150
+ * apply, and a column that has been resized (which sets `widthPx`) stops
151
+ * flexing — an explicit width outranks a computed one.
152
+ */
153
+ flex?: number;
105
154
  resizable?: boolean;
106
155
  reorderable?: boolean;
107
156
  /** Group rows by this column by default; levels follow column order. */
@@ -123,6 +172,17 @@ interface PretableFormatInput<TRow extends PretableRow = PretableRow> {
123
172
  row: TRow;
124
173
  column: PretableColumn<TRow>;
125
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
+ }
126
186
  /**
127
187
  * Options accepted by `createGrid`.
128
188
  *
@@ -144,6 +204,37 @@ interface PretableGridOptions<TRow extends PretableRow = PretableRow> {
144
204
  * Default `true`. Groups appearing mid-stream inherit it with no bookkeeping.
145
205
  */
146
206
  groupsDefaultExpanded?: boolean;
207
+ /**
208
+ * How many per-group expand/collapse decisions the grid remembers. Default
209
+ * `10_000`. Past the limit the least-recently-decided group is forgotten and
210
+ * reverts to `groupsDefaultExpanded`.
211
+ *
212
+ * **Why a limit exists.** Expansion state is keyed by a path-derived group id
213
+ * rather than owned by a node, which is what lets a group survive emptying and
214
+ * returning mid-stream. The price is that ids for groups which never return
215
+ * would otherwise accumulate forever under a stream whose grouping keys churn.
216
+ *
217
+ * Values below 1 clamp to 1; a non-finite value other than `Infinity` falls
218
+ * back to the default. Pass `Infinity` to opt out of the cap entirely and
219
+ * accept unbounded growth.
220
+ *
221
+ * `expandAll()` / `collapseAll()` are unaffected — they flip the default and
222
+ * clear the set, so "collapse everything" costs one entry-free operation no
223
+ * matter how many groups exist.
224
+ */
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;
147
238
  }
148
239
  /**
149
240
  * One entry in the ordered sort list; index in the list = priority.
@@ -348,6 +439,13 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
348
439
  subscribe(listener: () => void): () => void;
349
440
  /** Read the current snapshot. Stable reference until the next mutation. */
350
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>[];
351
449
  setSort(columnId: string | null, direction: PretableSortDirection): void;
352
450
  /** Atomically replace the ordered sort list. Unknown and `sortable: false` columns are dropped. */
353
451
  replaceSort(entries: PretableSortEntry[]): void;
@@ -435,4 +533,4 @@ interface PretableGrid<TRow extends PretableRow = PretableRow> {
435
533
  */
436
534
  declare function createGrid<TRow extends PretableRow = PretableRow>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
437
535
 
438
- 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,35 +585,59 @@ function matchesFilters(row, resolvedFilters) {
585
585
  return true;
586
586
  }
587
587
 
588
- // ../grid-core/dist/create-grid-core.js
589
- var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
590
- function isDataRow(entry) {
591
- return entry.kind === "data";
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];
592
599
  }
593
- function scanDataRows(rows, rowId) {
594
- let count2 = 0;
595
- let index = -1;
596
- for (const entry of rows) {
597
- if (!isDataRow(entry))
598
- continue;
599
- if (rowId !== null && entry.id === rowId)
600
- index = count2;
601
- count2 += 1;
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
+ };
611
+ return groupColumn?.pinned === "left" ? { ...column, pinned: "left" } : column;
612
+ }
613
+
614
+ // ../grid-core/dist/group-expansion.js
615
+ var DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT = 1e4;
616
+ function resolveGroupExpansionOverrideLimit(configured) {
617
+ if (configured === void 0)
618
+ return DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT;
619
+ if (configured === Number.POSITIVE_INFINITY)
620
+ return configured;
621
+ if (!Number.isFinite(configured)) {
622
+ return DEFAULT_GROUP_EXPANSION_OVERRIDE_LIMIT;
602
623
  }
603
- return { count: count2, index };
624
+ return Math.max(1, Math.floor(configured));
604
625
  }
605
- function dataRowAt(rows, ordinal) {
606
- if (ordinal < 0)
607
- return void 0;
608
- let seen = 0;
609
- for (const entry of rows) {
610
- if (!isDataRow(entry))
611
- continue;
612
- if (seen === ordinal)
613
- return entry;
614
- seen += 1;
626
+ function addGroupExpansionOverride(current, groupId, limit) {
627
+ const next = new Set(current);
628
+ next.delete(groupId);
629
+ next.add(groupId);
630
+ while (next.size > limit) {
631
+ const oldest = next.values().next().value;
632
+ next.delete(oldest);
615
633
  }
616
- return void 0;
634
+ return next;
635
+ }
636
+
637
+ // ../grid-core/dist/create-grid-core.js
638
+ var ROW_SELECT_COLUMN_ID = "__pretable_row_select__";
639
+ function isDataRow(entry) {
640
+ return entry.kind === "data";
617
641
  }
618
642
  function clampColumnWidth(width, column) {
619
643
  const min2 = column.minWidthPx ?? 40;
@@ -644,7 +668,7 @@ function groupColumnsByPin(columns) {
644
668
  const right = [];
645
669
  for (const column of columns) {
646
670
  const region = column.pinned === "left" ? left : column.pinned === "right" ? right : unpinned;
647
- if (column.id === ROW_SELECT_COLUMN_ID) {
671
+ if (column.id === ROW_SELECT_COLUMN_ID || column.id === GROUP_COLUMN_ID) {
648
672
  region.unshift(column);
649
673
  } else {
650
674
  region.push(column);
@@ -671,10 +695,14 @@ function createGridCore(inputOptions) {
671
695
  let cachedDerivedOverrides = null;
672
696
  let cachedDerivedDefaultExpanded = null;
673
697
  let cachedDerivedAggregateFiltered = null;
698
+ let cachedEffectiveColumns = null;
699
+ let cachedEffectiveColumnsSource = null;
700
+ let cachedEffectiveColumnsRowGroups = null;
674
701
  let sort = [];
675
702
  let filters = {};
676
703
  let rowGroups = sanitizeRowGroups(options.columns.filter((column) => column.rowGroup === true).map((c) => c.id), options.columns);
677
704
  let groupExpansionOverrides = /* @__PURE__ */ new Set();
705
+ const groupExpansionOverrideLimit = resolveGroupExpansionOverrideLimit(options.groupExpansionOverrideLimit);
678
706
  let groupsDefaultExpanded = options.groupsDefaultExpanded ?? true;
679
707
  let previousAggregates = /* @__PURE__ */ new Map();
680
708
  let selection = { ranges: [], anchor: null };
@@ -697,6 +725,7 @@ function createGridCore(inputOptions) {
697
725
  };
698
726
  },
699
727
  getSnapshot,
728
+ getColumns,
700
729
  setSort(columnId, direction) {
701
730
  const candidate = columnId && direction ? [{ columnId, direction }] : [];
702
731
  const next = sanitizeSortEntries(candidate, options.columns);
@@ -911,13 +940,15 @@ function createGridCore(inputOptions) {
911
940
  },
912
941
  moveFocus(direction, moveOptions = {}) {
913
942
  const snapshot = getSnapshot();
914
- const { count: dataRowCount, index: currentRowIndex } = scanDataRows(snapshot.visibleRows, focus.rowId);
915
- const columnList = options.columns;
916
- if (dataRowCount === 0 || columnList.length === 0) {
943
+ const rowList = snapshot.visibleRows;
944
+ const rowCount = rowList.length;
945
+ const columnList = getColumns();
946
+ if (rowCount === 0 || columnList.length === 0) {
917
947
  focus = { rowId: null, columnId: null };
918
948
  emit();
919
949
  return;
920
950
  }
951
+ const currentRowIndex = focus.rowId === null ? -1 : rowList.findIndex((entry) => entry.id === focus.rowId);
921
952
  const currentColumnIndex = focus.columnId ? columnList.findIndex((c) => c.id === focus.columnId) : -1;
922
953
  const hasRowFocus = currentRowIndex !== -1;
923
954
  const hasColumnFocus = currentColumnIndex !== -1;
@@ -925,28 +956,28 @@ function createGridCore(inputOptions) {
925
956
  const baseColumnIndex = hasColumnFocus ? currentColumnIndex : 0;
926
957
  let nextRowIndex = baseRowIndex;
927
958
  let nextColumnIndex = baseColumnIndex;
928
- const pageStep = computePageStep(viewport, dataRowCount);
959
+ const pageStep = computePageStep(viewport, rowCount);
929
960
  switch (direction) {
930
961
  case "up":
931
962
  if (moveOptions.jumpToEdge) {
932
963
  nextRowIndex = 0;
933
964
  } else if (!hasRowFocus) {
934
- nextRowIndex = dataRowCount - 1;
965
+ nextRowIndex = rowCount - 1;
935
966
  } else if (moveOptions.byPage) {
936
- nextRowIndex = clamp(baseRowIndex - pageStep, 0, dataRowCount - 1);
967
+ nextRowIndex = clamp(baseRowIndex - pageStep, 0, rowCount - 1);
937
968
  } else {
938
- nextRowIndex = clamp(baseRowIndex - 1, 0, dataRowCount - 1);
969
+ nextRowIndex = clamp(baseRowIndex - 1, 0, rowCount - 1);
939
970
  }
940
971
  break;
941
972
  case "down":
942
973
  if (moveOptions.jumpToEdge) {
943
- nextRowIndex = dataRowCount - 1;
974
+ nextRowIndex = rowCount - 1;
944
975
  } else if (!hasRowFocus) {
945
976
  nextRowIndex = 0;
946
977
  } else if (moveOptions.byPage) {
947
- nextRowIndex = clamp(baseRowIndex + pageStep, 0, dataRowCount - 1);
978
+ nextRowIndex = clamp(baseRowIndex + pageStep, 0, rowCount - 1);
948
979
  } else {
949
- nextRowIndex = clamp(baseRowIndex + 1, 0, dataRowCount - 1);
980
+ nextRowIndex = clamp(baseRowIndex + 1, 0, rowCount - 1);
950
981
  }
951
982
  break;
952
983
  case "left":
@@ -968,7 +999,7 @@ function createGridCore(inputOptions) {
968
999
  }
969
1000
  break;
970
1001
  }
971
- const nextRow = dataRowAt(snapshot.visibleRows, nextRowIndex);
1002
+ const nextRow = rowList[nextRowIndex];
972
1003
  const nextColumn = columnList[nextColumnIndex];
973
1004
  if (!nextRow || !nextColumn) {
974
1005
  return;
@@ -1355,13 +1386,15 @@ function createGridCore(inputOptions) {
1355
1386
  if (isGroupExpanded(groupId) === expanded) {
1356
1387
  return;
1357
1388
  }
1358
- const next = new Set(groupExpansionOverrides);
1389
+ const before = getSnapshot().visibleRows;
1359
1390
  if (expanded === groupsDefaultExpanded) {
1391
+ const next = new Set(groupExpansionOverrides);
1360
1392
  next.delete(groupId);
1393
+ groupExpansionOverrides = next;
1361
1394
  } else {
1362
- next.add(groupId);
1395
+ groupExpansionOverrides = addGroupExpansionOverride(groupExpansionOverrides, groupId, groupExpansionOverrideLimit);
1363
1396
  }
1364
- groupExpansionOverrides = next;
1397
+ reanchorFocusAfterCollapse(before);
1365
1398
  emit();
1366
1399
  },
1367
1400
  expandAll() {
@@ -1436,10 +1469,34 @@ function createGridCore(inputOptions) {
1436
1469
  if (groupsDefaultExpanded === expanded && groupExpansionOverrides.size === 0) {
1437
1470
  return;
1438
1471
  }
1472
+ const before = getSnapshot().visibleRows;
1439
1473
  groupsDefaultExpanded = expanded;
1440
1474
  groupExpansionOverrides = /* @__PURE__ */ new Set();
1475
+ reanchorFocusAfterCollapse(before);
1441
1476
  emit();
1442
1477
  }
1478
+ function reanchorFocusAfterCollapse(before) {
1479
+ if (focus.rowId === null)
1480
+ return;
1481
+ const fromIndex = before.findIndex((entry) => entry.id === focus.rowId);
1482
+ if (fromIndex === -1)
1483
+ return;
1484
+ cachedSnapshot = null;
1485
+ const after = getSnapshot().visibleRows;
1486
+ if (after.some((entry) => entry.id === focus.rowId))
1487
+ return;
1488
+ const surviving = new Set(after.map((entry) => entry.id));
1489
+ let nextRowId = null;
1490
+ for (let i = fromIndex - 1; i >= 0; i -= 1) {
1491
+ const candidate = before[i];
1492
+ if (candidate.kind === "group" && surviving.has(candidate.id)) {
1493
+ nextRowId = candidate.id;
1494
+ break;
1495
+ }
1496
+ }
1497
+ focus = nextRowId === null ? { rowId: null, columnId: null } : { rowId: nextRowId, columnId: focus.columnId };
1498
+ cachedSnapshot = null;
1499
+ }
1443
1500
  function preserveAggregateIdentity(rows) {
1444
1501
  const next = /* @__PURE__ */ new Map();
1445
1502
  let result = rows;
@@ -1460,6 +1517,22 @@ function createGridCore(inputOptions) {
1460
1517
  previousAggregates = next;
1461
1518
  return result;
1462
1519
  }
1520
+ function getColumns() {
1521
+ if (cachedEffectiveColumns !== null && cachedEffectiveColumnsSource === options.columns && cachedEffectiveColumnsRowGroups === rowGroups) {
1522
+ return cachedEffectiveColumns;
1523
+ }
1524
+ const resolved = resolveEffectiveColumns({
1525
+ columns: options.columns,
1526
+ rowGroups,
1527
+ groupColumn: options.groupColumn,
1528
+ hideGroupedColumns: options.hideGroupedColumns
1529
+ });
1530
+ const effective = resolved === options.columns ? resolved : groupColumnsByPin(resolved);
1531
+ cachedEffectiveColumns = effective;
1532
+ cachedEffectiveColumnsSource = options.columns;
1533
+ cachedEffectiveColumnsRowGroups = rowGroups;
1534
+ return effective;
1535
+ }
1463
1536
  function getSnapshot() {
1464
1537
  if (cachedSnapshot) {
1465
1538
  return cachedSnapshot;
@@ -1524,12 +1597,12 @@ function sameColumnLayout(a, b) {
1524
1597
  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;
1525
1598
  });
1526
1599
  }
1527
- function computePageStep(viewport, dataRowCount) {
1528
- if (viewport.height <= 0 || dataRowCount === 0) {
1600
+ function computePageStep(viewport, rowCount) {
1601
+ if (viewport.height <= 0 || rowCount === 0) {
1529
1602
  return 1;
1530
1603
  }
1531
1604
  const estimatedRowsPerPage = Math.max(1, Math.floor(viewport.height * 0.8 / 32));
1532
- return Math.min(estimatedRowsPerPage, dataRowCount);
1605
+ return Math.min(estimatedRowsPerPage, rowCount);
1533
1606
  }
1534
1607
  function isFullRowRange(range, rowId, firstColumnId, lastColumnId) {
1535
1608
  return range.startRowId === rowId && range.endRowId === rowId && range.startColumnId === firstColumnId && range.endColumnId === lastColumnId;
@@ -1631,6 +1704,7 @@ function createGrid(options) {
1631
1704
  },
1632
1705
  subscribe: engine.subscribe,
1633
1706
  getSnapshot: engine.getSnapshot,
1707
+ getColumns: engine.getColumns,
1634
1708
  setSort: engine.setSort,
1635
1709
  replaceSort: engine.replaceSort,
1636
1710
  setColumnFilter: engine.setColumnFilter,
@@ -1674,4 +1748,4 @@ function createGrid(options) {
1674
1748
  };
1675
1749
  }
1676
1750
 
1677
- export { createGrid };
1751
+ export { GROUP_COLUMN_ID, createGrid };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pretable/core",
3
- "version": "0.0.5",
3
+ "version": "0.0.8",
4
4
  "description": "Framework-agnostic grid state primitives for Pretable.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -43,6 +43,6 @@
43
43
  "lint": "eslint src --ext .ts",
44
44
  "lint:packaging": "publint --strict && attw --pack",
45
45
  "test": "pnpm --filter @pretable-internal/grid-core build && vitest run",
46
- "typecheck": "pnpm --filter @pretable-internal/grid-core build && tsc -p tsconfig.json --noEmit"
46
+ "typecheck": "pnpm --filter @pretable-internal/grid-core build && tsc -p tsconfig.typecheck.json --noEmit"
47
47
  }
48
48
  }