@tanstack/virtual-core 3.14.0 → 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,31 @@ 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
294
279
 
295
280
  type LaneAssignmentMode = 'estimate' | 'measured'
296
281
 
@@ -378,9 +363,14 @@ export class Virtualizer<
378
363
  isScrolling = false
379
364
  private scrollState: ScrollState | null = null
380
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
381
369
  private itemSizeCache = new Map<Key, number>()
370
+ private itemSizeCacheVersion = 0
382
371
  private laneAssignments = new Map<number, number>() // index → lane cache
383
- private pendingMeasuredCacheIndexes: Array<number> = []
372
+ // Earliest index dirtied since last getMeasurements() rebuild, or null.
373
+ private pendingMin: number | null = null
384
374
  private prevLanes: number | undefined = undefined
385
375
  private lanesChangedFlag = false
386
376
  private lanesSettling = false
@@ -388,6 +378,28 @@ export class Virtualizer<
388
378
  scrollOffset: number | null = null
389
379
  scrollDirection: ScrollDirection | null = null
390
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
391
403
  shouldAdjustScrollPositionOnItemSizeChange:
392
404
  | undefined
393
405
  | ((
@@ -417,6 +429,20 @@ export class Virtualizer<
417
429
 
418
430
  if (!node.isConnected) {
419
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
+ }
420
446
  return
421
447
  }
422
448
 
@@ -451,11 +477,9 @@ export class Virtualizer<
451
477
  }
452
478
 
453
479
  setOptions = (opts: VirtualizerOptions<TScrollElement, TItemElement>) => {
454
- Object.entries(opts).forEach(([key, value]) => {
455
- if (typeof value === 'undefined') delete (opts as any)[key]
456
- })
457
-
458
- this.options = {
480
+ // Skip `{...defaults, ...opts}` because explicit `undefined` values in
481
+ // opts would override defaults with `undefined`.
482
+ const merged = {
459
483
  debug: false,
460
484
  initialOffset: 0,
461
485
  overscan: 1,
@@ -480,8 +504,14 @@ export class Virtualizer<
480
504
  useScrollendEvent: false,
481
505
  useAnimationFrameWithResizeObserver: false,
482
506
  laneAssignmentMode: 'estimate',
483
- ...opts,
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
484
512
  }
513
+
514
+ this.options = merged
485
515
  }
486
516
 
487
517
  private notify = (sync: boolean) => {
@@ -565,6 +595,21 @@ export class Virtualizer<
565
595
 
566
596
  this.unsubs.push(
567
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
+
568
613
  this.scrollAdjustments = 0
569
614
  this.scrollDirection = isScrolling
570
615
  ? this.getScrollOffset() < offset
@@ -574,6 +619,11 @@ export class Virtualizer<
574
619
  this.scrollOffset = offset
575
620
  this.isScrolling = isScrolling
576
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
+
577
627
  if (this.scrollState) {
578
628
  this.scheduleScrollReconcile()
579
629
  }
@@ -581,6 +631,56 @@ export class Virtualizer<
581
631
  }),
582
632
  )
583
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
+
584
684
  this._scrollToOffset(this.getScrollOffset(), {
585
685
  adjustments: undefined,
586
686
  behavior: undefined,
@@ -588,6 +688,34 @@ export class Virtualizer<
588
688
  }
589
689
  }
590
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
+
591
719
  private rafId: number | null = null
592
720
  private scheduleScrollReconcile() {
593
721
  if (!this.targetWindow) {
@@ -631,6 +759,18 @@ export class Virtualizer<
631
759
  if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
632
760
  this.scrollState.stableFrames++
633
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
+ }
634
774
  this.scrollState = null
635
775
  return
636
776
  }
@@ -638,14 +778,26 @@ export class Virtualizer<
638
778
  this.scrollState.stableFrames = 0
639
779
 
640
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
+
641
793
  this.scrollState.lastTargetOffset = targetOffset
642
- // Switch to 'auto' behavior once measurements cause target to change
643
- // We want to jump directly to the correct position, not smoothly animate to it
644
- this.scrollState.behavior = 'auto'
794
+ if (!keepSmooth) {
795
+ this.scrollState.behavior = 'auto'
796
+ }
645
797
 
646
798
  this._scrollToOffset(targetOffset, {
647
799
  adjustments: undefined,
648
- behavior: 'auto',
800
+ behavior: keepSmooth ? 'smooth' : 'auto',
649
801
  })
650
802
  }
651
803
  }
@@ -751,7 +903,7 @@ export class Virtualizer<
751
903
  }
752
904
 
753
905
  this.prevLanes = lanes
754
- this.pendingMeasuredCacheIndexes = []
906
+ this.pendingMin = null
755
907
 
756
908
  return {
757
909
  count,
@@ -769,7 +921,7 @@ export class Virtualizer<
769
921
  )
770
922
 
771
923
  private getMeasurements = memo(
772
- () => [this.getMeasurementOptions(), this.itemSizeCache],
924
+ () => [this.getMeasurementOptions(), this.itemSizeCacheVersion],
773
925
  (
774
926
  {
775
927
  count,
@@ -780,8 +932,9 @@ export class Virtualizer<
780
932
  lanes,
781
933
  laneAssignmentMode,
782
934
  },
783
- itemSizeCache,
935
+ _itemSizeCacheVersion,
784
936
  ) => {
937
+ const itemSizeCache = this.itemSizeCache
785
938
  if (!enabled) {
786
939
  this.measurementsCache = []
787
940
  this.itemSizeCache.clear()
@@ -805,8 +958,8 @@ export class Virtualizer<
805
958
  this.measurementsCache = []
806
959
  this.itemSizeCache.clear()
807
960
  this.laneAssignments.clear() // Clear lane cache for new lane count
808
- // Clear pending indexes to force min = 0
809
- this.pendingMeasuredCacheIndexes = []
961
+ // Force min = 0 on the rebuild
962
+ this.pendingMin = null
810
963
  }
811
964
 
812
965
  // Don't restore from initialMeasurementsCache during lane changes
@@ -818,19 +971,62 @@ export class Virtualizer<
818
971
  })
819
972
  }
820
973
 
821
- // ✅ During lanes settling, ignore pendingMeasuredCacheIndexes to prevent repositioning
822
- const min = this.lanesSettling
823
- ? 0
824
- : this.pendingMeasuredCacheIndexes.length > 0
825
- ? Math.min(...this.pendingMeasuredCacheIndexes)
826
- : 0
827
- this.pendingMeasuredCacheIndexes = []
974
+ // During lanes settling, ignore pendingMin to prevent repositioning
975
+ const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0)
976
+ this.pendingMin = null
828
977
 
829
978
  // ✅ End settling period when cache is fully built
830
979
  if (this.lanesSettling && this.measurementsCache.length === count) {
831
980
  this.lanesSettling = false
832
981
  }
833
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
+
834
1030
  const measurements = this.measurementsCache.slice(0, min)
835
1031
 
836
1032
  // ✅ Performance: Track last item index per lane for O(1) lookup
@@ -932,6 +1128,13 @@ export class Virtualizer<
932
1128
  outerSize,
933
1129
  scrollOffset,
934
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,
935
1138
  })
936
1139
  : null)
937
1140
  },
@@ -1056,30 +1259,82 @@ export class Virtualizer<
1056
1259
  }
1057
1260
 
1058
1261
  resizeItem = (index: number, size: number) => {
1059
- const item = this.measurementsCache[index]
1060
- 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
+ }
1061
1282
 
1062
- const itemSize = this.itemSizeCache.get(item.key) ?? item.size
1283
+ const itemSize = this.itemSizeCache.get(key) ?? cachedSize
1063
1284
  const delta = size - itemSize
1064
1285
 
1065
1286
  if (delta !== 0) {
1066
1287
  if (
1067
1288
  this.scrollState?.behavior !== 'smooth' &&
1068
1289
  (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined
1069
- ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this)
1070
- : 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')
1071
1312
  ) {
1072
1313
  if (process.env.NODE_ENV !== 'production' && this.options.debug) {
1073
1314
  console.info('correction', delta)
1074
1315
  }
1075
- this._scrollToOffset(this.getScrollOffset(), {
1076
- adjustments: (this.scrollAdjustments += delta),
1077
- behavior: undefined,
1078
- })
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
+ }
1079
1331
  }
1080
1332
 
1081
- this.pendingMeasuredCacheIndexes.push(item.index)
1082
- 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++
1083
1338
 
1084
1339
  this.notify(false)
1085
1340
  }
@@ -1110,16 +1365,20 @@ export class Virtualizer<
1110
1365
  if (measurements.length === 0) {
1111
1366
  return undefined
1112
1367
  }
1113
- return notUndefined(
1114
- measurements[
1115
- findNearestBinarySearch(
1116
- 0,
1117
- measurements.length - 1,
1118
- (index: number) => notUndefined(measurements[index]).start,
1119
- offset,
1120
- )
1121
- ],
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,
1122
1380
  )
1381
+ return notUndefined(measurements[idx])
1123
1382
  }
1124
1383
 
1125
1384
  private getMaxScrollOffset = () => {
@@ -1284,7 +1543,16 @@ export class Virtualizer<
1284
1543
  if (measurements.length === 0) {
1285
1544
  end = this.options.paddingStart
1286
1545
  } else if (this.options.lanes === 1) {
1287
- 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
+ }
1288
1556
  } else {
1289
1557
  const endByLane = Array<number | null>(this.options.lanes).fill(null)
1290
1558
  let endIndex = measurements.length - 1
@@ -1306,6 +1574,39 @@ export class Virtualizer<
1306
1574
  )
1307
1575
  }
1308
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
+
1309
1610
  private _scrollToOffset = (
1310
1611
  offset: number,
1311
1612
  {
@@ -1316,12 +1617,20 @@ export class Virtualizer<
1316
1617
  behavior: ScrollBehavior | undefined
1317
1618
  },
1318
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)
1319
1623
  this.options.scrollToFn(offset, { behavior, adjustments }, this)
1320
1624
  }
1321
1625
 
1322
1626
  measure = () => {
1323
- this.itemSizeCache = new Map()
1324
- 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++
1325
1634
  this.notify(false)
1326
1635
  }
1327
1636
  }
@@ -1357,14 +1666,24 @@ function calculateRange({
1357
1666
  outerSize,
1358
1667
  scrollOffset,
1359
1668
  lanes,
1669
+ flat,
1360
1670
  }: {
1361
1671
  measurements: Array<VirtualItem>
1362
1672
  outerSize: number
1363
1673
  scrollOffset: number
1364
1674
  lanes: number
1675
+ flat: Float64Array | null
1365
1676
  }) {
1366
1677
  const lastIndex = measurements.length - 1
1367
- 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
1368
1687
 
1369
1688
  // handle case when item count is less than or equal to lanes
1370
1689
  if (measurements.length <= lanes) {
@@ -1374,18 +1693,13 @@ function calculateRange({
1374
1693
  }
1375
1694
  }
1376
1695
 
1377
- let startIndex = findNearestBinarySearch(
1378
- 0,
1379
- lastIndex,
1380
- getOffset,
1381
- scrollOffset,
1382
- )
1696
+ let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset)
1383
1697
  let endIndex = startIndex
1384
1698
 
1385
1699
  if (lanes === 1) {
1386
1700
  while (
1387
1701
  endIndex < lastIndex &&
1388
- measurements[endIndex]!.end < scrollOffset + outerSize
1702
+ getEnd(endIndex) < scrollOffset + outerSize
1389
1703
  ) {
1390
1704
  endIndex++
1391
1705
  }