Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): add the shared list-windowing module and Table's capability hook (#10656)

Humberto Virtudesd0ab3cb26475
diff --git a/.changeset/core-list-window-module.md b/.changeset/core-list-window-module.md
new file mode 100644
index 0000000000..fa5ddc2d8e
--- /dev/null
+++ b/.changeset/core-list-window-module.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: Core gains a private list-windowing module, the range, spacer and anchor arithmetic that windowed lists share, and Table's virtualization capability hook, which the package does not export yet. Apps import nothing new.
+
+@humbertovirtudes
diff --git a/packages/core/src/Table/plugins/virtualization/index.ts b/packages/core/src/Table/plugins/virtualization/index.ts
new file mode 100644
index 0000000000..05f93eba62
--- /dev/null
+++ b/packages/core/src/Table/plugins/virtualization/index.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input Public geometry-only Table virtualization hook
+ * @output Hook, config and opaque capability types; no engine or private controller
+ * @position Table virtualization plugin export seam
+ */
+export {useTableRowsVirtualization} from './useTableRowsVirtualization';
+export type {
+ UseTableRowsVirtualizationConfig,
+ TableVirtualizationCapability,
+} from './useTableRowsVirtualization';
diff --git a/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx
new file mode 100644
index 0000000000..821b94d48a
--- /dev/null
+++ b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableRowsVirtualization.test.tsx
+ * @input Public capability hook
+ * @output Capability identity and immutability tests
+ * @position Colocated Table virtualization capability coverage
+ */
+import {describe, it, expect} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {
+ getTableVirtualizationConfig,
+ useTableRowsVirtualization,
+} from './useTableRowsVirtualization';
+
+describe('Table virtualization capability', () => {
+ it('is immutable geometry intent with stable identity and no public payload or knobs', () => {
+ const {result, rerender} = renderHook(
+ ({rowHeight, viewportHeight}) =>
+ useTableRowsVirtualization({rowHeight, viewportHeight}),
+ {initialProps: {rowHeight: 48, viewportHeight: 240}},
+ );
+ const original = result.current;
+ expect(Object.keys(original)).toEqual([]);
+ expect(Object.isFrozen(original)).toBe(true);
+ expect(Object.isFrozen(getTableVirtualizationConfig(original))).toBe(true);
+ expect(getTableVirtualizationConfig(original)).toEqual({
+ rowHeight: 48,
+ viewportHeight: 240,
+ });
+ expect(
+ getTableVirtualizationConfig({rowHeight: 48, viewportHeight: 240}),
+ ).toBeUndefined();
+ rerender({rowHeight: 48, viewportHeight: 240});
+ expect(result.current).toBe(original);
+ rerender({rowHeight: 50, viewportHeight: 240});
+ expect(result.current).not.toBe(original);
+ });
+});
diff --git a/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.ts b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.ts
new file mode 100644
index 0000000000..994e123251
--- /dev/null
+++ b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.ts
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTableRowsVirtualization.ts
+ * @input Positive finite CSS-pixel row pitch and viewport height
+ * @output Stable opaque TableVirtualizationCapability and public config type
+ * @position Geometry-only opt-in; Table owns data, admission and rendering
+ */
+import {useMemo} from 'react';
+
+const capabilityBrand: unique symbol = Symbol('TableVirtualizationCapability');
+
+export interface UseTableRowsVirtualizationConfig {
+ /** Total body-row pitch, including padding and collapsed borders, in CSS pixels. */
+ rowHeight: number;
+ /** Bounded Table-owned viewport height in CSS pixels. */
+ viewportHeight: number;
+}
+
+/** Geometry intent, not a data slice, renderer, scroll handle or plugin. */
+export interface TableVirtualizationCapability {
+ readonly [capabilityBrand]: Readonly<UseTableRowsVirtualizationConfig>;
+}
+
+/** Private consumption seam. Parent validates geometry and all logical inputs. */
+export function getTableVirtualizationConfig(
+ capability: unknown,
+): Readonly<UseTableRowsVirtualizationConfig> | undefined {
+ if (
+ typeof capability !== 'object' ||
+ capability === null ||
+ !(capabilityBrand in capability)
+ ) {
+ return undefined;
+ }
+ return (capability as TableVirtualizationCapability)[capabilityBrand];
+}
+
+/**
+ * Opt into fixed-height flat-row Table rendering without transferring data ownership.
+ * Unsupported geometry, identity or content falls back to ordinary Table rendering.
+ *
+ * @example
+ * ```
+ * const virtualization = useTableRowsVirtualization({rowHeight: 48, viewportHeight: 480});
+ * <Table data={data} columns={columns} idKey="id" virtualization={virtualization} />;
+ * ```
+ */
+export function useTableRowsVirtualization({
+ rowHeight,
+ viewportHeight,
+}: UseTableRowsVirtualizationConfig): TableVirtualizationCapability {
+ return useMemo(
+ () =>
+ Object.freeze({
+ [capabilityBrand]: Object.freeze({rowHeight, viewportHeight}),
+ }),
+ [rowHeight, viewportHeight],
+ );
+}
diff --git a/packages/core/src/utils/listWindow.test.ts b/packages/core/src/utils/listWindow.test.ts
new file mode 100644
index 0000000000..f8a510f8f0
--- /dev/null
+++ b/packages/core/src/utils/listWindow.test.ts
@@ -0,0 +1,356 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file listWindow.test.ts
+ * @input The fixed-pitch range and anchor calculation
+ * @output Range, gap, guard and anchor assertions
+ * @position Colocated tests for the private list-windowing module
+ */
+import {describe, it} from 'vitest';
+import assert from 'node:assert/strict';
+import {calculateListWindow, reconcileListAnchor} from './listWindow';
+
+const defaults = {
+ rowCount: 100,
+ rowHeight: 20,
+ viewportHeight: 100,
+ scrollTop: 0,
+ startOffset: 0,
+ isMeasured: true,
+};
+const rows = (plan: NonNullable<ReturnType<typeof calculateListWindow>>) =>
+ plan.segments.flatMap(segment =>
+ segment.type === 'rows'
+ ? Array.from(
+ {length: segment.end - segment.start},
+ (_, i) => segment.start + i,
+ )
+ : [],
+ );
+
+describe('fixed-pitch list window', () => {
+ it('seeds SSR and first-client rows identically without rendering all data', () => {
+ const plan = calculateListWindow({
+ ...defaults,
+ isMeasured: false,
+ scrollTop: 800,
+ })!;
+ assert.deepEqual(rows(plan), [0, 1, 2, 3, 4, 5, 6, 7, 8]);
+ assert.deepEqual(plan.segments, [
+ {type: 'rows', start: 0, end: 9},
+ {type: 'gap', start: 9, end: 100, height: 1820},
+ ]);
+ });
+ it('intersects partial rows, then overscans four per side', () => {
+ const plan = calculateListWindow({...defaults, scrollTop: 210})!;
+ assert.deepEqual(
+ rows(plan),
+ Array.from({length: 14}, (_, i) => i + 6),
+ );
+ assert.equal(plan.firstVisibleIndex, 10);
+ assert.equal(plan.offset, 10);
+ });
+ it('reports the negative distance to the first row while the leading content shows', () => {
+ const plan = calculateListWindow({
+ ...defaults,
+ startOffset: 40,
+ scrollTop: 25,
+ })!;
+ assert.equal(plan.firstVisibleIndex, 0);
+ assert.equal(plan.offset, -15);
+ assert.equal(
+ calculateListWindow({...defaults, startOffset: 40})!.offset,
+ -40,
+ );
+ });
+ it('accounts for the start offset and a partly visible list', () => {
+ assert.deepEqual(
+ rows(calculateListWindow({...defaults, startOffset: 80})!),
+ [0, 1, 2, 3, 4],
+ );
+ assert.deepEqual(
+ rows(
+ calculateListWindow({...defaults, startOffset: 80, scrollTop: 100})!,
+ ),
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ );
+ });
+ it('retains exactly one high focused row in logical order with truthful gaps', () => {
+ const plan = calculateListWindow({
+ ...defaults,
+ scrollTop: 400,
+ focusIndex: 80,
+ })!;
+ assert.deepEqual(rows(plan), [
+ ...Array.from({length: 13}, (_, i) => 16 + i),
+ 80,
+ ]);
+ assert.equal(plan.segments.filter(s => s.type === 'gap').length, 3);
+ assert.equal(
+ plan.segments.reduce(
+ (height, s) =>
+ height + (s.type === 'gap' ? s.height : (s.end - s.start) * 20),
+ 0,
+ ),
+ 2000,
+ );
+ assert.equal(new Set(rows(plan)).size, rows(plan).length);
+ });
+ it('does not duplicate focus within or adjacent to the ordinary range', () => {
+ const plan = calculateListWindow({
+ ...defaults,
+ scrollTop: 400,
+ focusIndex: 28,
+ })!;
+ assert.equal(plan.segments.filter(s => s.type === 'rows').length, 1);
+ assert.deepEqual(
+ rows(plan),
+ Array.from({length: 13}, (_, i) => 16 + i),
+ );
+ assert.equal(
+ calculateListWindow({
+ ...defaults,
+ scrollTop: 400,
+ focusIndex: 29,
+ })!.segments.filter(s => s.type === 'rows').length,
+ 1,
+ );
+ });
+ it('clamps negative and stale end scrolls and supports fractional pitch', () => {
+ assert.deepEqual(
+ rows(calculateListWindow({...defaults, scrollTop: -100})!),
+ rows(calculateListWindow(defaults)!),
+ );
+ assert.deepEqual(
+ rows(calculateListWindow({...defaults, scrollTop: 1e9})!),
+ [91, 92, 93, 94, 95, 96, 97, 98, 99],
+ );
+ const plan = calculateListWindow({
+ ...defaults,
+ rowHeight: 12.5,
+ viewportHeight: 31.25,
+ scrollTop: 131.25,
+ })!;
+ assert.equal(plan.firstVisibleIndex, 10);
+ assert.equal(plan.offset, 6.25);
+ });
+ it('returns no rows or gaps for an empty list and bounds a short one', () => {
+ assert.deepEqual(
+ calculateListWindow({...defaults, rowCount: 0})!.segments,
+ [],
+ );
+ assert.deepEqual(
+ rows(calculateListWindow({...defaults, rowCount: 3})!),
+ [0, 1, 2],
+ );
+ });
+ it('rejects invalid arithmetic rather than compressing or fabricating an engine limit', () => {
+ for (const rowHeight of [0, -1, NaN, Infinity, Number.MIN_VALUE]) {
+ assert.equal(calculateListWindow({...defaults, rowHeight}), null);
+ }
+ for (const viewportHeight of [0, -1, NaN, Infinity]) {
+ assert.equal(calculateListWindow({...defaults, viewportHeight}), null);
+ }
+ for (const rowCount of [
+ -1,
+ 0.5,
+ NaN,
+ Infinity,
+ Number.MAX_SAFE_INTEGER + 1,
+ ]) {
+ assert.equal(calculateListWindow({...defaults, rowCount}), null);
+ }
+ assert.equal(calculateListWindow({...defaults, scrollTop: NaN}), null);
+ assert.equal(
+ calculateListWindow({...defaults, startOffset: Infinity}),
+ null,
+ );
+ assert.equal(
+ calculateListWindow({...defaults, rowCount: 100, rowHeight: 1e308}),
+ null,
+ );
+ assert.equal(
+ calculateListWindow({
+ ...defaults,
+ rowCount: 1,
+ rowHeight: 1e308,
+ startOffset: 1e308,
+ }),
+ null,
+ );
+ assert.ok(calculateListWindow({...defaults, rowCount: 1e6, rowHeight: 40}));
+ });
+ it('clamps scrolling to a larger scroll height and rejects an invalid one', () => {
+ const base = {...defaults, rowCount: 10, scrollTop: 250};
+ const rowsOnly = calculateListWindow(base);
+ const withTrailing = calculateListWindow({...base, scrollHeight: 300});
+ assert.ok(rowsOnly && withTrailing);
+ assert.ok(withTrailing.firstVisibleIndex > rowsOnly.firstVisibleIndex);
+ assert.equal(calculateListWindow({...base, scrollHeight: -1}), null);
+ assert.equal(
+ calculateListWindow({...base, scrollHeight: Number.NaN}),
+ null,
+ );
+ });
+ it('preserves ordered coverage, gap extent and mounted bounds across fractional/end cases', () => {
+ for (const rowCount of [0, 1, 9, 100, 100000]) {
+ for (const rowHeight of [12.5, 20, 48]) {
+ for (const viewportHeight of [1, 100, 240, 1000]) {
+ for (const scrollTop of [
+ 0,
+ 1,
+ 100,
+ rowCount * rowHeight,
+ rowCount * rowHeight * 10,
+ ]) {
+ for (const focusIndex of [
+ 0,
+ Math.floor(rowCount / 2),
+ rowCount - 1,
+ ]) {
+ const plan = calculateListWindow({
+ rowCount,
+ rowHeight,
+ viewportHeight,
+ scrollTop,
+ startOffset: 37,
+ isMeasured: true,
+ focusIndex,
+ })!;
+ const indices = rows(plan);
+ assert.equal(new Set(indices).size, indices.length);
+ assert.ok(
+ indices.every(
+ (value, index) => index === 0 || indices[index - 1] < value,
+ ),
+ );
+ assert.ok(
+ indices.length <=
+ Math.ceil(viewportHeight / rowHeight) + 1 + 8 + 1,
+ );
+ assert.ok(
+ plan.segments.filter(segment => segment.type === 'gap')
+ .length <= 3,
+ );
+ let end = 0;
+ let height = 0;
+ for (const segment of plan.segments) {
+ assert.equal(segment.start, end);
+ assert.ok(segment.end > segment.start);
+ end = segment.end;
+ height +=
+ segment.type === 'gap'
+ ? segment.height
+ : (segment.end - segment.start) * rowHeight;
+ }
+ assert.equal(end, rowCount);
+ assert.equal(height, rowCount * rowHeight);
+ }
+ }
+ }
+ }
+ }
+ });
+ it('bounds work at 100k without iterating offscreen rows', () => {
+ const plan = calculateListWindow({
+ ...defaults,
+ rowCount: 100000,
+ scrollTop: 1000010,
+ focusIndex: 99999,
+ })!;
+ assert.ok(rows(plan).length <= Math.ceil(100 / 20) + 1 + 8 + 1);
+ assert.ok(plan.segments.length <= 5);
+ });
+});
+
+describe('first-visible-key anchoring', () => {
+ const options = {
+ previousKeys: ['a', 'b', 'c', 'd'],
+ keys: ['x', 'a', 'b', 'c', 'd'],
+ firstVisibleIndex: 1,
+ offset: 5,
+ rowHeight: 20,
+ viewportHeight: 20,
+ startOffset: 10,
+ };
+ it('anchors the visible key and fraction, not focus or tail', () => {
+ assert.equal(reconcileListAnchor(options), 55);
+ assert.equal(
+ reconcileListAnchor({...options, keys: ['a', 'b', 'c', 'd', 'e']}),
+ 35,
+ );
+ });
+ it('chooses surviving successor, predecessor, then start when anchor disappears', () => {
+ assert.equal(reconcileListAnchor({...options, keys: ['d', 'c']}), 30);
+ assert.equal(reconcileListAnchor({...options, keys: ['a']}), 10);
+ // Headroom above the start fallback shows the predecessor is chosen.
+ assert.equal(
+ reconcileListAnchor({...options, keys: ['z', 'a'], viewportHeight: 1}),
+ 35,
+ );
+ assert.equal(reconcileListAnchor({...options, keys: ['x', 'y']}), 10);
+ });
+ it('preserves canonical number/string distinctions and clamps the new extent', () => {
+ assert.equal(
+ reconcileListAnchor({
+ ...options,
+ previousKeys: [0, '0', 1],
+ keys: ['0', 0, 1],
+ firstVisibleIndex: 1,
+ }),
+ 15,
+ );
+ assert.equal(
+ reconcileListAnchor({...options, keys: ['b'], viewportHeight: 100}),
+ 0,
+ );
+ });
+ it('keeps a scroll position inside the leading content after rows change', () => {
+ const top = {
+ ...options,
+ previousKeys: ['a', 'b'],
+ keys: ['a', 'b', 'c'],
+ firstVisibleIndex: 0,
+ startOffset: 40,
+ };
+ assert.equal(reconcileListAnchor({...top, offset: -40}), 0);
+ assert.equal(reconcileListAnchor({...top, offset: -15}), 25);
+ assert.equal(
+ reconcileListAnchor({...top, keys: ['x', 'a', 'b'], offset: -15}),
+ 45,
+ );
+ });
+ it('keeps a leading-content position when no key survives and sends a row position to the first row', () => {
+ const replaced = {
+ ...options,
+ previousKeys: ['a', 'b'],
+ keys: ['x', 'y', 'z'],
+ firstVisibleIndex: 0,
+ startOffset: 40,
+ };
+ assert.equal(reconcileListAnchor({...replaced, offset: -40}), 0);
+ assert.equal(reconcileListAnchor({...replaced, offset: -15}), 25);
+ assert.equal(reconcileListAnchor({...replaced, offset: 10}), 40);
+ });
+ it('clamps to trailing content and reads a supplied key index', () => {
+ const short = {
+ ...options,
+ previousKeys: ['a', 'b'],
+ keys: ['a', 'b'],
+ firstVisibleIndex: 1,
+ };
+ assert.equal(reconcileListAnchor(short), 30);
+ assert.equal(
+ reconcileListAnchor({...short, trailingContentHeight: 20}),
+ 35,
+ );
+ assert.equal(
+ reconcileListAnchor({
+ ...short,
+ trailingContentHeight: 100,
+ keyIndices: new Map([['b', 3]]),
+ }),
+ 75,
+ );
+ });
+});
diff --git a/packages/core/src/utils/listWindow.ts b/packages/core/src/utils/listWindow.ts
new file mode 100644
index 0000000000..b1178b3c40
--- /dev/null
+++ b/packages/core/src/utils/listWindow.ts
@@ -0,0 +1,246 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file listWindow.ts
+ * @input Fixed CSS-pixel row pitch, scroll geometry and canonical row keys
+ * @output Half-open row and gap segments, and first-visible-key reconciliation
+ * @position The one private long-list windowing module in Core
+ */
+export type ListWindowSegment =
+ | {type: 'rows'; start: number; end: number}
+ | {type: 'gap'; start: number; end: number; height: number};
+
+export interface ListWindowOptions {
+ rowCount: number;
+ rowHeight: number;
+ viewportHeight: number;
+ scrollTop: number;
+ /** Measured full content extent; does not change the logical row total. */
+ scrollHeight?: number;
+ /** Distance from the scroll origin to the first row, such as a header. */
+ startOffset: number;
+ isMeasured: boolean;
+ focusIndex?: number;
+}
+
+export interface ListWindowPlan {
+ segments: ListWindowSegment[];
+ start: number;
+ end: number;
+ firstVisibleIndex: number;
+ offset: number;
+ totalHeight: number;
+}
+
+export function isPositiveFinite(value: number): boolean {
+ return Number.isFinite(value) && value > 0;
+}
+
+/** Returns null when the inputs cannot form a finite window. */
+export function calculateListWindow(
+ options: ListWindowOptions,
+): ListWindowPlan | null {
+ const {
+ rowCount,
+ rowHeight,
+ viewportHeight,
+ scrollTop,
+ startOffset,
+ isMeasured,
+ focusIndex,
+ } = options;
+ const totalHeight = rowCount * rowHeight;
+ if (
+ !Number.isSafeInteger(rowCount) ||
+ rowCount < 0 ||
+ !isPositiveFinite(rowHeight) ||
+ !isPositiveFinite(viewportHeight) ||
+ !Number.isFinite(totalHeight) ||
+ !Number.isFinite(startOffset + totalHeight) ||
+ !Number.isFinite(viewportHeight / rowHeight) ||
+ !Number.isFinite(scrollTop) ||
+ (options.scrollHeight !== undefined &&
+ (!Number.isFinite(options.scrollHeight) || options.scrollHeight < 0)) ||
+ !Number.isFinite(startOffset) ||
+ startOffset < 0
+ ) {
+ return null;
+ }
+ if (rowCount === 0) {
+ return {
+ segments: [],
+ start: 0,
+ end: 0,
+ firstVisibleIndex: 0,
+ offset: 0,
+ totalHeight: 0,
+ };
+ }
+
+ // Clamp against the full body extent, not mounted DOM or window-local indices.
+ const contentHeight = Math.max(
+ startOffset + totalHeight,
+ options.scrollHeight ?? 0,
+ );
+ const maximumScroll = Math.max(0, contentHeight - viewportHeight);
+ const clampedScroll = Math.min(maximumScroll, Math.max(0, scrollTop));
+ const listTop = clampedScroll - startOffset;
+ const bodyTop = Math.min(totalHeight, Math.max(0, listTop));
+ const bodyBottom = Math.min(
+ totalHeight,
+ Math.max(0, clampedScroll + viewportHeight - startOffset),
+ );
+ const firstVisibleIndex = isMeasured
+ ? Math.min(rowCount - 1, Math.floor(bodyTop / rowHeight))
+ : 0;
+ // Above the first row, the offset is the negative distance to it, so an
+ // anchor round-trips a scroll position inside the leading content.
+ const offset = !isMeasured
+ ? 0
+ : listTop < 0
+ ? listTop
+ : bodyTop - firstVisibleIndex * rowHeight;
+ const start = isMeasured ? Math.max(0, firstVisibleIndex - 4) : 0;
+ const end = isMeasured
+ ? Math.min(
+ rowCount,
+ Math.max(firstVisibleIndex, Math.ceil(bodyBottom / rowHeight)) + 4,
+ )
+ : Math.min(rowCount, Math.ceil(viewportHeight / rowHeight) + 4);
+ return {
+ segments: createListWindowSegments(
+ rowCount,
+ rowHeight,
+ start,
+ end,
+ focusIndex,
+ ),
+ start,
+ end,
+ firstVisibleIndex,
+ offset,
+ totalHeight,
+ };
+}
+
+/** Mounted rows and gaps for a range, plus one retained row outside it. */
+export function createListWindowSegments(
+ rowCount: number,
+ rowHeight: number,
+ start: number,
+ end: number,
+ focusIndex?: number,
+): ListWindowSegment[] {
+ if (rowCount === 0) {
+ return [];
+ }
+ const intervals: {start: number; end: number}[] = [{start, end}];
+ if (
+ focusIndex !== undefined &&
+ Number.isInteger(focusIndex) &&
+ focusIndex >= 0 &&
+ focusIndex < rowCount &&
+ (focusIndex < start || focusIndex >= end)
+ ) {
+ intervals.push({start: focusIndex, end: focusIndex + 1});
+ intervals.sort((a, b) => a.start - b.start);
+ }
+ const merged: {start: number; end: number}[] = [];
+ for (const interval of intervals) {
+ const previous = merged[merged.length - 1];
+ if (previous && interval.start <= previous.end) {
+ previous.end = Math.max(previous.end, interval.end);
+ } else if (interval.end > interval.start) {
+ merged.push({...interval});
+ }
+ }
+ const segments: ListWindowSegment[] = [];
+ let cursor = 0;
+ for (const interval of merged) {
+ if (interval.start > cursor) {
+ segments.push({
+ type: 'gap',
+ start: cursor,
+ end: interval.start,
+ height: (interval.start - cursor) * rowHeight,
+ });
+ }
+ segments.push({type: 'rows', ...interval});
+ cursor = interval.end;
+ }
+ if (cursor < rowCount) {
+ segments.push({
+ type: 'gap',
+ start: cursor,
+ end: rowCount,
+ height: (rowCount - cursor) * rowHeight,
+ });
+ }
+ return segments;
+}
+
+export interface ListAnchorOptions {
+ previousKeys: ReadonlyArray<string | number>;
+ keys: ReadonlyArray<string | number>;
+ firstVisibleIndex: number;
+ offset: number;
+ rowHeight: number;
+ viewportHeight: number;
+ startOffset: number;
+ /** Existing non-row content extent retained across logical data changes. */
+ trailingContentHeight?: number;
+ /** Key-to-index map. Build it when the keys change, never on scroll. */
+ keyIndices?: ReadonlyMap<string | number, number>;
+}
+
+export function reconcileListAnchor(options: ListAnchorOptions): number {
+ const {
+ previousKeys,
+ keys,
+ firstVisibleIndex,
+ offset,
+ rowHeight,
+ viewportHeight,
+ startOffset,
+ } = options;
+ const indices =
+ options.keyIndices ?? new Map(keys.map((key, index) => [key, index]));
+ let index = indices.get(previousKeys[firstVisibleIndex]);
+ if (index === undefined) {
+ for (let i = firstVisibleIndex + 1; i < previousKeys.length; i++) {
+ index = indices.get(previousKeys[i]);
+ if (index !== undefined) {
+ break;
+ }
+ }
+ }
+ if (index === undefined) {
+ for (
+ let i = Math.min(firstVisibleIndex - 1, previousKeys.length - 1);
+ i >= 0;
+ i--
+ ) {
+ index = indices.get(previousKeys[i]);
+ if (index !== undefined) {
+ break;
+ }
+ }
+ }
+ const maximumScroll = Math.max(
+ 0,
+ startOffset +
+ keys.length * rowHeight +
+ (options.trailingContentHeight ?? 0) -
+ viewportHeight,
+ );
+ // With no surviving key, a position inside the leading content stays where
+ // it is, and a position inside the rows moves to the first row.
+ const fraction =
+ index === undefined
+ ? Math.min(0, Math.max(-startOffset, offset))
+ : Math.min(Math.max(-startOffset, offset), rowHeight);
+ return Math.min(
+ maximumScroll,
+ startOffset + (index ?? 0) * rowHeight + fraction,
+ );
+}