@tanstack/virtual-core 3.19.4 → 3.19.6

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
 
@@ -82,8 +74,8 @@ export interface Rect {
82
74
  //
83
75
 
84
76
  const getRect = (element: HTMLElement): Rect => {
85
- const { offsetWidth, offsetHeight } = element
86
- return { width: offsetWidth, height: offsetHeight }
77
+ const { clientWidth, clientHeight } = element
78
+ return { width: clientWidth, height: clientHeight }
87
79
  }
88
80
 
89
81
  // Animation frames for `useAnimationFrameWithResizeObserver`, requested from
@@ -149,16 +141,8 @@ export const observeElementRect = <T extends Element>(
149
141
  }
150
142
 
151
143
  const frames = createFrameQueue(targetWindow)
152
- const observer = new targetWindow.ResizeObserver((entries) => {
144
+ const observer = new targetWindow.ResizeObserver(() => {
153
145
  const run = () => {
154
- const entry = entries[0]
155
- if (entry?.borderBoxSize) {
156
- const box = entry.borderBoxSize[0]
157
- if (box) {
158
- handler({ width: box.inlineSize, height: box.blockSize })
159
- return
160
- }
161
- }
162
146
  handler(getRect(element as unknown as HTMLElement))
163
147
  }
164
148
 
@@ -167,7 +151,7 @@ export const observeElementRect = <T extends Element>(
167
151
  : run()
168
152
  })
169
153
 
170
- observer.observe(element, { box: 'border-box' })
154
+ observer.observe(element, { box: 'content-box' })
171
155
 
172
156
  return () => {
173
157
  observer.unobserve(element)
@@ -409,15 +393,6 @@ export interface VirtualizerOptions<
409
393
  useCachedMeasurements?: boolean
410
394
  }
411
395
 
412
- // Where an in-flight scroll command is in its lifecycle, which decides how
413
- // its scroll events and measurements are read:
414
- // smooth a smooth animation is travelling to the target
415
- // smoothLanded a smooth scroll is at its target, waiting to retire
416
- // smoothFinishing a smooth scroll switched to instant writes for the
417
- // final approach; its animation can still report positions
418
- // instant instant writes
419
- type ScrollPhase = 'smooth' | 'smoothLanded' | 'smoothFinishing' | 'instant'
420
-
421
396
  type ScrollState = {
422
397
  // what we want
423
398
  index: number | null
@@ -427,6 +402,8 @@ type ScrollState = {
427
402
 
428
403
  // lifecycle
429
404
  startedAt: number
405
+ // how the command was asked to scroll; a queued command writes with it
406
+ behavior: ScrollBehavior
430
407
 
431
408
  // target tracking
432
409
  lastTargetOffset: number
@@ -434,6 +411,11 @@ type ScrollState = {
434
411
  // settling
435
412
  stableFrames: number
436
413
  phase: ScrollPhase
414
+
415
+ // A `queued` command's view of the fling it waits for: the scroll events
416
+ // since it was queued, at most the last 200ms (`flingSpedUp`,
417
+ // `flingCaught`). Read only while `queued`.
418
+ samples?: Array<ScrollSample>
437
419
  }
438
420
 
439
421
  const initialScrollPhase = (
@@ -447,11 +429,6 @@ const initialScrollPhase = (
447
429
  const isSmoothScroll = (state: ScrollState | null): state is ScrollState =>
448
430
  state?.phase === 'smooth' || state?.phase === 'smoothLanded'
449
431
 
450
- // The smooth animation may still be reporting positions, so a scroll event
451
- // that isn't the read-back of our own write may not be the user.
452
- const isAnimating = (state: ScrollState) =>
453
- state.phase === 'smooth' || state.phase === 'smoothFinishing'
454
-
455
432
  // What `setOptions` decided about the scroll position for `_willUpdate` to
456
433
  // carry out once the consumer has rendered: keep the reading anchor in place
457
434
  // after a prepend (`scrollOffset` already moved by `delta`, the element has
@@ -518,37 +495,106 @@ export class Virtualizer<
518
495
  private lanesSettling = false
519
496
  private pendingScrollAnchor: PendingScrollAnchor | null = null
520
497
  scrollRect: Rect | null = null
498
+ /**
499
+ * The scroll position in the list's layout, consistent with
500
+ * `getOffsetForIndex`, `scrollToOffset` and `initialOffset`. While a
501
+ * correction is held (`_holdOffset`), `getVirtualItems()` and
502
+ * `getTotalSize()` describe what is rendered, shifted by the held amount;
503
+ * this stays the layout position.
504
+ */
521
505
  scrollOffset: number | null = null
522
506
  scrollDirection: ScrollDirection | null = null
523
- // Size compensation written to the element but not yet reflected in
524
- // `scrollOffset`: the element is expected at `scrollOffset +
525
- // scrollAdjustments` until the next scroll event reports it.
507
+ /**
508
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
509
+ * at once, so there is never an outstanding adjustment to add to it. Read
510
+ * `scrollOffset` alone.
511
+ */
526
512
  get scrollAdjustments() {
527
- return this.pendingWrite?.adjustments ?? 0
528
- }
529
- // Sum of size-change deltas above-viewport that were skipped during
530
- // iOS momentum scroll (writing scrollTop mid-momentum cancels it).
531
- // Flushed in a single scrollTo when iOS is fully settled.
532
- private _iosDeferredAdjustment = 0
533
- // The touch gesture in progress. iOS WebKit cancels momentum when
534
- // scrollTop is written, so adjustments are deferred not only during
535
- // `isScrolling` but through the whole gesture: `down` from touchstart to
536
- // touchend/touchcancel (active drag), then `tail` for a short grace window
537
- // after the finger lifts (early momentum — iOS fires touch events only
538
- // once at the start of momentum, so the tail is a timer rather than
539
- // another event). Null between gestures, and after touchend on non-iOS,
540
- // which arms no tail. The tail record owns its timer: `_endIosTouch` is
541
- // the only way to drop either, so a cleared record never leaves a timer
542
- // behind, and a live timer always has its record.
543
- private _iosTouch:
544
- | { phase: 'down' }
545
- | { phase: 'tail'; timerId: number }
546
- | null = null
513
+ return 0
514
+ }
515
+ // Scroll corrections (a prepend's anchor delta, size changes above the
516
+ // viewport) that could not be written to the element because a write was
517
+ // impossible at the time (see `_canWriteScroll`): the difference between
518
+ // `scrollOffset`, which always carries the corrected layout position, and
519
+ // where the element is. While it is non-zero the rows and the total size
520
+ // are exposed shifted by `-_holdOffset`, so every adapter renders the
521
+ // reader's row where it was, writes subtract it (`_scrollToOffset`) and
522
+ // scroll events add it back (the handler in `_willUpdate`). Released by
523
+ // `_flushHoldIfReady`: the rows re-render in layout coordinates and the
524
+ // element moves by the same amount in one paint.
525
+ private _holdOffset = 0
526
+ // Whether the element's last scroll event reported a position past either
527
+ // edge (the rubber-band bounce). Judged at report time against the
528
+ // element's own max, with a 1px tolerance for a fractional scrollTop: a
529
+ // sizer that shrinks after the report (a trim) is not a bounce, and
530
+ // `scrollOffset` is no judge either, since an eager bump past the max while
531
+ // the sizer has not grown yet (#1258) is not one.
532
+ //
533
+ // Stored rather than read from the element when a write is decided. The
534
+ // two differ once a write has landed but not been reported back, and in
535
+ // that window the element reads in bounds while `scrollOffset` is still
536
+ // the pre-write value. With the anchor sync now skipped in that window
537
+ // (`_awaitingCommandReadBack`), the remaining difference is the trim: a
538
+ // list that shrank under the position reads past the element's max until
539
+ // the browser clamps it, which is where the anchor's write has to go
540
+ // (`followOnAppend does not follow 'trim only'`; reading the element at
541
+ // write time still moves 49 of 1080 snapshot seeds).
542
+ private _reportedOverscroll = false
543
+ // The touch gesture in progress (see `IosGesture`). Its tail closing on
544
+ // its own makes a write possible again: the last momentum frame may have
545
+ // come before the timer. The hold is released first, so a command that
546
+ // waited for the tail is written over rows already back in layout
547
+ // coordinates.
548
+ private _iosGesture = new IosGesture({
549
+ getWindow: () => this.targetWindow,
550
+ now: () => this.now(),
551
+ // The end of a fling can move less than a pixel per scroll event, so
552
+ // events can stop for 150ms while the fling is still running (seen on
553
+ // an iPhone, 27.0.1). A command waiting for it would then be written
554
+ // into the fling and overridden. The element having moved since the
555
+ // last event means it has not ended: wait again. Not while our own
556
+ // write has yet to report: that moved it.
557
+ tailStillMoving: () => {
558
+ const state = this.scrollState
559
+ if (state?.phase !== 'queued' || this.pendingWrite !== null) {
560
+ return false
561
+ }
562
+ const now = this._readElementOffset()
563
+ if (
564
+ now === null ||
565
+ this._lastElementOffset === null ||
566
+ Math.abs(now - this._lastElementOffset) < 1
567
+ ) {
568
+ return false
569
+ }
570
+ this._lastElementOffset = now
571
+ // It moved with no event: a sample, so the speed `flingCaught` reads
572
+ // when it stops is not the one from before the silence.
573
+ state.samples = [...(state.samples ?? []), { t: this.now(), offset: now }]
574
+ return true
575
+ },
576
+ onTailClosed: () => {
577
+ // A fling that stopped at speed was caught by a finger that is still
578
+ // down, with no touch events: the user has taken over, as with a
579
+ // drag, and iOS would undo the write anyway.
580
+ const state = this.scrollState
581
+ if (state?.phase === 'queued' && flingCaught(state.samples ?? [])) {
582
+ this.scrollState = null
583
+ }
584
+ this._flushHoldIfReady(true)
585
+ this._writeAwaitingCommand()
586
+ },
587
+ })
588
+ // The last position the scroll handler was given, in the element's own
589
+ // coordinates. The tail compares it with the element (`tailStillMoving`
590
+ // above).
591
+ private _lastElementOffset: number | null = null
547
592
  // Our last write to the element, from `_scrollToOffset` until the next
548
593
  // scroll event reports it (the only place it is cleared). Until then
549
594
  // `scrollOffset` may still hold the old position.
550
595
  //
551
- // - `target`: where the write puts the element (offset + adjustments).
596
+ // - `target`: where the write puts the element (offset + the adjustment
597
+ // passed to `scrollToFn`).
552
598
  // Safari (and Chrome/Firefox under certain DPRs) round writes to whole
553
599
  // pixels: wrote 12345.5, read back 12346. A read-back within 1.5px of
554
600
  // `target` is taken as our own and adopts the exact value, so reconcile
@@ -556,12 +602,17 @@ export class Virtualizer<
556
602
  // further by the time it reports.
557
603
  // - `smooth`: the write animates, so until it lands the element is
558
604
  // somewhere between the old offset and `target`.
559
- // - `adjustments`: see `scrollAdjustments`. Writes that pass none keep the
560
- // previous value.
605
+ // - `lowMaxes`: for a command's instant write, each scroll max below
606
+ // `target` the element had since the write. A command's target is
607
+ // clamped to the max at the write, but the sizer can shrink under it
608
+ // before the report (rows measured smaller, a count change) and grow
609
+ // back, so the read-back is the max the browser clamped to then rather
610
+ // than the element's current one. Read wherever the sizer can have
611
+ // been committed (`_noteClampMax`).
561
612
  private pendingWrite: {
562
613
  target: number
563
614
  smooth: boolean
564
- adjustments: number
615
+ lowMaxes?: Array<number>
565
616
  } | null = null
566
617
  // A compensation write from `applyScrollAdjustment` whose target exceeded
567
618
  // the element's scroll max at the moment of the write. The browser clamps
@@ -615,6 +666,8 @@ export class Virtualizer<
615
666
  this._resizeBatch = null
616
667
  if (batch.notify) {
617
668
  this.notify(batch.sync)
669
+ this._noteClampMax()
670
+ this._flushHoldIfReady(true)
618
671
  this._retryClampedAdjustment()
619
672
  }
620
673
  }
@@ -798,8 +851,18 @@ export class Virtualizer<
798
851
  // the virtualizer would render the wrong items for one frame (the
799
852
  // estimate-based positions are stale) and then correct in the next
800
853
  // frame, producing a visible "jump" on prepend with dynamic sizes.
854
+ // Not before a scroll command's write has been read back: `scrollOffset`
855
+ // is still the pre-command position, so the anchor would be resolved
856
+ // against rows that are no longer where the command put the element, and
857
+ // the sync would write that stale offset over the command. Reconcile
858
+ // retargets an index or end command from the new layout; an offset
859
+ // command lands where it was written (#1307, step 5).
801
860
  let anchorDelta: number | null = null
802
- if (anchor && this.scrollOffset !== null) {
861
+ if (
862
+ anchor &&
863
+ this.scrollOffset !== null &&
864
+ !this._awaitingCommandReadBack()
865
+ ) {
803
866
  const [anchorKey, anchorOffset] = anchor
804
867
  const newMeasurements = this.getMeasurements()
805
868
  const { count, getItemKey } = this.options
@@ -827,7 +890,16 @@ export class Virtualizer<
827
890
  if (followOnAppend) {
828
891
  this.pendingScrollAnchor = { kind: 'follow', behavior: followOnAppend }
829
892
  } else if (anchorDelta !== null) {
830
- this.pendingScrollAnchor = { kind: 'anchor', delta: anchorDelta }
893
+ if (this._canWriteScroll()) {
894
+ this.pendingScrollAnchor = { kind: 'anchor', delta: anchorDelta }
895
+ } else {
896
+ // The element cannot take the write (a touch owns it on iOS, or it is
897
+ // overscrolled). Hold the delta instead: this render already exposes
898
+ // the rows and the total shifted back by it, so the reader's row
899
+ // stays put, and the flush writes it once a write is possible.
900
+ this._holdOffset += anchorDelta
901
+ this._followOffsetTarget(anchorDelta)
902
+ }
831
903
  }
832
904
  }
833
905
 
@@ -849,28 +921,23 @@ export class Virtualizer<
849
921
  console.info('correction', delta)
850
922
  }
851
923
 
852
- if (isIOSWebKit() && this._iosInMotion()) {
853
- // An index scroll retargets from fresh measurements in reconcileScroll;
854
- // replaying this delta after it lands would count it twice.
855
- if (this.scrollState?.index == null) {
856
- this._iosDeferredAdjustment += delta
857
- }
858
- return false
924
+ // The correction moves the content the viewport is on; an offset target
925
+ // moves with it, or reconcile would wait for a position it can never see.
926
+ this._followOffsetTarget(delta)
927
+
928
+ if (!this._canWriteScroll()) {
929
+ // Hold the correction: `scrollOffset` takes it as if written, the rows
930
+ // are exposed shifted back by it. The notify must be synchronous like
931
+ // a write's, so the shifted rows commit in the same paint as the
932
+ // content change that caused the correction.
933
+ this._holdOffset += delta
934
+ if (this.scrollOffset !== null) this.scrollOffset += delta
935
+ return true
859
936
  } else {
860
- const target = this.getScrollOffset() + this.scrollAdjustments + delta
861
- // Guarded so a bare test double without `scrollHeight` / `document`
862
- // does not crash in `getMaxScrollOffset`.
863
- const el = this.scrollElement
864
- const maxAtWrite =
865
- el !== null && ('scrollHeight' in el || 'document' in el)
866
- ? this.getMaxScrollOffset()
867
- : null
868
- this._clampedAdjustment =
869
- maxAtWrite !== null && target > maxAtWrite + 0.5
870
- ? { target, maxAtWrite }
871
- : null
872
- this._scrollToOffset(this.getScrollOffset(), {
873
- adjustments: this.scrollAdjustments + delta,
937
+ const offset = this.getScrollOffset()
938
+ this._clampedAdjustment = this._clampedBy(offset + delta)
939
+ const write = this._scrollToOffset(offset, {
940
+ adjustments: delta,
874
941
  behavior,
875
942
  })
876
943
  // Eagerly carry the intended target in `scrollOffset` so callers that
@@ -879,19 +946,18 @@ export class Virtualizer<
879
946
  // post-adjustment position even when the DOM `scrollTop` write was
880
947
  // clamped because the consumer hasn't grown the sizer yet (`notify()`
881
948
  // runs after this in `resizeItem`). Same idea as the eager
882
- // `scrollOffset` adjustment for prepend in `setOptions` (#1176). The
883
- // adjustment is now baked into `scrollOffset`, so zero
884
- // `scrollAdjustments` to keep their sum invariant.
949
+ // `scrollOffset` adjustment for prepend in `setOptions` (#1176). A
950
+ // `scrollToFn` that reports the write synchronously has already set
951
+ // `scrollOffset` to the read-back (and cleared `pendingWrite`).
885
952
  if (this.scrollOffset !== null) {
886
- this.scrollOffset += this.scrollAdjustments
953
+ if (this.pendingWrite === write) this.scrollOffset += delta
887
954
  // Clamp only the lower bound: a negative offset is unreachable, and
888
955
  // on an unscrollable element (content fits the viewport) no scroll
889
956
  // event ever fires to correct it, permanently skewing
890
- // getDistanceFromEnd() and wedging _flushIosDeferredIfReady (#1229).
957
+ // getDistanceFromEnd() and wedging the hold flush (#1229).
891
958
  // Upper-bound overflow stays untouched — it is transiently
892
959
  // legitimate mid-prepend while the consumer's sizer catches up.
893
960
  if (this.scrollOffset < 0) this.scrollOffset = 0
894
- if (this.pendingWrite) this.pendingWrite.adjustments = 0
895
961
  }
896
962
  return true
897
963
  }
@@ -930,6 +996,10 @@ export class Virtualizer<
930
996
  this.rafId = null
931
997
  }
932
998
  this.scrollState = null
999
+ // The element is let go of: give it back its overflow now. A stop the
1000
+ // next element needs starts afresh.
1001
+ this._momentumStop?.restore()
1002
+ this._momentumStop = null
933
1003
  // The debounce cancelled above is the only thing that writes `isScrolling`
934
1004
  // back to false, so a cleanup inside the reset window would strand it, and
935
1005
  // the direction derived from it, as true. That matters because `cleanup`
@@ -943,11 +1013,12 @@ export class Virtualizer<
943
1013
  // capture), so the new element never reports it. Carrying the state
944
1014
  // over would replay a stale deferred delta on the new element's first
945
1015
  // flush, and a cleanup that lands mid-touch or inside the post-touchend
946
- // grace window would strand `_iosTouch` (the listeners that end it were
1016
+ // grace window would strand the gesture (the listeners that end it were
947
1017
  // just removed), deferring every adjustment on the new element until
948
1018
  // its next touch cycle.
949
- this._iosDeferredAdjustment = 0
950
- this._endIosTouch()
1019
+ this._holdOffset = 0
1020
+ this._reportedOverscroll = false
1021
+ // (The gesture was ended with its listeners, in the unsubs above.)
951
1022
  this._clampedAdjustment = null
952
1023
  // A write to the old element will never be read back.
953
1024
  this.pendingWrite = null
@@ -995,50 +1066,47 @@ export class Virtualizer<
995
1066
 
996
1067
  this.unsubs.push(
997
1068
  this.options.observeElementOffset(this, (offset, isScrolling) => {
998
- // A scroll event that reports movement but lands on the offset we
999
- // already hold — and isn't a self-write read-back — is a spurious
1000
- // no-op re-emit that Safari/Firefox fire after a re-render's layout
1001
- // (Chrome doesn't). Treating it as scrolling re-arms `isScrolling`,
1002
- // which forces a render that triggers another such event: an
1003
- // infinite re-render loop. Ignore it. (Self-writes are matched to
1004
- // `pendingWrite` just below.)
1005
- if (
1006
- isScrolling &&
1007
- this.pendingWrite === null &&
1008
- offset === this.scrollOffset
1009
- ) {
1010
- return
1011
- }
1069
+ // Past the top is never a resting position. Past the bottom is
1070
+ // judged only while scrolling: at rest the element has clamped,
1071
+ // and a stale sizer makes no bounce.
1072
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null
1073
+ const wasOverscrolled = this._reportedOverscroll
1074
+ this._reportedOverscroll =
1075
+ offset < 0 || (elementMax !== null && offset > elementMax + 1)
1076
+ const elementOffset = offset
1077
+ this._lastElementOffset = elementOffset
1078
+ // Everything below works in layout coordinates.
1079
+ offset = this._toLayoutOffset(offset)
1080
+
1081
+ const kind = this._classifyScrollEvent(
1082
+ offset,
1083
+ isScrolling,
1084
+ elementMax,
1085
+ )
1086
+ if (kind === 'spurious') return
1012
1087
 
1013
- // The read-back of our own write: adopt the exact target over the
1014
- // browser's rounded value (see `pendingWrite`).
1015
- const pending = this.pendingWrite
1016
- if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
1017
- offset = pending.target
1088
+ if (kind === 'readBack') {
1089
+ // Adopt the exact target over the browser's rounded value (see
1090
+ // `pendingWrite`).
1091
+ offset = this.pendingWrite!.target
1018
1092
  } else if (
1093
+ kind === 'clampedReadBack' &&
1019
1094
  this.scrollState?.index != null &&
1020
- // A non-smooth write lands at once, so any other scroll event is
1021
- // the user's, even before reconcile saw the target reached (the
1022
- // target may keep moving, or iOS ignored the write under a
1023
- // finger). A write the browser clamped because the sizer hasn't
1024
- // grown yet reads back at the max, which is also where the fresh
1025
- // target clamps, so the check below keeps it reconciling (#1294).
1026
- // Not when rows above the target shrink before the read-back and
1027
- // pull the target below the new max: the read-back then looks
1028
- // like the user and the scroll stops at the max. That needs the
1029
- // sizer re-rendered before the scroll event, which browsers have
1030
- // not been seen to do (pinned by a `.fails` test).
1031
- // While a smooth scroll's animation may still report, its events
1032
- // look like a user's, so it yields only once it has landed.
1033
- !isAnimating(this.scrollState) &&
1034
- !approxEqual(offset, this.scrollState.lastTargetOffset) &&
1035
- !approxEqual(offset, this.getScrollStateTarget(this.scrollState)) &&
1036
- (this._clampedAdjustment === null ||
1037
- Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5)
1095
+ // Not `elementMax`: an adapter can report the read-back at rest.
1096
+ offset < this.getMaxScrollOffset() - 1.5
1097
+ ) {
1098
+ // Our write, clamped at a max the sizer has since grown back
1099
+ // from: reconcile writes the target again, even when the layout
1100
+ // came back to the same end.
1101
+ this.scrollState.lastTargetOffset = offset
1102
+ } else if (
1103
+ externalRetiresCommand({
1104
+ kind,
1105
+ offset,
1106
+ command: this.scrollState,
1107
+ target: () => this.getScrollStateTarget(this.scrollState!),
1108
+ })
1038
1109
  ) {
1039
- // An external scroll moved away from the index scroll's target.
1040
- // Our own measurement updates (including clamped writes) still
1041
- // need to reconcile.
1042
1110
  this.scrollState = null
1043
1111
  }
1044
1112
  this.pendingWrite = null
@@ -1047,6 +1115,9 @@ export class Virtualizer<
1047
1115
  // own read-back, which the browser reports at the scroll max we
1048
1116
  // saw at write time. Anything else is a real gesture (or the write
1049
1117
  // landing after all), so drop it rather than yank the user later.
1118
+ // Not `kind !== 'clampedEcho'`: the classifier ranks `readBack` and
1119
+ // `clampedReadBack` first, and either can also sit at that max, so
1120
+ // the record must survive them too.
1050
1121
  if (
1051
1122
  this._clampedAdjustment !== null &&
1052
1123
  Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5
@@ -1059,6 +1130,7 @@ export class Virtualizer<
1059
1130
  // into `scrollOffset`. There's no direction to infer, so leave
1060
1131
  // it alone; a real gesture always moves the offset.
1061
1132
  const prevOffset = this.getScrollOffset()
1133
+ const prevDirection = this.scrollDirection
1062
1134
  this.scrollDirection = isScrolling
1063
1135
  ? prevOffset === offset
1064
1136
  ? this.scrollDirection
@@ -1069,10 +1141,57 @@ export class Virtualizer<
1069
1141
  this.scrollOffset = offset
1070
1142
  this.isScrolling = isScrolling
1071
1143
 
1072
- // Flush deferred iOS adjustments if we're now fully settled.
1073
- // "Fully settled" means: not actively scrolling, no finger on
1074
- // screen, and the post-touchend grace window has expired.
1075
- this._flushIosDeferredIfReady()
1144
+ // A finger that lands on a fling fires no touch events (#1307), so
1145
+ // while a command waits for the fling, the scroll events are all
1146
+ // that show the user taking over: the scroll turns back, or speeds
1147
+ // up (`flingSpedUp`). Momentum does neither inside the scroll
1148
+ // range; a bounce does both, so no part of one counts.
1149
+ const queued = this.scrollState
1150
+ if (
1151
+ queued?.phase === 'queued' &&
1152
+ kind === 'external' &&
1153
+ isScrolling
1154
+ ) {
1155
+ if (wasOverscrolled || this._reportedOverscroll) {
1156
+ queued.samples = []
1157
+ } else {
1158
+ const t = this.now()
1159
+ queued.samples = [
1160
+ ...(queued.samples ?? []).filter(
1161
+ (sample) => t - sample.t <= 200,
1162
+ ),
1163
+ { t, offset: elementOffset },
1164
+ ]
1165
+ if (
1166
+ (prevDirection !== null &&
1167
+ this.scrollDirection !== prevDirection) ||
1168
+ flingSpedUp(queued.samples)
1169
+ ) {
1170
+ this.scrollState = null
1171
+ }
1172
+ }
1173
+ }
1174
+ if (
1175
+ this._iosGesture.onScroll({
1176
+ isScrolling,
1177
+ ownReadBack: kind === 'readBack',
1178
+ moved: offset !== prevOffset,
1179
+ // Neither our write's read-back nor a frame of our smooth
1180
+ // animation: the user or a fling moved it.
1181
+ external:
1182
+ kind === 'external' &&
1183
+ this.scrollState?.phase !== 'smooth' &&
1184
+ this.scrollState?.phase !== 'smoothFinishing',
1185
+ }) &&
1186
+ // The user scrolls: a command still waiting for the tail is
1187
+ // theirs to override, like a written one would be.
1188
+ this.scrollState?.phase === 'queued'
1189
+ ) {
1190
+ this.scrollState = null
1191
+ }
1192
+
1193
+ // A held correction is written once a write is possible.
1194
+ this._flushHoldIfReady(true)
1076
1195
 
1077
1196
  if (this.scrollState) {
1078
1197
  this.scheduleScrollReconcile()
@@ -1081,66 +1200,19 @@ export class Virtualizer<
1081
1200
  }),
1082
1201
  )
1083
1202
 
1084
- // Touch event listeners (iOS-aware deferral). We attach unconditionally
1085
- // — the listeners are passive and cheap; on non-touch devices they
1086
- // simply never fire. The gating by isIOSWebKit() lives in resizeItem
1087
- // and _flushIosDeferredIfReady so we only burn the path on iOS.
1203
+ // Touch event listeners (iOS-aware deferral).
1088
1204
  if ('addEventListener' in this.scrollElement) {
1089
- const scrollEl = this.scrollElement as unknown as EventTarget
1090
- const onTouchStart = () => {
1091
- // A finger back down inside the grace window cancels its tail.
1092
- this._endIosTouch()
1093
- this._iosTouch = { phase: 'down' }
1094
- }
1095
- const onTouchEnd = () => {
1096
- this._endIosTouch()
1097
- if (!isIOSWebKit() || this.targetWindow == null) {
1098
- // Non-iOS: nothing more to track.
1099
- return
1100
- }
1101
- // After ~150 ms with no scroll/touch events, momentum is done.
1102
- const tail = {
1103
- phase: 'tail' as const,
1104
- timerId: this.targetWindow.setTimeout(() => {
1105
- if (this._iosTouch === tail) this._iosTouch = null
1106
- // After the grace window, attempt to flush. The scroll event
1107
- // for momentum decay may have already fired before our timer.
1108
- this._flushIosDeferredIfReady()
1109
- }, 150),
1110
- }
1111
- this._iosTouch = tail
1112
- }
1113
- scrollEl.addEventListener(
1114
- 'touchstart',
1115
- onTouchStart,
1116
- addEventListenerOptions,
1117
- )
1118
- scrollEl.addEventListener(
1119
- 'touchend',
1120
- onTouchEnd,
1121
- addEventListenerOptions,
1205
+ this.unsubs.push(
1206
+ this._iosGesture.listen(this.scrollElement as unknown as EventTarget),
1122
1207
  )
1123
- // Same handler as touchend: iOS can end a touch with touchcancel
1124
- // (system gesture, interrupted scroll) and never fire touchend.
1125
- scrollEl.addEventListener(
1126
- 'touchcancel',
1127
- onTouchEnd,
1128
- addEventListenerOptions,
1129
- )
1130
- this.unsubs.push(() => {
1131
- scrollEl.removeEventListener('touchstart', onTouchStart)
1132
- scrollEl.removeEventListener('touchend', onTouchEnd)
1133
- scrollEl.removeEventListener('touchcancel', onTouchEnd)
1134
- this._endIosTouch()
1135
- })
1136
1208
  }
1137
1209
 
1138
- this._scrollToOffset(this.getScrollOffset(), {
1139
- adjustments: undefined,
1140
- behavior: undefined,
1141
- })
1210
+ this._scrollToOffset(this.getScrollOffset())
1142
1211
  }
1143
1212
 
1213
+ // The consumer has committed the sizer.
1214
+ this._noteClampMax()
1215
+
1144
1216
  const anchor = this.pendingScrollAnchor
1145
1217
  this.pendingScrollAnchor = null
1146
1218
 
@@ -1150,12 +1222,14 @@ export class Virtualizer<
1150
1222
  // virtualizer already computed the correct range during render.
1151
1223
  // Now sync the browser's actual scroll position to match.
1152
1224
  //
1153
- // On iOS WebKit, writing scrollTop during touch/momentum cancels
1154
- // the in-flight scroll. Defer the DOM sync the same way
1155
- // applyScrollAdjustment does — accumulate the delta and let
1156
- // _flushIosDeferredIfReady handle it once the scroll settles.
1157
- if (isIOSWebKit() && this._iosInMotion()) {
1158
- this._iosDeferredAdjustment += anchor.delta
1225
+ // `setOptions` found the element writable; a scroll event between
1226
+ // it and this commit (a concurrent render) can have changed that.
1227
+ // Hold the delta after all and have the rows re-rendered shifted;
1228
+ // an update scheduled from a layout effect commits before paint.
1229
+ if (!this._canWriteScroll()) {
1230
+ this._holdOffset += anchor.delta
1231
+ this._followOffsetTarget(anchor.delta)
1232
+ this.notify(false)
1159
1233
  } else if (
1160
1234
  isSmoothScroll(this.scrollState) &&
1161
1235
  !approxEqual(
@@ -1172,21 +1246,43 @@ export class Virtualizer<
1172
1246
  // A smooth scroll that has already landed (offset at its target,
1173
1247
  // reconcile not yet retired it) still gets the anchor sync.
1174
1248
  } else {
1175
- this._scrollToOffset(this.getScrollOffset(), {
1176
- adjustments: undefined,
1177
- behavior: undefined,
1178
- })
1249
+ this._followOffsetTarget(anchor.delta)
1250
+ this._scrollToOffset(this.getScrollOffset())
1179
1251
  }
1180
1252
  } else {
1181
1253
  this.scrollToEnd({ behavior: anchor.behavior })
1182
1254
  }
1183
1255
  }
1184
1256
 
1257
+ // A hold whose cause has passed without a scroll event (the sizer caught
1258
+ // up with a position that read as overscrolled) is written here. An
1259
+ // update scheduled from a layout effect commits before paint, so the
1260
+ // notify need not be synchronous.
1261
+ this._flushHoldIfReady(false)
1185
1262
  // The consumer has committed the new total size by now, so a clamped
1186
1263
  // compensation write may have room (#1258).
1187
1264
  this._retryClampedAdjustment()
1188
1265
  }
1189
1266
 
1267
+ // Classify a scroll event (see `ScrollEventKind`) from the state as it was
1268
+ // before the event. `offset` is the reported position in layout
1269
+ // coordinates; `elementMax` is the element's own max, read only while
1270
+ // scrolling (null otherwise).
1271
+ private _classifyScrollEvent = (
1272
+ offset: number,
1273
+ isScrolling: boolean,
1274
+ elementMax: number | null,
1275
+ ) =>
1276
+ classifyScrollEvent({
1277
+ offset,
1278
+ isScrolling,
1279
+ elementMax,
1280
+ holdOffset: this._holdOffset,
1281
+ scrollOffset: this.scrollOffset,
1282
+ pendingWrite: this.pendingWrite,
1283
+ clampedMaxAtWrite: this._clampedAdjustment?.maxAtWrite ?? null,
1284
+ })
1285
+
1190
1286
  // Re-issue a compensation write the browser clamped because the sizer had
1191
1287
  // not grown yet (#1258, #1266). Called after `notify` in `resizeItem`,
1192
1288
  // which covers consumers that size the container synchronously inside
@@ -1209,57 +1305,90 @@ export class Virtualizer<
1209
1305
  // the new max so the next opportunity retries.
1210
1306
  this._clampedAdjustment =
1211
1307
  target > max + 0.5 ? { target, maxAtWrite: max } : null
1212
- this._scrollToOffset(target, {
1213
- adjustments: undefined,
1214
- behavior: undefined,
1215
- })
1308
+ this._scrollToOffset(target)
1216
1309
  }
1217
1310
  }
1218
1311
 
1219
- // The element is moving or about to: a scroll in progress, or a touch
1220
- // gesture that may still turn into one (see `_iosTouch`). On iOS a write
1221
- // now would cancel the momentum, so adjustments wait for the flush below.
1222
- private _iosInMotion = () => this.isScrolling || this._iosTouch !== null
1312
+ // Write the command that `_startScroll` left waiting for the momentum
1313
+ // tail, against the layout as it is now (rows measured during the fling
1314
+ // have moved an index target).
1315
+ private _writeAwaitingCommand = () => {
1316
+ const state = this.scrollState
1317
+ if (state === null || state.phase !== 'queued') return
1318
+ const { behavior } = state
1319
+ this.getMeasurements()
1320
+ const offset = this.getScrollStateTarget(state)
1321
+ state.lastTargetOffset = offset
1322
+ // The hold flushed just before can leave a clamp retry (#1258); it
1323
+ // would write its old target over this command.
1324
+ this._clampedAdjustment = null
1325
+ state.phase = initialScrollPhase(
1326
+ behavior,
1327
+ state.index != null && approxEqual(offset, this.getScrollOffset()),
1328
+ )
1329
+ this._scrollToOffset(offset, { behavior })
1330
+ this.scheduleScrollReconcile()
1331
+ }
1223
1332
 
1224
- private _endIosTouch = () => {
1225
- if (this._iosTouch?.phase === 'tail' && this.targetWindow != null) {
1226
- this.targetWindow.clearTimeout(this._iosTouch.timerId)
1333
+ // The element's position as the offset observers report it, or null for a
1334
+ // scroll element that is neither an element nor a window.
1335
+ private _readElementOffset = (): number | null => {
1336
+ const el = this.scrollElement as unknown as Partial<
1337
+ Element & Pick<Window, 'scrollX' | 'scrollY'>
1338
+ > | null
1339
+ if (el == null) return null
1340
+ const { horizontal, isRtl } = this.options
1341
+ if (typeof el.scrollTop === 'number') {
1342
+ return horizontal ? el.scrollLeft! * ((isRtl && -1) || 1) : el.scrollTop
1227
1343
  }
1228
- this._iosTouch = null
1229
- }
1230
-
1231
- // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
1232
- // truly settled — not actively scrolling, not under an active touch, and
1233
- // past the post-touchend grace window. Called from the scroll callback
1234
- // and the touchend grace-timer.
1235
- private _flushIosDeferredIfReady = () => {
1236
- if (this._iosDeferredAdjustment === 0) return
1237
- if (this._iosInMotion()) return
1238
- // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go
1239
- // negative or beyond scrollHeight - clientHeight. Writing scrollTop
1240
- // while in that zone snaps the page back to the clamped value at the
1241
- // end of the bounce, often discarding the user's intent. Skip the
1242
- // flush; the next in-bounds scroll event will retry.
1243
- const cur = this.getScrollOffset()
1244
- const max = this.getMaxScrollOffset()
1245
- if (cur < 0 || cur > max) return
1246
- // At the end clamp the browser already absorbed a shrink above the
1247
- // viewport (it clamped scrollTop onto the new bottom), so replaying our
1248
- // deferred negative delta would lift the view off the bottom — drop it.
1249
- // Positive deltas still replay: growth above doesn't clamp. (#1233)
1250
- if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {
1251
- this._iosDeferredAdjustment = 0
1252
- return
1344
+ if (typeof el.scrollY === 'number') {
1345
+ return horizontal ? el.scrollX! : el.scrollY
1253
1346
  }
1254
- const delta = this._iosDeferredAdjustment
1255
- this._iosDeferredAdjustment = 0
1256
- // Roll the deferred delta into the running accumulator so any resize
1257
- // landing between now and the resulting scroll event computes from the
1258
- // post-flush offset rather than the stale one.
1259
- this._scrollToOffset(cur, {
1260
- adjustments: this.scrollAdjustments + delta,
1261
- behavior: undefined,
1262
- })
1347
+ return null
1348
+ }
1349
+
1350
+ // Whether a scrollTop write made now would reach the element and stay:
1351
+ // - not on iOS while a touch gesture owns the scroll (`IosGesture`): a
1352
+ // dragging finger ignores the write, momentum is cancelled by it on
1353
+ // iOS 26 and earlier and overrides it within a frame on 27 (#884,
1354
+ // #1307), so a correction is held through the tail on every version;
1355
+ // - not while the element is overscrolled past either edge (the
1356
+ // rubber-band bounce): WebKit discards the write and the bounce can
1357
+ // stall where it was (#1287).
1358
+ // A write that is unwanted for another reason (a travelling smooth scroll
1359
+ // owns the position) is a separate check at the call sites.
1360
+ private _canWriteScroll = () =>
1361
+ !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll
1362
+
1363
+ // Write a held correction once a write is possible, from the scroll
1364
+ // handler, the touch tail timer, `_willUpdate` and a resize notify. The
1365
+ // rows go back to layout coordinates and the total grows by the hold in a
1366
+ // notify issued before the write, so the sizer can take the position and
1367
+ // both commit in the paint the write lands in. `sync` is false only where
1368
+ // the caller already runs inside the consumer's commit (`_willUpdate`),
1369
+ // where an update it schedules commits before paint anyway.
1370
+ private _flushHoldIfReady = (sync: boolean) => {
1371
+ if (this._holdOffset === 0) return
1372
+ if (!this.scrollElement || !this.options.enabled) return
1373
+ if (!this._canWriteScroll()) return
1374
+ // Let a travelling smooth scroll land first (see `_willUpdate`).
1375
+ if (this.scrollState?.phase === 'smooth') return
1376
+ this._holdOffset = 0
1377
+ // A held shrink can leave the layout position above the top; the
1378
+ // element clamps that to 0 without an event to say so (#1229).
1379
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
1380
+ this.scrollOffset = 0
1381
+ }
1382
+ this.notify(sync)
1383
+ // A command whose write has not been reported back yet owns the target:
1384
+ // `scrollOffset` is still the pre-command position until its read-back,
1385
+ // and a command that closes the touch tail makes a write possible with
1386
+ // no scroll event in between, so this flush can run first.
1387
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset()
1388
+ // A consumer that sizes the container after this write gets the retry
1389
+ // (#1258).
1390
+ this._clampedAdjustment = this._clampedBy(target)
1391
+ this._scrollToOffset(target)
1263
1392
  }
1264
1393
 
1265
1394
  private rafId: number | null = null
@@ -1295,6 +1424,13 @@ export class Virtualizer<
1295
1424
  return
1296
1425
  }
1297
1426
 
1427
+ // Nothing to reconcile until the tail closes and the command is written;
1428
+ // only the safety valve above applies.
1429
+ if (this.scrollState.phase === 'queued') {
1430
+ this.scheduleScrollReconcile()
1431
+ return
1432
+ }
1433
+
1298
1434
  // A resize since the last render leaves measurementsCache stale until
1299
1435
  // something reads getMeasurements(); rebuild it (memoized) so an index
1300
1436
  // target reflects it even when no render ran in between.
@@ -1331,10 +1467,7 @@ export class Virtualizer<
1331
1467
  // end up at the EXACT computed position of item N — matching
1332
1468
  // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
1333
1469
  if (this.getScrollOffset() !== targetOffset) {
1334
- this._scrollToOffset(targetOffset, {
1335
- adjustments: undefined,
1336
- behavior: 'auto',
1337
- })
1470
+ this._scrollToOffset(targetOffset, { behavior: 'auto' })
1338
1471
  }
1339
1472
  this.scrollState = null
1340
1473
  return
@@ -1370,7 +1503,6 @@ export class Virtualizer<
1370
1503
  // until reconcile sees it at the target; 'instant' stays instant.
1371
1504
 
1372
1505
  this._scrollToOffset(targetOffset, {
1373
- adjustments: undefined,
1374
1506
  behavior: keepSmooth ? 'smooth' : 'auto',
1375
1507
  })
1376
1508
  }
@@ -1873,17 +2005,16 @@ export class Virtualizer<
1873
2005
  this.options.anchorTo === 'end' &&
1874
2006
  !isSmoothScroll(this.scrollState) &&
1875
2007
  this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold
1876
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0
2008
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0
1877
2009
  // Default anchoring predicate (used unless the consumer supplies a
1878
2010
  // custom shouldAdjustScrollPositionOnItemSizeChange).
1879
- const scrollOffsetWithAdj =
1880
- this.getScrollOffset() + this.scrollAdjustments
2011
+ const scrollOffset = this.getScrollOffset()
1881
2012
  const isFirstMeasure = !this.itemSizeCache.has(key)
1882
2013
  const defaultShouldAdjust = isFirstMeasure
1883
2014
  ? // First measurement: compensate any item whose top sits above the
1884
2015
  // fold — the estimate→actual delta must be corrected regardless of
1885
2016
  // scroll direction, since the whole estimated block was above it.
1886
- itemStart < scrollOffsetWithAdj
2017
+ itemStart < scrollOffset
1887
2018
  : // Re-measurement: only compensate an item that is ENTIRELY above the
1888
2019
  // fold. An item that merely *spans* the fold (top above, bottom
1889
2020
  // below — e.g. a streaming chat message growing at its bottom)
@@ -1891,7 +2022,7 @@ export class Virtualizer<
1891
2022
  // delta would drag the viewport downward on every growth (#1218).
1892
2023
  // Also skip during backward scroll to avoid the "items jump while
1893
2024
  // scrolling up" cascade.
1894
- itemStart + itemSize <= scrollOffsetWithAdj &&
2025
+ itemStart + itemSize <= scrollOffset &&
1895
2026
  this.scrollDirection !== 'backward'
1896
2027
  const shouldAdjustScroll =
1897
2028
  !isSmoothScroll(this.scrollState) &&
@@ -1918,30 +2049,14 @@ export class Virtualizer<
1918
2049
  this.itemSizeCache.set(key, size)
1919
2050
  this.itemSizeCacheVersion++
1920
2051
 
1921
- // A scroll command (or reconcile) wrote a new position that neither a
1922
- // scroll event nor an eager update has reflected in `scrollOffset` yet.
1923
- // The rows being measured were rendered for the old position, so
1924
- // "above the viewport" means nothing against either offset. An index
1925
- // or end target is retargeted from fresh measurements by
1926
- // reconcileScroll next frame; an offset target (scrollToOffset,
1927
- // scrollBy) lands where it was written and the delta is not applied,
1928
- // since compensating against the stale offset would overwrite the
1929
- // command. Compensation writes and the prepend anchor sync update
1930
- // `scrollOffset` eagerly, and the iOS flush writes exactly
1931
- // `scrollOffset + scrollAdjustments`, so none of them count.
1932
- const writtenOffset = this.getCommandWrittenOffset()
1933
- const awaitingCommandReadBack =
1934
- writtenOffset !== null &&
1935
- !approxEqual(
1936
- writtenOffset,
1937
- this.getScrollOffset() + this.scrollAdjustments,
1938
- )
1939
-
2052
+ // Before a command's read-back, an index or end target is retargeted
2053
+ // from fresh measurements by reconcileScroll next frame; an offset
2054
+ // target lands where it was written and the delta is not applied.
1940
2055
  let adjustedSync = false
1941
- if (!awaitingCommandReadBack) {
2056
+ if (!this._awaitingCommandReadBack()) {
1942
2057
  if (wasAtEnd) {
1943
2058
  adjustedSync = this.applyScrollAdjustment(
1944
- this.getTotalSize() - prevTotalSize,
2059
+ this._getLayoutTotalSize() - prevTotalSize,
1945
2060
  )
1946
2061
  } else if (shouldAdjustScroll) {
1947
2062
  adjustedSync = this.applyScrollAdjustment(delta)
@@ -1966,24 +2081,36 @@ export class Virtualizer<
1966
2081
  return
1967
2082
  }
1968
2083
  this.notify(adjustedSync)
2084
+ this._noteClampMax()
1969
2085
  // A consumer that grows the sizer synchronously inside `onChange`
1970
2086
  // (direct DOM updates) may never re-render when the range is
1971
2087
  // unchanged, so retry a clamped write here rather than only in
1972
2088
  // `_willUpdate` (#1266).
2089
+ this._flushHoldIfReady(true)
1973
2090
  this._retryClampedAdjustment()
1974
2091
  }
1975
2092
  }
1976
2093
 
1977
2094
  getVirtualItems = memo(
1978
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1979
- (indexes, measurements) => {
2095
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
2096
+ (indexes, measurements, hold) => {
1980
2097
  const virtualItems: Array<VirtualItem> = []
1981
2098
 
1982
2099
  for (let k = 0, len = indexes.length; k < len; k++) {
1983
2100
  const i = indexes[k]!
1984
2101
  const measurement = measurements[i]!
1985
2102
 
1986
- virtualItems.push(measurement)
2103
+ // A held correction is exposed as a shift of every row (see
2104
+ // `_holdOffset`); the layout itself is untouched.
2105
+ virtualItems.push(
2106
+ hold === 0
2107
+ ? measurement
2108
+ : {
2109
+ ...measurement,
2110
+ start: measurement.start - hold,
2111
+ end: measurement.end - hold,
2112
+ },
2113
+ )
1987
2114
  }
1988
2115
 
1989
2116
  return virtualItems
@@ -2015,26 +2142,129 @@ export class Virtualizer<
2015
2142
  return notUndefined(measurements[idx])
2016
2143
  }
2017
2144
 
2018
- private getMaxScrollOffset = () => {
2019
- if (!this.scrollElement) return 0
2145
+ // Record the element's max, in layout coordinates, as one a command's
2146
+ // pending instant write may be clamped to (see `lowMaxes` on
2147
+ // `pendingWrite`). Called where the sizer can have been committed: after
2148
+ // a notify, for a consumer that sizes it in `onChange`, and in
2149
+ // `_willUpdate`. The element cannot clamp below its own 0, which is the
2150
+ // hold in layout coordinates.
2151
+ private _noteClampMax = () => {
2152
+ if (!this._awaitingCommandReadBack()) return
2153
+ const elementMax = this._elementMaxScrollOffset()
2154
+ if (elementMax === null) return
2155
+ const write = this.pendingWrite!
2156
+ const max = Math.max(elementMax, 0) + this._holdOffset
2157
+ if (max >= write.target) return
2158
+ const lowMaxes = (write.lowMaxes ??= [])
2159
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max)
2160
+ }
2161
+
2162
+ // The element's scroll range in layout coordinates: while a correction is
2163
+ // held the sizer is short by the hold, so the element's own max is too.
2164
+ private getMaxScrollOffset = () =>
2165
+ (this._elementMaxScrollOffset() ?? 0) + this._holdOffset
2166
+
2167
+ // An element position in layout coordinates: how far the layout position
2168
+ // is ahead of the element. The element is `_holdOffset` behind while a
2169
+ // correction is held, and a prepend's anchor delta behind from
2170
+ // `setOptions` (which moved `scrollOffset` by it) until `_willUpdate`
2171
+ // writes or holds it. Writes (`_scrollToOffset`) and the clamp record
2172
+ // (`_clampedBy`) deliberately subtract the hold alone, not this whole
2173
+ // lead: by the time they run, the anchor delta is already in
2174
+ // `scrollOffset`, and writing that layout position is what closes it.
2175
+ private _toLayoutOffset = (elementOffset: number) => {
2176
+ let offset = elementOffset + this._holdOffset
2177
+ if (this.pendingScrollAnchor?.kind === 'anchor') {
2178
+ offset += this.pendingScrollAnchor.delta
2179
+ }
2180
+ return offset
2181
+ }
2020
2182
 
2021
- if ('scrollHeight' in this.scrollElement) {
2022
- // Element
2183
+ // The element's own scroll range, or null where it cannot be read (no
2184
+ // element, or a bare test double without `scrollHeight` / `document`).
2185
+ private _elementMaxScrollOffset = (): number | null => {
2186
+ const el = this.scrollElement
2187
+ if (el === null) return null
2188
+ if ('scrollHeight' in el) {
2023
2189
  return this.options.horizontal
2024
- ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth
2025
- : this.scrollElement.scrollHeight - this.scrollElement.clientHeight
2026
- } else {
2027
- // Window
2028
- const doc = this.scrollElement.document.documentElement
2190
+ ? el.scrollWidth - el.clientWidth
2191
+ : el.scrollHeight - el.clientHeight
2192
+ }
2193
+ if ('document' in el) {
2194
+ const doc = el.document.documentElement
2029
2195
  return this.options.horizontal
2030
- ? doc.scrollWidth - this.scrollElement.innerWidth
2031
- : doc.scrollHeight - this.scrollElement.innerHeight
2196
+ ? doc.scrollWidth - el.innerWidth
2197
+ : doc.scrollHeight - el.innerHeight
2198
+ }
2199
+ return null
2200
+ }
2201
+
2202
+ // Stop a running iOS fling, then call `done`: the momentum does not
2203
+ // survive the element losing its overflow for a frame. Hidden and
2204
+ // restored within one task, iOS never sees the change and the fling
2205
+ // carries on (27.0.1 iPhone); hidden for two frames, it stops at once.
2206
+ // Nothing moves on screen. A second call while one is in progress waits
2207
+ // for the same frames. The app's inline value comes back, unless the app
2208
+ // set a new one meanwhile; `done` is then not called.
2209
+ private _momentumStop: { restore: () => boolean; done: () => void } | null =
2210
+ null
2211
+ private _stopMomentum = (done: () => void) => {
2212
+ const el = this.scrollElement
2213
+ const win = this.targetWindow
2214
+ if (el === null || win === null) return
2215
+ const scroller = (
2216
+ 'document' in el ? el.document.scrollingElement : el
2217
+ ) as HTMLElement | null
2218
+ // A test double may have no style to change.
2219
+ if (!scroller?.style) return
2220
+ if (this._momentumStop) {
2221
+ this._momentumStop.done = done
2222
+ return
2223
+ }
2224
+ const { style } = scroller
2225
+ const property = this.options.horizontal ? 'overflow-x' : 'overflow-y'
2226
+ const value = style.getPropertyValue(property)
2227
+ const priority = style.getPropertyPriority(property)
2228
+ style.setProperty(property, 'hidden', 'important')
2229
+ const stop = {
2230
+ // False when the app replaced the hidden value: the fling may not
2231
+ // have stopped.
2232
+ restore: () => {
2233
+ if (
2234
+ style.getPropertyValue(property) !== 'hidden' ||
2235
+ style.getPropertyPriority(property) !== 'important'
2236
+ ) {
2237
+ return false
2238
+ }
2239
+ style.setProperty(property, value, priority)
2240
+ return true
2241
+ },
2242
+ done,
2032
2243
  }
2244
+ this._momentumStop = stop
2245
+ win.requestAnimationFrame(() =>
2246
+ win.requestAnimationFrame(() => {
2247
+ // Already restored by `cleanup`, which also drops its command.
2248
+ if (this._momentumStop !== stop) return
2249
+ this._momentumStop = null
2250
+ // The command waits for the tail, as without the stop.
2251
+ if (stop.restore()) stop.done()
2252
+ }),
2253
+ )
2254
+ }
2255
+
2256
+ // A compensation write past the element's current max (the sizer has not
2257
+ // grown yet) is clamped by the browser; record it for the retry (#1258).
2258
+ private _clampedBy = (target: number) => {
2259
+ const elementMax = this._elementMaxScrollOffset()
2260
+ if (elementMax === null) return null
2261
+ const maxAtWrite = elementMax + this._holdOffset
2262
+ return target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null
2033
2263
  }
2034
2264
 
2035
2265
  private getVirtualDistanceFromEnd = () => {
2036
2266
  return Math.max(
2037
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
2267
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
2038
2268
  0,
2039
2269
  )
2040
2270
  }
@@ -2137,13 +2367,8 @@ export class Virtualizer<
2137
2367
  index = Math.max(0, Math.min(index, this.options.count - 1))
2138
2368
 
2139
2369
  const offsetInfo = this.getOffsetForIndex(index, initialAlign)
2140
- if (!offsetInfo) {
2141
- // No target (an empty list), so nothing is written; still drop the
2142
- // deferral like every absolute command, or it replays once the list
2143
- // refills.
2144
- this._iosDeferredAdjustment = 0
2145
- return
2146
- }
2370
+ // No target (an empty list), so nothing is written.
2371
+ if (!offsetInfo) return
2147
2372
  const [offset, align] = offsetInfo
2148
2373
 
2149
2374
  this._startScroll({ index, align }, offset, behavior, 'absolute')
@@ -2190,12 +2415,10 @@ export class Virtualizer<
2190
2415
  // Every scroll command starts here: it becomes the in-flight command,
2191
2416
  // writes its first target and leaves reconcile to retarget and retire it.
2192
2417
  //
2193
- // An absolute command derives its target from current measurements, so
2194
- // any iOS-deferred compensation still pending is stale by definition —
2195
- // the command already accounts for the measurements the delta was
2196
- // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
2197
- // onto the just-established position. A relative command (scrollBy)
2198
- // builds on the current offset, so it keeps the deferral.
2418
+ // Targets are layout offsets. A held correction is not dropped by a
2419
+ // command: the write lands the element `_holdOffset` short of the target,
2420
+ // under the rows exposed shifted by the same amount, and the flush moves
2421
+ // both together once a write is possible.
2199
2422
  //
2200
2423
  // An index or end target that is already at its offset starts a smooth
2201
2424
  // scroll as landed; an offset target never does, so its first scroll
@@ -2206,20 +2429,68 @@ export class Virtualizer<
2206
2429
  behavior: ScrollBehavior,
2207
2430
  kind: 'absolute' | 'relative',
2208
2431
  ) {
2209
- if (kind === 'absolute') {
2210
- this._iosDeferredAdjustment = 0
2432
+ const tail = this._iosGesture.tail()
2433
+ if (kind === 'absolute' && tail !== null) {
2434
+ if (tail === 'fling' && iosMomentumOverridesWrites()) {
2435
+ // iOS 27: a write now shows for one frame and the fling carries on
2436
+ // along its own path, so the command would be lost (#1307, step 3).
2437
+ // Stop the fling and write two frames later. Otherwise (no style to
2438
+ // change, a finger down, a bounce) the tail stays open and
2439
+ // the command is written when it closes, ~150ms after the last
2440
+ // fling frame. The user taking over before the write (a drag, a
2441
+ // second flick, a finger stopping the fling) cancels the command
2442
+ // (see the scroll handler and `onTailClosed`). A relative command
2443
+ // (`scrollBy`) is not postponed: its target is taken from the
2444
+ // position at the call, which the fling leaves behind either way.
2445
+ this._stopMomentum(() => {
2446
+ const state = this.scrollState
2447
+ if (
2448
+ state?.phase !== 'queued' ||
2449
+ // A finger came down: it owns the scroll until it lifts.
2450
+ this._iosGesture.tail() !== 'fling' ||
2451
+ // In a bounce WebKit can drop the write (#1287): the tail
2452
+ // decides, as without the stop. (Not `flingCaught`: our stop
2453
+ // also ends the fling at speed, so a slow frame would read as
2454
+ // a catch and the tail would drop the command.)
2455
+ this._reportedOverscroll
2456
+ ) {
2457
+ return
2458
+ }
2459
+ this._iosGesture.end()
2460
+ this._flushHoldIfReady(true)
2461
+ this._writeAwaitingCommand()
2462
+ })
2463
+ this.scrollState = {
2464
+ ...target,
2465
+ startedAt: this.now(),
2466
+ lastTargetOffset: offset,
2467
+ stableFrames: 0,
2468
+ phase: 'queued',
2469
+ behavior,
2470
+ samples: [],
2471
+ }
2472
+ this.scheduleScrollReconcile()
2473
+ return
2474
+ }
2475
+ // The command takes over the scroll, so close the tail: the landing's
2476
+ // corrections then apply before paint, even for a command issued from
2477
+ // a tap handler inside the tail (#1250). On iOS 26 and earlier the
2478
+ // write stops the momentum. With a finger down the user owns the
2479
+ // scroll: leave it.
2480
+ this._iosGesture.end()
2211
2481
  }
2212
2482
  this.scrollState = {
2213
2483
  ...target,
2214
2484
  startedAt: this.now(),
2215
2485
  lastTargetOffset: offset,
2216
2486
  stableFrames: 0,
2487
+ behavior,
2217
2488
  phase: initialScrollPhase(
2218
2489
  behavior,
2219
2490
  target.index != null && approxEqual(offset, this.getScrollOffset()),
2220
2491
  ),
2221
2492
  }
2222
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2493
+ this._scrollToOffset(offset, { behavior })
2223
2494
  this.scheduleScrollReconcile()
2224
2495
  }
2225
2496
 
@@ -2235,7 +2506,13 @@ export class Virtualizer<
2235
2506
  this.scrollState = null
2236
2507
  }
2237
2508
 
2238
- getTotalSize = () => {
2509
+ // The size the consumer gives the container: the layout's total, short by
2510
+ // a held correction so the rows exposed shifted by it still fill it (see
2511
+ // `_holdOffset`).
2512
+ getTotalSize = () =>
2513
+ Math.max(this._getLayoutTotalSize() - this._holdOffset, 0)
2514
+
2515
+ private _getLayoutTotalSize = () => {
2239
2516
  const measurements = this.getMeasurements()
2240
2517
 
2241
2518
  let end: number
@@ -2314,17 +2591,21 @@ export class Virtualizer<
2314
2591
  {
2315
2592
  adjustments,
2316
2593
  behavior,
2317
- }: {
2318
- adjustments: number | undefined
2319
- behavior: ScrollBehavior | undefined
2320
- },
2594
+ }: { adjustments?: number; behavior?: ScrollBehavior } = {},
2321
2595
  ) => {
2322
- this.pendingWrite = {
2596
+ const write = {
2323
2597
  target: offset + (adjustments ?? 0),
2324
2598
  smooth: behavior === 'smooth',
2325
- adjustments: adjustments ?? this.scrollAdjustments,
2326
2599
  }
2327
- this.options.scrollToFn(offset, { behavior, adjustments }, this)
2600
+ this.pendingWrite = write
2601
+ // The element sits `_holdOffset` behind the layout while a correction
2602
+ // is held; `target` and the read-back stay in layout coordinates.
2603
+ this.options.scrollToFn(
2604
+ offset - this._holdOffset,
2605
+ { behavior, adjustments },
2606
+ this,
2607
+ )
2608
+ return write
2328
2609
  }
2329
2610
 
2330
2611
  // Where the in-flight command's last instant write put the element, until
@@ -2339,6 +2620,35 @@ export class Virtualizer<
2339
2620
  ? this.pendingWrite.target
2340
2621
  : null
2341
2622
 
2623
+ // A scroll command (or reconcile) wrote a new position that neither a
2624
+ // scroll event nor an eager update has reflected in `scrollOffset` yet.
2625
+ // The rows on screen were rendered for the old position, so "above the
2626
+ // viewport" means nothing against either offset: a correction decided now
2627
+ // would be written over the command. Compensation writes and the prepend
2628
+ // anchor sync update `scrollOffset` eagerly, and the hold's flush writes
2629
+ // exactly `scrollOffset`, so none of them count. Under a dragging finger
2630
+ // iOS ignores the write, so no read-back will come and the hold takes the
2631
+ // correction instead.
2632
+ private _awaitingCommandReadBack = () => {
2633
+ const writtenOffset = this.getCommandWrittenOffset()
2634
+ return (
2635
+ !(isIOSWebKit() && this._iosGesture.dragging()) &&
2636
+ writtenOffset !== null &&
2637
+ !approxEqual(writtenOffset, this.getScrollOffset())
2638
+ )
2639
+ }
2640
+
2641
+ // An offset target (scrollToOffset, scrollBy) is a layout position. A
2642
+ // correction for content above the viewport moves the viewport's layout
2643
+ // position by `delta`, and the target moves with it, so reconcile sees the
2644
+ // command reached rather than waiting for a position it can never see
2645
+ // (#1307, step 5). Index and end targets are recomputed from the layout.
2646
+ private _followOffsetTarget = (delta: number) => {
2647
+ if (this.scrollState !== null && this.scrollState.index == null) {
2648
+ this.scrollState.lastTargetOffset += delta
2649
+ }
2650
+ }
2651
+
2342
2652
  measure = () => {
2343
2653
  // Reset pendingMin so the next getMeasurements rebuilds from index 0.
2344
2654
  // Without this, a prior resizeItem() that left pendingMin > 0 would