@tanstack/virtual-core 3.19.3 → 3.19.5

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
@@ -3,28 +3,20 @@ import {
3
3
  getMeasurementKey,
4
4
  } from './lazy-measurements'
5
5
  import { approxEqual, debounce, memo, notUndefined } from './utils'
6
+ import {
7
+ classifyScrollEvent,
8
+ externalRetiresCommand,
9
+ flingCaught,
10
+ flingSpedUp,
11
+ } from './scroll-classifier'
12
+ import {
13
+ IosGesture,
14
+ iosMomentumOverridesWrites,
15
+ isIOSWebKit,
16
+ } from './ios-gesture'
17
+ import type { ScrollPhase, ScrollSample } from './scroll-classifier'
6
18
 
7
- // Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
8
- // during a momentum-scroll cancel the momentum on iOS WebKit, so we defer
9
- // scroll-position adjustments triggered by mid-scroll resizes until the
10
- // scroll settles. SSR-safe (returns false when navigator is unavailable).
11
- let _isIOSResult: boolean | undefined
12
- const isIOSWebKit = (): boolean => {
13
- if (_isIOSResult !== undefined) return _isIOSResult
14
- if (typeof navigator === 'undefined') return (_isIOSResult = false)
15
- if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)
16
- // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.
17
- const mtp = (navigator as Navigator & { maxTouchPoints?: number })
18
- .maxTouchPoints
19
- return (_isIOSResult =
20
- navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)
21
- }
22
-
23
- // Test hook: reset the iOS detection cache. Not exported.
24
- export const _resetIOSDetectionForTests = () => {
25
- _isIOSResult = undefined
26
- }
27
-
19
+ export { _resetIOSDetectionForTests } from './ios-gesture'
28
20
  export { approxEqual, debounce, memo, notUndefined } from './utils'
29
21
  export type { NoInfer, PartialKeys } from './utils'
30
22
 
@@ -86,6 +78,25 @@ const getRect = (element: HTMLElement): Rect => {
86
78
  return { width: offsetWidth, height: offsetHeight }
87
79
  }
88
80
 
81
+ // Animation frames for `useAnimationFrameWithResizeObserver`, requested from
82
+ // the scroll element's own window rather than the global one.
83
+ const createFrameQueue = (targetWindow: Window) => {
84
+ const ids = new Set<number>()
85
+ return {
86
+ schedule: (fn: () => void) => {
87
+ const id = targetWindow.requestAnimationFrame(() => {
88
+ ids.delete(id)
89
+ fn()
90
+ })
91
+ ids.add(id)
92
+ },
93
+ cancel: () => {
94
+ ids.forEach((id) => targetWindow.cancelAnimationFrame(id))
95
+ ids.clear()
96
+ },
97
+ }
98
+ }
99
+
89
100
  export const defaultKeyExtractor = (index: number) => index
90
101
 
91
102
  export const defaultRangeExtractor = (range: Range) => {
@@ -129,6 +140,7 @@ export const observeElementRect = <T extends Element>(
129
140
  return () => {}
130
141
  }
131
142
 
143
+ const frames = createFrameQueue(targetWindow)
132
144
  const observer = new targetWindow.ResizeObserver((entries) => {
133
145
  const run = () => {
134
146
  const entry = entries[0]
@@ -143,7 +155,7 @@ export const observeElementRect = <T extends Element>(
143
155
  }
144
156
 
145
157
  instance.options.useAnimationFrameWithResizeObserver
146
- ? requestAnimationFrame(run)
158
+ ? frames.schedule(run)
147
159
  : run()
148
160
  })
149
161
 
@@ -151,6 +163,7 @@ export const observeElementRect = <T extends Element>(
151
163
 
152
164
  return () => {
153
165
  observer.unobserve(element)
166
+ frames.cancel()
154
167
  }
155
168
  }
156
169
 
@@ -388,15 +401,6 @@ export interface VirtualizerOptions<
388
401
  useCachedMeasurements?: boolean
389
402
  }
390
403
 
391
- // Where an in-flight scroll command is in its lifecycle, which decides how
392
- // its scroll events and measurements are read:
393
- // smooth a smooth animation is travelling to the target
394
- // smoothLanded a smooth scroll is at its target, waiting to retire
395
- // smoothFinishing a smooth scroll switched to instant writes for the
396
- // final approach; its animation can still report positions
397
- // instant instant writes
398
- type ScrollPhase = 'smooth' | 'smoothLanded' | 'smoothFinishing' | 'instant'
399
-
400
404
  type ScrollState = {
401
405
  // what we want
402
406
  index: number | null
@@ -406,6 +410,8 @@ type ScrollState = {
406
410
 
407
411
  // lifecycle
408
412
  startedAt: number
413
+ // how the command was asked to scroll; a queued command writes with it
414
+ behavior: ScrollBehavior
409
415
 
410
416
  // target tracking
411
417
  lastTargetOffset: number
@@ -413,6 +419,11 @@ type ScrollState = {
413
419
  // settling
414
420
  stableFrames: number
415
421
  phase: ScrollPhase
422
+
423
+ // A `queued` command's view of the fling it waits for: the scroll events
424
+ // since it was queued, at most the last 200ms (`flingSpedUp`,
425
+ // `flingCaught`). Read only while `queued`.
426
+ samples?: Array<ScrollSample>
416
427
  }
417
428
 
418
429
  const initialScrollPhase = (
@@ -426,11 +437,6 @@ const initialScrollPhase = (
426
437
  const isSmoothScroll = (state: ScrollState | null): state is ScrollState =>
427
438
  state?.phase === 'smooth' || state?.phase === 'smoothLanded'
428
439
 
429
- // The smooth animation may still be reporting positions, so a scroll event
430
- // that isn't the read-back of our own write may not be the user.
431
- const isAnimating = (state: ScrollState) =>
432
- state.phase === 'smooth' || state.phase === 'smoothFinishing'
433
-
434
440
  // What `setOptions` decided about the scroll position for `_willUpdate` to
435
441
  // carry out once the consumer has rendered: keep the reading anchor in place
436
442
  // after a prepend (`scrollOffset` already moved by `delta`, the element has
@@ -497,37 +503,106 @@ export class Virtualizer<
497
503
  private lanesSettling = false
498
504
  private pendingScrollAnchor: PendingScrollAnchor | null = null
499
505
  scrollRect: Rect | null = null
506
+ /**
507
+ * The scroll position in the list's layout, consistent with
508
+ * `getOffsetForIndex`, `scrollToOffset` and `initialOffset`. While a
509
+ * correction is held (`_holdOffset`), `getVirtualItems()` and
510
+ * `getTotalSize()` describe what is rendered, shifted by the held amount;
511
+ * this stays the layout position.
512
+ */
500
513
  scrollOffset: number | null = null
501
514
  scrollDirection: ScrollDirection | null = null
502
- // Size compensation written to the element but not yet reflected in
503
- // `scrollOffset`: the element is expected at `scrollOffset +
504
- // scrollAdjustments` until the next scroll event reports it.
515
+ /**
516
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
517
+ * at once, so there is never an outstanding adjustment to add to it. Read
518
+ * `scrollOffset` alone.
519
+ */
505
520
  get scrollAdjustments() {
506
- return this.pendingWrite?.adjustments ?? 0
507
- }
508
- // Sum of size-change deltas above-viewport that were skipped during
509
- // iOS momentum scroll (writing scrollTop mid-momentum cancels it).
510
- // Flushed in a single scrollTo when iOS is fully settled.
511
- private _iosDeferredAdjustment = 0
512
- // The touch gesture in progress. iOS WebKit cancels momentum when
513
- // scrollTop is written, so adjustments are deferred not only during
514
- // `isScrolling` but through the whole gesture: `down` from touchstart to
515
- // touchend/touchcancel (active drag), then `tail` for a short grace window
516
- // after the finger lifts (early momentum — iOS fires touch events only
517
- // once at the start of momentum, so the tail is a timer rather than
518
- // another event). Null between gestures, and after touchend on non-iOS,
519
- // which arms no tail. The tail record owns its timer: `_endIosTouch` is
520
- // the only way to drop either, so a cleared record never leaves a timer
521
- // behind, and a live timer always has its record.
522
- private _iosTouch:
523
- | { phase: 'down' }
524
- | { phase: 'tail'; timerId: number }
525
- | null = null
521
+ return 0
522
+ }
523
+ // Scroll corrections (a prepend's anchor delta, size changes above the
524
+ // viewport) that could not be written to the element because a write was
525
+ // impossible at the time (see `_canWriteScroll`): the difference between
526
+ // `scrollOffset`, which always carries the corrected layout position, and
527
+ // where the element is. While it is non-zero the rows and the total size
528
+ // are exposed shifted by `-_holdOffset`, so every adapter renders the
529
+ // reader's row where it was, writes subtract it (`_scrollToOffset`) and
530
+ // scroll events add it back (the handler in `_willUpdate`). Released by
531
+ // `_flushHoldIfReady`: the rows re-render in layout coordinates and the
532
+ // element moves by the same amount in one paint.
533
+ private _holdOffset = 0
534
+ // Whether the element's last scroll event reported a position past either
535
+ // edge (the rubber-band bounce). Judged at report time against the
536
+ // element's own max, with a 1px tolerance for a fractional scrollTop: a
537
+ // sizer that shrinks after the report (a trim) is not a bounce, and
538
+ // `scrollOffset` is no judge either, since an eager bump past the max while
539
+ // the sizer has not grown yet (#1258) is not one.
540
+ //
541
+ // Stored rather than read from the element when a write is decided. The
542
+ // two differ once a write has landed but not been reported back, and in
543
+ // that window the element reads in bounds while `scrollOffset` is still
544
+ // the pre-write value. With the anchor sync now skipped in that window
545
+ // (`_awaitingCommandReadBack`), the remaining difference is the trim: a
546
+ // list that shrank under the position reads past the element's max until
547
+ // the browser clamps it, which is where the anchor's write has to go
548
+ // (`followOnAppend does not follow 'trim only'`; reading the element at
549
+ // write time still moves 49 of 1080 snapshot seeds).
550
+ private _reportedOverscroll = false
551
+ // The touch gesture in progress (see `IosGesture`). Its tail closing on
552
+ // its own makes a write possible again: the last momentum frame may have
553
+ // come before the timer. The hold is released first, so a command that
554
+ // waited for the tail is written over rows already back in layout
555
+ // coordinates.
556
+ private _iosGesture = new IosGesture({
557
+ getWindow: () => this.targetWindow,
558
+ now: () => this.now(),
559
+ // The end of a fling can move less than a pixel per scroll event, so
560
+ // events can stop for 150ms while the fling is still running (seen on
561
+ // an iPhone, 27.0.1). A command waiting for it would then be written
562
+ // into the fling and overridden. The element having moved since the
563
+ // last event means it has not ended: wait again. Not while our own
564
+ // write has yet to report: that moved it.
565
+ tailStillMoving: () => {
566
+ const state = this.scrollState
567
+ if (state?.phase !== 'queued' || this.pendingWrite !== null) {
568
+ return false
569
+ }
570
+ const now = this._readElementOffset()
571
+ if (
572
+ now === null ||
573
+ this._lastElementOffset === null ||
574
+ Math.abs(now - this._lastElementOffset) < 1
575
+ ) {
576
+ return false
577
+ }
578
+ this._lastElementOffset = now
579
+ // It moved with no event: a sample, so the speed `flingCaught` reads
580
+ // when it stops is not the one from before the silence.
581
+ state.samples = [...(state.samples ?? []), { t: this.now(), offset: now }]
582
+ return true
583
+ },
584
+ onTailClosed: () => {
585
+ // A fling that stopped at speed was caught by a finger that is still
586
+ // down, with no touch events: the user has taken over, as with a
587
+ // drag, and iOS would undo the write anyway.
588
+ const state = this.scrollState
589
+ if (state?.phase === 'queued' && flingCaught(state.samples ?? [])) {
590
+ this.scrollState = null
591
+ }
592
+ this._flushHoldIfReady(true)
593
+ this._writeAwaitingCommand()
594
+ },
595
+ })
596
+ // The last position the scroll handler was given, in the element's own
597
+ // coordinates. The tail compares it with the element (`tailStillMoving`
598
+ // above).
599
+ private _lastElementOffset: number | null = null
526
600
  // Our last write to the element, from `_scrollToOffset` until the next
527
601
  // scroll event reports it (the only place it is cleared). Until then
528
602
  // `scrollOffset` may still hold the old position.
529
603
  //
530
- // - `target`: where the write puts the element (offset + adjustments).
604
+ // - `target`: where the write puts the element (offset + the adjustment
605
+ // passed to `scrollToFn`).
531
606
  // Safari (and Chrome/Firefox under certain DPRs) round writes to whole
532
607
  // pixels: wrote 12345.5, read back 12346. A read-back within 1.5px of
533
608
  // `target` is taken as our own and adopts the exact value, so reconcile
@@ -535,12 +610,17 @@ export class Virtualizer<
535
610
  // further by the time it reports.
536
611
  // - `smooth`: the write animates, so until it lands the element is
537
612
  // somewhere between the old offset and `target`.
538
- // - `adjustments`: see `scrollAdjustments`. Writes that pass none keep the
539
- // previous value.
613
+ // - `lowMaxes`: for a command's instant write, each scroll max below
614
+ // `target` the element had since the write. A command's target is
615
+ // clamped to the max at the write, but the sizer can shrink under it
616
+ // before the report (rows measured smaller, a count change) and grow
617
+ // back, so the read-back is the max the browser clamped to then rather
618
+ // than the element's current one. Read wherever the sizer can have
619
+ // been committed (`_noteClampMax`).
540
620
  private pendingWrite: {
541
621
  target: number
542
622
  smooth: boolean
543
- adjustments: number
623
+ lowMaxes?: Array<number>
544
624
  } | null = null
545
625
  // A compensation write from `applyScrollAdjustment` whose target exceeded
546
626
  // the element's scroll max at the moment of the write. The browser clamps
@@ -566,17 +646,20 @@ export class Virtualizer<
566
646
  private now = () => this.targetWindow?.performance?.now?.() ?? Date.now()
567
647
  private observer = (() => {
568
648
  let _ro: ResizeObserver | null = null
649
+ let _frames: ReturnType<typeof createFrameQueue> | null = null
569
650
 
570
651
  const get = () => {
571
652
  if (_ro) {
572
653
  return _ro
573
654
  }
574
655
 
575
- if (!this.targetWindow || !this.targetWindow.ResizeObserver) {
656
+ const targetWindow = this.targetWindow
657
+ if (!targetWindow || !targetWindow.ResizeObserver) {
576
658
  return null
577
659
  }
578
660
 
579
- return (_ro = new this.targetWindow.ResizeObserver((entries) => {
661
+ const frames = (_frames = createFrameQueue(targetWindow))
662
+ return (_ro = new targetWindow.ResizeObserver((entries) => {
580
663
  const run = () => {
581
664
  // Measure every entry before notifying. A notify that adjusted
582
665
  // scroll re-renders synchronously, and that render can unmount
@@ -591,12 +674,14 @@ export class Virtualizer<
591
674
  this._resizeBatch = null
592
675
  if (batch.notify) {
593
676
  this.notify(batch.sync)
677
+ this._noteClampMax()
678
+ this._flushHoldIfReady(true)
594
679
  this._retryClampedAdjustment()
595
680
  }
596
681
  }
597
682
  }
598
683
  this.options.useAnimationFrameWithResizeObserver
599
- ? requestAnimationFrame(run)
684
+ ? frames.schedule(run)
600
685
  : run()
601
686
  }))
602
687
  }
@@ -634,7 +719,9 @@ export class Virtualizer<
634
719
  return {
635
720
  disconnect: () => {
636
721
  get()?.disconnect()
722
+ _frames?.cancel()
637
723
  _ro = null
724
+ _frames = null
638
725
  },
639
726
  observe: (target: Element) =>
640
727
  get()?.observe(target, { box: 'border-box' }),
@@ -772,8 +859,18 @@ export class Virtualizer<
772
859
  // the virtualizer would render the wrong items for one frame (the
773
860
  // estimate-based positions are stale) and then correct in the next
774
861
  // frame, producing a visible "jump" on prepend with dynamic sizes.
862
+ // Not before a scroll command's write has been read back: `scrollOffset`
863
+ // is still the pre-command position, so the anchor would be resolved
864
+ // against rows that are no longer where the command put the element, and
865
+ // the sync would write that stale offset over the command. Reconcile
866
+ // retargets an index or end command from the new layout; an offset
867
+ // command lands where it was written (#1307, step 5).
775
868
  let anchorDelta: number | null = null
776
- if (anchor && this.scrollOffset !== null) {
869
+ if (
870
+ anchor &&
871
+ this.scrollOffset !== null &&
872
+ !this._awaitingCommandReadBack()
873
+ ) {
777
874
  const [anchorKey, anchorOffset] = anchor
778
875
  const newMeasurements = this.getMeasurements()
779
876
  const { count, getItemKey } = this.options
@@ -801,7 +898,16 @@ export class Virtualizer<
801
898
  if (followOnAppend) {
802
899
  this.pendingScrollAnchor = { kind: 'follow', behavior: followOnAppend }
803
900
  } else if (anchorDelta !== null) {
804
- this.pendingScrollAnchor = { kind: 'anchor', delta: anchorDelta }
901
+ if (this._canWriteScroll()) {
902
+ this.pendingScrollAnchor = { kind: 'anchor', delta: anchorDelta }
903
+ } else {
904
+ // The element cannot take the write (a touch owns it on iOS, or it is
905
+ // overscrolled). Hold the delta instead: this render already exposes
906
+ // the rows and the total shifted back by it, so the reader's row
907
+ // stays put, and the flush writes it once a write is possible.
908
+ this._holdOffset += anchorDelta
909
+ this._followOffsetTarget(anchorDelta)
910
+ }
805
911
  }
806
912
  }
807
913
 
@@ -823,28 +929,23 @@ export class Virtualizer<
823
929
  console.info('correction', delta)
824
930
  }
825
931
 
826
- if (isIOSWebKit() && this._iosInMotion()) {
827
- // An index scroll retargets from fresh measurements in reconcileScroll;
828
- // replaying this delta after it lands would count it twice.
829
- if (this.scrollState?.index == null) {
830
- this._iosDeferredAdjustment += delta
831
- }
832
- return false
932
+ // The correction moves the content the viewport is on; an offset target
933
+ // moves with it, or reconcile would wait for a position it can never see.
934
+ this._followOffsetTarget(delta)
935
+
936
+ if (!this._canWriteScroll()) {
937
+ // Hold the correction: `scrollOffset` takes it as if written, the rows
938
+ // are exposed shifted back by it. The notify must be synchronous like
939
+ // a write's, so the shifted rows commit in the same paint as the
940
+ // content change that caused the correction.
941
+ this._holdOffset += delta
942
+ if (this.scrollOffset !== null) this.scrollOffset += delta
943
+ return true
833
944
  } else {
834
- const target = this.getScrollOffset() + this.scrollAdjustments + delta
835
- // Guarded so a bare test double without `scrollHeight` / `document`
836
- // does not crash in `getMaxScrollOffset`.
837
- const el = this.scrollElement
838
- const maxAtWrite =
839
- el !== null && ('scrollHeight' in el || 'document' in el)
840
- ? this.getMaxScrollOffset()
841
- : null
842
- this._clampedAdjustment =
843
- maxAtWrite !== null && target > maxAtWrite + 0.5
844
- ? { target, maxAtWrite }
845
- : null
846
- this._scrollToOffset(this.getScrollOffset(), {
847
- adjustments: this.scrollAdjustments + delta,
945
+ const offset = this.getScrollOffset()
946
+ this._clampedAdjustment = this._clampedBy(offset + delta)
947
+ const write = this._scrollToOffset(offset, {
948
+ adjustments: delta,
848
949
  behavior,
849
950
  })
850
951
  // Eagerly carry the intended target in `scrollOffset` so callers that
@@ -853,19 +954,18 @@ export class Virtualizer<
853
954
  // post-adjustment position even when the DOM `scrollTop` write was
854
955
  // clamped because the consumer hasn't grown the sizer yet (`notify()`
855
956
  // runs after this in `resizeItem`). Same idea as the eager
856
- // `scrollOffset` adjustment for prepend in `setOptions` (#1176). The
857
- // adjustment is now baked into `scrollOffset`, so zero
858
- // `scrollAdjustments` to keep their sum invariant.
957
+ // `scrollOffset` adjustment for prepend in `setOptions` (#1176). A
958
+ // `scrollToFn` that reports the write synchronously has already set
959
+ // `scrollOffset` to the read-back (and cleared `pendingWrite`).
859
960
  if (this.scrollOffset !== null) {
860
- this.scrollOffset += this.scrollAdjustments
961
+ if (this.pendingWrite === write) this.scrollOffset += delta
861
962
  // Clamp only the lower bound: a negative offset is unreachable, and
862
963
  // on an unscrollable element (content fits the viewport) no scroll
863
964
  // event ever fires to correct it, permanently skewing
864
- // getDistanceFromEnd() and wedging _flushIosDeferredIfReady (#1229).
965
+ // getDistanceFromEnd() and wedging the hold flush (#1229).
865
966
  // Upper-bound overflow stays untouched — it is transiently
866
967
  // legitimate mid-prepend while the consumer's sizer catches up.
867
968
  if (this.scrollOffset < 0) this.scrollOffset = 0
868
- if (this.pendingWrite) this.pendingWrite.adjustments = 0
869
969
  }
870
970
  return true
871
971
  }
@@ -904,6 +1004,10 @@ export class Virtualizer<
904
1004
  this.rafId = null
905
1005
  }
906
1006
  this.scrollState = null
1007
+ // The element is let go of: give it back its overflow now. A stop the
1008
+ // next element needs starts afresh.
1009
+ this._momentumStop?.restore()
1010
+ this._momentumStop = null
907
1011
  // The debounce cancelled above is the only thing that writes `isScrolling`
908
1012
  // back to false, so a cleanup inside the reset window would strand it, and
909
1013
  // the direction derived from it, as true. That matters because `cleanup`
@@ -917,11 +1021,12 @@ export class Virtualizer<
917
1021
  // capture), so the new element never reports it. Carrying the state
918
1022
  // over would replay a stale deferred delta on the new element's first
919
1023
  // flush, and a cleanup that lands mid-touch or inside the post-touchend
920
- // grace window would strand `_iosTouch` (the listeners that end it were
1024
+ // grace window would strand the gesture (the listeners that end it were
921
1025
  // just removed), deferring every adjustment on the new element until
922
1026
  // its next touch cycle.
923
- this._iosDeferredAdjustment = 0
924
- this._endIosTouch()
1027
+ this._holdOffset = 0
1028
+ this._reportedOverscroll = false
1029
+ // (The gesture was ended with its listeners, in the unsubs above.)
925
1030
  this._clampedAdjustment = null
926
1031
  // A write to the old element will never be read back.
927
1032
  this.pendingWrite = null
@@ -969,50 +1074,47 @@ export class Virtualizer<
969
1074
 
970
1075
  this.unsubs.push(
971
1076
  this.options.observeElementOffset(this, (offset, isScrolling) => {
972
- // A scroll event that reports movement but lands on the offset we
973
- // already hold — and isn't a self-write read-back — is a spurious
974
- // no-op re-emit that Safari/Firefox fire after a re-render's layout
975
- // (Chrome doesn't). Treating it as scrolling re-arms `isScrolling`,
976
- // which forces a render that triggers another such event: an
977
- // infinite re-render loop. Ignore it. (Self-writes are matched to
978
- // `pendingWrite` just below.)
979
- if (
980
- isScrolling &&
981
- this.pendingWrite === null &&
982
- offset === this.scrollOffset
983
- ) {
984
- return
985
- }
1077
+ // Past the top is never a resting position. Past the bottom is
1078
+ // judged only while scrolling: at rest the element has clamped,
1079
+ // and a stale sizer makes no bounce.
1080
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null
1081
+ const wasOverscrolled = this._reportedOverscroll
1082
+ this._reportedOverscroll =
1083
+ offset < 0 || (elementMax !== null && offset > elementMax + 1)
1084
+ const elementOffset = offset
1085
+ this._lastElementOffset = elementOffset
1086
+ // Everything below works in layout coordinates.
1087
+ offset = this._toLayoutOffset(offset)
1088
+
1089
+ const kind = this._classifyScrollEvent(
1090
+ offset,
1091
+ isScrolling,
1092
+ elementMax,
1093
+ )
1094
+ if (kind === 'spurious') return
986
1095
 
987
- // The read-back of our own write: adopt the exact target over the
988
- // browser's rounded value (see `pendingWrite`).
989
- const pending = this.pendingWrite
990
- if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
991
- offset = pending.target
1096
+ if (kind === 'readBack') {
1097
+ // Adopt the exact target over the browser's rounded value (see
1098
+ // `pendingWrite`).
1099
+ offset = this.pendingWrite!.target
992
1100
  } else if (
1101
+ kind === 'clampedReadBack' &&
993
1102
  this.scrollState?.index != null &&
994
- // A non-smooth write lands at once, so any other scroll event is
995
- // the user's, even before reconcile saw the target reached (the
996
- // target may keep moving, or iOS ignored the write under a
997
- // finger). A write the browser clamped because the sizer hasn't
998
- // grown yet reads back at the max, which is also where the fresh
999
- // target clamps, so the check below keeps it reconciling (#1294).
1000
- // Not when rows above the target shrink before the read-back and
1001
- // pull the target below the new max: the read-back then looks
1002
- // like the user and the scroll stops at the max. That needs the
1003
- // sizer re-rendered before the scroll event, which browsers have
1004
- // not been seen to do (pinned by a `.fails` test).
1005
- // While a smooth scroll's animation may still report, its events
1006
- // look like a user's, so it yields only once it has landed.
1007
- !isAnimating(this.scrollState) &&
1008
- !approxEqual(offset, this.scrollState.lastTargetOffset) &&
1009
- !approxEqual(offset, this.getScrollStateTarget(this.scrollState)) &&
1010
- (this._clampedAdjustment === null ||
1011
- Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5)
1103
+ // Not `elementMax`: an adapter can report the read-back at rest.
1104
+ offset < this.getMaxScrollOffset() - 1.5
1105
+ ) {
1106
+ // Our write, clamped at a max the sizer has since grown back
1107
+ // from: reconcile writes the target again, even when the layout
1108
+ // came back to the same end.
1109
+ this.scrollState.lastTargetOffset = offset
1110
+ } else if (
1111
+ externalRetiresCommand({
1112
+ kind,
1113
+ offset,
1114
+ command: this.scrollState,
1115
+ target: () => this.getScrollStateTarget(this.scrollState!),
1116
+ })
1012
1117
  ) {
1013
- // An external scroll moved away from the index scroll's target.
1014
- // Our own measurement updates (including clamped writes) still
1015
- // need to reconcile.
1016
1118
  this.scrollState = null
1017
1119
  }
1018
1120
  this.pendingWrite = null
@@ -1021,6 +1123,9 @@ export class Virtualizer<
1021
1123
  // own read-back, which the browser reports at the scroll max we
1022
1124
  // saw at write time. Anything else is a real gesture (or the write
1023
1125
  // landing after all), so drop it rather than yank the user later.
1126
+ // Not `kind !== 'clampedEcho'`: the classifier ranks `readBack` and
1127
+ // `clampedReadBack` first, and either can also sit at that max, so
1128
+ // the record must survive them too.
1024
1129
  if (
1025
1130
  this._clampedAdjustment !== null &&
1026
1131
  Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5
@@ -1033,6 +1138,7 @@ export class Virtualizer<
1033
1138
  // into `scrollOffset`. There's no direction to infer, so leave
1034
1139
  // it alone; a real gesture always moves the offset.
1035
1140
  const prevOffset = this.getScrollOffset()
1141
+ const prevDirection = this.scrollDirection
1036
1142
  this.scrollDirection = isScrolling
1037
1143
  ? prevOffset === offset
1038
1144
  ? this.scrollDirection
@@ -1043,10 +1149,57 @@ export class Virtualizer<
1043
1149
  this.scrollOffset = offset
1044
1150
  this.isScrolling = isScrolling
1045
1151
 
1046
- // Flush deferred iOS adjustments if we're now fully settled.
1047
- // "Fully settled" means: not actively scrolling, no finger on
1048
- // screen, and the post-touchend grace window has expired.
1049
- this._flushIosDeferredIfReady()
1152
+ // A finger that lands on a fling fires no touch events (#1307), so
1153
+ // while a command waits for the fling, the scroll events are all
1154
+ // that show the user taking over: the scroll turns back, or speeds
1155
+ // up (`flingSpedUp`). Momentum does neither inside the scroll
1156
+ // range; a bounce does both, so no part of one counts.
1157
+ const queued = this.scrollState
1158
+ if (
1159
+ queued?.phase === 'queued' &&
1160
+ kind === 'external' &&
1161
+ isScrolling
1162
+ ) {
1163
+ if (wasOverscrolled || this._reportedOverscroll) {
1164
+ queued.samples = []
1165
+ } else {
1166
+ const t = this.now()
1167
+ queued.samples = [
1168
+ ...(queued.samples ?? []).filter(
1169
+ (sample) => t - sample.t <= 200,
1170
+ ),
1171
+ { t, offset: elementOffset },
1172
+ ]
1173
+ if (
1174
+ (prevDirection !== null &&
1175
+ this.scrollDirection !== prevDirection) ||
1176
+ flingSpedUp(queued.samples)
1177
+ ) {
1178
+ this.scrollState = null
1179
+ }
1180
+ }
1181
+ }
1182
+ if (
1183
+ this._iosGesture.onScroll({
1184
+ isScrolling,
1185
+ ownReadBack: kind === 'readBack',
1186
+ moved: offset !== prevOffset,
1187
+ // Neither our write's read-back nor a frame of our smooth
1188
+ // animation: the user or a fling moved it.
1189
+ external:
1190
+ kind === 'external' &&
1191
+ this.scrollState?.phase !== 'smooth' &&
1192
+ this.scrollState?.phase !== 'smoothFinishing',
1193
+ }) &&
1194
+ // The user scrolls: a command still waiting for the tail is
1195
+ // theirs to override, like a written one would be.
1196
+ this.scrollState?.phase === 'queued'
1197
+ ) {
1198
+ this.scrollState = null
1199
+ }
1200
+
1201
+ // A held correction is written once a write is possible.
1202
+ this._flushHoldIfReady(true)
1050
1203
 
1051
1204
  if (this.scrollState) {
1052
1205
  this.scheduleScrollReconcile()
@@ -1055,66 +1208,19 @@ export class Virtualizer<
1055
1208
  }),
1056
1209
  )
1057
1210
 
1058
- // Touch event listeners (iOS-aware deferral). We attach unconditionally
1059
- // — the listeners are passive and cheap; on non-touch devices they
1060
- // simply never fire. The gating by isIOSWebKit() lives in resizeItem
1061
- // and _flushIosDeferredIfReady so we only burn the path on iOS.
1211
+ // Touch event listeners (iOS-aware deferral).
1062
1212
  if ('addEventListener' in this.scrollElement) {
1063
- const scrollEl = this.scrollElement as unknown as EventTarget
1064
- const onTouchStart = () => {
1065
- // A finger back down inside the grace window cancels its tail.
1066
- this._endIosTouch()
1067
- this._iosTouch = { phase: 'down' }
1068
- }
1069
- const onTouchEnd = () => {
1070
- this._endIosTouch()
1071
- if (!isIOSWebKit() || this.targetWindow == null) {
1072
- // Non-iOS: nothing more to track.
1073
- return
1074
- }
1075
- // After ~150 ms with no scroll/touch events, momentum is done.
1076
- const tail = {
1077
- phase: 'tail' as const,
1078
- timerId: this.targetWindow.setTimeout(() => {
1079
- if (this._iosTouch === tail) this._iosTouch = null
1080
- // After the grace window, attempt to flush. The scroll event
1081
- // for momentum decay may have already fired before our timer.
1082
- this._flushIosDeferredIfReady()
1083
- }, 150),
1084
- }
1085
- this._iosTouch = tail
1086
- }
1087
- scrollEl.addEventListener(
1088
- 'touchstart',
1089
- onTouchStart,
1090
- addEventListenerOptions,
1213
+ this.unsubs.push(
1214
+ this._iosGesture.listen(this.scrollElement as unknown as EventTarget),
1091
1215
  )
1092
- scrollEl.addEventListener(
1093
- 'touchend',
1094
- onTouchEnd,
1095
- addEventListenerOptions,
1096
- )
1097
- // Same handler as touchend: iOS can end a touch with touchcancel
1098
- // (system gesture, interrupted scroll) and never fire touchend.
1099
- scrollEl.addEventListener(
1100
- 'touchcancel',
1101
- onTouchEnd,
1102
- addEventListenerOptions,
1103
- )
1104
- this.unsubs.push(() => {
1105
- scrollEl.removeEventListener('touchstart', onTouchStart)
1106
- scrollEl.removeEventListener('touchend', onTouchEnd)
1107
- scrollEl.removeEventListener('touchcancel', onTouchEnd)
1108
- this._endIosTouch()
1109
- })
1110
1216
  }
1111
1217
 
1112
- this._scrollToOffset(this.getScrollOffset(), {
1113
- adjustments: undefined,
1114
- behavior: undefined,
1115
- })
1218
+ this._scrollToOffset(this.getScrollOffset())
1116
1219
  }
1117
1220
 
1221
+ // The consumer has committed the sizer.
1222
+ this._noteClampMax()
1223
+
1118
1224
  const anchor = this.pendingScrollAnchor
1119
1225
  this.pendingScrollAnchor = null
1120
1226
 
@@ -1124,12 +1230,14 @@ export class Virtualizer<
1124
1230
  // virtualizer already computed the correct range during render.
1125
1231
  // Now sync the browser's actual scroll position to match.
1126
1232
  //
1127
- // On iOS WebKit, writing scrollTop during touch/momentum cancels
1128
- // the in-flight scroll. Defer the DOM sync the same way
1129
- // applyScrollAdjustment does — accumulate the delta and let
1130
- // _flushIosDeferredIfReady handle it once the scroll settles.
1131
- if (isIOSWebKit() && this._iosInMotion()) {
1132
- this._iosDeferredAdjustment += anchor.delta
1233
+ // `setOptions` found the element writable; a scroll event between
1234
+ // it and this commit (a concurrent render) can have changed that.
1235
+ // Hold the delta after all and have the rows re-rendered shifted;
1236
+ // an update scheduled from a layout effect commits before paint.
1237
+ if (!this._canWriteScroll()) {
1238
+ this._holdOffset += anchor.delta
1239
+ this._followOffsetTarget(anchor.delta)
1240
+ this.notify(false)
1133
1241
  } else if (
1134
1242
  isSmoothScroll(this.scrollState) &&
1135
1243
  !approxEqual(
@@ -1146,21 +1254,43 @@ export class Virtualizer<
1146
1254
  // A smooth scroll that has already landed (offset at its target,
1147
1255
  // reconcile not yet retired it) still gets the anchor sync.
1148
1256
  } else {
1149
- this._scrollToOffset(this.getScrollOffset(), {
1150
- adjustments: undefined,
1151
- behavior: undefined,
1152
- })
1257
+ this._followOffsetTarget(anchor.delta)
1258
+ this._scrollToOffset(this.getScrollOffset())
1153
1259
  }
1154
1260
  } else {
1155
1261
  this.scrollToEnd({ behavior: anchor.behavior })
1156
1262
  }
1157
1263
  }
1158
1264
 
1265
+ // A hold whose cause has passed without a scroll event (the sizer caught
1266
+ // up with a position that read as overscrolled) is written here. An
1267
+ // update scheduled from a layout effect commits before paint, so the
1268
+ // notify need not be synchronous.
1269
+ this._flushHoldIfReady(false)
1159
1270
  // The consumer has committed the new total size by now, so a clamped
1160
1271
  // compensation write may have room (#1258).
1161
1272
  this._retryClampedAdjustment()
1162
1273
  }
1163
1274
 
1275
+ // Classify a scroll event (see `ScrollEventKind`) from the state as it was
1276
+ // before the event. `offset` is the reported position in layout
1277
+ // coordinates; `elementMax` is the element's own max, read only while
1278
+ // scrolling (null otherwise).
1279
+ private _classifyScrollEvent = (
1280
+ offset: number,
1281
+ isScrolling: boolean,
1282
+ elementMax: number | null,
1283
+ ) =>
1284
+ classifyScrollEvent({
1285
+ offset,
1286
+ isScrolling,
1287
+ elementMax,
1288
+ holdOffset: this._holdOffset,
1289
+ scrollOffset: this.scrollOffset,
1290
+ pendingWrite: this.pendingWrite,
1291
+ clampedMaxAtWrite: this._clampedAdjustment?.maxAtWrite ?? null,
1292
+ })
1293
+
1164
1294
  // Re-issue a compensation write the browser clamped because the sizer had
1165
1295
  // not grown yet (#1258, #1266). Called after `notify` in `resizeItem`,
1166
1296
  // which covers consumers that size the container synchronously inside
@@ -1183,57 +1313,90 @@ export class Virtualizer<
1183
1313
  // the new max so the next opportunity retries.
1184
1314
  this._clampedAdjustment =
1185
1315
  target > max + 0.5 ? { target, maxAtWrite: max } : null
1186
- this._scrollToOffset(target, {
1187
- adjustments: undefined,
1188
- behavior: undefined,
1189
- })
1316
+ this._scrollToOffset(target)
1190
1317
  }
1191
1318
  }
1192
1319
 
1193
- // The element is moving or about to: a scroll in progress, or a touch
1194
- // gesture that may still turn into one (see `_iosTouch`). On iOS a write
1195
- // now would cancel the momentum, so adjustments wait for the flush below.
1196
- private _iosInMotion = () => this.isScrolling || this._iosTouch !== null
1320
+ // Write the command that `_startScroll` left waiting for the momentum
1321
+ // tail, against the layout as it is now (rows measured during the fling
1322
+ // have moved an index target).
1323
+ private _writeAwaitingCommand = () => {
1324
+ const state = this.scrollState
1325
+ if (state === null || state.phase !== 'queued') return
1326
+ const { behavior } = state
1327
+ this.getMeasurements()
1328
+ const offset = this.getScrollStateTarget(state)
1329
+ state.lastTargetOffset = offset
1330
+ // The hold flushed just before can leave a clamp retry (#1258); it
1331
+ // would write its old target over this command.
1332
+ this._clampedAdjustment = null
1333
+ state.phase = initialScrollPhase(
1334
+ behavior,
1335
+ state.index != null && approxEqual(offset, this.getScrollOffset()),
1336
+ )
1337
+ this._scrollToOffset(offset, { behavior })
1338
+ this.scheduleScrollReconcile()
1339
+ }
1197
1340
 
1198
- private _endIosTouch = () => {
1199
- if (this._iosTouch?.phase === 'tail' && this.targetWindow != null) {
1200
- this.targetWindow.clearTimeout(this._iosTouch.timerId)
1341
+ // The element's position as the offset observers report it, or null for a
1342
+ // scroll element that is neither an element nor a window.
1343
+ private _readElementOffset = (): number | null => {
1344
+ const el = this.scrollElement as unknown as Partial<
1345
+ Element & Pick<Window, 'scrollX' | 'scrollY'>
1346
+ > | null
1347
+ if (el == null) return null
1348
+ const { horizontal, isRtl } = this.options
1349
+ if (typeof el.scrollTop === 'number') {
1350
+ return horizontal ? el.scrollLeft! * ((isRtl && -1) || 1) : el.scrollTop
1201
1351
  }
1202
- this._iosTouch = null
1203
- }
1204
-
1205
- // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
1206
- // truly settled — not actively scrolling, not under an active touch, and
1207
- // past the post-touchend grace window. Called from the scroll callback
1208
- // and the touchend grace-timer.
1209
- private _flushIosDeferredIfReady = () => {
1210
- if (this._iosDeferredAdjustment === 0) return
1211
- if (this._iosInMotion()) return
1212
- // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go
1213
- // negative or beyond scrollHeight - clientHeight. Writing scrollTop
1214
- // while in that zone snaps the page back to the clamped value at the
1215
- // end of the bounce, often discarding the user's intent. Skip the
1216
- // flush; the next in-bounds scroll event will retry.
1217
- const cur = this.getScrollOffset()
1218
- const max = this.getMaxScrollOffset()
1219
- if (cur < 0 || cur > max) return
1220
- // At the end clamp the browser already absorbed a shrink above the
1221
- // viewport (it clamped scrollTop onto the new bottom), so replaying our
1222
- // deferred negative delta would lift the view off the bottom — drop it.
1223
- // Positive deltas still replay: growth above doesn't clamp. (#1233)
1224
- if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {
1225
- this._iosDeferredAdjustment = 0
1226
- return
1352
+ if (typeof el.scrollY === 'number') {
1353
+ return horizontal ? el.scrollX! : el.scrollY
1227
1354
  }
1228
- const delta = this._iosDeferredAdjustment
1229
- this._iosDeferredAdjustment = 0
1230
- // Roll the deferred delta into the running accumulator so any resize
1231
- // landing between now and the resulting scroll event computes from the
1232
- // post-flush offset rather than the stale one.
1233
- this._scrollToOffset(cur, {
1234
- adjustments: this.scrollAdjustments + delta,
1235
- behavior: undefined,
1236
- })
1355
+ return null
1356
+ }
1357
+
1358
+ // Whether a scrollTop write made now would reach the element and stay:
1359
+ // - not on iOS while a touch gesture owns the scroll (`IosGesture`): a
1360
+ // dragging finger ignores the write, momentum is cancelled by it on
1361
+ // iOS 26 and earlier and overrides it within a frame on 27 (#884,
1362
+ // #1307), so a correction is held through the tail on every version;
1363
+ // - not while the element is overscrolled past either edge (the
1364
+ // rubber-band bounce): WebKit discards the write and the bounce can
1365
+ // stall where it was (#1287).
1366
+ // A write that is unwanted for another reason (a travelling smooth scroll
1367
+ // owns the position) is a separate check at the call sites.
1368
+ private _canWriteScroll = () =>
1369
+ !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll
1370
+
1371
+ // Write a held correction once a write is possible, from the scroll
1372
+ // handler, the touch tail timer, `_willUpdate` and a resize notify. The
1373
+ // rows go back to layout coordinates and the total grows by the hold in a
1374
+ // notify issued before the write, so the sizer can take the position and
1375
+ // both commit in the paint the write lands in. `sync` is false only where
1376
+ // the caller already runs inside the consumer's commit (`_willUpdate`),
1377
+ // where an update it schedules commits before paint anyway.
1378
+ private _flushHoldIfReady = (sync: boolean) => {
1379
+ if (this._holdOffset === 0) return
1380
+ if (!this.scrollElement || !this.options.enabled) return
1381
+ if (!this._canWriteScroll()) return
1382
+ // Let a travelling smooth scroll land first (see `_willUpdate`).
1383
+ if (this.scrollState?.phase === 'smooth') return
1384
+ this._holdOffset = 0
1385
+ // A held shrink can leave the layout position above the top; the
1386
+ // element clamps that to 0 without an event to say so (#1229).
1387
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
1388
+ this.scrollOffset = 0
1389
+ }
1390
+ this.notify(sync)
1391
+ // A command whose write has not been reported back yet owns the target:
1392
+ // `scrollOffset` is still the pre-command position until its read-back,
1393
+ // and a command that closes the touch tail makes a write possible with
1394
+ // no scroll event in between, so this flush can run first.
1395
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset()
1396
+ // A consumer that sizes the container after this write gets the retry
1397
+ // (#1258).
1398
+ this._clampedAdjustment = this._clampedBy(target)
1399
+ this._scrollToOffset(target)
1237
1400
  }
1238
1401
 
1239
1402
  private rafId: number | null = null
@@ -1269,6 +1432,13 @@ export class Virtualizer<
1269
1432
  return
1270
1433
  }
1271
1434
 
1435
+ // Nothing to reconcile until the tail closes and the command is written;
1436
+ // only the safety valve above applies.
1437
+ if (this.scrollState.phase === 'queued') {
1438
+ this.scheduleScrollReconcile()
1439
+ return
1440
+ }
1441
+
1272
1442
  // A resize since the last render leaves measurementsCache stale until
1273
1443
  // something reads getMeasurements(); rebuild it (memoized) so an index
1274
1444
  // target reflects it even when no render ran in between.
@@ -1305,10 +1475,7 @@ export class Virtualizer<
1305
1475
  // end up at the EXACT computed position of item N — matching
1306
1476
  // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
1307
1477
  if (this.getScrollOffset() !== targetOffset) {
1308
- this._scrollToOffset(targetOffset, {
1309
- adjustments: undefined,
1310
- behavior: 'auto',
1311
- })
1478
+ this._scrollToOffset(targetOffset, { behavior: 'auto' })
1312
1479
  }
1313
1480
  this.scrollState = null
1314
1481
  return
@@ -1344,7 +1511,6 @@ export class Virtualizer<
1344
1511
  // until reconcile sees it at the target; 'instant' stays instant.
1345
1512
 
1346
1513
  this._scrollToOffset(targetOffset, {
1347
- adjustments: undefined,
1348
1514
  behavior: keepSmooth ? 'smooth' : 'auto',
1349
1515
  })
1350
1516
  }
@@ -1847,17 +2013,16 @@ export class Virtualizer<
1847
2013
  this.options.anchorTo === 'end' &&
1848
2014
  !isSmoothScroll(this.scrollState) &&
1849
2015
  this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold
1850
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0
2016
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0
1851
2017
  // Default anchoring predicate (used unless the consumer supplies a
1852
2018
  // custom shouldAdjustScrollPositionOnItemSizeChange).
1853
- const scrollOffsetWithAdj =
1854
- this.getScrollOffset() + this.scrollAdjustments
2019
+ const scrollOffset = this.getScrollOffset()
1855
2020
  const isFirstMeasure = !this.itemSizeCache.has(key)
1856
2021
  const defaultShouldAdjust = isFirstMeasure
1857
2022
  ? // First measurement: compensate any item whose top sits above the
1858
2023
  // fold — the estimate→actual delta must be corrected regardless of
1859
2024
  // scroll direction, since the whole estimated block was above it.
1860
- itemStart < scrollOffsetWithAdj
2025
+ itemStart < scrollOffset
1861
2026
  : // Re-measurement: only compensate an item that is ENTIRELY above the
1862
2027
  // fold. An item that merely *spans* the fold (top above, bottom
1863
2028
  // below — e.g. a streaming chat message growing at its bottom)
@@ -1865,7 +2030,7 @@ export class Virtualizer<
1865
2030
  // delta would drag the viewport downward on every growth (#1218).
1866
2031
  // Also skip during backward scroll to avoid the "items jump while
1867
2032
  // scrolling up" cascade.
1868
- itemStart + itemSize <= scrollOffsetWithAdj &&
2033
+ itemStart + itemSize <= scrollOffset &&
1869
2034
  this.scrollDirection !== 'backward'
1870
2035
  const shouldAdjustScroll =
1871
2036
  !isSmoothScroll(this.scrollState) &&
@@ -1892,30 +2057,14 @@ export class Virtualizer<
1892
2057
  this.itemSizeCache.set(key, size)
1893
2058
  this.itemSizeCacheVersion++
1894
2059
 
1895
- // A scroll command (or reconcile) wrote a new position that neither a
1896
- // scroll event nor an eager update has reflected in `scrollOffset` yet.
1897
- // The rows being measured were rendered for the old position, so
1898
- // "above the viewport" means nothing against either offset. An index
1899
- // or end target is retargeted from fresh measurements by
1900
- // reconcileScroll next frame; an offset target (scrollToOffset,
1901
- // scrollBy) lands where it was written and the delta is not applied,
1902
- // since compensating against the stale offset would overwrite the
1903
- // command. Compensation writes and the prepend anchor sync update
1904
- // `scrollOffset` eagerly, and the iOS flush writes exactly
1905
- // `scrollOffset + scrollAdjustments`, so none of them count.
1906
- const writtenOffset = this.getCommandWrittenOffset()
1907
- const awaitingCommandReadBack =
1908
- writtenOffset !== null &&
1909
- !approxEqual(
1910
- writtenOffset,
1911
- this.getScrollOffset() + this.scrollAdjustments,
1912
- )
1913
-
2060
+ // Before a command's read-back, an index or end target is retargeted
2061
+ // from fresh measurements by reconcileScroll next frame; an offset
2062
+ // target lands where it was written and the delta is not applied.
1914
2063
  let adjustedSync = false
1915
- if (!awaitingCommandReadBack) {
2064
+ if (!this._awaitingCommandReadBack()) {
1916
2065
  if (wasAtEnd) {
1917
2066
  adjustedSync = this.applyScrollAdjustment(
1918
- this.getTotalSize() - prevTotalSize,
2067
+ this._getLayoutTotalSize() - prevTotalSize,
1919
2068
  )
1920
2069
  } else if (shouldAdjustScroll) {
1921
2070
  adjustedSync = this.applyScrollAdjustment(delta)
@@ -1940,24 +2089,36 @@ export class Virtualizer<
1940
2089
  return
1941
2090
  }
1942
2091
  this.notify(adjustedSync)
2092
+ this._noteClampMax()
1943
2093
  // A consumer that grows the sizer synchronously inside `onChange`
1944
2094
  // (direct DOM updates) may never re-render when the range is
1945
2095
  // unchanged, so retry a clamped write here rather than only in
1946
2096
  // `_willUpdate` (#1266).
2097
+ this._flushHoldIfReady(true)
1947
2098
  this._retryClampedAdjustment()
1948
2099
  }
1949
2100
  }
1950
2101
 
1951
2102
  getVirtualItems = memo(
1952
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1953
- (indexes, measurements) => {
2103
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
2104
+ (indexes, measurements, hold) => {
1954
2105
  const virtualItems: Array<VirtualItem> = []
1955
2106
 
1956
2107
  for (let k = 0, len = indexes.length; k < len; k++) {
1957
2108
  const i = indexes[k]!
1958
2109
  const measurement = measurements[i]!
1959
2110
 
1960
- virtualItems.push(measurement)
2111
+ // A held correction is exposed as a shift of every row (see
2112
+ // `_holdOffset`); the layout itself is untouched.
2113
+ virtualItems.push(
2114
+ hold === 0
2115
+ ? measurement
2116
+ : {
2117
+ ...measurement,
2118
+ start: measurement.start - hold,
2119
+ end: measurement.end - hold,
2120
+ },
2121
+ )
1961
2122
  }
1962
2123
 
1963
2124
  return virtualItems
@@ -1989,26 +2150,129 @@ export class Virtualizer<
1989
2150
  return notUndefined(measurements[idx])
1990
2151
  }
1991
2152
 
1992
- private getMaxScrollOffset = () => {
1993
- if (!this.scrollElement) return 0
2153
+ // Record the element's max, in layout coordinates, as one a command's
2154
+ // pending instant write may be clamped to (see `lowMaxes` on
2155
+ // `pendingWrite`). Called where the sizer can have been committed: after
2156
+ // a notify, for a consumer that sizes it in `onChange`, and in
2157
+ // `_willUpdate`. The element cannot clamp below its own 0, which is the
2158
+ // hold in layout coordinates.
2159
+ private _noteClampMax = () => {
2160
+ if (!this._awaitingCommandReadBack()) return
2161
+ const elementMax = this._elementMaxScrollOffset()
2162
+ if (elementMax === null) return
2163
+ const write = this.pendingWrite!
2164
+ const max = Math.max(elementMax, 0) + this._holdOffset
2165
+ if (max >= write.target) return
2166
+ const lowMaxes = (write.lowMaxes ??= [])
2167
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max)
2168
+ }
1994
2169
 
1995
- if ('scrollHeight' in this.scrollElement) {
1996
- // Element
2170
+ // The element's scroll range in layout coordinates: while a correction is
2171
+ // held the sizer is short by the hold, so the element's own max is too.
2172
+ private getMaxScrollOffset = () =>
2173
+ (this._elementMaxScrollOffset() ?? 0) + this._holdOffset
2174
+
2175
+ // An element position in layout coordinates: how far the layout position
2176
+ // is ahead of the element. The element is `_holdOffset` behind while a
2177
+ // correction is held, and a prepend's anchor delta behind from
2178
+ // `setOptions` (which moved `scrollOffset` by it) until `_willUpdate`
2179
+ // writes or holds it. Writes (`_scrollToOffset`) and the clamp record
2180
+ // (`_clampedBy`) deliberately subtract the hold alone, not this whole
2181
+ // lead: by the time they run, the anchor delta is already in
2182
+ // `scrollOffset`, and writing that layout position is what closes it.
2183
+ private _toLayoutOffset = (elementOffset: number) => {
2184
+ let offset = elementOffset + this._holdOffset
2185
+ if (this.pendingScrollAnchor?.kind === 'anchor') {
2186
+ offset += this.pendingScrollAnchor.delta
2187
+ }
2188
+ return offset
2189
+ }
2190
+
2191
+ // The element's own scroll range, or null where it cannot be read (no
2192
+ // element, or a bare test double without `scrollHeight` / `document`).
2193
+ private _elementMaxScrollOffset = (): number | null => {
2194
+ const el = this.scrollElement
2195
+ if (el === null) return null
2196
+ if ('scrollHeight' in el) {
1997
2197
  return this.options.horizontal
1998
- ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth
1999
- : this.scrollElement.scrollHeight - this.scrollElement.clientHeight
2000
- } else {
2001
- // Window
2002
- const doc = this.scrollElement.document.documentElement
2198
+ ? el.scrollWidth - el.clientWidth
2199
+ : el.scrollHeight - el.clientHeight
2200
+ }
2201
+ if ('document' in el) {
2202
+ const doc = el.document.documentElement
2003
2203
  return this.options.horizontal
2004
- ? doc.scrollWidth - this.scrollElement.innerWidth
2005
- : doc.scrollHeight - this.scrollElement.innerHeight
2204
+ ? doc.scrollWidth - el.innerWidth
2205
+ : doc.scrollHeight - el.innerHeight
2206
+ }
2207
+ return null
2208
+ }
2209
+
2210
+ // Stop a running iOS fling, then call `done`: the momentum does not
2211
+ // survive the element losing its overflow for a frame. Hidden and
2212
+ // restored within one task, iOS never sees the change and the fling
2213
+ // carries on (27.0.1 iPhone); hidden for two frames, it stops at once.
2214
+ // Nothing moves on screen. A second call while one is in progress waits
2215
+ // for the same frames. The app's inline value comes back, unless the app
2216
+ // set a new one meanwhile; `done` is then not called.
2217
+ private _momentumStop: { restore: () => boolean; done: () => void } | null =
2218
+ null
2219
+ private _stopMomentum = (done: () => void) => {
2220
+ const el = this.scrollElement
2221
+ const win = this.targetWindow
2222
+ if (el === null || win === null) return
2223
+ const scroller = (
2224
+ 'document' in el ? el.document.scrollingElement : el
2225
+ ) as HTMLElement | null
2226
+ // A test double may have no style to change.
2227
+ if (!scroller?.style) return
2228
+ if (this._momentumStop) {
2229
+ this._momentumStop.done = done
2230
+ return
2231
+ }
2232
+ const { style } = scroller
2233
+ const property = this.options.horizontal ? 'overflow-x' : 'overflow-y'
2234
+ const value = style.getPropertyValue(property)
2235
+ const priority = style.getPropertyPriority(property)
2236
+ style.setProperty(property, 'hidden', 'important')
2237
+ const stop = {
2238
+ // False when the app replaced the hidden value: the fling may not
2239
+ // have stopped.
2240
+ restore: () => {
2241
+ if (
2242
+ style.getPropertyValue(property) !== 'hidden' ||
2243
+ style.getPropertyPriority(property) !== 'important'
2244
+ ) {
2245
+ return false
2246
+ }
2247
+ style.setProperty(property, value, priority)
2248
+ return true
2249
+ },
2250
+ done,
2006
2251
  }
2252
+ this._momentumStop = stop
2253
+ win.requestAnimationFrame(() =>
2254
+ win.requestAnimationFrame(() => {
2255
+ // Already restored by `cleanup`, which also drops its command.
2256
+ if (this._momentumStop !== stop) return
2257
+ this._momentumStop = null
2258
+ // The command waits for the tail, as without the stop.
2259
+ if (stop.restore()) stop.done()
2260
+ }),
2261
+ )
2262
+ }
2263
+
2264
+ // A compensation write past the element's current max (the sizer has not
2265
+ // grown yet) is clamped by the browser; record it for the retry (#1258).
2266
+ private _clampedBy = (target: number) => {
2267
+ const elementMax = this._elementMaxScrollOffset()
2268
+ if (elementMax === null) return null
2269
+ const maxAtWrite = elementMax + this._holdOffset
2270
+ return target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null
2007
2271
  }
2008
2272
 
2009
2273
  private getVirtualDistanceFromEnd = () => {
2010
2274
  return Math.max(
2011
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
2275
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
2012
2276
  0,
2013
2277
  )
2014
2278
  }
@@ -2111,13 +2375,8 @@ export class Virtualizer<
2111
2375
  index = Math.max(0, Math.min(index, this.options.count - 1))
2112
2376
 
2113
2377
  const offsetInfo = this.getOffsetForIndex(index, initialAlign)
2114
- if (!offsetInfo) {
2115
- // No target (an empty list), so nothing is written; still drop the
2116
- // deferral like every absolute command, or it replays once the list
2117
- // refills.
2118
- this._iosDeferredAdjustment = 0
2119
- return
2120
- }
2378
+ // No target (an empty list), so nothing is written.
2379
+ if (!offsetInfo) return
2121
2380
  const [offset, align] = offsetInfo
2122
2381
 
2123
2382
  this._startScroll({ index, align }, offset, behavior, 'absolute')
@@ -2164,12 +2423,10 @@ export class Virtualizer<
2164
2423
  // Every scroll command starts here: it becomes the in-flight command,
2165
2424
  // writes its first target and leaves reconcile to retarget and retire it.
2166
2425
  //
2167
- // An absolute command derives its target from current measurements, so
2168
- // any iOS-deferred compensation still pending is stale by definition —
2169
- // the command already accounts for the measurements the delta was
2170
- // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
2171
- // onto the just-established position. A relative command (scrollBy)
2172
- // builds on the current offset, so it keeps the deferral.
2426
+ // Targets are layout offsets. A held correction is not dropped by a
2427
+ // command: the write lands the element `_holdOffset` short of the target,
2428
+ // under the rows exposed shifted by the same amount, and the flush moves
2429
+ // both together once a write is possible.
2173
2430
  //
2174
2431
  // An index or end target that is already at its offset starts a smooth
2175
2432
  // scroll as landed; an offset target never does, so its first scroll
@@ -2180,20 +2437,68 @@ export class Virtualizer<
2180
2437
  behavior: ScrollBehavior,
2181
2438
  kind: 'absolute' | 'relative',
2182
2439
  ) {
2183
- if (kind === 'absolute') {
2184
- this._iosDeferredAdjustment = 0
2440
+ const tail = this._iosGesture.tail()
2441
+ if (kind === 'absolute' && tail !== null) {
2442
+ if (tail === 'fling' && iosMomentumOverridesWrites()) {
2443
+ // iOS 27: a write now shows for one frame and the fling carries on
2444
+ // along its own path, so the command would be lost (#1307, step 3).
2445
+ // Stop the fling and write two frames later. Otherwise (no style to
2446
+ // change, a finger down, a bounce) the tail stays open and
2447
+ // the command is written when it closes, ~150ms after the last
2448
+ // fling frame. The user taking over before the write (a drag, a
2449
+ // second flick, a finger stopping the fling) cancels the command
2450
+ // (see the scroll handler and `onTailClosed`). A relative command
2451
+ // (`scrollBy`) is not postponed: its target is taken from the
2452
+ // position at the call, which the fling leaves behind either way.
2453
+ this._stopMomentum(() => {
2454
+ const state = this.scrollState
2455
+ if (
2456
+ state?.phase !== 'queued' ||
2457
+ // A finger came down: it owns the scroll until it lifts.
2458
+ this._iosGesture.tail() !== 'fling' ||
2459
+ // In a bounce WebKit can drop the write (#1287): the tail
2460
+ // decides, as without the stop. (Not `flingCaught`: our stop
2461
+ // also ends the fling at speed, so a slow frame would read as
2462
+ // a catch and the tail would drop the command.)
2463
+ this._reportedOverscroll
2464
+ ) {
2465
+ return
2466
+ }
2467
+ this._iosGesture.end()
2468
+ this._flushHoldIfReady(true)
2469
+ this._writeAwaitingCommand()
2470
+ })
2471
+ this.scrollState = {
2472
+ ...target,
2473
+ startedAt: this.now(),
2474
+ lastTargetOffset: offset,
2475
+ stableFrames: 0,
2476
+ phase: 'queued',
2477
+ behavior,
2478
+ samples: [],
2479
+ }
2480
+ this.scheduleScrollReconcile()
2481
+ return
2482
+ }
2483
+ // The command takes over the scroll, so close the tail: the landing's
2484
+ // corrections then apply before paint, even for a command issued from
2485
+ // a tap handler inside the tail (#1250). On iOS 26 and earlier the
2486
+ // write stops the momentum. With a finger down the user owns the
2487
+ // scroll: leave it.
2488
+ this._iosGesture.end()
2185
2489
  }
2186
2490
  this.scrollState = {
2187
2491
  ...target,
2188
2492
  startedAt: this.now(),
2189
2493
  lastTargetOffset: offset,
2190
2494
  stableFrames: 0,
2495
+ behavior,
2191
2496
  phase: initialScrollPhase(
2192
2497
  behavior,
2193
2498
  target.index != null && approxEqual(offset, this.getScrollOffset()),
2194
2499
  ),
2195
2500
  }
2196
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2501
+ this._scrollToOffset(offset, { behavior })
2197
2502
  this.scheduleScrollReconcile()
2198
2503
  }
2199
2504
 
@@ -2209,7 +2514,13 @@ export class Virtualizer<
2209
2514
  this.scrollState = null
2210
2515
  }
2211
2516
 
2212
- getTotalSize = () => {
2517
+ // The size the consumer gives the container: the layout's total, short by
2518
+ // a held correction so the rows exposed shifted by it still fill it (see
2519
+ // `_holdOffset`).
2520
+ getTotalSize = () =>
2521
+ Math.max(this._getLayoutTotalSize() - this._holdOffset, 0)
2522
+
2523
+ private _getLayoutTotalSize = () => {
2213
2524
  const measurements = this.getMeasurements()
2214
2525
 
2215
2526
  let end: number
@@ -2288,17 +2599,21 @@ export class Virtualizer<
2288
2599
  {
2289
2600
  adjustments,
2290
2601
  behavior,
2291
- }: {
2292
- adjustments: number | undefined
2293
- behavior: ScrollBehavior | undefined
2294
- },
2602
+ }: { adjustments?: number; behavior?: ScrollBehavior } = {},
2295
2603
  ) => {
2296
- this.pendingWrite = {
2604
+ const write = {
2297
2605
  target: offset + (adjustments ?? 0),
2298
2606
  smooth: behavior === 'smooth',
2299
- adjustments: adjustments ?? this.scrollAdjustments,
2300
2607
  }
2301
- this.options.scrollToFn(offset, { behavior, adjustments }, this)
2608
+ this.pendingWrite = write
2609
+ // The element sits `_holdOffset` behind the layout while a correction
2610
+ // is held; `target` and the read-back stay in layout coordinates.
2611
+ this.options.scrollToFn(
2612
+ offset - this._holdOffset,
2613
+ { behavior, adjustments },
2614
+ this,
2615
+ )
2616
+ return write
2302
2617
  }
2303
2618
 
2304
2619
  // Where the in-flight command's last instant write put the element, until
@@ -2313,6 +2628,35 @@ export class Virtualizer<
2313
2628
  ? this.pendingWrite.target
2314
2629
  : null
2315
2630
 
2631
+ // A scroll command (or reconcile) wrote a new position that neither a
2632
+ // scroll event nor an eager update has reflected in `scrollOffset` yet.
2633
+ // The rows on screen were rendered for the old position, so "above the
2634
+ // viewport" means nothing against either offset: a correction decided now
2635
+ // would be written over the command. Compensation writes and the prepend
2636
+ // anchor sync update `scrollOffset` eagerly, and the hold's flush writes
2637
+ // exactly `scrollOffset`, so none of them count. Under a dragging finger
2638
+ // iOS ignores the write, so no read-back will come and the hold takes the
2639
+ // correction instead.
2640
+ private _awaitingCommandReadBack = () => {
2641
+ const writtenOffset = this.getCommandWrittenOffset()
2642
+ return (
2643
+ !(isIOSWebKit() && this._iosGesture.dragging()) &&
2644
+ writtenOffset !== null &&
2645
+ !approxEqual(writtenOffset, this.getScrollOffset())
2646
+ )
2647
+ }
2648
+
2649
+ // An offset target (scrollToOffset, scrollBy) is a layout position. A
2650
+ // correction for content above the viewport moves the viewport's layout
2651
+ // position by `delta`, and the target moves with it, so reconcile sees the
2652
+ // command reached rather than waiting for a position it can never see
2653
+ // (#1307, step 5). Index and end targets are recomputed from the layout.
2654
+ private _followOffsetTarget = (delta: number) => {
2655
+ if (this.scrollState !== null && this.scrollState.index == null) {
2656
+ this.scrollState.lastTargetOffset += delta
2657
+ }
2658
+ }
2659
+
2316
2660
  measure = () => {
2317
2661
  // Reset pendingMin so the next getMeasurements rebuilds from index 0.
2318
2662
  // Without this, a prior resizeItem() that left pendingMin > 0 would