@omnigrid/core 0.1.21 → 0.1.22

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/columns.d.ts CHANGED
@@ -17,6 +17,13 @@ export declare function isColumnLeaf<T>(column: ColumnDef<T>): column is ColumnL
17
17
  * the caller's concern.
18
18
  */
19
19
  export declare function flattenColumns<T>(columns: ColumnDef<T>[]): ColumnLeafDef<T>[];
20
+ /**
21
+ * Applies the grid-level `wrapText` flag to every leaf column that does not
22
+ * define it explicitly — a column-level `wrapText` always wins.
23
+ *
24
+ * Returns the input untouched when the grid-level flag is not set.
25
+ */
26
+ export declare function applyWrapText<T>(columns: ColumnDef<T>[], wrapText: boolean | undefined): ColumnDef<T>[];
20
27
  /**
21
28
  * Projects every group onto the flat VISIBLE leaf layout.
22
29
  *
package/dist/columns.js CHANGED
@@ -32,6 +32,23 @@ export function flattenColumns(columns) {
32
32
  }
33
33
  return result;
34
34
  }
35
+ /**
36
+ * Applies the grid-level `wrapText` flag to every leaf column that does not
37
+ * define it explicitly — a column-level `wrapText` always wins.
38
+ *
39
+ * Returns the input untouched when the grid-level flag is not set.
40
+ */
41
+ export function applyWrapText(columns, wrapText) {
42
+ if (wrapText === undefined)
43
+ return columns;
44
+ const walk = (nodes) => nodes.map((node) => {
45
+ if (isColumnGroup(node)) {
46
+ return { ...node, children: walk(node.children) };
47
+ }
48
+ return node.wrapText === undefined ? { ...node, wrapText } : node;
49
+ });
50
+ return walk(columns);
51
+ }
35
52
  /**
36
53
  * Projects every group onto the flat VISIBLE leaf layout.
37
54
  *
@@ -33,6 +33,7 @@ export declare class DomPool<T> {
33
33
  /** Whether slot i's content (bindRow) has been bound since its last position change. */
34
34
  private readonly hostContentBound;
35
35
  private readonly hostOffsetY;
36
+ private readonly hostHeight;
36
37
  /** Scratch flags: whether slot i was claimed by the current window (ring mapping). */
37
38
  private readonly slotActive;
38
39
  /** Data changed — force-rebind visible nodes on the next frame. */
package/dist/dom-pool.js CHANGED
@@ -24,6 +24,7 @@ export class DomPool {
24
24
  /** Whether slot i's content (bindRow) has been bound since its last position change. */
25
25
  this.hostContentBound = [];
26
26
  this.hostOffsetY = [];
27
+ this.hostHeight = [];
27
28
  /** Scratch flags: whether slot i was claimed by the current window (ring mapping). */
28
29
  this.slotActive = [];
29
30
  /** Data changed — force-rebind visible nodes on the next frame. */
@@ -47,7 +48,7 @@ export class DomPool {
47
48
  */
48
49
  update(viewport) {
49
50
  this.assertActive();
50
- const { data, rowRange, rowHeight, rowWidth, skipBind } = viewport;
51
+ const { data, rowRange, rowHeight, rowOffsets, rowHeights, visibleRowRange, rowWidth, skipBind } = viewport;
51
52
  if (data !== this.lastData) {
52
53
  this.lastData = data;
53
54
  this.forceRebind = true;
@@ -63,6 +64,7 @@ export class DomPool {
63
64
  this.hostRowIndex.push(null);
64
65
  this.hostContentBound.push(false);
65
66
  this.hostOffsetY.push(OFFSCREEN_Y);
67
+ this.hostHeight.push(-1);
66
68
  }
67
69
  const bound = [];
68
70
  const positioned = [];
@@ -74,6 +76,10 @@ export class DomPool {
74
76
  // `REBIND_PER_FRAME` stale slots, then resumes normal binding for
75
77
  // new rows.
76
78
  //
79
+ // The quota covers the OFF-SCREEN rows only: the rows that intersect
80
+ // the viewport are always bound (see below) — they carry the data the
81
+ // user actually reads.
82
+ //
77
83
  // With RING mapping the quota rarely engages during slow scroll:
78
84
  // scrolling by k rows reassigns only k slots (the ones recycled from
79
85
  // rows that left the window), so steady scrolling performs O(k) binds
@@ -104,7 +110,9 @@ export class DomPool {
104
110
  const slot = rowIndex % poolSize;
105
111
  this.slotActive[slot] = true;
106
112
  const host = this.hosts[slot];
107
- const offsetY = rowIndex * rowHeight;
113
+ const rangeIndex = rowIndex - range.start;
114
+ const offsetY = rowOffsets ? (rowOffsets[rangeIndex] ?? rowIndex * rowHeight) : rowIndex * rowHeight;
115
+ const currentHeight = rowHeights ? (rowHeights[rangeIndex] ?? rowHeight) : rowHeight;
108
116
  // Position is always updated — we need the transform to keep rows
109
117
  // at the correct offset regardless of whether content is bound.
110
118
  if (this.hostOffsetY[slot] !== offsetY) {
@@ -113,13 +121,41 @@ export class DomPool {
113
121
  positioned.push({ host, offsetY });
114
122
  }
115
123
  const indexChanged = this.hostRowIndex[slot] !== rowIndex;
124
+ const heightChanged = this.hostHeight[slot] !== currentHeight;
116
125
  const isNewSlot = this.hostRowIndex[slot] === null;
117
- const needsBind = indexChanged || this.forceRebind || !this.hostContentBound[slot];
126
+ const contentBound = this.hostContentBound[slot];
127
+ // The row BOX follows the virtualizer unconditionally: position AND
128
+ // height are geometry, not content. During a fast scroll the
129
+ // content of a recycled node is stale (it still belongs to the
130
+ // previous row), but the node must get the size of the row it
131
+ // stands for NOW — otherwise a 60px node occupies a 32px slot and
132
+ // the rows overlap (or leave gaps when the height shrinks).
133
+ // `resizeRow` only touches the box, never the content.
134
+ const resizeRow = this.bindings.resizeRow;
135
+ const canResize = resizeRow !== undefined && !this.forceRebind;
136
+ if (heightChanged && canResize && !isNewSlot) {
137
+ this.hostHeight[slot] = currentHeight;
138
+ resizeRow?.(host, currentHeight);
139
+ }
140
+ // A content re-bind is needed when the node shows a different row,
141
+ // when it has no content at all, or on a forced re-bind. A height
142
+ // change alone never invalidates the content — unless the adapter
143
+ // cannot resize a node, in which case the row has to be re-bound
144
+ // to pick up the new height.
145
+ const needsBind = indexChanged || this.forceRebind || !contentBound || (heightChanged && !canResize);
118
146
  // New slots (never been bound) must always bind — empty rows at the
119
147
  // viewport edge are visible as empty space, worse than a one-frame
120
- // bind cost. During fast scroll (skipBind), only DEFER rebinding
121
- // slots that already had content at a different row index.
122
- const mustBind = isNewSlot || this.forceRebind || (needsBind && !skipBind && quota > 0);
148
+ // bind cost.
149
+ //
150
+ // The rows that intersect the viewport must bind as well, even
151
+ // during a fast scroll: the pool recycles its nodes in a ring, so
152
+ // a node that is not re-bound keeps the content of a completely
153
+ // unrelated row — the user would read another row's data (e.g. the
154
+ // wrong ID) in the visible area. Only the off-screen rows (the
155
+ // overscan corridor) follow the rebind quota.
156
+ const inViewport = visibleRowRange !== undefined && rowIndex >= visibleRowRange.start && rowIndex < visibleRowRange.end;
157
+ const quotaBind = needsBind && !skipBind && quota > 0;
158
+ const mustBind = isNewSlot || this.forceRebind || (needsBind && (inViewport || quotaBind));
123
159
  if (needsBind && mustBind) {
124
160
  const dataRow = data[rowIndex];
125
161
  const row = {
@@ -127,14 +163,15 @@ export class DomPool {
127
163
  rowId: this.getRowId(dataRow, rowIndex),
128
164
  data: dataRow,
129
165
  offsetY,
130
- height: rowHeight,
166
+ height: currentHeight,
131
167
  width: rowWidth,
132
168
  };
133
169
  this.hostRowIndex[slot] = rowIndex;
170
+ this.hostHeight[slot] = currentHeight;
134
171
  this.hostContentBound[slot] = true;
135
172
  this.bindings.bindRow(host, row);
136
173
  bound.push({ host, row });
137
- if (!isNewSlot && !this.forceRebind)
174
+ if (!isNewSlot && !this.forceRebind && quotaBind)
138
175
  quota -= 1;
139
176
  }
140
177
  else if (indexChanged || this.forceRebind) {
@@ -144,6 +181,10 @@ export class DomPool {
144
181
  // at the correct new position until the next slow frame.
145
182
  this.hostRowIndex[slot] = rowIndex;
146
183
  this.hostContentBound[slot] = false;
184
+ // The node stands for the new row from now on: the adapters
185
+ // look rows up by index (hover highlight), so the index has to
186
+ // follow the position even while the content is still stale.
187
+ this.bindings.updateRowIndex?.(host, rowIndex);
147
188
  }
148
189
  }
149
190
  // Slots not claimed by the current window (their row left the window):
@@ -157,6 +198,7 @@ export class DomPool {
157
198
  continue;
158
199
  const host = this.hosts[slot];
159
200
  this.hostRowIndex[slot] = null;
201
+ this.hostHeight[slot] = -1;
160
202
  this.hostContentBound[slot] = false;
161
203
  this.hostOffsetY[slot] = OFFSCREEN_Y;
162
204
  this.bindings.recycleRow(host);
@@ -196,6 +238,7 @@ export class DomPool {
196
238
  this.hostRowIndex.length = 0;
197
239
  this.hostContentBound.length = 0;
198
240
  this.hostOffsetY.length = 0;
241
+ this.hostHeight.length = 0;
199
242
  this.slotActive.length = 0;
200
243
  this.lastData = null;
201
244
  this.destroyed = true;
package/dist/grid.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { FilterCondition, FilterModel } from "./filtering";
2
2
  import type { UIPopupAnchor, UIPopupDescriptor } from "./ui";
3
3
  import { IconRegistry } from "./icons";
4
4
  import { SlotManager } from "./slots";
5
- import type { ColumnLeafDef, DataProcessor, GridApi, GridEvents, GridOptions, GridPlugin, GridState, RowClickEvent, RowHoverEvent, RowId, RowSpanLayout, ScrollPosition, SlotMount, SlotName, ViewportData, ViewportState } from "./types";
5
+ import type { ColumnLeafDef, DataProcessor, GridApi, GridEvents, GridOptions, GridPlugin, GridState, RowClickEvent, RowHeightUpdateOptions, RowHoverEvent, RowId, RowSpanLayout, ScrollPosition, SlotMount, SlotName, ViewportData, ViewportState } from "./types";
6
6
  import type { OverlayOptions, OverlayState } from "./overlays";
7
7
  export declare class Grid<T> implements GridApi<T> {
8
8
  private readonly store;
@@ -35,6 +35,8 @@ export declare class Grid<T> implements GridApi<T> {
35
35
  private loadError;
36
36
  private overlayState;
37
37
  private overlayManual;
38
+ /** Grid-level `wrapText` flag — applied to every column without an explicit one. */
39
+ private wrapTextAll;
38
40
  /**
39
41
  * Separate ephemeral scroll position that is NOT stored in the Store.
40
42
  *
@@ -139,6 +141,46 @@ export declare class Grid<T> implements GridApi<T> {
139
141
  closePopup(): void;
140
142
  getPopup(): UIPopupDescriptor | null;
141
143
  getRowId(row: T, index: number): RowId;
144
+ /**
145
+ * Records the measured DOM height of a row (variable-height mode).
146
+ * Returns the scrollTop correction (px) the adapter must apply to keep
147
+ * the anchored row visually stable when rows above the viewport change.
148
+ *
149
+ * A height change is a GEOMETRY change, not a structural one: the row
150
+ * content stays valid, so the grid does not bump its structural revision
151
+ * (which would force the DOM pool to re-bind every visible row).
152
+ * @param rowIndex - Zero-based index in the processed dataset.
153
+ * @param height - Measured row height in pixels (must be finite and > 0).
154
+ * @param options - Set `anchor: false` to suppress the built-in scroll
155
+ * anchoring correction (the caller applies it later).
156
+ * @api
157
+ */
158
+ setRowHeight(rowIndex: number, height: number, options?: RowHeightUpdateOptions): number;
159
+ /**
160
+ * Removes a measured row height (falls back to the estimate).
161
+ * Returns the scrollTop correction like `setRowHeight`.
162
+ * @param rowIndex - Zero-based index in the processed dataset.
163
+ * @param options - Set `anchor: false` to suppress the built-in scroll
164
+ * anchoring correction (the caller applies it later).
165
+ * @api
166
+ */
167
+ resetRowHeight(rowIndex: number, options?: RowHeightUpdateOptions): number;
168
+ /** Removes all measured row heights (e.g. after `setColumns`). @api */
169
+ resetAllRowHeights(): void;
170
+ /**
171
+ * Returns the absolute vertical offset (px) of the top of a row,
172
+ * accounting for variable heights. Falls back to `index * rowHeight`
173
+ * when no measurements exist.
174
+ * @param rowIndex - Zero-based index in the processed dataset.
175
+ * @api
176
+ */
177
+ getRowTop(rowIndex: number): number;
178
+ /**
179
+ * Returns the current (measured, resolved, or estimated) height of a row.
180
+ * @param rowIndex - Zero-based index in the processed dataset.
181
+ * @api
182
+ */
183
+ getRowHeight(rowIndex: number): number;
142
184
  setData(data: T[] | null | undefined): void;
143
185
  /**
144
186
  * Chunk-append API for incremental data loading (infinite scroll, live
package/dist/grid.js CHANGED
@@ -1,4 +1,4 @@
1
- import { flattenColumns, getColumnGroups, getRowSpans, resolveColSpan } from "./columns";
1
+ import { applyWrapText, flattenColumns, getColumnGroups, getRowSpans, resolveColSpan } from "./columns";
2
2
  import { EventBus } from "./events";
3
3
  import { applyFilterModel, applyQuickFilter, isActiveCondition } from "./filtering";
4
4
  import { PopupManager } from "./ui";
@@ -37,7 +37,7 @@ export class Grid {
37
37
  this.scrollPosition = { scrollTop: 0, scrollLeft: 0 };
38
38
  const state = {
39
39
  data: options.data ?? [],
40
- columns: options.columns,
40
+ columns: applyWrapText(options.columns, options.wrapText),
41
41
  viewport: { width: 0, height: 0, scrollTop: 0, scrollLeft: 0 },
42
42
  rowHeight: options.rowHeight ?? 32,
43
43
  rowOverscan: options.rowOverscan ?? 5,
@@ -50,10 +50,19 @@ export class Grid {
50
50
  this.resolveRowId = options.getRowId ?? ((_row, index) => index);
51
51
  this.loading = options.loading ?? false;
52
52
  this.hasData = options.data !== undefined && options.data !== null;
53
+ this.wrapTextAll = options.wrapText;
53
54
  if (options.filterModel)
54
55
  this.filterModel = Grid.cloneFilterModel(options.filterModel);
55
56
  this.virtualizer = new Virtualizer({
56
57
  rowHeight: state.rowHeight,
58
+ estimatedRowHeight: options.estimatedRowHeight ?? options.rowHeight,
59
+ getRowHeight: options.getRowHeight
60
+ ? (rowIndex) => {
61
+ const data = this.getProcessedData();
62
+ const row = data[rowIndex];
63
+ return row !== undefined ? options.getRowHeight(rowIndex, row) : undefined;
64
+ }
65
+ : undefined,
57
66
  rowOverscan: state.rowOverscan,
58
67
  columnOverscan: state.columnOverscan,
59
68
  });
@@ -169,7 +178,18 @@ export class Grid {
169
178
  ? this.virtualizer.getColumnRange(scrollable, scrollLeft, scrollableViewWidth, scrollableOffsets)
170
179
  : { start: 0, end: 0 };
171
180
  const columnRange = Grid.expandColumnRangeForSpans(scrollable, baseColumnRange);
172
- const rowRange = this.virtualizer.getRowRange(processedData.length, this.scrollPosition.scrollTop, state.viewport.height);
181
+ const hasVariable = this.virtualizer.hasVariableHeights;
182
+ const rowRange = this.virtualizer.getRowRange(processedData.length, this.scrollPosition.scrollTop, state.viewport.height, hasVariable);
183
+ // The rows that actually intersect the viewport (no overscan): the
184
+ // adapter binds them eagerly so a recycled node never shows the data
185
+ // of a different row.
186
+ const visibleRowRange = this.virtualizer.getVisibleRowRange(processedData.length, this.scrollPosition.scrollTop, state.viewport.height);
187
+ const rowOffsets = hasVariable
188
+ ? Array.from({ length: rowRange.end - rowRange.start }, (_, i) => this.virtualizer.getRowTop(rowRange.start + i, processedData.length))
189
+ : undefined;
190
+ const rowHeights = hasVariable
191
+ ? Array.from({ length: rowRange.end - rowRange.start }, (_, i) => this.virtualizer.getRowHeight(rowRange.start + i))
192
+ : undefined;
173
193
  // Offset composition:
174
194
  // pinned-left: absolute from 0
175
195
  // scrollable: shifted by pinnedLeftWidth
@@ -200,7 +220,13 @@ export class Grid {
200
220
  return {
201
221
  rows: processedData.slice(rowRange.start, rowRange.end).map((data, index) => {
202
222
  const rowIndex = rowRange.start + index;
203
- return { id: this.getRowId(data, rowIndex), data, index: rowIndex, offset: rowIndex * state.rowHeight };
223
+ return {
224
+ id: this.getRowId(data, rowIndex),
225
+ data,
226
+ index: rowIndex,
227
+ offset: rowOffsets ? rowOffsets[index] : rowIndex * state.rowHeight,
228
+ height: rowHeights ? rowHeights[index] : state.rowHeight,
229
+ };
204
230
  }),
205
231
  columns,
206
232
  pinnedLeftColumns,
@@ -215,7 +241,10 @@ export class Grid {
215
241
  headerRowCount,
216
242
  columnGroupDepth,
217
243
  rowRange,
244
+ visibleRowRange,
218
245
  columnRange,
246
+ rowOffsets,
247
+ rowHeights,
219
248
  totalWidth,
220
249
  totalHeight: this.virtualizer.getTotalHeight(processedData.length),
221
250
  };
@@ -429,6 +458,81 @@ export class Grid {
429
458
  getRowId(row, index) {
430
459
  return this.resolveRowId(row, index);
431
460
  }
461
+ /**
462
+ * Records the measured DOM height of a row (variable-height mode).
463
+ * Returns the scrollTop correction (px) the adapter must apply to keep
464
+ * the anchored row visually stable when rows above the viewport change.
465
+ *
466
+ * A height change is a GEOMETRY change, not a structural one: the row
467
+ * content stays valid, so the grid does not bump its structural revision
468
+ * (which would force the DOM pool to re-bind every visible row).
469
+ * @param rowIndex - Zero-based index in the processed dataset.
470
+ * @param height - Measured row height in pixels (must be finite and > 0).
471
+ * @param options - Set `anchor: false` to suppress the built-in scroll
472
+ * anchoring correction (the caller applies it later).
473
+ * @api
474
+ */
475
+ setRowHeight(rowIndex, height, options) {
476
+ this.assertActive();
477
+ const count = this.getProcessedData().length;
478
+ const scrollTop = this.scrollPosition.scrollTop;
479
+ const previousHeight = this.virtualizer.getRowHeight(rowIndex);
480
+ const correction = this.virtualizer.setRowHeight(rowIndex, height, scrollTop, count);
481
+ if (this.virtualizer.getRowHeight(rowIndex) === previousHeight)
482
+ return 0;
483
+ if (options?.notify !== false)
484
+ this.store.setState({});
485
+ if (correction !== 0 && options?.anchor !== false) {
486
+ this.scrollTo({ scrollTop: scrollTop + correction });
487
+ }
488
+ return correction;
489
+ }
490
+ /**
491
+ * Removes a measured row height (falls back to the estimate).
492
+ * Returns the scrollTop correction like `setRowHeight`.
493
+ * @param rowIndex - Zero-based index in the processed dataset.
494
+ * @param options - Set `anchor: false` to suppress the built-in scroll
495
+ * anchoring correction (the caller applies it later).
496
+ * @api
497
+ */
498
+ resetRowHeight(rowIndex, options) {
499
+ this.assertActive();
500
+ const count = this.getProcessedData().length;
501
+ const scrollTop = this.scrollPosition.scrollTop;
502
+ const correction = this.virtualizer.resetRowHeight(rowIndex, scrollTop, count);
503
+ if (options?.notify !== false)
504
+ this.store.setState({});
505
+ if (correction !== 0 && options?.anchor !== false) {
506
+ this.scrollTo({ scrollTop: scrollTop + correction });
507
+ }
508
+ return correction;
509
+ }
510
+ /** Removes all measured row heights (e.g. after `setColumns`). @api */
511
+ resetAllRowHeights() {
512
+ this.assertActive();
513
+ this.virtualizer.resetAllRowHeights();
514
+ this.revision += 1;
515
+ this.store.setState({});
516
+ }
517
+ /**
518
+ * Returns the absolute vertical offset (px) of the top of a row,
519
+ * accounting for variable heights. Falls back to `index * rowHeight`
520
+ * when no measurements exist.
521
+ * @param rowIndex - Zero-based index in the processed dataset.
522
+ * @api
523
+ */
524
+ getRowTop(rowIndex) {
525
+ const count = this.getProcessedData().length;
526
+ return this.virtualizer.getRowTop(rowIndex, count);
527
+ }
528
+ /**
529
+ * Returns the current (measured, resolved, or estimated) height of a row.
530
+ * @param rowIndex - Zero-based index in the processed dataset.
531
+ * @api
532
+ */
533
+ getRowHeight(rowIndex) {
534
+ return this.virtualizer.getRowHeight(rowIndex);
535
+ }
432
536
  setData(data) {
433
537
  this.assertActive();
434
538
  this.loadError = undefined;
@@ -436,6 +540,7 @@ export class Grid {
436
540
  const nextData = data ?? [];
437
541
  this.filteredDataCache = null;
438
542
  this.processedDataCache = null;
543
+ this.virtualizer.resetAllRowHeights();
439
544
  this.revision += 1;
440
545
  this.store.setState({ data: nextData });
441
546
  this.events.emit("dataChange", nextData);
@@ -522,7 +627,7 @@ export class Grid {
522
627
  this.filteredDataCache = null;
523
628
  this.processedDataCache = null;
524
629
  this.revision += 1;
525
- this.store.setState({ columns });
630
+ this.store.setState({ columns: applyWrapText(columns, this.wrapTextAll) });
526
631
  this.recomputeOverlay();
527
632
  }
528
633
  registerDataProcessor(processor) {
package/dist/index.d.ts CHANGED
@@ -11,6 +11,6 @@ export { applyFilterModel, applyQuickFilter, isActiveCondition, isFilterModelAct
11
11
  export type { ColumnFilterModel, FilterCondition, FilterModel, FilterOperator } from "./filtering";
12
12
  export type { UIButtonControl, UICheckboxDescriptor, UIControlBase, UIControlDescriptor, UIGroupControl, UIInputControl, UIPopupAnchor, UIPopupDescriptor, UISelectControl, UISelectOption, UITextBlockControl, UIMultiSelectControl, UIMultiSelectOption, } from "./ui";
13
13
  export type { OverlayOptions, OverlayScope, OverlayState, OverlayType } from "./overlays";
14
- export type { BlockConfig, CellAlign, CellRenderParams, CellClassRules, CellSpan, CellSpanningParams, CheckboxControl, CheckboxRenderParams, ColSpanDef, ColumnClassRules, ColumnDataType, ColumnFilterType, ColumnDef, ColumnGroupDef, ColumnGroupViewport, ColumnLeafDef, ColumnStyle, ColumnStyleParams, DataProcessor, DomPoolBindings, DomPoolUpdate, DomPoolUpdateOptions, GridApi, GridEvents, GridOptions, GridPlugin, GridState, HeaderClassRules, HeaderGroupClassRules, HeaderGroupRenderParams, HeaderRenderParams, HeaderStyle, OverlayComponent, OverlayComponentProps, PooledRow, Range, RowClassRules, RowClickEvent, RowHost, RowHoverEvent, RowId, RowNode, RowRenderParams, RowSpanLayout, RowStyle, ScrollPosition, SlotComponentContent, SlotContent, SlotHtmlContent, SlotMount, SlotMountOptions, SlotName, SlotNodeContent, SlotNodeEvent, SlotNodeEventName, SlotPosition, SlotProvider, SlotRenderContext, SortDirection, ViewportData, ViewportState, VirtualItem, } from "./types";
14
+ export type { BlockConfig, CellAlign, CellRenderParams, CellClassRules, CellSpan, CellSpanningParams, CheckboxControl, CheckboxRenderParams, ColSpanDef, ColumnClassRules, ColumnDataType, ColumnFilterType, ColumnDef, ColumnGroupDef, ColumnGroupViewport, ColumnLeafDef, ColumnStyle, ColumnStyleParams, DataProcessor, DomPoolBindings, DomPoolUpdate, DomPoolUpdateOptions, GridApi, GridEvents, GridOptions, GridPlugin, GridState, HeaderClassRules, HeaderGroupClassRules, HeaderGroupRenderParams, HeaderRenderParams, HeaderStyle, OverlayComponent, OverlayComponentProps, PooledRow, Range, RowClassRules, RowClickEvent, RowHeightUpdateOptions, RowHost, RowHoverEvent, RowId, RowNode, RowRenderParams, RowSpanLayout, RowStyle, ScrollPosition, SlotComponentContent, SlotContent, SlotHtmlContent, SlotMount, SlotMountOptions, SlotName, SlotNodeContent, SlotNodeEvent, SlotNodeEventName, SlotPosition, SlotProvider, SlotRenderContext, SortDirection, ViewportData, ViewportState, VirtualItem, } from "./types";
15
15
  export { getColumnGroups, flattenColumns, isColumnGroup, isColumnLeaf, getCellValue, getCellSpanningParams, resolveColSpan, getRowSpans } from "./columns";
16
- export { Virtualizer } from "./virtualizer";
16
+ export { Virtualizer, RowHeightRegistry } from "./virtualizer";
package/dist/index.js CHANGED
@@ -8,4 +8,4 @@ export { SlotManager } from "./slots";
8
8
  export { Store } from "./store";
9
9
  export { applyFilterModel, applyQuickFilter, isActiveCondition, isFilterModelActive, matchesColumnFilter } from "./filtering";
10
10
  export { getColumnGroups, flattenColumns, isColumnGroup, isColumnLeaf, getCellValue, getCellSpanningParams, resolveColSpan, getRowSpans } from "./columns";
11
- export { Virtualizer } from "./virtualizer";
11
+ export { Virtualizer, RowHeightRegistry } from "./virtualizer";
package/dist/types.d.ts CHANGED
@@ -305,6 +305,8 @@ export interface ColumnLeafDef<T> extends BaseColumnDef<T> {
305
305
  }>;
306
306
  /** Horizontal alignment of cell content. */
307
307
  align?: CellAlign;
308
+ /** Enables automatic text wrapping instead of ellipsis truncation. @default false @api */
309
+ wrapText?: boolean;
308
310
  /** Initial sort direction used by SortingPlugin. */
309
311
  sortState?: SortDirection;
310
312
  /** 1-based sort priority, set only while multiple columns are sorted. */
@@ -402,6 +404,32 @@ export interface OverlayComponentProps<T> {
402
404
  * @api
403
405
  */
404
406
  export type OverlayComponent<T> = ((props: OverlayComponentProps<T>) => unknown) | ((payload: unknown, state: GridState<T>) => unknown);
407
+ /**
408
+ * Options for a single row-height update.
409
+ *
410
+ * @api
411
+ */
412
+ export interface RowHeightUpdateOptions {
413
+ /**
414
+ * Whether the grid applies the scroll anchoring correction itself.
415
+ * Set to `false` when the adapter wants to defer the correction — e.g.
416
+ * while the user is actively scrolling, where a scrollTop jump fights
417
+ * the user's input. The returned correction stays valid either way.
418
+ * @default true
419
+ */
420
+ anchor?: boolean;
421
+ /**
422
+ * Whether the grid notifies its Store subscribers about the change.
423
+ *
424
+ * The row heights are NOT part of the grid state — the notification only
425
+ * re-renders the host framework. Adapters that update the row geometry
426
+ * imperatively (the DOM pool) can opt out: a re-render per measured row
427
+ * starves the frame budget while the user scrolls, and the grid then
428
+ * lags behind the native scroll position.
429
+ * @default true
430
+ */
431
+ notify?: boolean;
432
+ }
405
433
  export interface GridOptions<T> {
406
434
  /** Row data; omitted or null means an initial load is pending. */
407
435
  data?: T[] | null;
@@ -409,6 +437,29 @@ export interface GridOptions<T> {
409
437
  /** Returns a stable row ID; defaults to the row's current index. Use a stable ID to preserve row identity when rows are reordered. */
410
438
  getRowId?: (row: T, index: number) => RowId;
411
439
  rowHeight?: number;
440
+ /** Enables automatic text wrapping for all cells. @default false @api */
441
+ wrapText?: boolean;
442
+ /**
443
+ * Fallback row height (px) for rows that have not been measured yet.
444
+ * When set (or when `getRowHeight` is set), the grid switches to
445
+ * variable-height mode: each row may have its own height, while unknown
446
+ * rows use this estimate for scrollbar and range math.
447
+ * Defaults to `rowHeight`.
448
+ * @api
449
+ */
450
+ estimatedRowHeight?: number;
451
+ /**
452
+ * Synchronous per-row height resolver. Must be O(1) — it is consulted
453
+ * during virtualization math. Return `undefined` to fall back to the
454
+ * estimated height for that row. Dynamically measured heights (via
455
+ * `setRowHeight`) always win over this resolver.
456
+ *
457
+ * The result is captured when the offset index is (re)built, so the
458
+ * resolver must be stable for a given row index — changing it requires
459
+ * a `setData` / `setColumns` call (or `resetAllRowHeights`).
460
+ * @api
461
+ */
462
+ getRowHeight?: (rowIndex: number, row: T) => number | undefined;
412
463
  /** Rows to render beyond the visible viewport (top + bottom buffer). @default 5 */
413
464
  rowOverscan?: number;
414
465
  /** Columns to render beyond the visible viewport (left + right buffer). @default 2 */
@@ -491,6 +542,7 @@ export interface ViewportData<T> {
491
542
  data: T;
492
543
  index: number;
493
544
  offset: number;
545
+ height?: number;
494
546
  }>;
495
547
  /** Scrollable (virtualized) leaf columns of the current horizontal window. */
496
548
  columns: Array<{
@@ -556,7 +608,29 @@ export interface ViewportData<T> {
556
608
  */
557
609
  columnGroupDepth: Map<number, number>;
558
610
  rowRange: Range;
611
+ /**
612
+ * Rows that intersect the viewport — `rowRange` without the overscan
613
+ * buffer.
614
+ *
615
+ * Adapters must bind these rows eagerly: pooled nodes are recycled in a
616
+ * ring, so a node that was not re-bound shows the data of an unrelated
617
+ * row.
618
+ * @api
619
+ */
620
+ visibleRowRange: Range;
559
621
  columnRange: Range;
622
+ /**
623
+ * Per-row vertical offsets aligned with `rowRange` in variable-height mode.
624
+ * Omitted in fixed-height mode.
625
+ * @api
626
+ */
627
+ rowOffsets?: number[];
628
+ /**
629
+ * Per-row heights aligned with `rowRange` in variable-height mode.
630
+ * Omitted in fixed-height mode.
631
+ * @api
632
+ */
633
+ rowHeights?: number[];
560
634
  totalWidth: number;
561
635
  totalHeight: number;
562
636
  }
@@ -629,6 +703,34 @@ export interface DomPoolBindings<T> {
629
703
  bindRow(host: RowHost<T>, row: PooledRow<T>): void;
630
704
  transformRow(host: RowHost<T>, offsetY: number): void;
631
705
  recycleRow(host: RowHost<T>): void;
706
+ /**
707
+ * Applies a new height to an already bound row node.
708
+ *
709
+ * Called when only the row HEIGHT changed (variable-height mode) while
710
+ * the row itself stayed the same: the content is still valid, so the
711
+ * node only needs a new box. Rebinding instead would re-render every
712
+ * cell of the row and re-trigger its measurement.
713
+ *
714
+ * Optional: when it is not implemented the pool falls back to a full
715
+ * re-bind for height changes.
716
+ * @api
717
+ */
718
+ resizeRow?(host: RowHost<T>, height: number): void;
719
+ /**
720
+ * Updates the row index a node stands for.
721
+ *
722
+ * Called when the node was re-used for a different row but its content
723
+ * could not be re-bound in the same frame (fast scroll, rebind quota).
724
+ * The node keeps the PREVIOUS content until it is bound, but its row
725
+ * index must already describe the NEW row — adapters look rows up by
726
+ * index (e.g. the hover highlight), and a stale index would highlight
727
+ * the wrong node.
728
+ *
729
+ * Optional: when it is not implemented the node keeps its old index
730
+ * until the content is bound.
731
+ * @api
732
+ */
733
+ updateRowIndex?(host: RowHost<T>, rowIndex: number): void;
632
734
  }
633
735
  /**
634
736
  * Options passed to `DomPool.update()` to control binding behavior.
@@ -642,6 +744,27 @@ export interface DomPoolUpdateOptions<T> {
642
744
  rowRange: Range;
643
745
  /** Pixel height of each row. */
644
746
  rowHeight: number;
747
+ /**
748
+ * Per-row geometry for variable-height mode, aligned with `rowRange`:
749
+ * `rowOffsets[i]` / `rowHeights[i]` describe `data[rowRange.start + i]`.
750
+ * When present, the pool positions each row at its own offset and height
751
+ * instead of `rowIndex * rowHeight`. Omitted in fixed-height mode.
752
+ * @api
753
+ */
754
+ rowOffsets?: number[];
755
+ /** Per-row heights aligned with `rowOffsets`. See `rowOffsets`. @api */
756
+ rowHeights?: number[];
757
+ /**
758
+ * Rows that intersect the viewport (a subset of `rowRange`, without the
759
+ * overscan buffer).
760
+ *
761
+ * These rows are bound even when `skipBind` is set: a recycled node that
762
+ * is not re-bound keeps the content of a completely unrelated row, and
763
+ * the user would see the wrong data in the visible area. The off-screen
764
+ * rows follow the rebind quota.
765
+ * @api
766
+ */
767
+ visibleRowRange?: Range;
645
768
  /** Pixel width of each row (sum of all column widths). */
646
769
  rowWidth: number;
647
770
  /**
@@ -823,6 +946,45 @@ export interface GridApi<T> {
823
946
  * @api
824
947
  */
825
948
  appendData(rows: T[] | null | undefined): void;
949
+ /**
950
+ * Records the measured DOM height of a row (variable-height mode).
951
+ * Heights below 1px delta are ignored to prevent feedback loops between
952
+ * measurement and layout. Switching the height of rows above the current
953
+ * scroll position keeps the anchored row visually stable: the returned
954
+ * value is the scrollTop correction (px, may be negative) the adapter
955
+ * must apply to its scroll container to prevent viewport jumps.
956
+ * @param rowIndex - Zero-based index in the processed dataset.
957
+ * @param height - Measured row height in pixels (must be finite and > 0).
958
+ * @param options - Optional anchoring control.
959
+ * @returns ScrollTop adjustment in pixels (`0` = no anchoring needed).
960
+ * @api
961
+ */
962
+ setRowHeight(rowIndex: number, height: number, options?: RowHeightUpdateOptions): number;
963
+ /**
964
+ * Removes a measured row height (e.g. when row content collapses back to
965
+ * the estimate). Returns the scrollTop correction like `setRowHeight`.
966
+ * @param rowIndex - Zero-based index in the processed dataset.
967
+ * @param options - Optional anchoring control.
968
+ * @returns ScrollTop adjustment in pixels (`0` = no anchoring needed).
969
+ * @api
970
+ */
971
+ resetRowHeight(rowIndex: number, options?: RowHeightUpdateOptions): number;
972
+ /** Removes all measured row heights (e.g. after `setColumns`). @api */
973
+ resetAllRowHeights(): void;
974
+ /**
975
+ * Returns the absolute vertical offset (px) of the top of a row,
976
+ * accounting for variable heights. Falls back to `index * rowHeight`
977
+ * when no measurements exist.
978
+ * @param rowIndex - Zero-based index in the processed dataset.
979
+ * @api
980
+ */
981
+ getRowTop(rowIndex: number): number;
982
+ /**
983
+ * Returns the current (measured, resolved, or estimated) height of a row.
984
+ * @param rowIndex - Zero-based index in the processed dataset.
985
+ * @api
986
+ */
987
+ getRowHeight(rowIndex: number): number;
826
988
  setViewport(viewport: Partial<ViewportState>): void;
827
989
  refresh(): void;
828
990
  subscribe(listener: () => void): () => void;
@@ -1,17 +1,154 @@
1
1
  import type { ColumnLeafDef, Range, VirtualItem } from "./types";
2
2
  export interface VirtualizerOptions {
3
3
  rowHeight: number;
4
+ /** Fallback height for unmeasured rows in variable-height mode. */
5
+ estimatedRowHeight?: number;
6
+ /** Synchronous per-row height resolver. */
7
+ getRowHeight?: (rowIndex: number) => number | undefined;
4
8
  rowOverscan: number;
5
9
  columnOverscan: number;
6
10
  }
11
+ /**
12
+ * Dynamic row-height registry: `rowIndex -> measured px height`.
13
+ *
14
+ * Heights live in a Fenwick tree (binary indexed tree) over the row indexes.
15
+ * A single measurement is applied in O(log n) — the prefix sums are patched
16
+ * in place instead of rebuilding the whole offset table — and row offsets /
17
+ * range lookups are answered with O(log n) prefix queries and searches.
18
+ * Rebuilding the whole table is only needed when the dataset size or the
19
+ * estimate changes, which happens on structural changes only.
20
+ *
21
+ * Rows without a measurement use the resolver value, or the estimate. The
22
+ * resolver result is captured when the index is (re)built, so it must be
23
+ * stable for a given row index.
24
+ */
25
+ export declare class RowHeightRegistry {
26
+ private heights;
27
+ /** Estimated height for rows without a measurement. */
28
+ private estimatedHeight;
29
+ private readonly resolver?;
30
+ private currentVersion;
31
+ /** Fenwick tree of row heights (1-based indexing). */
32
+ private tree;
33
+ /** Raw height of every row the tree covers — mirrors the tree leaves. */
34
+ private leaves;
35
+ /** Number of rows the tree currently covers. */
36
+ private treeCount;
37
+ /** Whether the tree has to be rebuilt before the next query. */
38
+ private treeDirty;
39
+ constructor(estimatedHeight: number, resolver?: (rowIndex: number) => number | undefined);
40
+ /** Total number of rows with an explicit measured height. @api */
41
+ get size(): number;
42
+ /** Monotonically increasing revision number bumped on any measurement or estimate change. @api */
43
+ get version(): number;
44
+ /** Whether any variable-height input exists (resolver or measured heights). @api */
45
+ get hasVariableHeights(): boolean;
46
+ /** Updates the fallback estimated height for unmeasured rows. @api */
47
+ setEstimatedHeight(height: number): void;
48
+ /**
49
+ * Records a measured height. Returns `true` when the value actually
50
+ * changed (delta > 1px); sub-pixel noise is ignored to prevent
51
+ * measurement/layout feedback loops.
52
+ */
53
+ set(rowIndex: number, height: number): boolean;
54
+ /** Removes a single measured height. Returns `true` when one existed. */
55
+ reset(rowIndex: number): boolean;
56
+ /** Removes all measured heights. */
57
+ clear(): void;
58
+ /** Returns the measured height of a row if one has been recorded, or undefined. @api */
59
+ get(rowIndex: number): number | undefined;
60
+ /** Returns the resolved height of a row (measured, dynamic callback, or estimated). */
61
+ getRowHeight(rowIndex: number): number;
62
+ /** Materializes the cumulative offsets table (`offsets[i]` = top of row `i`). @api */
63
+ getOffsets(count: number): number[];
64
+ /** Total scrollable content height for `count` rows. @api */
65
+ getTotalHeight(count: number): number;
66
+ /** Absolute top offset of a row (clamped to the dataset). @api */
67
+ getTop(rowIndex: number, count: number): number;
68
+ /**
69
+ * First row whose bottom edge is strictly below `offset`
70
+ * (binary search over the Fenwick tree).
71
+ * @api
72
+ */
73
+ findStart(count: number, offset: number): number;
74
+ /**
75
+ * First row whose top edge is at or past `offset`
76
+ * (binary search over the Fenwick tree). Used as the exclusive window end.
77
+ * @api
78
+ */
79
+ findEnd(count: number, offset: number): number;
80
+ /** Marks the offset index dirty when the dataset identity changes. @api */
81
+ invalidate(count: number): void;
82
+ /** Resolves the effective height of a row: measured, resolver, or estimate. */
83
+ private resolveHeight;
84
+ /** Rebuilds the Fenwick tree when the dataset size or the estimate changed. */
85
+ private ensureTree;
86
+ /** Patches a single row height into the live tree (O(log n)). */
87
+ private applyDelta;
88
+ /** Sum of the first `count` row heights. */
89
+ private static prefixSum;
90
+ /**
91
+ * Finds the largest row count whose cumulative height does not exceed
92
+ * `offset` — i.e. the number of rows fully above the offset.
93
+ */
94
+ private static findFloor;
95
+ }
7
96
  export declare class Virtualizer<T> {
8
97
  private readonly options;
98
+ private readonly heights;
9
99
  private lastScrollTop;
10
100
  private lastRowRange;
11
101
  private lastRowCount;
12
102
  private lastRowViewportHeight;
103
+ private lastHeightsVersion;
13
104
  constructor(options: VirtualizerOptions);
14
- getRowRange(count: number, scrollTop: number, viewportHeight: number): Range;
105
+ /** Dynamic height registry backing variable-height mode. @api */
106
+ get rowHeights(): RowHeightRegistry;
107
+ /** Estimated height used for rows without a measurement. @api */
108
+ get estimatedRowHeight(): number;
109
+ /** Whether any variable-height input exists (resolver counts or measured heights exist). @api */
110
+ get hasVariableHeights(): boolean;
111
+ /**
112
+ * Visible row range calculation for fixed or variable heights.
113
+ * @api
114
+ */
115
+ getRowRange(count: number, scrollTop: number, viewportHeight: number, variableHeights?: boolean): Range;
116
+ /**
117
+ * Computes the visible row window for variable-height mode using the
118
+ * incremental offset index (binary search over the Fenwick tree).
119
+ * @api
120
+ */
121
+ getVariableRowRange(count: number, scrollTop: number, viewportHeight: number): Range;
122
+ /**
123
+ * Rows that intersect the viewport — the range WITHOUT the overscan
124
+ * buffer.
125
+ *
126
+ * The DOM pool reuses its nodes in a ring: a node that was not re-bound
127
+ * keeps the content of a completely unrelated row. The rows that
128
+ * intersect the viewport must therefore always be bound, even while a
129
+ * fast scroll defers the off-screen (overscan) rows.
130
+ * @api
131
+ */
132
+ getVisibleRowRange(count: number, scrollTop: number, viewportHeight: number): Range;
133
+ /**
134
+ * Absolute vertical offset (px) of the top of a row, accounting for variable heights.
135
+ * @api
136
+ */
137
+ getRowTop(rowIndex: number, count: number): number;
138
+ /** Current (measured, resolved, or estimated) height of a row. @api */
139
+ getRowHeight(rowIndex: number): number;
140
+ /**
141
+ * Records a measured row height and returns the scrollTop correction needed
142
+ * to keep the visually anchored row stable (scroll anchoring).
143
+ * @api
144
+ */
145
+ setRowHeight(rowIndex: number, height: number, scrollTop: number, count: number): number;
146
+ /** Removes a measured row height (falls back to resolver or estimate). @api */
147
+ resetRowHeight(rowIndex: number, scrollTop: number, count: number): number;
148
+ /** Removes all measured row heights (e.g. after `setColumns`). @api */
149
+ resetAllRowHeights(): void;
150
+ /** Total scrollable content height for `count` rows, accounting for variable heights. @api */
151
+ getTotalHeight(count: number): number;
15
152
  /**
16
153
  * Column geometry works on the FLAT working set of leaf columns only —
17
154
  * groups never reach the Virtualizer (see `Grid.getViewportData()`).
@@ -23,7 +160,6 @@ export declare class Virtualizer<T> {
23
160
  getColumnRange(columns: ColumnLeafDef<T>[], scrollLeft: number, viewportWidth: number, offsets?: VirtualItem[]): Range;
24
161
  private readonly widthsCache;
25
162
  getColumnOffsets(columns: ColumnLeafDef<T>[], viewportWidth?: number): VirtualItem[];
26
- getTotalHeight(rowCount: number): number;
27
163
  getTotalWidth(columns: ColumnLeafDef<T>[], viewportWidth?: number): number;
28
164
  private getRange;
29
165
  private getColumnWidths;
@@ -1,20 +1,277 @@
1
+ /**
2
+ * Dynamic row-height registry: `rowIndex -> measured px height`.
3
+ *
4
+ * Heights live in a Fenwick tree (binary indexed tree) over the row indexes.
5
+ * A single measurement is applied in O(log n) — the prefix sums are patched
6
+ * in place instead of rebuilding the whole offset table — and row offsets /
7
+ * range lookups are answered with O(log n) prefix queries and searches.
8
+ * Rebuilding the whole table is only needed when the dataset size or the
9
+ * estimate changes, which happens on structural changes only.
10
+ *
11
+ * Rows without a measurement use the resolver value, or the estimate. The
12
+ * resolver result is captured when the index is (re)built, so it must be
13
+ * stable for a given row index.
14
+ */
15
+ export class RowHeightRegistry {
16
+ constructor(estimatedHeight, resolver) {
17
+ this.heights = new Map();
18
+ this.currentVersion = 0;
19
+ /** Fenwick tree of row heights (1-based indexing). */
20
+ this.tree = new Float64Array(1);
21
+ /** Raw height of every row the tree covers — mirrors the tree leaves. */
22
+ this.leaves = new Float64Array(0);
23
+ /** Number of rows the tree currently covers. */
24
+ this.treeCount = -1;
25
+ /** Whether the tree has to be rebuilt before the next query. */
26
+ this.treeDirty = true;
27
+ this.estimatedHeight = estimatedHeight;
28
+ this.resolver = resolver;
29
+ }
30
+ /** Total number of rows with an explicit measured height. @api */
31
+ get size() {
32
+ return this.heights.size;
33
+ }
34
+ /** Monotonically increasing revision number bumped on any measurement or estimate change. @api */
35
+ get version() {
36
+ return this.currentVersion;
37
+ }
38
+ /** Whether any variable-height input exists (resolver or measured heights). @api */
39
+ get hasVariableHeights() {
40
+ return this.heights.size > 0 || this.resolver !== undefined;
41
+ }
42
+ /** Updates the fallback estimated height for unmeasured rows. @api */
43
+ setEstimatedHeight(height) {
44
+ if (height === this.estimatedHeight)
45
+ return;
46
+ this.estimatedHeight = height;
47
+ this.currentVersion += 1;
48
+ this.treeDirty = true;
49
+ }
50
+ /**
51
+ * Records a measured height. Returns `true` when the value actually
52
+ * changed (delta > 1px); sub-pixel noise is ignored to prevent
53
+ * measurement/layout feedback loops.
54
+ */
55
+ set(rowIndex, height) {
56
+ if (!Number.isFinite(rowIndex) || rowIndex < 0 || !Number.isInteger(rowIndex))
57
+ return false;
58
+ if (!Number.isFinite(height) || height <= 0)
59
+ return false;
60
+ const rounded = Math.max(1, Math.round(height));
61
+ const prev = this.heights.get(rowIndex);
62
+ if (prev !== undefined && Math.abs(rounded - prev) <= 1)
63
+ return false;
64
+ const previousHeight = this.resolveHeight(rowIndex);
65
+ this.heights.set(rowIndex, rounded);
66
+ this.currentVersion += 1;
67
+ this.applyDelta(rowIndex, rounded - previousHeight);
68
+ return true;
69
+ }
70
+ /** Removes a single measured height. Returns `true` when one existed. */
71
+ reset(rowIndex) {
72
+ if (!this.heights.has(rowIndex))
73
+ return false;
74
+ const previousHeight = this.resolveHeight(rowIndex);
75
+ this.heights.delete(rowIndex);
76
+ this.currentVersion += 1;
77
+ this.applyDelta(rowIndex, this.resolveHeight(rowIndex) - previousHeight);
78
+ return true;
79
+ }
80
+ /** Removes all measured heights. */
81
+ clear() {
82
+ if (this.heights.size === 0)
83
+ return;
84
+ this.heights.clear();
85
+ this.currentVersion += 1;
86
+ this.treeDirty = true;
87
+ }
88
+ /** Returns the measured height of a row if one has been recorded, or undefined. @api */
89
+ get(rowIndex) {
90
+ return this.heights.get(rowIndex);
91
+ }
92
+ /** Returns the resolved height of a row (measured, dynamic callback, or estimated). */
93
+ getRowHeight(rowIndex) {
94
+ return this.resolveHeight(rowIndex);
95
+ }
96
+ /** Materializes the cumulative offsets table (`offsets[i]` = top of row `i`). @api */
97
+ getOffsets(count) {
98
+ const size = Math.max(0, count);
99
+ this.ensureTree(size);
100
+ const offsets = new Array(size + 1);
101
+ let top = 0;
102
+ offsets[0] = 0;
103
+ for (let index = 0; index < size; index += 1) {
104
+ top += this.leaves[index] ?? 0;
105
+ offsets[index + 1] = top;
106
+ }
107
+ return offsets;
108
+ }
109
+ /** Total scrollable content height for `count` rows. @api */
110
+ getTotalHeight(count) {
111
+ if (count <= 0)
112
+ return 0;
113
+ this.ensureTree(count);
114
+ return RowHeightRegistry.prefixSum(this.tree, count);
115
+ }
116
+ /** Absolute top offset of a row (clamped to the dataset). @api */
117
+ getTop(rowIndex, count) {
118
+ if (count <= 0)
119
+ return 0;
120
+ const clamped = Math.max(0, Math.min(count - 1, Math.floor(rowIndex)));
121
+ this.ensureTree(count);
122
+ return RowHeightRegistry.prefixSum(this.tree, clamped);
123
+ }
124
+ /**
125
+ * First row whose bottom edge is strictly below `offset`
126
+ * (binary search over the Fenwick tree).
127
+ * @api
128
+ */
129
+ findStart(count, offset) {
130
+ if (count <= 0)
131
+ return 0;
132
+ if (offset <= 0)
133
+ return 0;
134
+ this.ensureTree(count);
135
+ return Math.min(count, RowHeightRegistry.findFloor(this.tree, count, offset).index);
136
+ }
137
+ /**
138
+ * First row whose top edge is at or past `offset`
139
+ * (binary search over the Fenwick tree). Used as the exclusive window end.
140
+ * @api
141
+ */
142
+ findEnd(count, offset) {
143
+ if (count <= 0)
144
+ return 0;
145
+ if (offset <= 0)
146
+ return 0;
147
+ this.ensureTree(count);
148
+ const floor = RowHeightRegistry.findFloor(this.tree, count, offset);
149
+ // The first row whose TOP edge is at or past the offset: the row that
150
+ // starts exactly at the offset is included, otherwise the next one.
151
+ const index = floor.sum >= offset ? floor.index : floor.index + 1;
152
+ return Math.min(count, index);
153
+ }
154
+ /** Marks the offset index dirty when the dataset identity changes. @api */
155
+ invalidate(count) {
156
+ if (count !== this.treeCount)
157
+ this.treeDirty = true;
158
+ }
159
+ /** Resolves the effective height of a row: measured, resolver, or estimate. */
160
+ resolveHeight(rowIndex) {
161
+ const measured = this.heights.get(rowIndex);
162
+ if (measured !== undefined)
163
+ return measured;
164
+ const resolved = this.resolver?.(rowIndex);
165
+ if (resolved !== undefined && Number.isFinite(resolved) && resolved > 0) {
166
+ return Math.max(1, Math.round(resolved));
167
+ }
168
+ return this.estimatedHeight;
169
+ }
170
+ /** Rebuilds the Fenwick tree when the dataset size or the estimate changed. */
171
+ ensureTree(count) {
172
+ const size = Math.max(0, count);
173
+ if (!this.treeDirty && this.treeCount === size)
174
+ return;
175
+ const tree = new Float64Array(size + 1);
176
+ const leaves = new Float64Array(size);
177
+ for (let index = 0; index < size; index += 1) {
178
+ const height = this.resolveHeight(index);
179
+ leaves[index] = height;
180
+ tree[index + 1] = height;
181
+ }
182
+ // O(n) Fenwick build: every node accumulates its children.
183
+ for (let index = 1; index <= size; index += 1) {
184
+ const parent = index + (index & -index);
185
+ if (parent <= size)
186
+ tree[parent] += tree[index];
187
+ }
188
+ this.tree = tree;
189
+ this.leaves = leaves;
190
+ this.treeCount = size;
191
+ this.treeDirty = false;
192
+ }
193
+ /** Patches a single row height into the live tree (O(log n)). */
194
+ applyDelta(rowIndex, delta) {
195
+ if (delta === 0)
196
+ return;
197
+ // A dirty tree is rebuilt from scratch on the next query — the delta
198
+ // is already part of the source data at that point.
199
+ if (this.treeDirty)
200
+ return;
201
+ if (rowIndex >= this.treeCount)
202
+ return;
203
+ this.leaves[rowIndex] = (this.leaves[rowIndex] ?? 0) + delta;
204
+ for (let position = rowIndex + 1; position < this.tree.length; position += position & -position) {
205
+ this.tree[position] += delta;
206
+ }
207
+ }
208
+ /** Sum of the first `count` row heights. */
209
+ static prefixSum(tree, count) {
210
+ let sum = 0;
211
+ for (let position = count; position > 0; position -= position & -position) {
212
+ sum += tree[position];
213
+ }
214
+ return sum;
215
+ }
216
+ /**
217
+ * Finds the largest row count whose cumulative height does not exceed
218
+ * `offset` — i.e. the number of rows fully above the offset.
219
+ */
220
+ static findFloor(tree, count, offset) {
221
+ let index = 0;
222
+ let remaining = offset;
223
+ let step = 1;
224
+ while (step * 2 <= count)
225
+ step *= 2;
226
+ for (; step >= 1; step = Math.floor(step / 2)) {
227
+ const next = index + step;
228
+ if (next <= count && tree[next] <= remaining) {
229
+ index = next;
230
+ remaining -= tree[next];
231
+ }
232
+ }
233
+ return { index, sum: offset - remaining };
234
+ }
235
+ }
1
236
  export class Virtualizer {
2
237
  constructor(options) {
3
238
  this.lastScrollTop = null;
4
239
  this.lastRowRange = null;
5
240
  this.lastRowCount = 0;
6
241
  this.lastRowViewportHeight = 0;
242
+ this.lastHeightsVersion = 0;
7
243
  this.widthsCache = new WeakMap();
8
244
  this.options = options;
245
+ this.heights = new RowHeightRegistry(options.estimatedRowHeight ?? options.rowHeight, options.getRowHeight);
246
+ }
247
+ /** Dynamic height registry backing variable-height mode. @api */
248
+ get rowHeights() {
249
+ return this.heights;
250
+ }
251
+ /** Estimated height used for rows without a measurement. @api */
252
+ get estimatedRowHeight() {
253
+ return this.options.estimatedRowHeight ?? this.options.rowHeight;
9
254
  }
10
- getRowRange(count, scrollTop, viewportHeight) {
255
+ /** Whether any variable-height input exists (resolver counts or measured heights exist). @api */
256
+ get hasVariableHeights() {
257
+ return this.heights.hasVariableHeights;
258
+ }
259
+ /**
260
+ * Visible row range calculation for fixed or variable heights.
261
+ * @api
262
+ */
263
+ getRowRange(count, scrollTop, viewportHeight, variableHeights = false) {
11
264
  if (count === 0) {
12
265
  this.lastScrollTop = null;
13
266
  this.lastRowRange = null;
14
267
  this.lastRowCount = 0;
15
268
  this.lastRowViewportHeight = 0;
269
+ this.lastHeightsVersion = this.heights.version;
16
270
  return { start: 0, end: 0 };
17
271
  }
272
+ if (variableHeights || this.hasVariableHeights) {
273
+ return this.getVariableRowRange(count, scrollTop, viewportHeight);
274
+ }
18
275
  const rowHeight = this.options.rowHeight;
19
276
  const visibleStart = Math.floor(Math.max(0, scrollTop) / rowHeight);
20
277
  const visibleEnd = Math.ceil((Math.max(0, scrollTop) + Math.max(0, viewportHeight)) / rowHeight);
@@ -63,6 +320,138 @@ export class Virtualizer {
63
320
  this.lastRowRange = corridor;
64
321
  return corridor;
65
322
  }
323
+ /**
324
+ * Computes the visible row window for variable-height mode using the
325
+ * incremental offset index (binary search over the Fenwick tree).
326
+ * @api
327
+ */
328
+ getVariableRowRange(count, scrollTop, viewportHeight) {
329
+ const visibleStart = this.heights.findStart(count, Math.max(0, scrollTop));
330
+ const visibleEnd = this.heights.findEnd(count, Math.max(0, scrollTop) + Math.max(0, viewportHeight));
331
+ const visibleRows = Math.max(1, visibleEnd - visibleStart);
332
+ const overscan = Math.max(this.options.rowOverscan, visibleRows);
333
+ const windowed = {
334
+ start: Math.max(0, visibleStart - overscan),
335
+ end: Math.min(count, visibleEnd + overscan),
336
+ };
337
+ if (scrollTop === this.lastScrollTop &&
338
+ count === this.lastRowCount &&
339
+ viewportHeight === this.lastRowViewportHeight &&
340
+ this.lastHeightsVersion === this.heights.version) {
341
+ return this.lastRowRange ?? windowed;
342
+ }
343
+ const previousTop = this.lastScrollTop;
344
+ this.lastScrollTop = scrollTop;
345
+ this.lastRowCount = count;
346
+ this.lastRowViewportHeight = viewportHeight;
347
+ this.lastHeightsVersion = this.heights.version;
348
+ if (previousTop === null) {
349
+ this.lastRowRange = windowed;
350
+ return windowed;
351
+ }
352
+ const prevVisibleStart = this.heights.findStart(count, Math.max(0, previousTop));
353
+ const prevVisibleEnd = this.heights.findEnd(count, Math.max(0, previousTop) + Math.max(0, viewportHeight));
354
+ const closeEnough = visibleStart <= prevVisibleEnd + overscan && prevVisibleStart <= visibleEnd + overscan;
355
+ if (closeEnough) {
356
+ this.lastRowRange = windowed;
357
+ return windowed;
358
+ }
359
+ const corridorCap = visibleRows * 2 + this.options.rowOverscan * 2;
360
+ const corridorStart = Math.max(0, Math.min(prevVisibleStart, visibleStart) - overscan);
361
+ const corridorEnd = Math.min(count, Math.max(prevVisibleEnd, visibleEnd) + overscan);
362
+ if (corridorEnd - corridorStart > corridorCap) {
363
+ this.lastRowRange = windowed;
364
+ return windowed;
365
+ }
366
+ const corridor = { start: corridorStart, end: corridorEnd };
367
+ this.lastRowRange = corridor;
368
+ return corridor;
369
+ }
370
+ /**
371
+ * Rows that intersect the viewport — the range WITHOUT the overscan
372
+ * buffer.
373
+ *
374
+ * The DOM pool reuses its nodes in a ring: a node that was not re-bound
375
+ * keeps the content of a completely unrelated row. The rows that
376
+ * intersect the viewport must therefore always be bound, even while a
377
+ * fast scroll defers the off-screen (overscan) rows.
378
+ * @api
379
+ */
380
+ getVisibleRowRange(count, scrollTop, viewportHeight) {
381
+ if (count <= 0)
382
+ return { start: 0, end: 0 };
383
+ if (this.hasVariableHeights) {
384
+ return {
385
+ start: this.heights.findStart(count, Math.max(0, scrollTop)),
386
+ end: this.heights.findEnd(count, Math.max(0, scrollTop) + Math.max(0, viewportHeight)),
387
+ };
388
+ }
389
+ const rowHeight = this.options.rowHeight;
390
+ const start = Math.floor(Math.max(0, scrollTop) / rowHeight);
391
+ const end = Math.ceil((Math.max(0, scrollTop) + Math.max(0, viewportHeight)) / rowHeight);
392
+ return { start: Math.min(count, start), end: Math.min(count, end) };
393
+ }
394
+ /**
395
+ * Absolute vertical offset (px) of the top of a row, accounting for variable heights.
396
+ * @api
397
+ */
398
+ getRowTop(rowIndex, count) {
399
+ if (count <= 0)
400
+ return 0;
401
+ const clamped = Math.max(0, Math.min(count - 1, Math.floor(rowIndex)));
402
+ return this.heights.getTop(clamped, count);
403
+ }
404
+ /** Current (measured, resolved, or estimated) height of a row. @api */
405
+ getRowHeight(rowIndex) {
406
+ return this.heights.getRowHeight(rowIndex);
407
+ }
408
+ /**
409
+ * Records a measured row height and returns the scrollTop correction needed
410
+ * to keep the visually anchored row stable (scroll anchoring).
411
+ * @api
412
+ */
413
+ setRowHeight(rowIndex, height, scrollTop, count) {
414
+ const rowTop = this.getRowTop(rowIndex, count);
415
+ const prevHeight = this.getRowHeight(rowIndex);
416
+ const changed = this.heights.set(rowIndex, height);
417
+ if (!changed)
418
+ return 0;
419
+ const newHeight = this.getRowHeight(rowIndex);
420
+ const delta = newHeight - prevHeight;
421
+ if (rowTop < scrollTop) {
422
+ return delta;
423
+ }
424
+ return 0;
425
+ }
426
+ /** Removes a measured row height (falls back to resolver or estimate). @api */
427
+ resetRowHeight(rowIndex, scrollTop, count) {
428
+ const hadHeight = this.heights.get(rowIndex) !== undefined;
429
+ if (!hadHeight)
430
+ return 0;
431
+ const rowTop = this.getRowTop(rowIndex, count);
432
+ const prevHeight = this.getRowHeight(rowIndex);
433
+ const removed = this.heights.reset(rowIndex);
434
+ if (!removed)
435
+ return 0;
436
+ const newHeight = this.getRowHeight(rowIndex);
437
+ const delta = newHeight - prevHeight;
438
+ if (rowTop < scrollTop) {
439
+ return delta;
440
+ }
441
+ return 0;
442
+ }
443
+ /** Removes all measured row heights (e.g. after `setColumns`). @api */
444
+ resetAllRowHeights() {
445
+ this.heights.clear();
446
+ }
447
+ /** Total scrollable content height for `count` rows, accounting for variable heights. @api */
448
+ getTotalHeight(count) {
449
+ if (count <= 0)
450
+ return 0;
451
+ if (!this.hasVariableHeights)
452
+ return count * this.options.rowHeight;
453
+ return this.heights.getTotalHeight(count);
454
+ }
66
455
  /**
67
456
  * Column geometry works on the FLAT working set of leaf columns only —
68
457
  * groups never reach the Virtualizer (see `Grid.getViewportData()`).
@@ -90,9 +479,6 @@ export class Virtualizer {
90
479
  return item;
91
480
  });
92
481
  }
93
- getTotalHeight(rowCount) {
94
- return rowCount * this.options.rowHeight;
95
- }
96
482
  getTotalWidth(columns, viewportWidth = 0) {
97
483
  return this.getColumnOffsets(columns, viewportWidth).reduce((total, item) => total + item.size, 0);
98
484
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnigrid/core",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "Framework-agnostic core engine for OmniGrid",
5
5
  "keywords": [
6
6
  "omnigrid",