@tanstack/virtual-core 3.19.4 → 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
 
@@ -409,15 +401,6 @@ export interface VirtualizerOptions<
409
401
  useCachedMeasurements?: boolean
410
402
  }
411
403
 
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
404
  type ScrollState = {
422
405
  // what we want
423
406
  index: number | null
@@ -427,6 +410,8 @@ type ScrollState = {
427
410
 
428
411
  // lifecycle
429
412
  startedAt: number
413
+ // how the command was asked to scroll; a queued command writes with it
414
+ behavior: ScrollBehavior
430
415
 
431
416
  // target tracking
432
417
  lastTargetOffset: number
@@ -434,6 +419,11 @@ type ScrollState = {
434
419
  // settling
435
420
  stableFrames: number
436
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>
437
427
  }
438
428
 
439
429
  const initialScrollPhase = (
@@ -447,11 +437,6 @@ const initialScrollPhase = (
447
437
  const isSmoothScroll = (state: ScrollState | null): state is ScrollState =>
448
438
  state?.phase === 'smooth' || state?.phase === 'smoothLanded'
449
439
 
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
440
  // What `setOptions` decided about the scroll position for `_willUpdate` to
456
441
  // carry out once the consumer has rendered: keep the reading anchor in place
457
442
  // after a prepend (`scrollOffset` already moved by `delta`, the element has
@@ -518,37 +503,106 @@ export class Virtualizer<
518
503
  private lanesSettling = false
519
504
  private pendingScrollAnchor: PendingScrollAnchor | null = null
520
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
+ */
521
513
  scrollOffset: number | null = null
522
514
  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.
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
+ */
526
520
  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
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
547
600
  // Our last write to the element, from `_scrollToOffset` until the next
548
601
  // scroll event reports it (the only place it is cleared). Until then
549
602
  // `scrollOffset` may still hold the old position.
550
603
  //
551
- // - `target`: where the write puts the element (offset + adjustments).
604
+ // - `target`: where the write puts the element (offset + the adjustment
605
+ // passed to `scrollToFn`).
552
606
  // Safari (and Chrome/Firefox under certain DPRs) round writes to whole
553
607
  // pixels: wrote 12345.5, read back 12346. A read-back within 1.5px of
554
608
  // `target` is taken as our own and adopts the exact value, so reconcile
@@ -556,12 +610,17 @@ export class Virtualizer<
556
610
  // further by the time it reports.
557
611
  // - `smooth`: the write animates, so until it lands the element is
558
612
  // somewhere between the old offset and `target`.
559
- // - `adjustments`: see `scrollAdjustments`. Writes that pass none keep the
560
- // 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`).
561
620
  private pendingWrite: {
562
621
  target: number
563
622
  smooth: boolean
564
- adjustments: number
623
+ lowMaxes?: Array<number>
565
624
  } | null = null
566
625
  // A compensation write from `applyScrollAdjustment` whose target exceeded
567
626
  // the element's scroll max at the moment of the write. The browser clamps
@@ -615,6 +674,8 @@ export class Virtualizer<
615
674
  this._resizeBatch = null
616
675
  if (batch.notify) {
617
676
  this.notify(batch.sync)
677
+ this._noteClampMax()
678
+ this._flushHoldIfReady(true)
618
679
  this._retryClampedAdjustment()
619
680
  }
620
681
  }
@@ -798,8 +859,18 @@ export class Virtualizer<
798
859
  // the virtualizer would render the wrong items for one frame (the
799
860
  // estimate-based positions are stale) and then correct in the next
800
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).
801
868
  let anchorDelta: number | null = null
802
- if (anchor && this.scrollOffset !== null) {
869
+ if (
870
+ anchor &&
871
+ this.scrollOffset !== null &&
872
+ !this._awaitingCommandReadBack()
873
+ ) {
803
874
  const [anchorKey, anchorOffset] = anchor
804
875
  const newMeasurements = this.getMeasurements()
805
876
  const { count, getItemKey } = this.options
@@ -827,7 +898,16 @@ export class Virtualizer<
827
898
  if (followOnAppend) {
828
899
  this.pendingScrollAnchor = { kind: 'follow', behavior: followOnAppend }
829
900
  } else if (anchorDelta !== null) {
830
- 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
+ }
831
911
  }
832
912
  }
833
913
 
@@ -849,28 +929,23 @@ export class Virtualizer<
849
929
  console.info('correction', delta)
850
930
  }
851
931
 
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
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
859
944
  } 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,
945
+ const offset = this.getScrollOffset()
946
+ this._clampedAdjustment = this._clampedBy(offset + delta)
947
+ const write = this._scrollToOffset(offset, {
948
+ adjustments: delta,
874
949
  behavior,
875
950
  })
876
951
  // Eagerly carry the intended target in `scrollOffset` so callers that
@@ -879,19 +954,18 @@ export class Virtualizer<
879
954
  // post-adjustment position even when the DOM `scrollTop` write was
880
955
  // clamped because the consumer hasn't grown the sizer yet (`notify()`
881
956
  // 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.
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`).
885
960
  if (this.scrollOffset !== null) {
886
- this.scrollOffset += this.scrollAdjustments
961
+ if (this.pendingWrite === write) this.scrollOffset += delta
887
962
  // Clamp only the lower bound: a negative offset is unreachable, and
888
963
  // on an unscrollable element (content fits the viewport) no scroll
889
964
  // event ever fires to correct it, permanently skewing
890
- // getDistanceFromEnd() and wedging _flushIosDeferredIfReady (#1229).
965
+ // getDistanceFromEnd() and wedging the hold flush (#1229).
891
966
  // Upper-bound overflow stays untouched — it is transiently
892
967
  // legitimate mid-prepend while the consumer's sizer catches up.
893
968
  if (this.scrollOffset < 0) this.scrollOffset = 0
894
- if (this.pendingWrite) this.pendingWrite.adjustments = 0
895
969
  }
896
970
  return true
897
971
  }
@@ -930,6 +1004,10 @@ export class Virtualizer<
930
1004
  this.rafId = null
931
1005
  }
932
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
933
1011
  // The debounce cancelled above is the only thing that writes `isScrolling`
934
1012
  // back to false, so a cleanup inside the reset window would strand it, and
935
1013
  // the direction derived from it, as true. That matters because `cleanup`
@@ -943,11 +1021,12 @@ export class Virtualizer<
943
1021
  // capture), so the new element never reports it. Carrying the state
944
1022
  // over would replay a stale deferred delta on the new element's first
945
1023
  // 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
1024
+ // grace window would strand the gesture (the listeners that end it were
947
1025
  // just removed), deferring every adjustment on the new element until
948
1026
  // its next touch cycle.
949
- this._iosDeferredAdjustment = 0
950
- this._endIosTouch()
1027
+ this._holdOffset = 0
1028
+ this._reportedOverscroll = false
1029
+ // (The gesture was ended with its listeners, in the unsubs above.)
951
1030
  this._clampedAdjustment = null
952
1031
  // A write to the old element will never be read back.
953
1032
  this.pendingWrite = null
@@ -995,50 +1074,47 @@ export class Virtualizer<
995
1074
 
996
1075
  this.unsubs.push(
997
1076
  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
- }
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
1012
1095
 
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
1096
+ if (kind === 'readBack') {
1097
+ // Adopt the exact target over the browser's rounded value (see
1098
+ // `pendingWrite`).
1099
+ offset = this.pendingWrite!.target
1018
1100
  } else if (
1101
+ kind === 'clampedReadBack' &&
1019
1102
  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)
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
+ })
1038
1117
  ) {
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
1118
  this.scrollState = null
1043
1119
  }
1044
1120
  this.pendingWrite = null
@@ -1047,6 +1123,9 @@ export class Virtualizer<
1047
1123
  // own read-back, which the browser reports at the scroll max we
1048
1124
  // saw at write time. Anything else is a real gesture (or the write
1049
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.
1050
1129
  if (
1051
1130
  this._clampedAdjustment !== null &&
1052
1131
  Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5
@@ -1059,6 +1138,7 @@ export class Virtualizer<
1059
1138
  // into `scrollOffset`. There's no direction to infer, so leave
1060
1139
  // it alone; a real gesture always moves the offset.
1061
1140
  const prevOffset = this.getScrollOffset()
1141
+ const prevDirection = this.scrollDirection
1062
1142
  this.scrollDirection = isScrolling
1063
1143
  ? prevOffset === offset
1064
1144
  ? this.scrollDirection
@@ -1069,10 +1149,57 @@ export class Virtualizer<
1069
1149
  this.scrollOffset = offset
1070
1150
  this.isScrolling = isScrolling
1071
1151
 
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()
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)
1076
1203
 
1077
1204
  if (this.scrollState) {
1078
1205
  this.scheduleScrollReconcile()
@@ -1081,66 +1208,19 @@ export class Virtualizer<
1081
1208
  }),
1082
1209
  )
1083
1210
 
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.
1211
+ // Touch event listeners (iOS-aware deferral).
1088
1212
  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,
1122
- )
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,
1213
+ this.unsubs.push(
1214
+ this._iosGesture.listen(this.scrollElement as unknown as EventTarget),
1129
1215
  )
1130
- this.unsubs.push(() => {
1131
- scrollEl.removeEventListener('touchstart', onTouchStart)
1132
- scrollEl.removeEventListener('touchend', onTouchEnd)
1133
- scrollEl.removeEventListener('touchcancel', onTouchEnd)
1134
- this._endIosTouch()
1135
- })
1136
1216
  }
1137
1217
 
1138
- this._scrollToOffset(this.getScrollOffset(), {
1139
- adjustments: undefined,
1140
- behavior: undefined,
1141
- })
1218
+ this._scrollToOffset(this.getScrollOffset())
1142
1219
  }
1143
1220
 
1221
+ // The consumer has committed the sizer.
1222
+ this._noteClampMax()
1223
+
1144
1224
  const anchor = this.pendingScrollAnchor
1145
1225
  this.pendingScrollAnchor = null
1146
1226
 
@@ -1150,12 +1230,14 @@ export class Virtualizer<
1150
1230
  // virtualizer already computed the correct range during render.
1151
1231
  // Now sync the browser's actual scroll position to match.
1152
1232
  //
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
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)
1159
1241
  } else if (
1160
1242
  isSmoothScroll(this.scrollState) &&
1161
1243
  !approxEqual(
@@ -1172,21 +1254,43 @@ export class Virtualizer<
1172
1254
  // A smooth scroll that has already landed (offset at its target,
1173
1255
  // reconcile not yet retired it) still gets the anchor sync.
1174
1256
  } else {
1175
- this._scrollToOffset(this.getScrollOffset(), {
1176
- adjustments: undefined,
1177
- behavior: undefined,
1178
- })
1257
+ this._followOffsetTarget(anchor.delta)
1258
+ this._scrollToOffset(this.getScrollOffset())
1179
1259
  }
1180
1260
  } else {
1181
1261
  this.scrollToEnd({ behavior: anchor.behavior })
1182
1262
  }
1183
1263
  }
1184
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)
1185
1270
  // The consumer has committed the new total size by now, so a clamped
1186
1271
  // compensation write may have room (#1258).
1187
1272
  this._retryClampedAdjustment()
1188
1273
  }
1189
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
+
1190
1294
  // Re-issue a compensation write the browser clamped because the sizer had
1191
1295
  // not grown yet (#1258, #1266). Called after `notify` in `resizeItem`,
1192
1296
  // which covers consumers that size the container synchronously inside
@@ -1209,57 +1313,90 @@ export class Virtualizer<
1209
1313
  // the new max so the next opportunity retries.
1210
1314
  this._clampedAdjustment =
1211
1315
  target > max + 0.5 ? { target, maxAtWrite: max } : null
1212
- this._scrollToOffset(target, {
1213
- adjustments: undefined,
1214
- behavior: undefined,
1215
- })
1316
+ this._scrollToOffset(target)
1216
1317
  }
1217
1318
  }
1218
1319
 
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
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
+ }
1223
1340
 
1224
- private _endIosTouch = () => {
1225
- if (this._iosTouch?.phase === 'tail' && this.targetWindow != null) {
1226
- 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
1227
1351
  }
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
1352
+ if (typeof el.scrollY === 'number') {
1353
+ return horizontal ? el.scrollX! : el.scrollY
1253
1354
  }
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
- })
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)
1263
1400
  }
1264
1401
 
1265
1402
  private rafId: number | null = null
@@ -1295,6 +1432,13 @@ export class Virtualizer<
1295
1432
  return
1296
1433
  }
1297
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
+
1298
1442
  // A resize since the last render leaves measurementsCache stale until
1299
1443
  // something reads getMeasurements(); rebuild it (memoized) so an index
1300
1444
  // target reflects it even when no render ran in between.
@@ -1331,10 +1475,7 @@ export class Virtualizer<
1331
1475
  // end up at the EXACT computed position of item N — matching
1332
1476
  // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
1333
1477
  if (this.getScrollOffset() !== targetOffset) {
1334
- this._scrollToOffset(targetOffset, {
1335
- adjustments: undefined,
1336
- behavior: 'auto',
1337
- })
1478
+ this._scrollToOffset(targetOffset, { behavior: 'auto' })
1338
1479
  }
1339
1480
  this.scrollState = null
1340
1481
  return
@@ -1370,7 +1511,6 @@ export class Virtualizer<
1370
1511
  // until reconcile sees it at the target; 'instant' stays instant.
1371
1512
 
1372
1513
  this._scrollToOffset(targetOffset, {
1373
- adjustments: undefined,
1374
1514
  behavior: keepSmooth ? 'smooth' : 'auto',
1375
1515
  })
1376
1516
  }
@@ -1873,17 +2013,16 @@ export class Virtualizer<
1873
2013
  this.options.anchorTo === 'end' &&
1874
2014
  !isSmoothScroll(this.scrollState) &&
1875
2015
  this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold
1876
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0
2016
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0
1877
2017
  // Default anchoring predicate (used unless the consumer supplies a
1878
2018
  // custom shouldAdjustScrollPositionOnItemSizeChange).
1879
- const scrollOffsetWithAdj =
1880
- this.getScrollOffset() + this.scrollAdjustments
2019
+ const scrollOffset = this.getScrollOffset()
1881
2020
  const isFirstMeasure = !this.itemSizeCache.has(key)
1882
2021
  const defaultShouldAdjust = isFirstMeasure
1883
2022
  ? // First measurement: compensate any item whose top sits above the
1884
2023
  // fold — the estimate→actual delta must be corrected regardless of
1885
2024
  // scroll direction, since the whole estimated block was above it.
1886
- itemStart < scrollOffsetWithAdj
2025
+ itemStart < scrollOffset
1887
2026
  : // Re-measurement: only compensate an item that is ENTIRELY above the
1888
2027
  // fold. An item that merely *spans* the fold (top above, bottom
1889
2028
  // below — e.g. a streaming chat message growing at its bottom)
@@ -1891,7 +2030,7 @@ export class Virtualizer<
1891
2030
  // delta would drag the viewport downward on every growth (#1218).
1892
2031
  // Also skip during backward scroll to avoid the "items jump while
1893
2032
  // scrolling up" cascade.
1894
- itemStart + itemSize <= scrollOffsetWithAdj &&
2033
+ itemStart + itemSize <= scrollOffset &&
1895
2034
  this.scrollDirection !== 'backward'
1896
2035
  const shouldAdjustScroll =
1897
2036
  !isSmoothScroll(this.scrollState) &&
@@ -1918,30 +2057,14 @@ export class Virtualizer<
1918
2057
  this.itemSizeCache.set(key, size)
1919
2058
  this.itemSizeCacheVersion++
1920
2059
 
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
-
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.
1940
2063
  let adjustedSync = false
1941
- if (!awaitingCommandReadBack) {
2064
+ if (!this._awaitingCommandReadBack()) {
1942
2065
  if (wasAtEnd) {
1943
2066
  adjustedSync = this.applyScrollAdjustment(
1944
- this.getTotalSize() - prevTotalSize,
2067
+ this._getLayoutTotalSize() - prevTotalSize,
1945
2068
  )
1946
2069
  } else if (shouldAdjustScroll) {
1947
2070
  adjustedSync = this.applyScrollAdjustment(delta)
@@ -1966,24 +2089,36 @@ export class Virtualizer<
1966
2089
  return
1967
2090
  }
1968
2091
  this.notify(adjustedSync)
2092
+ this._noteClampMax()
1969
2093
  // A consumer that grows the sizer synchronously inside `onChange`
1970
2094
  // (direct DOM updates) may never re-render when the range is
1971
2095
  // unchanged, so retry a clamped write here rather than only in
1972
2096
  // `_willUpdate` (#1266).
2097
+ this._flushHoldIfReady(true)
1973
2098
  this._retryClampedAdjustment()
1974
2099
  }
1975
2100
  }
1976
2101
 
1977
2102
  getVirtualItems = memo(
1978
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1979
- (indexes, measurements) => {
2103
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
2104
+ (indexes, measurements, hold) => {
1980
2105
  const virtualItems: Array<VirtualItem> = []
1981
2106
 
1982
2107
  for (let k = 0, len = indexes.length; k < len; k++) {
1983
2108
  const i = indexes[k]!
1984
2109
  const measurement = measurements[i]!
1985
2110
 
1986
- 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
+ )
1987
2122
  }
1988
2123
 
1989
2124
  return virtualItems
@@ -2015,26 +2150,129 @@ export class Virtualizer<
2015
2150
  return notUndefined(measurements[idx])
2016
2151
  }
2017
2152
 
2018
- private getMaxScrollOffset = () => {
2019
- 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
+ }
2169
+
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
+ }
2020
2190
 
2021
- if ('scrollHeight' in this.scrollElement) {
2022
- // Element
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) {
2023
2197
  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
2198
+ ? el.scrollWidth - el.clientWidth
2199
+ : el.scrollHeight - el.clientHeight
2200
+ }
2201
+ if ('document' in el) {
2202
+ const doc = el.document.documentElement
2029
2203
  return this.options.horizontal
2030
- ? doc.scrollWidth - this.scrollElement.innerWidth
2031
- : doc.scrollHeight - this.scrollElement.innerHeight
2204
+ ? doc.scrollWidth - el.innerWidth
2205
+ : doc.scrollHeight - el.innerHeight
2032
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,
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
2033
2271
  }
2034
2272
 
2035
2273
  private getVirtualDistanceFromEnd = () => {
2036
2274
  return Math.max(
2037
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
2275
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
2038
2276
  0,
2039
2277
  )
2040
2278
  }
@@ -2137,13 +2375,8 @@ export class Virtualizer<
2137
2375
  index = Math.max(0, Math.min(index, this.options.count - 1))
2138
2376
 
2139
2377
  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
- }
2378
+ // No target (an empty list), so nothing is written.
2379
+ if (!offsetInfo) return
2147
2380
  const [offset, align] = offsetInfo
2148
2381
 
2149
2382
  this._startScroll({ index, align }, offset, behavior, 'absolute')
@@ -2190,12 +2423,10 @@ export class Virtualizer<
2190
2423
  // Every scroll command starts here: it becomes the in-flight command,
2191
2424
  // writes its first target and leaves reconcile to retarget and retire it.
2192
2425
  //
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.
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.
2199
2430
  //
2200
2431
  // An index or end target that is already at its offset starts a smooth
2201
2432
  // scroll as landed; an offset target never does, so its first scroll
@@ -2206,20 +2437,68 @@ export class Virtualizer<
2206
2437
  behavior: ScrollBehavior,
2207
2438
  kind: 'absolute' | 'relative',
2208
2439
  ) {
2209
- if (kind === 'absolute') {
2210
- 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()
2211
2489
  }
2212
2490
  this.scrollState = {
2213
2491
  ...target,
2214
2492
  startedAt: this.now(),
2215
2493
  lastTargetOffset: offset,
2216
2494
  stableFrames: 0,
2495
+ behavior,
2217
2496
  phase: initialScrollPhase(
2218
2497
  behavior,
2219
2498
  target.index != null && approxEqual(offset, this.getScrollOffset()),
2220
2499
  ),
2221
2500
  }
2222
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2501
+ this._scrollToOffset(offset, { behavior })
2223
2502
  this.scheduleScrollReconcile()
2224
2503
  }
2225
2504
 
@@ -2235,7 +2514,13 @@ export class Virtualizer<
2235
2514
  this.scrollState = null
2236
2515
  }
2237
2516
 
2238
- 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 = () => {
2239
2524
  const measurements = this.getMeasurements()
2240
2525
 
2241
2526
  let end: number
@@ -2314,17 +2599,21 @@ export class Virtualizer<
2314
2599
  {
2315
2600
  adjustments,
2316
2601
  behavior,
2317
- }: {
2318
- adjustments: number | undefined
2319
- behavior: ScrollBehavior | undefined
2320
- },
2602
+ }: { adjustments?: number; behavior?: ScrollBehavior } = {},
2321
2603
  ) => {
2322
- this.pendingWrite = {
2604
+ const write = {
2323
2605
  target: offset + (adjustments ?? 0),
2324
2606
  smooth: behavior === 'smooth',
2325
- adjustments: adjustments ?? this.scrollAdjustments,
2326
2607
  }
2327
- 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
2328
2617
  }
2329
2618
 
2330
2619
  // Where the in-flight command's last instant write put the element, until
@@ -2339,6 +2628,35 @@ export class Virtualizer<
2339
2628
  ? this.pendingWrite.target
2340
2629
  : null
2341
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
+
2342
2660
  measure = () => {
2343
2661
  // Reset pendingMin so the next getMeasurements rebuilds from index 0.
2344
2662
  // Without this, a prior resizeItem() that left pendingMin > 0 would