@tanstack/virtual-core 3.14.0 → 3.16.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
 
@@ -10,6 +33,10 @@ type ScrollAlignment = 'start' | 'center' | 'end' | 'auto'
10
33
 
11
34
  type ScrollBehavior = 'auto' | 'smooth' | 'instant'
12
35
 
36
+ type ScrollAnchor = 'start' | 'end'
37
+
38
+ type FollowOnAppend = boolean | ScrollBehavior
39
+
13
40
  export interface ScrollToOptions {
14
41
  align?: ScrollAlignment
15
42
  behavior?: ScrollBehavior
@@ -19,6 +46,8 @@ type ScrollToOffsetOptions = ScrollToOptions
19
46
 
20
47
  type ScrollToIndexOptions = ScrollToOptions
21
48
 
49
+ type ScrollToEndOptions = Pick<ScrollToOptions, 'behavior'>
50
+
22
51
  export interface Range {
23
52
  startIndex: number
24
53
  endIndex: number
@@ -54,13 +83,12 @@ export const defaultKeyExtractor = (index: number) => index
54
83
  export const defaultRangeExtractor = (range: Range) => {
55
84
  const start = Math.max(range.startIndex - range.overscan, 0)
56
85
  const end = Math.min(range.endIndex + range.overscan, range.count - 1)
86
+ const len = end - start + 1
57
87
 
58
- const arr = []
59
-
60
- for (let i = start; i <= end; i++) {
61
- arr.push(i)
88
+ const arr = new Array<number>(len)
89
+ for (let i = 0; i < len; i++) {
90
+ arr[i] = start + i
62
91
  }
63
-
64
92
  return arr
65
93
  }
66
94
 
@@ -143,9 +171,13 @@ const supportsScrollend =
143
171
 
144
172
  type ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void
145
173
 
146
- export const observeElementOffset = <T extends Element>(
174
+ // Shared core: both element and window variants attach scroll/scrollend
175
+ // listeners with the same lifecycle; they only differ in how to read the
176
+ // current offset from the scroll target.
177
+ const observeOffset = <T extends Element | Window>(
147
178
  instance: Virtualizer<T, any>,
148
179
  cb: ObserveOffsetCallBack,
180
+ readOffset: (target: T) => number,
149
181
  ) => {
150
182
  const element = instance.scrollElement
151
183
  if (!element) {
@@ -156,32 +188,27 @@ export const observeElementOffset = <T extends Element>(
156
188
  return
157
189
  }
158
190
 
159
- let offset = 0
160
- const fallback =
191
+ const registerScrollendEvent =
161
192
  instance.options.useScrollendEvent && supportsScrollend
162
- ? () => undefined
163
- : debounce(
164
- targetWindow,
165
- () => {
166
- cb(offset, false)
167
- },
168
- instance.options.isScrollingResetDelay,
169
- )
193
+
194
+ let offset = 0
195
+ const fallback = registerScrollendEvent
196
+ ? null
197
+ : debounce(
198
+ targetWindow,
199
+ () => cb(offset, false),
200
+ instance.options.isScrollingResetDelay,
201
+ )
170
202
 
171
203
  const createHandler = (isScrolling: boolean) => () => {
172
- const { horizontal, isRtl } = instance.options
173
- offset = horizontal
174
- ? element['scrollLeft'] * ((isRtl && -1) || 1)
175
- : element['scrollTop']
176
- fallback()
204
+ offset = readOffset(element)
205
+ fallback?.()
177
206
  cb(offset, isScrolling)
178
207
  }
179
208
  const handler = createHandler(true)
180
209
  const endHandler = createHandler(false)
181
210
 
182
211
  element.addEventListener('scroll', handler, addEventListenerOptions)
183
- const registerScrollendEvent =
184
- instance.options.useScrollendEvent && supportsScrollend
185
212
  if (registerScrollendEvent) {
186
213
  element.addEventListener('scrollend', endHandler, addEventListenerOptions)
187
214
  }
@@ -193,52 +220,22 @@ export const observeElementOffset = <T extends Element>(
193
220
  }
194
221
  }
195
222
 
223
+ export const observeElementOffset = <T extends Element>(
224
+ instance: Virtualizer<T, any>,
225
+ cb: ObserveOffsetCallBack,
226
+ ) =>
227
+ observeOffset(instance, cb, (el) => {
228
+ const { horizontal, isRtl } = instance.options
229
+ return horizontal ? el.scrollLeft * ((isRtl && -1) || 1) : el.scrollTop
230
+ })
231
+
196
232
  export const observeWindowOffset = (
197
233
  instance: Virtualizer<Window, any>,
198
234
  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
- }
235
+ ) =>
236
+ observeOffset(instance, cb, (win) =>
237
+ instance.options.horizontal ? win.scrollX : win.scrollY,
238
+ )
242
239
 
243
240
  export const measureElement = <TItemElement extends Element>(
244
241
  element: TItemElement,
@@ -260,37 +257,31 @@ export const measureElement = <TItemElement extends Element>(
260
257
  ]
261
258
  }
262
259
 
263
- export const windowScroll = <T extends Window>(
260
+ const scrollWithAdjustments = (
264
261
  offset: number,
265
262
  {
266
263
  adjustments = 0,
267
264
  behavior,
268
265
  }: { adjustments?: number; behavior?: ScrollBehavior },
269
- instance: Virtualizer<T, any>,
266
+ instance: Virtualizer<any, any>,
270
267
  ) => {
271
- const toOffset = offset + adjustments
272
-
273
268
  instance.scrollElement?.scrollTo?.({
274
- [instance.options.horizontal ? 'left' : 'top']: toOffset,
269
+ [instance.options.horizontal ? 'left' : 'top']: offset + adjustments,
275
270
  behavior,
276
271
  })
277
272
  }
278
273
 
279
- export const elementScroll = <T extends Element>(
274
+ export const windowScroll: <T extends Window>(
280
275
  offset: number,
281
- {
282
- adjustments = 0,
283
- behavior,
284
- }: { adjustments?: number; behavior?: ScrollBehavior },
276
+ options: { adjustments?: number; behavior?: ScrollBehavior },
285
277
  instance: Virtualizer<T, any>,
286
- ) => {
287
- const toOffset = offset + adjustments
278
+ ) => void = scrollWithAdjustments
288
279
 
289
- instance.scrollElement?.scrollTo?.({
290
- [instance.options.horizontal ? 'left' : 'top']: toOffset,
291
- behavior,
292
- })
293
- }
280
+ export const elementScroll: <T extends Element>(
281
+ offset: number,
282
+ options: { adjustments?: number; behavior?: ScrollBehavior },
283
+ instance: Virtualizer<T, any>,
284
+ ) => void = scrollWithAdjustments
294
285
 
295
286
  type LaneAssignmentMode = 'estimate' | 'measured'
296
287
 
@@ -343,6 +334,9 @@ export interface VirtualizerOptions<
343
334
  indexAttribute?: string
344
335
  initialMeasurementsCache?: Array<VirtualItem>
345
336
  lanes?: number
337
+ anchorTo?: ScrollAnchor
338
+ followOnAppend?: FollowOnAppend
339
+ scrollEndThreshold?: number
346
340
  isScrollingResetDelay?: number
347
341
  useScrollendEvent?: boolean
348
342
  enabled?: boolean
@@ -367,6 +361,12 @@ type ScrollState = {
367
361
  stableFrames: number
368
362
  }
369
363
 
364
+ type PendingScrollAnchor = [
365
+ key: Key | null,
366
+ offset: number,
367
+ followOnAppend: ScrollBehavior | null,
368
+ ]
369
+
370
370
  export class Virtualizer<
371
371
  TScrollElement extends Element | Window,
372
372
  TItemElement extends Element,
@@ -378,16 +378,44 @@ export class Virtualizer<
378
378
  isScrolling = false
379
379
  private scrollState: ScrollState | null = null
380
380
  measurementsCache: Array<VirtualItem> = []
381
+ // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].
382
+ // null until the first single-lane build; reused (and grown) across rebuilds.
383
+ private _flatMeasurements: Float64Array | null = null
381
384
  private itemSizeCache = new Map<Key, number>()
385
+ private itemSizeCacheVersion = 0
382
386
  private laneAssignments = new Map<number, number>() // index → lane cache
383
- private pendingMeasuredCacheIndexes: Array<number> = []
387
+ // Earliest index dirtied since last getMeasurements() rebuild, or null.
388
+ private pendingMin: number | null = null
384
389
  private prevLanes: number | undefined = undefined
385
390
  private lanesChangedFlag = false
386
391
  private lanesSettling = false
392
+ private pendingScrollAnchor: PendingScrollAnchor | null = null
387
393
  scrollRect: Rect | null = null
388
394
  scrollOffset: number | null = null
389
395
  scrollDirection: ScrollDirection | null = null
390
396
  private scrollAdjustments = 0
397
+ // Sum of size-change deltas above-viewport that were skipped during
398
+ // iOS momentum scroll (writing scrollTop mid-momentum cancels it).
399
+ // Flushed in a single scrollTo when iOS is fully settled.
400
+ private _iosDeferredAdjustment = 0
401
+ // Touch state. iOS WebKit cancels momentum when scrollTop is written, so
402
+ // we defer adjustments not only during `isScrolling` but also through the
403
+ // touchstart→touchend window (active drag) and a short tail after
404
+ // touchend (early-momentum window — iOS only fires touch events once at
405
+ // the start of momentum, so we use a timer rather than another event).
406
+ private _iosTouching = false
407
+ private _iosJustTouchEnded = false
408
+ private _iosTouchEndTimerId: number | null = null
409
+ // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs)
410
+ // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5
411
+ // but the browser reports back 12346, the next reconcileScroll sees a
412
+ // "target changed" and re-fires scrollTo — a feedback loop that the
413
+ // approxEqual(<1.01) tolerance otherwise absorbs as a workaround.
414
+ // By remembering the intended value of our most-recent self-driven
415
+ // scrollTo, we can match the browser's rounded read back to the intended
416
+ // value when the diff is < 1.5 px, distinguishing it from a real user
417
+ // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.
418
+ private _intendedScrollOffset: number | null = null
391
419
  shouldAdjustScrollPositionOnItemSizeChange:
392
420
  | undefined
393
421
  | ((
@@ -417,6 +445,20 @@ export class Virtualizer<
417
445
 
418
446
  if (!node.isConnected) {
419
447
  this.observer.unobserve(node)
448
+ // Find the cache entry pointing to this exact node and remove
449
+ // it. We can't call getItemKey(index) here because items may
450
+ // have been removed since this node was rendered — the index
451
+ // could be stale and out-of-bounds in the user's data array
452
+ // (regression test in e2e/.../stale-index.spec.ts, fix #1148).
453
+ // The === comparison naturally handles the React-replaced-
454
+ // a-node-for-the-same-key case: that entry now points to a
455
+ // different node, so this loop won't match.
456
+ for (const [cacheKey, cachedNode] of this.elementsCache) {
457
+ if (cachedNode === node) {
458
+ this.elementsCache.delete(cacheKey)
459
+ break
460
+ }
461
+ }
420
462
  return
421
463
  }
422
464
 
@@ -451,11 +493,9 @@ export class Virtualizer<
451
493
  }
452
494
 
453
495
  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 = {
496
+ // Skip `{...defaults, ...opts}` because explicit `undefined` values in
497
+ // opts would override defaults with `undefined`.
498
+ const merged = {
459
499
  debug: false,
460
500
  initialOffset: 0,
461
501
  overscan: 1,
@@ -474,13 +514,90 @@ export class Virtualizer<
474
514
  indexAttribute: 'data-index',
475
515
  initialMeasurementsCache: [],
476
516
  lanes: 1,
517
+ anchorTo: 'start',
518
+ followOnAppend: false,
519
+ scrollEndThreshold: 1,
477
520
  isScrollingResetDelay: 150,
478
521
  enabled: true,
479
522
  isRtl: false,
480
523
  useScrollendEvent: false,
481
524
  useAnimationFrameWithResizeObserver: false,
482
525
  laneAssignmentMode: 'estimate',
483
- ...opts,
526
+ } as unknown as Required<VirtualizerOptions<TScrollElement, TItemElement>>
527
+
528
+ for (const key in opts) {
529
+ const v = (opts as any)[key]
530
+ if (v !== undefined) (merged as any)[key] = v
531
+ }
532
+
533
+ const prevOptions = this.options as
534
+ | Required<VirtualizerOptions<TScrollElement, TItemElement>>
535
+ | undefined
536
+ let anchor: [Key, number] | null = null
537
+ let followOnAppend: ScrollBehavior | null = null
538
+
539
+ if (
540
+ prevOptions !== undefined &&
541
+ prevOptions.enabled &&
542
+ merged.enabled &&
543
+ merged.anchorTo === 'end' &&
544
+ this.scrollElement !== null
545
+ ) {
546
+ const prevCount = prevOptions.count
547
+ const nextCount = merged.count
548
+ const measurements = this.getMeasurements()
549
+ const prevFirstKey =
550
+ prevCount > 0
551
+ ? (measurements[0]?.key ?? prevOptions.getItemKey(0))
552
+ : null
553
+ const prevLastKey =
554
+ prevCount > 0
555
+ ? (measurements[prevCount - 1]?.key ??
556
+ prevOptions.getItemKey(prevCount - 1))
557
+ : null
558
+ const didCountChange = nextCount !== prevCount
559
+ const didEdgeKeysChange =
560
+ didCountChange ||
561
+ (prevCount > 0 &&
562
+ nextCount > 0 &&
563
+ (merged.getItemKey(0) !== prevFirstKey ||
564
+ merged.getItemKey(nextCount - 1) !== prevLastKey))
565
+
566
+ if (didEdgeKeysChange) {
567
+ const item =
568
+ prevCount > 0
569
+ ? (this.getVirtualItemForOffset(this.getScrollOffset()) ??
570
+ measurements[0])
571
+ : null
572
+
573
+ if (item) {
574
+ anchor = [item.key, this.getScrollOffset() - item.start]
575
+ }
576
+
577
+ const behavior =
578
+ merged.followOnAppend === true
579
+ ? 'auto'
580
+ : merged.followOnAppend || null
581
+
582
+ if (
583
+ behavior &&
584
+ nextCount > prevCount &&
585
+ this.isAtEnd(prevOptions.scrollEndThreshold) &&
586
+ (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)
587
+ ) {
588
+ followOnAppend = behavior
589
+ }
590
+ }
591
+ }
592
+
593
+ this.options = merged
594
+
595
+ if (anchor || followOnAppend) {
596
+ this.pendingScrollAnchor = [
597
+ anchor?.[0] ?? null,
598
+ anchor?.[1] ?? 0,
599
+ followOnAppend,
600
+ ]
484
601
  }
485
602
  }
486
603
 
@@ -488,6 +605,26 @@ export class Virtualizer<
488
605
  this.options.onChange?.(this, sync)
489
606
  }
490
607
 
608
+ private applyScrollAdjustment(delta: number, behavior?: ScrollBehavior) {
609
+ if (delta === 0) return
610
+
611
+ if (process.env.NODE_ENV !== 'production' && this.options.debug) {
612
+ console.info('correction', delta)
613
+ }
614
+
615
+ if (
616
+ isIOSWebKit() &&
617
+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
618
+ ) {
619
+ this._iosDeferredAdjustment += delta
620
+ } else {
621
+ this._scrollToOffset(this.getScrollOffset(), {
622
+ adjustments: (this.scrollAdjustments += delta),
623
+ behavior,
624
+ })
625
+ }
626
+ }
627
+
491
628
  private maybeNotify = memo(
492
629
  () => {
493
630
  this.calculateRange()
@@ -565,6 +702,21 @@ export class Virtualizer<
565
702
 
566
703
  this.unsubs.push(
567
704
  this.options.observeElementOffset(this, (offset, isScrolling) => {
705
+ // If this scroll event looks like the browser's read-back of a
706
+ // value we just wrote, prefer our intended (sub-pixel-accurate)
707
+ // value over the browser's rounded one. The 1.5 px tolerance is
708
+ // tight enough to avoid mistaking a real user scroll for a
709
+ // self-write — by the time the user has moved 1.5 px, the
710
+ // intended value will already have been consumed by a prior
711
+ // scroll event and cleared.
712
+ if (
713
+ this._intendedScrollOffset !== null &&
714
+ Math.abs(offset - this._intendedScrollOffset) < 1.5
715
+ ) {
716
+ offset = this._intendedScrollOffset
717
+ }
718
+ this._intendedScrollOffset = null
719
+
568
720
  this.scrollAdjustments = 0
569
721
  this.scrollDirection = isScrolling
570
722
  ? this.getScrollOffset() < offset
@@ -574,6 +726,11 @@ export class Virtualizer<
574
726
  this.scrollOffset = offset
575
727
  this.isScrolling = isScrolling
576
728
 
729
+ // Flush deferred iOS adjustments if we're now fully settled.
730
+ // "Fully settled" means: not actively scrolling, no finger on
731
+ // screen, and the post-touchend grace window has expired.
732
+ this._flushIosDeferredIfReady()
733
+
577
734
  if (this.scrollState) {
578
735
  this.scheduleScrollReconcile()
579
736
  }
@@ -581,11 +738,117 @@ export class Virtualizer<
581
738
  }),
582
739
  )
583
740
 
741
+ // Touch event listeners (iOS-aware deferral). We attach unconditionally
742
+ // — the listeners are passive and cheap; on non-touch devices they
743
+ // simply never fire. The gating by isIOSWebKit() lives in resizeItem
744
+ // and _flushIosDeferredIfReady so we only burn the path on iOS.
745
+ if ('addEventListener' in this.scrollElement) {
746
+ const scrollEl = this.scrollElement as unknown as EventTarget
747
+ const onTouchStart = () => {
748
+ this._iosTouching = true
749
+ this._iosJustTouchEnded = false
750
+ if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
751
+ this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
752
+ this._iosTouchEndTimerId = null
753
+ }
754
+ }
755
+ const onTouchEnd = () => {
756
+ this._iosTouching = false
757
+ if (!isIOSWebKit() || this.targetWindow == null) {
758
+ // Non-iOS: nothing more to track. Just clear the touching flag.
759
+ return
760
+ }
761
+ this._iosJustTouchEnded = true
762
+ // After ~150 ms with no scroll/touch events, momentum is done.
763
+ this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => {
764
+ this._iosJustTouchEnded = false
765
+ this._iosTouchEndTimerId = null
766
+ // After the grace window, attempt to flush. The scroll event
767
+ // for momentum decay may have already fired before our timer.
768
+ this._flushIosDeferredIfReady()
769
+ }, 150)
770
+ }
771
+ scrollEl.addEventListener(
772
+ 'touchstart',
773
+ onTouchStart,
774
+ addEventListenerOptions,
775
+ )
776
+ scrollEl.addEventListener(
777
+ 'touchend',
778
+ onTouchEnd,
779
+ addEventListenerOptions,
780
+ )
781
+ this.unsubs.push(() => {
782
+ scrollEl.removeEventListener('touchstart', onTouchStart)
783
+ scrollEl.removeEventListener('touchend', onTouchEnd)
784
+ if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
785
+ this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
786
+ this._iosTouchEndTimerId = null
787
+ }
788
+ })
789
+ }
790
+
584
791
  this._scrollToOffset(this.getScrollOffset(), {
585
792
  adjustments: undefined,
586
793
  behavior: undefined,
587
794
  })
588
795
  }
796
+
797
+ const anchor = this.pendingScrollAnchor
798
+ this.pendingScrollAnchor = null
799
+
800
+ if (anchor && this.scrollElement && this.options.enabled) {
801
+ const [key, offset, followOnAppend] = anchor
802
+
803
+ if (key !== null) {
804
+ const { count, getItemKey } = this.options
805
+ let index = 0
806
+ while (index < count && getItemKey(index) !== key) {
807
+ index++
808
+ }
809
+
810
+ const item = index < count ? this.getMeasurements()[index] : undefined
811
+ if (item) {
812
+ const delta = item.start + offset - this.getScrollOffset()
813
+
814
+ if (!approxEqual(delta, 0)) {
815
+ this.applyScrollAdjustment(delta)
816
+ }
817
+ }
818
+ }
819
+
820
+ if (followOnAppend) {
821
+ this.scrollToEnd({ behavior: followOnAppend })
822
+ }
823
+ }
824
+ }
825
+
826
+ // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
827
+ // truly settled — not actively scrolling, not under an active touch, and
828
+ // past the post-touchend grace window. Called from the scroll callback
829
+ // and the touchend grace-timer.
830
+ private _flushIosDeferredIfReady = () => {
831
+ if (this._iosDeferredAdjustment === 0) return
832
+ if (this.isScrolling) return
833
+ if (this._iosTouching) return
834
+ if (this._iosJustTouchEnded) return
835
+ // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go
836
+ // negative or beyond scrollHeight - clientHeight. Writing scrollTop
837
+ // while in that zone snaps the page back to the clamped value at the
838
+ // end of the bounce, often discarding the user's intent. Skip the
839
+ // flush; the next in-bounds scroll event will retry.
840
+ const cur = this.getScrollOffset()
841
+ const max = this.getMaxScrollOffset()
842
+ if (cur < 0 || cur > max) return
843
+ const delta = this._iosDeferredAdjustment
844
+ this._iosDeferredAdjustment = 0
845
+ // Roll the deferred delta into the running accumulator so any resize
846
+ // landing between now and the resulting scroll event computes from the
847
+ // post-flush offset rather than the stale one.
848
+ this._scrollToOffset(cur, {
849
+ adjustments: (this.scrollAdjustments += delta),
850
+ behavior: undefined,
851
+ })
589
852
  }
590
853
 
591
854
  private rafId: number | null = null
@@ -631,6 +894,18 @@ export class Virtualizer<
631
894
  if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
632
895
  this.scrollState.stableFrames++
633
896
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
897
+ // Final-pass exact landing. The reconcile-stable check uses a 1.01px
898
+ // tolerance (approxEqual) so we don't fight subpixel browser rounding
899
+ // during the converging phase. Once we're definitively settled,
900
+ // commit the exact target so consumers calling scrollToIndex(N)
901
+ // end up at the EXACT computed position of item N — matching
902
+ // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
903
+ if (this.getScrollOffset() !== targetOffset) {
904
+ this._scrollToOffset(targetOffset, {
905
+ adjustments: undefined,
906
+ behavior: 'auto',
907
+ })
908
+ }
634
909
  this.scrollState = null
635
910
  return
636
911
  }
@@ -638,14 +913,26 @@ export class Virtualizer<
638
913
  this.scrollState.stableFrames = 0
639
914
 
640
915
  if (targetChanged) {
916
+ // When the target moves during smooth scroll (because items came into
917
+ // view and got measured, shifting positions), the original logic was
918
+ // to immediately snap to 'auto' — visibly jarring on long
919
+ // scroll-to-index calls. Now: keep smooth while we're still far
920
+ // (more than a viewport) from the new target. Only fall back to
921
+ // 'auto' for the final approach, so the user sees one continuous
922
+ // motion that smoothly adjusts its endpoint as measurements arrive.
923
+ const viewport = this.getSize() || 600
924
+ const distance = Math.abs(targetOffset - this.getScrollOffset())
925
+ const keepSmooth =
926
+ this.scrollState.behavior === 'smooth' && distance > viewport
927
+
641
928
  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'
929
+ if (!keepSmooth) {
930
+ this.scrollState.behavior = 'auto'
931
+ }
645
932
 
646
933
  this._scrollToOffset(targetOffset, {
647
934
  adjustments: undefined,
648
- behavior: 'auto',
935
+ behavior: keepSmooth ? 'smooth' : 'auto',
649
936
  })
650
937
  }
651
938
  }
@@ -751,7 +1038,7 @@ export class Virtualizer<
751
1038
  }
752
1039
 
753
1040
  this.prevLanes = lanes
754
- this.pendingMeasuredCacheIndexes = []
1041
+ this.pendingMin = null
755
1042
 
756
1043
  return {
757
1044
  count,
@@ -769,7 +1056,7 @@ export class Virtualizer<
769
1056
  )
770
1057
 
771
1058
  private getMeasurements = memo(
772
- () => [this.getMeasurementOptions(), this.itemSizeCache],
1059
+ () => [this.getMeasurementOptions(), this.itemSizeCacheVersion],
773
1060
  (
774
1061
  {
775
1062
  count,
@@ -780,8 +1067,9 @@ export class Virtualizer<
780
1067
  lanes,
781
1068
  laneAssignmentMode,
782
1069
  },
783
- itemSizeCache,
1070
+ _itemSizeCacheVersion,
784
1071
  ) => {
1072
+ const itemSizeCache = this.itemSizeCache
785
1073
  if (!enabled) {
786
1074
  this.measurementsCache = []
787
1075
  this.itemSizeCache.clear()
@@ -805,8 +1093,8 @@ export class Virtualizer<
805
1093
  this.measurementsCache = []
806
1094
  this.itemSizeCache.clear()
807
1095
  this.laneAssignments.clear() // Clear lane cache for new lane count
808
- // Clear pending indexes to force min = 0
809
- this.pendingMeasuredCacheIndexes = []
1096
+ // Force min = 0 on the rebuild
1097
+ this.pendingMin = null
810
1098
  }
811
1099
 
812
1100
  // Don't restore from initialMeasurementsCache during lane changes
@@ -818,19 +1106,62 @@ export class Virtualizer<
818
1106
  })
819
1107
  }
820
1108
 
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 = []
1109
+ // During lanes settling, ignore pendingMin to prevent repositioning
1110
+ const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0)
1111
+ this.pendingMin = null
828
1112
 
829
1113
  // ✅ End settling period when cache is fully built
830
1114
  if (this.lanesSettling && this.measurementsCache.length === count) {
831
1115
  this.lanesSettling = false
832
1116
  }
833
1117
 
1118
+ // ─── Fast path: single-lane lazy materialization ────────────────────
1119
+ // For lanes === 1 (the default and most common case), skip the
1120
+ // per-item VirtualItem object allocation. We write start/size pairs
1121
+ // into a Float64Array and return a Proxy that builds VirtualItem
1122
+ // objects on demand (only the indices a consumer actually reads).
1123
+ //
1124
+ // At n=100k this drops cold-mount cost from ~2.5ms (eager object
1125
+ // allocation) to roughly the cost of a single typed-array fill.
1126
+ if (lanes === 1) {
1127
+ const gap = this.options.gap
1128
+ // Reuse flat backing if large enough; else grow (preserving data
1129
+ // before `min` to mirror the slice-and-rebuild contract).
1130
+ const need = count * 2
1131
+ let flat = this._flatMeasurements
1132
+ if (!flat || flat.length < need) {
1133
+ const next = new Float64Array(need)
1134
+ if (flat && min > 0) next.set(flat.subarray(0, min * 2))
1135
+ flat = next
1136
+ this._flatMeasurements = flat
1137
+ }
1138
+
1139
+ let runningStart: number
1140
+ if (min === 0) {
1141
+ runningStart = paddingStart + scrollMargin
1142
+ } else {
1143
+ // Continue from where we left off
1144
+ const prevIdx = min - 1
1145
+ runningStart = flat[prevIdx * 2]! + flat[prevIdx * 2 + 1]! + gap
1146
+ }
1147
+
1148
+ for (let i = min; i < count; i++) {
1149
+ const key = getItemKey(i)
1150
+ const measuredSize = itemSizeCache.get(key)
1151
+ const size =
1152
+ typeof measuredSize === 'number'
1153
+ ? measuredSize
1154
+ : this.options.estimateSize(i)
1155
+ flat[i * 2] = runningStart
1156
+ flat[i * 2 + 1] = size
1157
+ runningStart += size + gap
1158
+ }
1159
+
1160
+ const view = createLazyMeasurementsView(count, flat, getItemKey)
1161
+ this.measurementsCache = view
1162
+ return view
1163
+ }
1164
+
834
1165
  const measurements = this.measurementsCache.slice(0, min)
835
1166
 
836
1167
  // ✅ Performance: Track last item index per lane for O(1) lookup
@@ -932,6 +1263,13 @@ export class Virtualizer<
932
1263
  outerSize,
933
1264
  scrollOffset,
934
1265
  lanes,
1266
+ // Pass the typed array so binary search + forward-walk can
1267
+ // read start/end directly from Float64Array, skipping the
1268
+ // Proxy traps that materialize a full VirtualItem per probe.
1269
+ flat:
1270
+ lanes === 1 && this._flatMeasurements != null
1271
+ ? this._flatMeasurements
1272
+ : null,
935
1273
  })
936
1274
  : null)
937
1275
  },
@@ -1056,30 +1394,73 @@ export class Virtualizer<
1056
1394
  }
1057
1395
 
1058
1396
  resizeItem = (index: number, size: number) => {
1059
- const item = this.measurementsCache[index]
1060
- if (!item) return
1397
+ if (index < 0 || index >= this.options.count) return
1398
+
1399
+ // Fast field reads. For lanes===1 we read raw start/size from the flat
1400
+ // typed array, avoiding a Proxy.get + VirtualItem allocation per call.
1401
+ // For lanes>1 we fall back to the cached VirtualItem array.
1402
+ let cachedSize: number
1403
+ let itemStart: number
1404
+ let key: Key
1405
+ const flat = this._flatMeasurements
1406
+ if (this.options.lanes === 1 && flat !== null) {
1407
+ key = this.options.getItemKey(index)
1408
+ itemStart = flat[index * 2]!
1409
+ cachedSize = flat[index * 2 + 1]!
1410
+ } else {
1411
+ const item = this.measurementsCache[index]
1412
+ if (!item) return
1413
+ key = item.key
1414
+ itemStart = item.start
1415
+ cachedSize = item.size
1416
+ }
1061
1417
 
1062
- const itemSize = this.itemSizeCache.get(item.key) ?? item.size
1418
+ const itemSize = this.itemSizeCache.get(key) ?? cachedSize
1063
1419
  const delta = size - itemSize
1064
1420
 
1065
1421
  if (delta !== 0) {
1066
- if (
1422
+ const wasAtEnd =
1423
+ this.options.anchorTo === 'end' &&
1424
+ this.scrollState?.behavior !== 'smooth' &&
1425
+ this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold
1426
+ const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0
1427
+ const shouldAdjustScroll =
1067
1428
  this.scrollState?.behavior !== 'smooth' &&
1068
1429
  (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined
1069
- ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this)
1070
- : item.start < this.getScrollOffset() + this.scrollAdjustments)
1071
- ) {
1072
- if (process.env.NODE_ENV !== 'production' && this.options.debug) {
1073
- console.info('correction', delta)
1074
- }
1075
- this._scrollToOffset(this.getScrollOffset(), {
1076
- adjustments: (this.scrollAdjustments += delta),
1077
- behavior: undefined,
1078
- })
1430
+ ? this.shouldAdjustScrollPositionOnItemSizeChange(
1431
+ // The callback expects a VirtualItem; build one lazily only
1432
+ // when the consumer actually supplied a custom predicate.
1433
+ this.measurementsCache[index] ?? {
1434
+ index,
1435
+ key,
1436
+ start: itemStart,
1437
+ size: cachedSize,
1438
+ end: itemStart + cachedSize,
1439
+ lane: 0,
1440
+ },
1441
+ delta,
1442
+ this,
1443
+ )
1444
+ : // Default: adjust scrollTop only when the resize is an above-
1445
+ // viewport item AND we're not actively scrolling backward.
1446
+ // Adjusting during backward scroll fights the user's scroll
1447
+ // direction and produces the "items jump while scrolling up"
1448
+ // jank reported across many issues. Users who want the old
1449
+ // behavior can pass shouldAdjustScrollPositionOnItemSizeChange.
1450
+ itemStart < this.getScrollOffset() + this.scrollAdjustments &&
1451
+ this.scrollDirection !== 'backward')
1452
+
1453
+ if (this.pendingMin === null || index < this.pendingMin) {
1454
+ this.pendingMin = index
1079
1455
  }
1456
+ this.itemSizeCache.set(key, size)
1457
+ this.itemSizeCacheVersion++
1080
1458
 
1081
- this.pendingMeasuredCacheIndexes.push(item.index)
1082
- this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size))
1459
+ if (wasAtEnd) {
1460
+ this.applyScrollAdjustment(this.getTotalSize() - prevTotalSize)
1461
+ } else if (shouldAdjustScroll) {
1462
+ this.applyScrollAdjustment(delta)
1463
+ }
1083
1464
 
1084
1465
  this.notify(false)
1085
1466
  }
@@ -1110,16 +1491,20 @@ export class Virtualizer<
1110
1491
  if (measurements.length === 0) {
1111
1492
  return undefined
1112
1493
  }
1113
- return notUndefined(
1114
- measurements[
1115
- findNearestBinarySearch(
1116
- 0,
1117
- measurements.length - 1,
1118
- (index: number) => notUndefined(measurements[index]).start,
1119
- offset,
1120
- )
1121
- ],
1494
+ // Same fast-path as calculateRange: read start values directly from the
1495
+ // typed array during binary search to skip the Proxy.get materialization
1496
+ // per probe.
1497
+ const flat = this._flatMeasurements
1498
+ const useFlat = this.options.lanes === 1 && flat != null
1499
+ const idx = findNearestBinarySearch(
1500
+ 0,
1501
+ measurements.length - 1,
1502
+ useFlat
1503
+ ? (i: number) => flat[i * 2]!
1504
+ : (i: number) => notUndefined(measurements[i]).start,
1505
+ offset,
1122
1506
  )
1507
+ return notUndefined(measurements[idx])
1123
1508
  }
1124
1509
 
1125
1510
  private getMaxScrollOffset = () => {
@@ -1139,6 +1524,21 @@ export class Virtualizer<
1139
1524
  }
1140
1525
  }
1141
1526
 
1527
+ private getVirtualDistanceFromEnd = () => {
1528
+ return Math.max(
1529
+ this.getTotalSize() - this.getSize() - this.getScrollOffset(),
1530
+ 0,
1531
+ )
1532
+ }
1533
+
1534
+ getDistanceFromEnd = () => {
1535
+ return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0)
1536
+ }
1537
+
1538
+ isAtEnd = (threshold = this.options.scrollEndThreshold) => {
1539
+ return this.getDistanceFromEnd() <= threshold
1540
+ }
1541
+
1142
1542
  getOffsetForAlignment = (
1143
1543
  toOffset: number,
1144
1544
  align: ScrollAlignment,
@@ -1274,6 +1674,20 @@ export class Virtualizer<
1274
1674
  this.scheduleScrollReconcile()
1275
1675
  }
1276
1676
 
1677
+ scrollToEnd = ({ behavior = 'auto' }: ScrollToEndOptions = {}) => {
1678
+ if (this.options.count > 0) {
1679
+ this.scrollToIndex(this.options.count - 1, {
1680
+ align: 'end',
1681
+ behavior,
1682
+ })
1683
+ return
1684
+ }
1685
+
1686
+ this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), {
1687
+ behavior,
1688
+ })
1689
+ }
1690
+
1277
1691
  getTotalSize = () => {
1278
1692
  const measurements = this.getMeasurements()
1279
1693
 
@@ -1284,7 +1698,16 @@ export class Virtualizer<
1284
1698
  if (measurements.length === 0) {
1285
1699
  end = this.options.paddingStart
1286
1700
  } else if (this.options.lanes === 1) {
1287
- end = measurements[measurements.length - 1]?.end ?? 0
1701
+ // Fast path: read last item's end directly from the flat typed array
1702
+ // when available; avoids a Proxy.get + VirtualItem materialization
1703
+ // just to call getTotalSize (which React renders trigger every commit).
1704
+ const lastIdx = measurements.length - 1
1705
+ const flat = this._flatMeasurements
1706
+ if (flat != null) {
1707
+ end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!
1708
+ } else {
1709
+ end = measurements[lastIdx]?.end ?? 0
1710
+ }
1288
1711
  } else {
1289
1712
  const endByLane = Array<number | null>(this.options.lanes).fill(null)
1290
1713
  let endIndex = measurements.length - 1
@@ -1306,6 +1729,39 @@ export class Virtualizer<
1306
1729
  )
1307
1730
  }
1308
1731
 
1732
+ /**
1733
+ * Returns a snapshot of currently-measured items suitable for round-
1734
+ * tripping through state storage (sessionStorage, history, etc.) and
1735
+ * passing back as `initialMeasurementsCache` on remount. Pair with the
1736
+ * current `scrollOffset` to restore exact scroll position after navigation.
1737
+ *
1738
+ * Only items the consumer has actually rendered (and thus measured) appear
1739
+ * in the snapshot; unmeasured items will fall back to `estimateSize` on
1740
+ * restore. Returns an empty array if no items have been measured.
1741
+ */
1742
+ takeSnapshot = (): Array<VirtualItem> => {
1743
+ const snapshot: Array<VirtualItem> = []
1744
+ if (this.itemSizeCache.size === 0) return snapshot
1745
+ // Iterate measurementsCache only for indices whose key is in itemSizeCache
1746
+ // (i.e., have been measured). We build VirtualItem objects with the
1747
+ // current start/size/end so they can be persisted as plain data.
1748
+ const m = this.getMeasurements()
1749
+ for (const item of m) {
1750
+ if (item && this.itemSizeCache.has(item.key)) {
1751
+ // Force materialization (lazy path) and copy plain fields.
1752
+ snapshot.push({
1753
+ index: item.index,
1754
+ key: item.key,
1755
+ start: item.start,
1756
+ size: item.size,
1757
+ end: item.end,
1758
+ lane: item.lane,
1759
+ })
1760
+ }
1761
+ }
1762
+ return snapshot
1763
+ }
1764
+
1309
1765
  private _scrollToOffset = (
1310
1766
  offset: number,
1311
1767
  {
@@ -1316,12 +1772,20 @@ export class Virtualizer<
1316
1772
  behavior: ScrollBehavior | undefined
1317
1773
  },
1318
1774
  ) => {
1775
+ // Record the intended logical scroll target so the next scroll event
1776
+ // can reconcile against subpixel rounding by the browser.
1777
+ this._intendedScrollOffset = offset + (adjustments ?? 0)
1319
1778
  this.options.scrollToFn(offset, { behavior, adjustments }, this)
1320
1779
  }
1321
1780
 
1322
1781
  measure = () => {
1323
- this.itemSizeCache = new Map()
1324
- this.laneAssignments = new Map() // Clear lane cache for full re-layout
1782
+ // Reset pendingMin so the next getMeasurements rebuilds from index 0.
1783
+ // Without this, a prior resizeItem() that left pendingMin > 0 would
1784
+ // cause the rebuild to preserve stale items before that index.
1785
+ this.pendingMin = null
1786
+ this.itemSizeCache.clear()
1787
+ this.laneAssignments.clear() // Clear lane cache for full re-layout
1788
+ this.itemSizeCacheVersion++
1325
1789
  this.notify(false)
1326
1790
  }
1327
1791
  }
@@ -1357,14 +1821,24 @@ function calculateRange({
1357
1821
  outerSize,
1358
1822
  scrollOffset,
1359
1823
  lanes,
1824
+ flat,
1360
1825
  }: {
1361
1826
  measurements: Array<VirtualItem>
1362
1827
  outerSize: number
1363
1828
  scrollOffset: number
1364
1829
  lanes: number
1830
+ flat: Float64Array | null
1365
1831
  }) {
1366
1832
  const lastIndex = measurements.length - 1
1367
- const getOffset = (index: number) => measurements[index]!.start
1833
+ // When the lanes===1 fast-path is active, read start/end directly from the
1834
+ // flat Float64Array instead of going through the lazy-view Proxy. Cuts
1835
+ // ~17 Proxy.get traps per scroll for the binary search alone.
1836
+ const getStart = flat
1837
+ ? (index: number) => flat[index * 2]!
1838
+ : (index: number) => measurements[index]!.start
1839
+ const getEnd = flat
1840
+ ? (index: number) => flat[index * 2]! + flat[index * 2 + 1]!
1841
+ : (index: number) => measurements[index]!.end
1368
1842
 
1369
1843
  // handle case when item count is less than or equal to lanes
1370
1844
  if (measurements.length <= lanes) {
@@ -1374,18 +1848,13 @@ function calculateRange({
1374
1848
  }
1375
1849
  }
1376
1850
 
1377
- let startIndex = findNearestBinarySearch(
1378
- 0,
1379
- lastIndex,
1380
- getOffset,
1381
- scrollOffset,
1382
- )
1851
+ let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset)
1383
1852
  let endIndex = startIndex
1384
1853
 
1385
1854
  if (lanes === 1) {
1386
1855
  while (
1387
1856
  endIndex < lastIndex &&
1388
- measurements[endIndex]!.end < scrollOffset + outerSize
1857
+ getEnd(endIndex) < scrollOffset + outerSize
1389
1858
  ) {
1390
1859
  endIndex++
1391
1860
  }