@tanstack/virtual-core 3.13.23 → 3.15.0

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/src/index.ts CHANGED
@@ -1,6 +1,29 @@
1
+ import { createLazyMeasurementsView } from './lazy-measurements'
1
2
  import { approxEqual, debounce, memo, notUndefined } from './utils'
2
3
 
3
- export * from './utils'
4
+ // Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
5
+ // during a momentum-scroll cancel the momentum on iOS WebKit, so we defer
6
+ // scroll-position adjustments triggered by mid-scroll resizes until the
7
+ // scroll settles. SSR-safe (returns false when navigator is unavailable).
8
+ let _isIOSResult: boolean | undefined
9
+ const isIOSWebKit = (): boolean => {
10
+ if (_isIOSResult !== undefined) return _isIOSResult
11
+ if (typeof navigator === 'undefined') return (_isIOSResult = false)
12
+ if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)
13
+ // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.
14
+ const mtp = (navigator as Navigator & { maxTouchPoints?: number })
15
+ .maxTouchPoints
16
+ return (_isIOSResult =
17
+ navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)
18
+ }
19
+
20
+ // Test hook: reset the iOS detection cache. Not exported.
21
+ export const _resetIOSDetectionForTests = () => {
22
+ _isIOSResult = undefined
23
+ }
24
+
25
+ export { approxEqual, debounce, memo, notUndefined } from './utils'
26
+ export type { NoInfer, PartialKeys } from './utils'
4
27
 
5
28
  //
6
29
 
@@ -54,13 +77,12 @@ export const defaultKeyExtractor = (index: number) => index
54
77
  export const defaultRangeExtractor = (range: Range) => {
55
78
  const start = Math.max(range.startIndex - range.overscan, 0)
56
79
  const end = Math.min(range.endIndex + range.overscan, range.count - 1)
80
+ const len = end - start + 1
57
81
 
58
- const arr = []
59
-
60
- for (let i = start; i <= end; i++) {
61
- arr.push(i)
82
+ const arr = new Array<number>(len)
83
+ for (let i = 0; i < len; i++) {
84
+ arr[i] = start + i
62
85
  }
63
-
64
86
  return arr
65
87
  }
66
88
 
@@ -143,9 +165,13 @@ const supportsScrollend =
143
165
 
144
166
  type ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void
145
167
 
146
- export const observeElementOffset = <T extends Element>(
168
+ // Shared core: both element and window variants attach scroll/scrollend
169
+ // listeners with the same lifecycle; they only differ in how to read the
170
+ // current offset from the scroll target.
171
+ const observeOffset = <T extends Element | Window>(
147
172
  instance: Virtualizer<T, any>,
148
173
  cb: ObserveOffsetCallBack,
174
+ readOffset: (target: T) => number,
149
175
  ) => {
150
176
  const element = instance.scrollElement
151
177
  if (!element) {
@@ -156,32 +182,27 @@ export const observeElementOffset = <T extends Element>(
156
182
  return
157
183
  }
158
184
 
159
- let offset = 0
160
- const fallback =
185
+ const registerScrollendEvent =
161
186
  instance.options.useScrollendEvent && supportsScrollend
162
- ? () => undefined
163
- : debounce(
164
- targetWindow,
165
- () => {
166
- cb(offset, false)
167
- },
168
- instance.options.isScrollingResetDelay,
169
- )
187
+
188
+ let offset = 0
189
+ const fallback = registerScrollendEvent
190
+ ? null
191
+ : debounce(
192
+ targetWindow,
193
+ () => cb(offset, false),
194
+ instance.options.isScrollingResetDelay,
195
+ )
170
196
 
171
197
  const createHandler = (isScrolling: boolean) => () => {
172
- const { horizontal, isRtl } = instance.options
173
- offset = horizontal
174
- ? element['scrollLeft'] * ((isRtl && -1) || 1)
175
- : element['scrollTop']
176
- fallback()
198
+ offset = readOffset(element)
199
+ fallback?.()
177
200
  cb(offset, isScrolling)
178
201
  }
179
202
  const handler = createHandler(true)
180
203
  const endHandler = createHandler(false)
181
204
 
182
205
  element.addEventListener('scroll', handler, addEventListenerOptions)
183
- const registerScrollendEvent =
184
- instance.options.useScrollendEvent && supportsScrollend
185
206
  if (registerScrollendEvent) {
186
207
  element.addEventListener('scrollend', endHandler, addEventListenerOptions)
187
208
  }
@@ -193,52 +214,22 @@ export const observeElementOffset = <T extends Element>(
193
214
  }
194
215
  }
195
216
 
217
+ export const observeElementOffset = <T extends Element>(
218
+ instance: Virtualizer<T, any>,
219
+ cb: ObserveOffsetCallBack,
220
+ ) =>
221
+ observeOffset(instance, cb, (el) => {
222
+ const { horizontal, isRtl } = instance.options
223
+ return horizontal ? el.scrollLeft * ((isRtl && -1) || 1) : el.scrollTop
224
+ })
225
+
196
226
  export const observeWindowOffset = (
197
227
  instance: Virtualizer<Window, any>,
198
228
  cb: ObserveOffsetCallBack,
199
- ) => {
200
- const element = instance.scrollElement
201
- if (!element) {
202
- return
203
- }
204
- const targetWindow = instance.targetWindow
205
- if (!targetWindow) {
206
- return
207
- }
208
-
209
- let offset = 0
210
- const fallback =
211
- instance.options.useScrollendEvent && supportsScrollend
212
- ? () => undefined
213
- : debounce(
214
- targetWindow,
215
- () => {
216
- cb(offset, false)
217
- },
218
- instance.options.isScrollingResetDelay,
219
- )
220
-
221
- const createHandler = (isScrolling: boolean) => () => {
222
- offset = element[instance.options.horizontal ? 'scrollX' : 'scrollY']
223
- fallback()
224
- cb(offset, isScrolling)
225
- }
226
- const handler = createHandler(true)
227
- const endHandler = createHandler(false)
228
-
229
- element.addEventListener('scroll', handler, addEventListenerOptions)
230
- const registerScrollendEvent =
231
- instance.options.useScrollendEvent && supportsScrollend
232
- if (registerScrollendEvent) {
233
- element.addEventListener('scrollend', endHandler, addEventListenerOptions)
234
- }
235
- return () => {
236
- element.removeEventListener('scroll', handler)
237
- if (registerScrollendEvent) {
238
- element.removeEventListener('scrollend', endHandler)
239
- }
240
- }
241
- }
229
+ ) =>
230
+ observeOffset(instance, cb, (win) =>
231
+ instance.options.horizontal ? win.scrollX : win.scrollY,
232
+ )
242
233
 
243
234
  export const measureElement = <TItemElement extends Element>(
244
235
  element: TItemElement,
@@ -260,37 +251,33 @@ export const measureElement = <TItemElement extends Element>(
260
251
  ]
261
252
  }
262
253
 
263
- export const windowScroll = <T extends Window>(
254
+ const scrollWithAdjustments = (
264
255
  offset: number,
265
256
  {
266
257
  adjustments = 0,
267
258
  behavior,
268
259
  }: { adjustments?: number; behavior?: ScrollBehavior },
269
- instance: Virtualizer<T, any>,
260
+ instance: Virtualizer<any, any>,
270
261
  ) => {
271
- const toOffset = offset + adjustments
272
-
273
262
  instance.scrollElement?.scrollTo?.({
274
- [instance.options.horizontal ? 'left' : 'top']: toOffset,
263
+ [instance.options.horizontal ? 'left' : 'top']: offset + adjustments,
275
264
  behavior,
276
265
  })
277
266
  }
278
267
 
279
- export const elementScroll = <T extends Element>(
268
+ export const windowScroll: <T extends Window>(
280
269
  offset: number,
281
- {
282
- adjustments = 0,
283
- behavior,
284
- }: { adjustments?: number; behavior?: ScrollBehavior },
270
+ options: { adjustments?: number; behavior?: ScrollBehavior },
285
271
  instance: Virtualizer<T, any>,
286
- ) => {
287
- const toOffset = offset + adjustments
272
+ ) => void = scrollWithAdjustments
288
273
 
289
- instance.scrollElement?.scrollTo?.({
290
- [instance.options.horizontal ? 'left' : 'top']: toOffset,
291
- behavior,
292
- })
293
- }
274
+ export const elementScroll: <T extends Element>(
275
+ offset: number,
276
+ options: { adjustments?: number; behavior?: ScrollBehavior },
277
+ instance: Virtualizer<T, any>,
278
+ ) => void = scrollWithAdjustments
279
+
280
+ type LaneAssignmentMode = 'estimate' | 'measured'
294
281
 
295
282
  export interface VirtualizerOptions<
296
283
  TScrollElement extends Element | Window,
@@ -346,6 +333,7 @@ export interface VirtualizerOptions<
346
333
  enabled?: boolean
347
334
  isRtl?: boolean
348
335
  useAnimationFrameWithResizeObserver?: boolean
336
+ laneAssignmentMode?: LaneAssignmentMode
349
337
  }
350
338
 
351
339
  type ScrollState = {
@@ -375,9 +363,14 @@ export class Virtualizer<
375
363
  isScrolling = false
376
364
  private scrollState: ScrollState | null = null
377
365
  measurementsCache: Array<VirtualItem> = []
366
+ // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].
367
+ // null until the first single-lane build; reused (and grown) across rebuilds.
368
+ private _flatMeasurements: Float64Array | null = null
378
369
  private itemSizeCache = new Map<Key, number>()
370
+ private itemSizeCacheVersion = 0
379
371
  private laneAssignments = new Map<number, number>() // index → lane cache
380
- private pendingMeasuredCacheIndexes: Array<number> = []
372
+ // Earliest index dirtied since last getMeasurements() rebuild, or null.
373
+ private pendingMin: number | null = null
381
374
  private prevLanes: number | undefined = undefined
382
375
  private lanesChangedFlag = false
383
376
  private lanesSettling = false
@@ -385,6 +378,28 @@ export class Virtualizer<
385
378
  scrollOffset: number | null = null
386
379
  scrollDirection: ScrollDirection | null = null
387
380
  private scrollAdjustments = 0
381
+ // Sum of size-change deltas above-viewport that were skipped during
382
+ // iOS momentum scroll (writing scrollTop mid-momentum cancels it).
383
+ // Flushed in a single scrollTo when iOS is fully settled.
384
+ private _iosDeferredAdjustment = 0
385
+ // Touch state. iOS WebKit cancels momentum when scrollTop is written, so
386
+ // we defer adjustments not only during `isScrolling` but also through the
387
+ // touchstart→touchend window (active drag) and a short tail after
388
+ // touchend (early-momentum window — iOS only fires touch events once at
389
+ // the start of momentum, so we use a timer rather than another event).
390
+ private _iosTouching = false
391
+ private _iosJustTouchEnded = false
392
+ private _iosTouchEndTimerId: number | null = null
393
+ // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs)
394
+ // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5
395
+ // but the browser reports back 12346, the next reconcileScroll sees a
396
+ // "target changed" and re-fires scrollTo — a feedback loop that the
397
+ // approxEqual(<1.01) tolerance otherwise absorbs as a workaround.
398
+ // By remembering the intended value of our most-recent self-driven
399
+ // scrollTo, we can match the browser's rounded read back to the intended
400
+ // value when the diff is < 1.5 px, distinguishing it from a real user
401
+ // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.
402
+ private _intendedScrollOffset: number | null = null
388
403
  shouldAdjustScrollPositionOnItemSizeChange:
389
404
  | undefined
390
405
  | ((
@@ -414,6 +429,20 @@ export class Virtualizer<
414
429
 
415
430
  if (!node.isConnected) {
416
431
  this.observer.unobserve(node)
432
+ // Find the cache entry pointing to this exact node and remove
433
+ // it. We can't call getItemKey(index) here because items may
434
+ // have been removed since this node was rendered — the index
435
+ // could be stale and out-of-bounds in the user's data array
436
+ // (regression test in e2e/.../stale-index.spec.ts, fix #1148).
437
+ // The === comparison naturally handles the React-replaced-
438
+ // a-node-for-the-same-key case: that entry now points to a
439
+ // different node, so this loop won't match.
440
+ for (const [cacheKey, cachedNode] of this.elementsCache) {
441
+ if (cachedNode === node) {
442
+ this.elementsCache.delete(cacheKey)
443
+ break
444
+ }
445
+ }
417
446
  return
418
447
  }
419
448
 
@@ -448,11 +477,9 @@ export class Virtualizer<
448
477
  }
449
478
 
450
479
  setOptions = (opts: VirtualizerOptions<TScrollElement, TItemElement>) => {
451
- Object.entries(opts).forEach(([key, value]) => {
452
- if (typeof value === 'undefined') delete (opts as any)[key]
453
- })
454
-
455
- this.options = {
480
+ // Skip `{...defaults, ...opts}` because explicit `undefined` values in
481
+ // opts would override defaults with `undefined`.
482
+ const merged = {
456
483
  debug: false,
457
484
  initialOffset: 0,
458
485
  overscan: 1,
@@ -476,8 +503,15 @@ export class Virtualizer<
476
503
  isRtl: false,
477
504
  useScrollendEvent: false,
478
505
  useAnimationFrameWithResizeObserver: false,
479
- ...opts,
506
+ laneAssignmentMode: 'estimate',
507
+ } as unknown as Required<VirtualizerOptions<TScrollElement, TItemElement>>
508
+
509
+ for (const key in opts) {
510
+ const v = (opts as any)[key]
511
+ if (v !== undefined) (merged as any)[key] = v
480
512
  }
513
+
514
+ this.options = merged
481
515
  }
482
516
 
483
517
  private notify = (sync: boolean) => {
@@ -561,6 +595,21 @@ export class Virtualizer<
561
595
 
562
596
  this.unsubs.push(
563
597
  this.options.observeElementOffset(this, (offset, isScrolling) => {
598
+ // If this scroll event looks like the browser's read-back of a
599
+ // value we just wrote, prefer our intended (sub-pixel-accurate)
600
+ // value over the browser's rounded one. The 1.5 px tolerance is
601
+ // tight enough to avoid mistaking a real user scroll for a
602
+ // self-write — by the time the user has moved 1.5 px, the
603
+ // intended value will already have been consumed by a prior
604
+ // scroll event and cleared.
605
+ if (
606
+ this._intendedScrollOffset !== null &&
607
+ Math.abs(offset - this._intendedScrollOffset) < 1.5
608
+ ) {
609
+ offset = this._intendedScrollOffset
610
+ }
611
+ this._intendedScrollOffset = null
612
+
564
613
  this.scrollAdjustments = 0
565
614
  this.scrollDirection = isScrolling
566
615
  ? this.getScrollOffset() < offset
@@ -570,6 +619,11 @@ export class Virtualizer<
570
619
  this.scrollOffset = offset
571
620
  this.isScrolling = isScrolling
572
621
 
622
+ // Flush deferred iOS adjustments if we're now fully settled.
623
+ // "Fully settled" means: not actively scrolling, no finger on
624
+ // screen, and the post-touchend grace window has expired.
625
+ this._flushIosDeferredIfReady()
626
+
573
627
  if (this.scrollState) {
574
628
  this.scheduleScrollReconcile()
575
629
  }
@@ -577,6 +631,56 @@ export class Virtualizer<
577
631
  }),
578
632
  )
579
633
 
634
+ // Touch event listeners (iOS-aware deferral). We attach unconditionally
635
+ // — the listeners are passive and cheap; on non-touch devices they
636
+ // simply never fire. The gating by isIOSWebKit() lives in resizeItem
637
+ // and _flushIosDeferredIfReady so we only burn the path on iOS.
638
+ if ('addEventListener' in this.scrollElement) {
639
+ const scrollEl = this.scrollElement as unknown as EventTarget
640
+ const onTouchStart = () => {
641
+ this._iosTouching = true
642
+ this._iosJustTouchEnded = false
643
+ if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
644
+ this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
645
+ this._iosTouchEndTimerId = null
646
+ }
647
+ }
648
+ const onTouchEnd = () => {
649
+ this._iosTouching = false
650
+ if (!isIOSWebKit() || this.targetWindow == null) {
651
+ // Non-iOS: nothing more to track. Just clear the touching flag.
652
+ return
653
+ }
654
+ this._iosJustTouchEnded = true
655
+ // After ~150 ms with no scroll/touch events, momentum is done.
656
+ this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => {
657
+ this._iosJustTouchEnded = false
658
+ this._iosTouchEndTimerId = null
659
+ // After the grace window, attempt to flush. The scroll event
660
+ // for momentum decay may have already fired before our timer.
661
+ this._flushIosDeferredIfReady()
662
+ }, 150)
663
+ }
664
+ scrollEl.addEventListener(
665
+ 'touchstart',
666
+ onTouchStart,
667
+ addEventListenerOptions,
668
+ )
669
+ scrollEl.addEventListener(
670
+ 'touchend',
671
+ onTouchEnd,
672
+ addEventListenerOptions,
673
+ )
674
+ this.unsubs.push(() => {
675
+ scrollEl.removeEventListener('touchstart', onTouchStart)
676
+ scrollEl.removeEventListener('touchend', onTouchEnd)
677
+ if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
678
+ this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
679
+ this._iosTouchEndTimerId = null
680
+ }
681
+ })
682
+ }
683
+
580
684
  this._scrollToOffset(this.getScrollOffset(), {
581
685
  adjustments: undefined,
582
686
  behavior: undefined,
@@ -584,6 +688,34 @@ export class Virtualizer<
584
688
  }
585
689
  }
586
690
 
691
+ // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
692
+ // truly settled — not actively scrolling, not under an active touch, and
693
+ // past the post-touchend grace window. Called from the scroll callback
694
+ // and the touchend grace-timer.
695
+ private _flushIosDeferredIfReady = () => {
696
+ if (this._iosDeferredAdjustment === 0) return
697
+ if (this.isScrolling) return
698
+ if (this._iosTouching) return
699
+ if (this._iosJustTouchEnded) return
700
+ // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go
701
+ // negative or beyond scrollHeight - clientHeight. Writing scrollTop
702
+ // while in that zone snaps the page back to the clamped value at the
703
+ // end of the bounce, often discarding the user's intent. Skip the
704
+ // flush; the next in-bounds scroll event will retry.
705
+ const cur = this.getScrollOffset()
706
+ const max = this.getMaxScrollOffset()
707
+ if (cur < 0 || cur > max) return
708
+ const delta = this._iosDeferredAdjustment
709
+ this._iosDeferredAdjustment = 0
710
+ // Roll the deferred delta into the running accumulator so any resize
711
+ // landing between now and the resulting scroll event computes from the
712
+ // post-flush offset rather than the stale one.
713
+ this._scrollToOffset(cur, {
714
+ adjustments: (this.scrollAdjustments += delta),
715
+ behavior: undefined,
716
+ })
717
+ }
718
+
587
719
  private rafId: number | null = null
588
720
  private scheduleScrollReconcile() {
589
721
  if (!this.targetWindow) {
@@ -627,6 +759,18 @@ export class Virtualizer<
627
759
  if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
628
760
  this.scrollState.stableFrames++
629
761
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
762
+ // Final-pass exact landing. The reconcile-stable check uses a 1.01px
763
+ // tolerance (approxEqual) so we don't fight subpixel browser rounding
764
+ // during the converging phase. Once we're definitively settled,
765
+ // commit the exact target so consumers calling scrollToIndex(N)
766
+ // end up at the EXACT computed position of item N — matching
767
+ // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
768
+ if (this.getScrollOffset() !== targetOffset) {
769
+ this._scrollToOffset(targetOffset, {
770
+ adjustments: undefined,
771
+ behavior: 'auto',
772
+ })
773
+ }
630
774
  this.scrollState = null
631
775
  return
632
776
  }
@@ -634,14 +778,26 @@ export class Virtualizer<
634
778
  this.scrollState.stableFrames = 0
635
779
 
636
780
  if (targetChanged) {
781
+ // When the target moves during smooth scroll (because items came into
782
+ // view and got measured, shifting positions), the original logic was
783
+ // to immediately snap to 'auto' — visibly jarring on long
784
+ // scroll-to-index calls. Now: keep smooth while we're still far
785
+ // (more than a viewport) from the new target. Only fall back to
786
+ // 'auto' for the final approach, so the user sees one continuous
787
+ // motion that smoothly adjusts its endpoint as measurements arrive.
788
+ const viewport = this.getSize() || 600
789
+ const distance = Math.abs(targetOffset - this.getScrollOffset())
790
+ const keepSmooth =
791
+ this.scrollState.behavior === 'smooth' && distance > viewport
792
+
637
793
  this.scrollState.lastTargetOffset = targetOffset
638
- // Switch to 'auto' behavior once measurements cause target to change
639
- // We want to jump directly to the correct position, not smoothly animate to it
640
- this.scrollState.behavior = 'auto'
794
+ if (!keepSmooth) {
795
+ this.scrollState.behavior = 'auto'
796
+ }
641
797
 
642
798
  this._scrollToOffset(targetOffset, {
643
799
  adjustments: undefined,
644
- behavior: 'auto',
800
+ behavior: keepSmooth ? 'smooth' : 'auto',
645
801
  })
646
802
  }
647
803
  }
@@ -727,8 +883,17 @@ export class Virtualizer<
727
883
  this.options.getItemKey,
728
884
  this.options.enabled,
729
885
  this.options.lanes,
886
+ this.options.laneAssignmentMode,
730
887
  ],
731
- (count, paddingStart, scrollMargin, getItemKey, enabled, lanes) => {
888
+ (
889
+ count,
890
+ paddingStart,
891
+ scrollMargin,
892
+ getItemKey,
893
+ enabled,
894
+ lanes,
895
+ laneAssignmentMode,
896
+ ) => {
732
897
  const lanesChanged =
733
898
  this.prevLanes !== undefined && this.prevLanes !== lanes
734
899
 
@@ -738,7 +903,7 @@ export class Virtualizer<
738
903
  }
739
904
 
740
905
  this.prevLanes = lanes
741
- this.pendingMeasuredCacheIndexes = []
906
+ this.pendingMin = null
742
907
 
743
908
  return {
744
909
  count,
@@ -747,6 +912,7 @@ export class Virtualizer<
747
912
  getItemKey,
748
913
  enabled,
749
914
  lanes,
915
+ laneAssignmentMode,
750
916
  }
751
917
  },
752
918
  {
@@ -755,11 +921,20 @@ export class Virtualizer<
755
921
  )
756
922
 
757
923
  private getMeasurements = memo(
758
- () => [this.getMeasurementOptions(), this.itemSizeCache],
924
+ () => [this.getMeasurementOptions(), this.itemSizeCacheVersion],
759
925
  (
760
- { count, paddingStart, scrollMargin, getItemKey, enabled, lanes },
761
- itemSizeCache,
926
+ {
927
+ count,
928
+ paddingStart,
929
+ scrollMargin,
930
+ getItemKey,
931
+ enabled,
932
+ lanes,
933
+ laneAssignmentMode,
934
+ },
935
+ _itemSizeCacheVersion,
762
936
  ) => {
937
+ const itemSizeCache = this.itemSizeCache
763
938
  if (!enabled) {
764
939
  this.measurementsCache = []
765
940
  this.itemSizeCache.clear()
@@ -783,8 +958,8 @@ export class Virtualizer<
783
958
  this.measurementsCache = []
784
959
  this.itemSizeCache.clear()
785
960
  this.laneAssignments.clear() // Clear lane cache for new lane count
786
- // Clear pending indexes to force min = 0
787
- this.pendingMeasuredCacheIndexes = []
961
+ // Force min = 0 on the rebuild
962
+ this.pendingMin = null
788
963
  }
789
964
 
790
965
  // Don't restore from initialMeasurementsCache during lane changes
@@ -796,19 +971,62 @@ export class Virtualizer<
796
971
  })
797
972
  }
798
973
 
799
- // ✅ During lanes settling, ignore pendingMeasuredCacheIndexes to prevent repositioning
800
- const min = this.lanesSettling
801
- ? 0
802
- : this.pendingMeasuredCacheIndexes.length > 0
803
- ? Math.min(...this.pendingMeasuredCacheIndexes)
804
- : 0
805
- this.pendingMeasuredCacheIndexes = []
974
+ // During lanes settling, ignore pendingMin to prevent repositioning
975
+ const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0)
976
+ this.pendingMin = null
806
977
 
807
978
  // ✅ End settling period when cache is fully built
808
979
  if (this.lanesSettling && this.measurementsCache.length === count) {
809
980
  this.lanesSettling = false
810
981
  }
811
982
 
983
+ // ─── Fast path: single-lane lazy materialization ────────────────────
984
+ // For lanes === 1 (the default and most common case), skip the
985
+ // per-item VirtualItem object allocation. We write start/size pairs
986
+ // into a Float64Array and return a Proxy that builds VirtualItem
987
+ // objects on demand (only the indices a consumer actually reads).
988
+ //
989
+ // At n=100k this drops cold-mount cost from ~2.5ms (eager object
990
+ // allocation) to roughly the cost of a single typed-array fill.
991
+ if (lanes === 1) {
992
+ const gap = this.options.gap
993
+ // Reuse flat backing if large enough; else grow (preserving data
994
+ // before `min` to mirror the slice-and-rebuild contract).
995
+ const need = count * 2
996
+ let flat = this._flatMeasurements
997
+ if (!flat || flat.length < need) {
998
+ const next = new Float64Array(need)
999
+ if (flat && min > 0) next.set(flat.subarray(0, min * 2))
1000
+ flat = next
1001
+ this._flatMeasurements = flat
1002
+ }
1003
+
1004
+ let runningStart: number
1005
+ if (min === 0) {
1006
+ runningStart = paddingStart + scrollMargin
1007
+ } else {
1008
+ // Continue from where we left off
1009
+ const prevIdx = min - 1
1010
+ runningStart = flat[prevIdx * 2]! + flat[prevIdx * 2 + 1]! + gap
1011
+ }
1012
+
1013
+ for (let i = min; i < count; i++) {
1014
+ const key = getItemKey(i)
1015
+ const measuredSize = itemSizeCache.get(key)
1016
+ const size =
1017
+ typeof measuredSize === 'number'
1018
+ ? measuredSize
1019
+ : this.options.estimateSize(i)
1020
+ flat[i * 2] = runningStart
1021
+ flat[i * 2 + 1] = size
1022
+ runningStart += size + gap
1023
+ }
1024
+
1025
+ const view = createLazyMeasurementsView(count, flat, getItemKey)
1026
+ this.measurementsCache = view
1027
+ return view
1028
+ }
1029
+
812
1030
  const measurements = this.measurementsCache.slice(0, min)
813
1031
 
814
1032
  // ✅ Performance: Track last item index per lane for O(1) lookup
@@ -832,6 +1050,9 @@ export class Virtualizer<
832
1050
  let lane: number
833
1051
  let start: number
834
1052
 
1053
+ const shouldCacheLane =
1054
+ laneAssignmentMode === 'estimate' || itemSizeCache.has(key)
1055
+
835
1056
  if (cachedLane !== undefined && this.options.lanes > 1) {
836
1057
  // Use cached lane - O(1) lookup for previous item in same lane
837
1058
  lane = cachedLane
@@ -856,8 +1077,7 @@ export class Virtualizer<
856
1077
  ? furthestMeasurement.lane
857
1078
  : i % this.options.lanes
858
1079
 
859
- // Cache the lane assignment
860
- if (this.options.lanes > 1) {
1080
+ if (this.options.lanes > 1 && shouldCacheLane) {
861
1081
  this.laneAssignments.set(i, lane)
862
1082
  }
863
1083
  }
@@ -908,6 +1128,13 @@ export class Virtualizer<
908
1128
  outerSize,
909
1129
  scrollOffset,
910
1130
  lanes,
1131
+ // Pass the typed array so binary search + forward-walk can
1132
+ // read start/end directly from Float64Array, skipping the
1133
+ // Proxy traps that materialize a full VirtualItem per probe.
1134
+ flat:
1135
+ lanes === 1 && this._flatMeasurements != null
1136
+ ? this._flatMeasurements
1137
+ : null,
911
1138
  })
912
1139
  : null)
913
1140
  },
@@ -1032,30 +1259,82 @@ export class Virtualizer<
1032
1259
  }
1033
1260
 
1034
1261
  resizeItem = (index: number, size: number) => {
1035
- const item = this.measurementsCache[index]
1036
- if (!item) return
1262
+ if (index < 0 || index >= this.options.count) return
1263
+
1264
+ // Fast field reads. For lanes===1 we read raw start/size from the flat
1265
+ // typed array, avoiding a Proxy.get + VirtualItem allocation per call.
1266
+ // For lanes>1 we fall back to the cached VirtualItem array.
1267
+ let cachedSize: number
1268
+ let itemStart: number
1269
+ let key: Key
1270
+ const flat = this._flatMeasurements
1271
+ if (this.options.lanes === 1 && flat !== null) {
1272
+ key = this.options.getItemKey(index)
1273
+ itemStart = flat[index * 2]!
1274
+ cachedSize = flat[index * 2 + 1]!
1275
+ } else {
1276
+ const item = this.measurementsCache[index]
1277
+ if (!item) return
1278
+ key = item.key
1279
+ itemStart = item.start
1280
+ cachedSize = item.size
1281
+ }
1037
1282
 
1038
- const itemSize = this.itemSizeCache.get(item.key) ?? item.size
1283
+ const itemSize = this.itemSizeCache.get(key) ?? cachedSize
1039
1284
  const delta = size - itemSize
1040
1285
 
1041
1286
  if (delta !== 0) {
1042
1287
  if (
1043
1288
  this.scrollState?.behavior !== 'smooth' &&
1044
1289
  (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined
1045
- ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this)
1046
- : item.start < this.getScrollOffset() + this.scrollAdjustments)
1290
+ ? this.shouldAdjustScrollPositionOnItemSizeChange(
1291
+ // The callback expects a VirtualItem; build one lazily only
1292
+ // when the consumer actually supplied a custom predicate.
1293
+ this.measurementsCache[index] ?? {
1294
+ index,
1295
+ key,
1296
+ start: itemStart,
1297
+ size: cachedSize,
1298
+ end: itemStart + cachedSize,
1299
+ lane: 0,
1300
+ },
1301
+ delta,
1302
+ this,
1303
+ )
1304
+ : // Default: adjust scrollTop only when the resize is an above-
1305
+ // viewport item AND we're not actively scrolling backward.
1306
+ // Adjusting during backward scroll fights the user's scroll
1307
+ // direction and produces the "items jump while scrolling up"
1308
+ // jank reported across many issues. Users who want the old
1309
+ // behavior can pass shouldAdjustScrollPositionOnItemSizeChange.
1310
+ itemStart < this.getScrollOffset() + this.scrollAdjustments &&
1311
+ this.scrollDirection !== 'backward')
1047
1312
  ) {
1048
1313
  if (process.env.NODE_ENV !== 'production' && this.options.debug) {
1049
1314
  console.info('correction', delta)
1050
1315
  }
1051
- this._scrollToOffset(this.getScrollOffset(), {
1052
- adjustments: (this.scrollAdjustments += delta),
1053
- behavior: undefined,
1054
- })
1316
+ // On iOS WebKit, writing scrollTop while a finger is on screen or
1317
+ // momentum-scroll is running cancels the in-flight scroll. Defer
1318
+ // the adjustment until iOS is fully settled — flushed by either
1319
+ // the scroll callback or the touchend grace-timer.
1320
+ if (
1321
+ isIOSWebKit() &&
1322
+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
1323
+ ) {
1324
+ this._iosDeferredAdjustment += delta
1325
+ } else {
1326
+ this._scrollToOffset(this.getScrollOffset(), {
1327
+ adjustments: (this.scrollAdjustments += delta),
1328
+ behavior: undefined,
1329
+ })
1330
+ }
1055
1331
  }
1056
1332
 
1057
- this.pendingMeasuredCacheIndexes.push(item.index)
1058
- this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size))
1333
+ if (this.pendingMin === null || index < this.pendingMin) {
1334
+ this.pendingMin = index
1335
+ }
1336
+ this.itemSizeCache.set(key, size)
1337
+ this.itemSizeCacheVersion++
1059
1338
 
1060
1339
  this.notify(false)
1061
1340
  }
@@ -1086,16 +1365,20 @@ export class Virtualizer<
1086
1365
  if (measurements.length === 0) {
1087
1366
  return undefined
1088
1367
  }
1089
- return notUndefined(
1090
- measurements[
1091
- findNearestBinarySearch(
1092
- 0,
1093
- measurements.length - 1,
1094
- (index: number) => notUndefined(measurements[index]).start,
1095
- offset,
1096
- )
1097
- ],
1368
+ // Same fast-path as calculateRange: read start values directly from the
1369
+ // typed array during binary search to skip the Proxy.get materialization
1370
+ // per probe.
1371
+ const flat = this._flatMeasurements
1372
+ const useFlat = this.options.lanes === 1 && flat != null
1373
+ const idx = findNearestBinarySearch(
1374
+ 0,
1375
+ measurements.length - 1,
1376
+ useFlat
1377
+ ? (i: number) => flat[i * 2]!
1378
+ : (i: number) => notUndefined(measurements[i]).start,
1379
+ offset,
1098
1380
  )
1381
+ return notUndefined(measurements[idx])
1099
1382
  }
1100
1383
 
1101
1384
  private getMaxScrollOffset = () => {
@@ -1260,7 +1543,16 @@ export class Virtualizer<
1260
1543
  if (measurements.length === 0) {
1261
1544
  end = this.options.paddingStart
1262
1545
  } else if (this.options.lanes === 1) {
1263
- end = measurements[measurements.length - 1]?.end ?? 0
1546
+ // Fast path: read last item's end directly from the flat typed array
1547
+ // when available; avoids a Proxy.get + VirtualItem materialization
1548
+ // just to call getTotalSize (which React renders trigger every commit).
1549
+ const lastIdx = measurements.length - 1
1550
+ const flat = this._flatMeasurements
1551
+ if (flat != null) {
1552
+ end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!
1553
+ } else {
1554
+ end = measurements[lastIdx]?.end ?? 0
1555
+ }
1264
1556
  } else {
1265
1557
  const endByLane = Array<number | null>(this.options.lanes).fill(null)
1266
1558
  let endIndex = measurements.length - 1
@@ -1282,6 +1574,39 @@ export class Virtualizer<
1282
1574
  )
1283
1575
  }
1284
1576
 
1577
+ /**
1578
+ * Returns a snapshot of currently-measured items suitable for round-
1579
+ * tripping through state storage (sessionStorage, history, etc.) and
1580
+ * passing back as `initialMeasurementsCache` on remount. Pair with the
1581
+ * current `scrollOffset` to restore exact scroll position after navigation.
1582
+ *
1583
+ * Only items the consumer has actually rendered (and thus measured) appear
1584
+ * in the snapshot; unmeasured items will fall back to `estimateSize` on
1585
+ * restore. Returns an empty array if no items have been measured.
1586
+ */
1587
+ takeSnapshot = (): Array<VirtualItem> => {
1588
+ const snapshot: Array<VirtualItem> = []
1589
+ if (this.itemSizeCache.size === 0) return snapshot
1590
+ // Iterate measurementsCache only for indices whose key is in itemSizeCache
1591
+ // (i.e., have been measured). We build VirtualItem objects with the
1592
+ // current start/size/end so they can be persisted as plain data.
1593
+ const m = this.getMeasurements()
1594
+ for (const item of m) {
1595
+ if (item && this.itemSizeCache.has(item.key)) {
1596
+ // Force materialization (lazy path) and copy plain fields.
1597
+ snapshot.push({
1598
+ index: item.index,
1599
+ key: item.key,
1600
+ start: item.start,
1601
+ size: item.size,
1602
+ end: item.end,
1603
+ lane: item.lane,
1604
+ })
1605
+ }
1606
+ }
1607
+ return snapshot
1608
+ }
1609
+
1285
1610
  private _scrollToOffset = (
1286
1611
  offset: number,
1287
1612
  {
@@ -1292,12 +1617,20 @@ export class Virtualizer<
1292
1617
  behavior: ScrollBehavior | undefined
1293
1618
  },
1294
1619
  ) => {
1620
+ // Record the intended logical scroll target so the next scroll event
1621
+ // can reconcile against subpixel rounding by the browser.
1622
+ this._intendedScrollOffset = offset + (adjustments ?? 0)
1295
1623
  this.options.scrollToFn(offset, { behavior, adjustments }, this)
1296
1624
  }
1297
1625
 
1298
1626
  measure = () => {
1299
- this.itemSizeCache = new Map()
1300
- this.laneAssignments = new Map() // Clear lane cache for full re-layout
1627
+ // Reset pendingMin so the next getMeasurements rebuilds from index 0.
1628
+ // Without this, a prior resizeItem() that left pendingMin > 0 would
1629
+ // cause the rebuild to preserve stale items before that index.
1630
+ this.pendingMin = null
1631
+ this.itemSizeCache.clear()
1632
+ this.laneAssignments.clear() // Clear lane cache for full re-layout
1633
+ this.itemSizeCacheVersion++
1301
1634
  this.notify(false)
1302
1635
  }
1303
1636
  }
@@ -1333,14 +1666,24 @@ function calculateRange({
1333
1666
  outerSize,
1334
1667
  scrollOffset,
1335
1668
  lanes,
1669
+ flat,
1336
1670
  }: {
1337
1671
  measurements: Array<VirtualItem>
1338
1672
  outerSize: number
1339
1673
  scrollOffset: number
1340
1674
  lanes: number
1675
+ flat: Float64Array | null
1341
1676
  }) {
1342
1677
  const lastIndex = measurements.length - 1
1343
- const getOffset = (index: number) => measurements[index]!.start
1678
+ // When the lanes===1 fast-path is active, read start/end directly from the
1679
+ // flat Float64Array instead of going through the lazy-view Proxy. Cuts
1680
+ // ~17 Proxy.get traps per scroll for the binary search alone.
1681
+ const getStart = flat
1682
+ ? (index: number) => flat[index * 2]!
1683
+ : (index: number) => measurements[index]!.start
1684
+ const getEnd = flat
1685
+ ? (index: number) => flat[index * 2]! + flat[index * 2 + 1]!
1686
+ : (index: number) => measurements[index]!.end
1344
1687
 
1345
1688
  // handle case when item count is less than or equal to lanes
1346
1689
  if (measurements.length <= lanes) {
@@ -1350,18 +1693,13 @@ function calculateRange({
1350
1693
  }
1351
1694
  }
1352
1695
 
1353
- let startIndex = findNearestBinarySearch(
1354
- 0,
1355
- lastIndex,
1356
- getOffset,
1357
- scrollOffset,
1358
- )
1696
+ let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset)
1359
1697
  let endIndex = startIndex
1360
1698
 
1361
1699
  if (lanes === 1) {
1362
1700
  while (
1363
1701
  endIndex < lastIndex &&
1364
- measurements[endIndex]!.end < scrollOffset + outerSize
1702
+ getEnd(endIndex) < scrollOffset + outerSize
1365
1703
  ) {
1366
1704
  endIndex++
1367
1705
  }