diff --git a/.changeset/loud-insects-itch.md b/.changeset/loud-insects-itch.md new file mode 100644 index 00000000..ebc0ff93 --- /dev/null +++ b/.changeset/loud-insects-itch.md @@ -0,0 +1,5 @@ +--- +'@tanstack/virtual-core': patch +--- + +feat(virtual-core): add deferLaneAssignment option diff --git a/docs/api/virtual-item.md b/docs/api/virtual-item.md index 2393788b..d5bcf996 100644 --- a/docs/api/virtual-item.md +++ b/docs/api/virtual-item.md @@ -62,4 +62,5 @@ The size of the item. This is usually mapped to a css property like `width/heigh lane: number ``` -The lane index of the item. In regular lists it will always be set to `0` but becomes useful for masonry layouts (see variable examples for more details). +The lane index of the item. Items are assigned to the shortest lane. Lane assignments are cached immediately based on the size estimated by `estimateSize` by default; use `deferLaneAssignment: true` to base assignments on measured sizes instead. +In regular lists it will always be set to `0` but becomes useful for masonry layouts (see variable examples for more details). \ No newline at end of file diff --git a/docs/api/virtualizer.md b/docs/api/virtualizer.md index cee8b2d1..05946ddc 100644 --- a/docs/api/virtualizer.md +++ b/docs/api/virtualizer.md @@ -230,7 +230,18 @@ This option allows you to set the spacing between items in the virtualized list. lanes: number ``` -The number of lanes the list is divided into (aka columns for vertical lists and rows for horizontal lists). +The number of lanes the list is divided into (aka columns for vertical lists and rows for horizontal lists). Items are assigned to the lane with the shortest total size. By default, when `deferLaneAssignment` is `false`, lane assignments are cached immediately based on `estimateSize` to prevent items from jumping between lanes (see `deferLaneAssignment` below to defer this behavior). + +### `deferLaneAssignment` + +```tsx +deferLaneAssignment?: boolean +``` + +**Default**: `false` + +When `true`, defers lane caching until items are measured via `measureElement`. This allows lane assignments to be based on actual measured sizes rather than `estimateSize`. After initial measurement, lanes are cached and remain stable. + ### `isScrollingResetDelay` diff --git a/packages/virtual-core/src/index.ts b/packages/virtual-core/src/index.ts index bc966a6c..e09a1105 100644 --- a/packages/virtual-core/src/index.ts +++ b/packages/virtual-core/src/index.ts @@ -346,6 +346,7 @@ export interface VirtualizerOptions< enabled?: boolean isRtl?: boolean useAnimationFrameWithResizeObserver?: boolean + deferLaneAssignment?: boolean } type ScrollState = { @@ -463,6 +464,7 @@ export class Virtualizer< isRtl: false, useScrollendEvent: false, useAnimationFrameWithResizeObserver: false, + deferLaneAssignment: false, ...opts, } } @@ -714,8 +716,9 @@ export class Virtualizer< this.options.getItemKey, this.options.enabled, this.options.lanes, + this.options.deferLaneAssignment, ], - (count, paddingStart, scrollMargin, getItemKey, enabled, lanes) => { + (count, paddingStart, scrollMargin, getItemKey, enabled, lanes, deferLaneAssignment) => { const lanesChanged = this.prevLanes !== undefined && this.prevLanes !== lanes @@ -734,6 +737,7 @@ export class Virtualizer< getItemKey, enabled, lanes, + deferLaneAssignment, } }, { @@ -744,7 +748,7 @@ export class Virtualizer< private getMeasurements = memo( () => [this.getMeasurementOptions(), this.itemSizeCache], ( - { count, paddingStart, scrollMargin, getItemKey, enabled, lanes }, + { count, paddingStart, scrollMargin, getItemKey, enabled, lanes, deferLaneAssignment }, itemSizeCache, ) => { if (!enabled) { @@ -819,6 +823,10 @@ export class Virtualizer< let lane: number let start: number + // Check if this item has been measured (for deferLaneAssignment mode) + const isMeasured = itemSizeCache.has(key) + const shouldDeferLane = deferLaneAssignment && !isMeasured + if (cachedLane !== undefined && this.options.lanes > 1) { // Use cached lane - O(1) lookup for previous item in same lane lane = cachedLane @@ -843,8 +851,8 @@ export class Virtualizer< ? furthestMeasurement.lane : i % this.options.lanes - // Cache the lane assignment - if (this.options.lanes > 1) { + // Cache the lane assignment (skip if deferring and not yet measured) + if (this.options.lanes > 1 && !shouldDeferLane) { this.laneAssignments.set(i, lane) } } diff --git a/packages/virtual-core/tests/index.test.ts b/packages/virtual-core/tests/index.test.ts index 7f8fc862..3a42598e 100644 --- a/packages/virtual-core/tests/index.test.ts +++ b/packages/virtual-core/tests/index.test.ts @@ -233,6 +233,59 @@ test('should not throw when component unmounts during scrollToIndex rAF loop', ( }).not.toThrow() }) +test('should defer lane caching until measurement when deferLaneAssignment is true', () => { + const virtualizer = new Virtualizer({ + count: 4, + lanes: 2, + estimateSize: () => 100, + deferLaneAssignment: true, + getScrollElement: () => null, + scrollToFn: vi.fn(), + observeElementRect: vi.fn(), + observeElementOffset: vi.fn(), + }) + + virtualizer['getMeasurements']() + + // No laneAssignments cached yet + expect(virtualizer['laneAssignments'].size).toBe(0) + + // Simulate measurements + virtualizer.resizeItem(0, 200) + virtualizer.resizeItem(1, 50) + virtualizer.resizeItem(2, 80) + virtualizer.resizeItem(3, 120) + + const measurements = virtualizer['getMeasurements']() + + // After measurement: lane assignments based on actual sizes + cached + expect(virtualizer['laneAssignments'].size).toBe(4) + expect(measurements[2].lane).toBe(1) // lane 1 is shorter, so assigned there + + // Lane assignments remain stable after size changes + const lanesBeforeResize = measurements.map((m) => m.lane) + virtualizer.resizeItem(0, 50) + virtualizer.resizeItem(1, 200) + const lanesAfterResize = virtualizer['getMeasurements']().map((m) => m.lane) + expect(lanesBeforeResize).toEqual(lanesAfterResize) +}) + +test('should cache lanes immediately when deferLaneAssignment is false (default)', () => { + const virtualizer = new Virtualizer({ + count: 4, + lanes: 2, + estimateSize: () => 100, + getScrollElement: () => null, + scrollToFn: vi.fn(), + observeElementRect: vi.fn(), + observeElementOffset: vi.fn(), + }) + + virtualizer['getMeasurements']() + + expect(virtualizer['laneAssignments'].size).toBe(4) +}) + function createMockEnvironment() { const rafCallbacks: Array = [] let rafIdCounter = 0