@tanstack/virtual-core 3.19.1 → 3.19.3

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
@@ -388,11 +388,19 @@ export interface VirtualizerOptions<
388
388
  useCachedMeasurements?: boolean
389
389
  }
390
390
 
391
+ // Where an in-flight scroll command is in its lifecycle, which decides how
392
+ // its scroll events and measurements are read:
393
+ // smooth a smooth animation is travelling to the target
394
+ // smoothLanded a smooth scroll is at its target, waiting to retire
395
+ // smoothFinishing a smooth scroll switched to instant writes for the
396
+ // final approach; its animation can still report positions
397
+ // instant instant writes
398
+ type ScrollPhase = 'smooth' | 'smoothLanded' | 'smoothFinishing' | 'instant'
399
+
391
400
  type ScrollState = {
392
401
  // what we want
393
402
  index: number | null
394
403
  align: ScrollAlignment
395
- behavior: ScrollBehavior
396
404
  // scrollToEnd: track the DOM max scroll offset instead of the item's offset
397
405
  toEnd?: boolean
398
406
 
@@ -404,28 +412,33 @@ type ScrollState = {
404
412
 
405
413
  // settling
406
414
  stableFrames: number
407
- // Keep arrival across measurement-driven retargets so external scrolls can cancel.
408
- hasReachedTarget: boolean
409
- // The command asked for a smooth scroll. Unlike `behavior`, which reconcile
410
- // switches to 'auto' for the final approach, this stays set: the smooth
411
- // animation can still deliver scroll events after that switch.
412
- startedSmooth: boolean
413
-
414
- // Where our last non-smooth write for this command put the element, until
415
- // its scroll event arrives. Until then `scrollOffset` still holds the old
416
- // position, and the rows on screen are the ones rendered for it. A smooth
417
- // write leaves it null: the element is somewhere between the two offsets.
418
- // It goes with the scroll state, so a write the browser ignored (no read-back)
419
- // does not outlive its command.
420
- writtenOffset?: number | null
415
+ phase: ScrollPhase
421
416
  }
422
417
 
423
- type PendingScrollAnchor = [
424
- key: Key | null,
425
- offset: number,
426
- followOnAppend: ScrollBehavior | null,
427
- anchorDelta: number,
428
- ]
418
+ const initialScrollPhase = (
419
+ behavior: ScrollBehavior,
420
+ atTarget: boolean,
421
+ ): ScrollPhase =>
422
+ behavior === 'smooth' ? (atTarget ? 'smoothLanded' : 'smooth') : 'instant'
423
+
424
+ // A smooth scroll owns the position: size compensation, the prepend anchor
425
+ // sync and far measurements hold off until it switches to instant writes.
426
+ const isSmoothScroll = (state: ScrollState | null): state is ScrollState =>
427
+ state?.phase === 'smooth' || state?.phase === 'smoothLanded'
428
+
429
+ // The smooth animation may still be reporting positions, so a scroll event
430
+ // that isn't the read-back of our own write may not be the user.
431
+ const isAnimating = (state: ScrollState) =>
432
+ state.phase === 'smooth' || state.phase === 'smoothFinishing'
433
+
434
+ // What `setOptions` decided about the scroll position for `_willUpdate` to
435
+ // carry out once the consumer has rendered: keep the reading anchor in place
436
+ // after a prepend (`scrollOffset` already moved by `delta`, the element has
437
+ // not), or follow an append to the end. A prepend that qualifies for both
438
+ // only follows.
439
+ type PendingScrollAnchor =
440
+ | { kind: 'anchor'; delta: number }
441
+ | { kind: 'follow'; behavior: ScrollBehavior }
429
442
 
430
443
  function isAppendWithTrim(
431
444
  prevCount: number,
@@ -486,29 +499,49 @@ export class Virtualizer<
486
499
  scrollRect: Rect | null = null
487
500
  scrollOffset: number | null = null
488
501
  scrollDirection: ScrollDirection | null = null
489
- scrollAdjustments = 0
502
+ // Size compensation written to the element but not yet reflected in
503
+ // `scrollOffset`: the element is expected at `scrollOffset +
504
+ // scrollAdjustments` until the next scroll event reports it.
505
+ get scrollAdjustments() {
506
+ return this.pendingWrite?.adjustments ?? 0
507
+ }
490
508
  // Sum of size-change deltas above-viewport that were skipped during
491
509
  // iOS momentum scroll (writing scrollTop mid-momentum cancels it).
492
510
  // Flushed in a single scrollTo when iOS is fully settled.
493
511
  private _iosDeferredAdjustment = 0
494
- // Touch state. iOS WebKit cancels momentum when scrollTop is written, so
495
- // we defer adjustments not only during `isScrolling` but also through the
496
- // touchstart→touchend window (active drag) and a short tail after
497
- // touchend (early-momentum window — iOS only fires touch events once at
498
- // the start of momentum, so we use a timer rather than another event).
499
- private _iosTouching = false
500
- private _iosJustTouchEnded = false
501
- private _iosTouchEndTimerId: number | null = null
502
- // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs)
503
- // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5
504
- // but the browser reports back 12346, the next reconcileScroll sees a
505
- // "target changed" and re-fires scrollTo — a feedback loop that the
506
- // approxEqual(<1.01) tolerance otherwise absorbs as a workaround.
507
- // By remembering the intended value of our most-recent self-driven
508
- // scrollTo, we can match the browser's rounded read back to the intended
509
- // value when the diff is < 1.5 px, distinguishing it from a real user
510
- // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.
511
- private _intendedScrollOffset: number | null = null
512
+ // The touch gesture in progress. iOS WebKit cancels momentum when
513
+ // scrollTop is written, so adjustments are deferred not only during
514
+ // `isScrolling` but through the whole gesture: `down` from touchstart to
515
+ // touchend/touchcancel (active drag), then `tail` for a short grace window
516
+ // after the finger lifts (early momentum — iOS fires touch events only
517
+ // once at the start of momentum, so the tail is a timer rather than
518
+ // another event). Null between gestures, and after touchend on non-iOS,
519
+ // which arms no tail. The tail record owns its timer: `_endIosTouch` is
520
+ // the only way to drop either, so a cleared record never leaves a timer
521
+ // behind, and a live timer always has its record.
522
+ private _iosTouch:
523
+ | { phase: 'down' }
524
+ | { phase: 'tail'; timerId: number }
525
+ | null = null
526
+ // Our last write to the element, from `_scrollToOffset` until the next
527
+ // scroll event reports it (the only place it is cleared). Until then
528
+ // `scrollOffset` may still hold the old position.
529
+ //
530
+ // - `target`: where the write puts the element (offset + adjustments).
531
+ // Safari (and Chrome/Firefox under certain DPRs) round writes to whole
532
+ // pixels: wrote 12345.5, read back 12346. A read-back within 1.5px of
533
+ // `target` is taken as our own and adopts the exact value, so reconcile
534
+ // does not see a moved target and write again; a user scroll has moved
535
+ // further by the time it reports.
536
+ // - `smooth`: the write animates, so until it lands the element is
537
+ // somewhere between the old offset and `target`.
538
+ // - `adjustments`: see `scrollAdjustments`. Writes that pass none keep the
539
+ // previous value.
540
+ private pendingWrite: {
541
+ target: number
542
+ smooth: boolean
543
+ adjustments: number
544
+ } | null = null
512
545
  // A compensation write from `applyScrollAdjustment` whose target exceeded
513
546
  // the element's scroll max at the moment of the write. The browser clamps
514
547
  // such a write because the consumer's sizer has not grown yet: an
@@ -739,8 +772,7 @@ export class Virtualizer<
739
772
  // the virtualizer would render the wrong items for one frame (the
740
773
  // estimate-based positions are stale) and then correct in the next
741
774
  // frame, producing a visible "jump" on prepend with dynamic sizes.
742
- let anchorResolved = false
743
- let anchorDelta = 0
775
+ let anchorDelta: number | null = null
744
776
  if (anchor && this.scrollOffset !== null) {
745
777
  const [anchorKey, anchorOffset] = anchor
746
778
  const newMeasurements = this.getMeasurements()
@@ -761,19 +793,15 @@ export class Virtualizer<
761
793
  if (!followOnAppend && newOffset !== this.scrollOffset) {
762
794
  anchorDelta = newOffset - this.scrollOffset
763
795
  this.scrollOffset = newOffset
764
- anchorResolved = true
765
796
  }
766
797
  }
767
798
  }
768
799
  }
769
800
 
770
- if (anchorResolved || followOnAppend) {
771
- this.pendingScrollAnchor = [
772
- anchorResolved ? anchor![0] : null,
773
- anchorResolved ? anchor![1] : 0,
774
- followOnAppend,
775
- anchorDelta,
776
- ]
801
+ if (followOnAppend) {
802
+ this.pendingScrollAnchor = { kind: 'follow', behavior: followOnAppend }
803
+ } else if (anchorDelta !== null) {
804
+ this.pendingScrollAnchor = { kind: 'anchor', delta: anchorDelta }
777
805
  }
778
806
  }
779
807
 
@@ -795,10 +823,7 @@ export class Virtualizer<
795
823
  console.info('correction', delta)
796
824
  }
797
825
 
798
- if (
799
- isIOSWebKit() &&
800
- (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
801
- ) {
826
+ if (isIOSWebKit() && this._iosInMotion()) {
802
827
  // An index scroll retargets from fresh measurements in reconcileScroll;
803
828
  // replaying this delta after it lands would count it twice.
804
829
  if (this.scrollState?.index == null) {
@@ -819,7 +844,7 @@ export class Virtualizer<
819
844
  ? { target, maxAtWrite }
820
845
  : null
821
846
  this._scrollToOffset(this.getScrollOffset(), {
822
- adjustments: (this.scrollAdjustments += delta),
847
+ adjustments: this.scrollAdjustments + delta,
823
848
  behavior,
824
849
  })
825
850
  // Eagerly carry the intended target in `scrollOffset` so callers that
@@ -840,7 +865,7 @@ export class Virtualizer<
840
865
  // Upper-bound overflow stays untouched — it is transiently
841
866
  // legitimate mid-prepend while the consumer's sizer catches up.
842
867
  if (this.scrollOffset < 0) this.scrollOffset = 0
843
- this.scrollAdjustments = 0
868
+ if (this.pendingWrite) this.pendingWrite.adjustments = 0
844
869
  }
845
870
  return true
846
871
  }
@@ -892,14 +917,14 @@ export class Virtualizer<
892
917
  // capture), so the new element never reports it. Carrying the state
893
918
  // over would replay a stale deferred delta on the new element's first
894
919
  // flush, and a cleanup that lands mid-touch or inside the post-touchend
895
- // grace window would strand _iosTouching / _iosJustTouchEnded as true
896
- // (the listener unsub clears the grace timer, and with it the only
897
- // pending reset of the flag), deferring every adjustment on the new
898
- // element until its next touch cycle.
920
+ // grace window would strand `_iosTouch` (the listeners that end it were
921
+ // just removed), deferring every adjustment on the new element until
922
+ // its next touch cycle.
899
923
  this._iosDeferredAdjustment = 0
900
- this._iosTouching = false
901
- this._iosJustTouchEnded = false
924
+ this._endIosTouch()
902
925
  this._clampedAdjustment = null
926
+ // A write to the old element will never be read back.
927
+ this.pendingWrite = null
903
928
  this.scrollElement = null
904
929
  this.targetWindow = null
905
930
  }
@@ -949,28 +974,21 @@ export class Virtualizer<
949
974
  // no-op re-emit that Safari/Firefox fire after a re-render's layout
950
975
  // (Chrome doesn't). Treating it as scrolling re-arms `isScrolling`,
951
976
  // which forces a render that triggers another such event: an
952
- // infinite re-render loop. Ignore it. (Self-writes are handled by
953
- // the `_intendedScrollOffset` reconciliation just below.)
977
+ // infinite re-render loop. Ignore it. (Self-writes are matched to
978
+ // `pendingWrite` just below.)
954
979
  if (
955
980
  isScrolling &&
956
- this._intendedScrollOffset === null &&
981
+ this.pendingWrite === null &&
957
982
  offset === this.scrollOffset
958
983
  ) {
959
984
  return
960
985
  }
961
986
 
962
- // If this scroll event looks like the browser's read-back of a
963
- // value we just wrote, prefer our intended (sub-pixel-accurate)
964
- // value over the browser's rounded one. The 1.5 px tolerance is
965
- // tight enough to avoid mistaking a real user scroll for a
966
- // self-write — by the time the user has moved 1.5 px, the
967
- // intended value will already have been consumed by a prior
968
- // scroll event and cleared.
969
- if (
970
- this._intendedScrollOffset !== null &&
971
- Math.abs(offset - this._intendedScrollOffset) < 1.5
972
- ) {
973
- offset = this._intendedScrollOffset
987
+ // The read-back of our own write: adopt the exact target over the
988
+ // browser's rounded value (see `pendingWrite`).
989
+ const pending = this.pendingWrite
990
+ if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
991
+ offset = pending.target
974
992
  } else if (
975
993
  this.scrollState?.index != null &&
976
994
  // A non-smooth write lands at once, so any other scroll event is
@@ -984,10 +1002,9 @@ export class Virtualizer<
984
1002
  // like the user and the scroll stops at the max. That needs the
985
1003
  // sizer re-rendered before the scroll event, which browsers have
986
1004
  // not been seen to do (pinned by a `.fails` test).
987
- // A smooth scroll's own animation events look like a user's, so
988
- // it only yields once it has reached the target.
989
- (this.scrollState.hasReachedTarget ||
990
- !this.scrollState.startedSmooth) &&
1005
+ // While a smooth scroll's animation may still report, its events
1006
+ // look like a user's, so it yields only once it has landed.
1007
+ !isAnimating(this.scrollState) &&
991
1008
  !approxEqual(offset, this.scrollState.lastTargetOffset) &&
992
1009
  !approxEqual(offset, this.getScrollStateTarget(this.scrollState)) &&
993
1010
  (this._clampedAdjustment === null ||
@@ -998,8 +1015,7 @@ export class Virtualizer<
998
1015
  // need to reconcile.
999
1016
  this.scrollState = null
1000
1017
  }
1001
- this._intendedScrollOffset = null
1002
- if (this.scrollState) this.scrollState.writtenOffset = null
1018
+ this.pendingWrite = null
1003
1019
 
1004
1020
  // A pending clamped compensation write (#1258) survives only its
1005
1021
  // own read-back, which the browser reports at the scroll max we
@@ -1012,7 +1028,6 @@ export class Virtualizer<
1012
1028
  this._clampedAdjustment = null
1013
1029
  }
1014
1030
 
1015
- this.scrollAdjustments = 0
1016
1031
  // If the offset hasn't moved, this is the echo of our own
1017
1032
  // adjustment write — `applyScrollAdjustment` already folded it
1018
1033
  // into `scrollOffset`. There's no direction to infer, so leave
@@ -1047,28 +1062,27 @@ export class Virtualizer<
1047
1062
  if ('addEventListener' in this.scrollElement) {
1048
1063
  const scrollEl = this.scrollElement as unknown as EventTarget
1049
1064
  const onTouchStart = () => {
1050
- this._iosTouching = true
1051
- this._iosJustTouchEnded = false
1052
- if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
1053
- this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
1054
- this._iosTouchEndTimerId = null
1055
- }
1065
+ // A finger back down inside the grace window cancels its tail.
1066
+ this._endIosTouch()
1067
+ this._iosTouch = { phase: 'down' }
1056
1068
  }
1057
1069
  const onTouchEnd = () => {
1058
- this._iosTouching = false
1070
+ this._endIosTouch()
1059
1071
  if (!isIOSWebKit() || this.targetWindow == null) {
1060
- // Non-iOS: nothing more to track. Just clear the touching flag.
1072
+ // Non-iOS: nothing more to track.
1061
1073
  return
1062
1074
  }
1063
- this._iosJustTouchEnded = true
1064
1075
  // After ~150 ms with no scroll/touch events, momentum is done.
1065
- this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => {
1066
- this._iosJustTouchEnded = false
1067
- this._iosTouchEndTimerId = null
1068
- // After the grace window, attempt to flush. The scroll event
1069
- // for momentum decay may have already fired before our timer.
1070
- this._flushIosDeferredIfReady()
1071
- }, 150)
1076
+ const tail = {
1077
+ phase: 'tail' as const,
1078
+ timerId: this.targetWindow.setTimeout(() => {
1079
+ if (this._iosTouch === tail) this._iosTouch = null
1080
+ // After the grace window, attempt to flush. The scroll event
1081
+ // for momentum decay may have already fired before our timer.
1082
+ this._flushIosDeferredIfReady()
1083
+ }, 150),
1084
+ }
1085
+ this._iosTouch = tail
1072
1086
  }
1073
1087
  scrollEl.addEventListener(
1074
1088
  'touchstart',
@@ -1080,13 +1094,18 @@ export class Virtualizer<
1080
1094
  onTouchEnd,
1081
1095
  addEventListenerOptions,
1082
1096
  )
1097
+ // Same handler as touchend: iOS can end a touch with touchcancel
1098
+ // (system gesture, interrupted scroll) and never fire touchend.
1099
+ scrollEl.addEventListener(
1100
+ 'touchcancel',
1101
+ onTouchEnd,
1102
+ addEventListenerOptions,
1103
+ )
1083
1104
  this.unsubs.push(() => {
1084
1105
  scrollEl.removeEventListener('touchstart', onTouchStart)
1085
1106
  scrollEl.removeEventListener('touchend', onTouchEnd)
1086
- if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
1087
- this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
1088
- this._iosTouchEndTimerId = null
1089
- }
1107
+ scrollEl.removeEventListener('touchcancel', onTouchEnd)
1108
+ this._endIosTouch()
1090
1109
  })
1091
1110
  }
1092
1111
 
@@ -1100,29 +1119,21 @@ export class Virtualizer<
1100
1119
  this.pendingScrollAnchor = null
1101
1120
 
1102
1121
  if (anchor && this.scrollElement && this.options.enabled) {
1103
- const [key, _offset, followOnAppend, anchorDelta] = anchor
1104
-
1105
- if (key !== null && !followOnAppend) {
1122
+ if (anchor.kind === 'anchor') {
1106
1123
  // scrollOffset was eagerly adjusted in setOptions so the
1107
1124
  // virtualizer already computed the correct range during render.
1108
1125
  // Now sync the browser's actual scroll position to match.
1109
- // Skip when followOnAppend is set — scrollToEnd will handle it.
1110
1126
  //
1111
1127
  // On iOS WebKit, writing scrollTop during touch/momentum cancels
1112
1128
  // the in-flight scroll. Defer the DOM sync the same way
1113
1129
  // applyScrollAdjustment does — accumulate the delta and let
1114
1130
  // _flushIosDeferredIfReady handle it once the scroll settles.
1115
- if (
1116
- isIOSWebKit() &&
1117
- (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
1118
- ) {
1119
- if (anchorDelta !== 0) {
1120
- this._iosDeferredAdjustment += anchorDelta
1121
- }
1131
+ if (isIOSWebKit() && this._iosInMotion()) {
1132
+ this._iosDeferredAdjustment += anchor.delta
1122
1133
  } else if (
1123
- this.scrollState?.behavior === 'smooth' &&
1134
+ isSmoothScroll(this.scrollState) &&
1124
1135
  !approxEqual(
1125
- this.getScrollOffset() - anchorDelta,
1136
+ this.getScrollOffset() - anchor.delta,
1126
1137
  this.scrollState.lastTargetOffset,
1127
1138
  )
1128
1139
  ) {
@@ -1140,10 +1151,8 @@ export class Virtualizer<
1140
1151
  behavior: undefined,
1141
1152
  })
1142
1153
  }
1143
- }
1144
-
1145
- if (followOnAppend) {
1146
- this.scrollToEnd({ behavior: followOnAppend })
1154
+ } else {
1155
+ this.scrollToEnd({ behavior: anchor.behavior })
1147
1156
  }
1148
1157
  }
1149
1158
 
@@ -1181,15 +1190,25 @@ export class Virtualizer<
1181
1190
  }
1182
1191
  }
1183
1192
 
1193
+ // The element is moving or about to: a scroll in progress, or a touch
1194
+ // gesture that may still turn into one (see `_iosTouch`). On iOS a write
1195
+ // now would cancel the momentum, so adjustments wait for the flush below.
1196
+ private _iosInMotion = () => this.isScrolling || this._iosTouch !== null
1197
+
1198
+ private _endIosTouch = () => {
1199
+ if (this._iosTouch?.phase === 'tail' && this.targetWindow != null) {
1200
+ this.targetWindow.clearTimeout(this._iosTouch.timerId)
1201
+ }
1202
+ this._iosTouch = null
1203
+ }
1204
+
1184
1205
  // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
1185
1206
  // truly settled — not actively scrolling, not under an active touch, and
1186
1207
  // past the post-touchend grace window. Called from the scroll callback
1187
1208
  // and the touchend grace-timer.
1188
1209
  private _flushIosDeferredIfReady = () => {
1189
1210
  if (this._iosDeferredAdjustment === 0) return
1190
- if (this.isScrolling) return
1191
- if (this._iosTouching) return
1192
- if (this._iosJustTouchEnded) return
1211
+ if (this._iosInMotion()) return
1193
1212
  // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go
1194
1213
  // negative or beyond scrollHeight - clientHeight. Writing scrollTop
1195
1214
  // while in that zone snaps the page back to the clamped value at the
@@ -1212,7 +1231,7 @@ export class Virtualizer<
1212
1231
  // landing between now and the resulting scroll event computes from the
1213
1232
  // post-flush offset rather than the stale one.
1214
1233
  this._scrollToOffset(cur, {
1215
- adjustments: (this.scrollAdjustments += delta),
1234
+ adjustments: this.scrollAdjustments + delta,
1216
1235
  behavior: undefined,
1217
1236
  })
1218
1237
  }
@@ -1270,7 +1289,13 @@ export class Virtualizer<
1270
1289
  const targetChanged = targetOffset !== this.scrollState.lastTargetOffset
1271
1290
 
1272
1291
  if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
1273
- this.scrollState.hasReachedTarget = true
1292
+ // At the target: a travelling smooth scroll has landed, and a
1293
+ // finishing one is now an instant scroll.
1294
+ if (this.scrollState.phase === 'smooth') {
1295
+ this.scrollState.phase = 'smoothLanded'
1296
+ } else if (this.scrollState.phase === 'smoothFinishing') {
1297
+ this.scrollState.phase = 'instant'
1298
+ }
1274
1299
  this.scrollState.stableFrames++
1275
1300
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1276
1301
  // Final-pass exact landing. The reconcile-stable check uses a 1.01px
@@ -1302,16 +1327,21 @@ export class Virtualizer<
1302
1327
  const viewport = this.getSize() || 600
1303
1328
  const distance = Math.abs(targetOffset - this.getScrollOffset())
1304
1329
  const keepSmooth =
1305
- this.scrollState.behavior === 'smooth' && distance > viewport
1330
+ isSmoothScroll(this.scrollState) && distance > viewport
1306
1331
 
1307
1332
  this.scrollState.lastTargetOffset = targetOffset
1308
1333
  if (keepSmooth) {
1309
1334
  // A smooth retarget travels again, so its intermediate scroll
1310
1335
  // events must not read as an external scroll away from the target.
1311
- this.scrollState.hasReachedTarget = false
1312
- } else {
1313
- this.scrollState.behavior = 'auto'
1336
+ this.scrollState.phase = 'smooth'
1337
+ } else if (this.scrollState.phase === 'smooth') {
1338
+ // The final approach is instant, but the animation can still report.
1339
+ this.scrollState.phase = 'smoothFinishing'
1340
+ } else if (this.scrollState.phase === 'smoothLanded') {
1341
+ this.scrollState.phase = 'instant'
1314
1342
  }
1343
+ // 'smoothFinishing' stays as it is (its animation may still report)
1344
+ // until reconcile sees it at the target; 'instant' stays instant.
1315
1345
 
1316
1346
  this._scrollToOffset(targetOffset, {
1317
1347
  adjustments: undefined,
@@ -1713,7 +1743,7 @@ export class Virtualizer<
1713
1743
  */
1714
1744
  private shouldMeasureDuringScroll = (index: number): boolean => {
1715
1745
  // No scroll state or not smooth scroll - always allow measurements
1716
- if (!this.scrollState || this.scrollState.behavior !== 'smooth') {
1746
+ if (!isSmoothScroll(this.scrollState)) {
1717
1747
  return true
1718
1748
  }
1719
1749
 
@@ -1815,7 +1845,7 @@ export class Virtualizer<
1815
1845
  if (delta !== 0) {
1816
1846
  const wasAtEnd =
1817
1847
  this.options.anchorTo === 'end' &&
1818
- this.scrollState?.behavior !== 'smooth' &&
1848
+ !isSmoothScroll(this.scrollState) &&
1819
1849
  this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold
1820
1850
  const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0
1821
1851
  // Default anchoring predicate (used unless the consumer supplies a
@@ -1838,7 +1868,7 @@ export class Virtualizer<
1838
1868
  itemStart + itemSize <= scrollOffsetWithAdj &&
1839
1869
  this.scrollDirection !== 'backward'
1840
1870
  const shouldAdjustScroll =
1841
- this.scrollState?.behavior !== 'smooth' &&
1871
+ !isSmoothScroll(this.scrollState) &&
1842
1872
  (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined
1843
1873
  ? this.shouldAdjustScrollPositionOnItemSizeChange(
1844
1874
  // The callback expects a VirtualItem; build one lazily only
@@ -1873,10 +1903,11 @@ export class Virtualizer<
1873
1903
  // command. Compensation writes and the prepend anchor sync update
1874
1904
  // `scrollOffset` eagerly, and the iOS flush writes exactly
1875
1905
  // `scrollOffset + scrollAdjustments`, so none of them count.
1906
+ const writtenOffset = this.getCommandWrittenOffset()
1876
1907
  const awaitingCommandReadBack =
1877
- this.scrollState?.writtenOffset != null &&
1908
+ writtenOffset !== null &&
1878
1909
  !approxEqual(
1879
- this.scrollState.writtenOffset,
1910
+ writtenOffset,
1880
1911
  this.getScrollOffset() + this.scrollAdjustments,
1881
1912
  )
1882
1913
 
@@ -2062,31 +2093,12 @@ export class Virtualizer<
2062
2093
  toOffset: number,
2063
2094
  { align = 'start', behavior = 'auto' }: ScrollToOffsetOptions = {},
2064
2095
  ) => {
2065
- // An absolute scroll command derives its target from current
2066
- // measurements, so any iOS-deferred compensation still pending is stale by
2067
- // definition — the command already accounts for the measurements the delta
2068
- // was compensating for. Drop it so _flushIosDeferredIfReady doesn't replay
2069
- // it onto the just-established position (relative commands like scrollBy
2070
- // intentionally keep the deferral, since they build on the current offset).
2071
- this._iosDeferredAdjustment = 0
2072
-
2073
- const offset = this.getOffsetForAlignment(toOffset, align)
2074
-
2075
- const now = this.now()
2076
- this.scrollState = {
2077
- index: null,
2078
- align,
2096
+ this._startScroll(
2097
+ { index: null, align },
2098
+ this.getOffsetForAlignment(toOffset, align),
2079
2099
  behavior,
2080
- startedAt: now,
2081
- lastTargetOffset: offset,
2082
- stableFrames: 0,
2083
- hasReachedTarget: false,
2084
- startedSmooth: behavior === 'smooth',
2085
- }
2086
-
2087
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2088
-
2089
- this.scheduleScrollReconcile()
2100
+ 'absolute',
2101
+ )
2090
2102
  }
2091
2103
 
2092
2104
  scrollToIndex = (
@@ -2096,33 +2108,19 @@ export class Virtualizer<
2096
2108
  behavior = 'auto',
2097
2109
  }: ScrollToIndexOptions = {},
2098
2110
  ) => {
2099
- // See scrollToOffset: an absolute target invalidates any pending
2100
- // iOS-deferred compensation.
2101
- this._iosDeferredAdjustment = 0
2102
-
2103
2111
  index = Math.max(0, Math.min(index, this.options.count - 1))
2104
2112
 
2105
2113
  const offsetInfo = this.getOffsetForIndex(index, initialAlign)
2106
2114
  if (!offsetInfo) {
2115
+ // No target (an empty list), so nothing is written; still drop the
2116
+ // deferral like every absolute command, or it replays once the list
2117
+ // refills.
2118
+ this._iosDeferredAdjustment = 0
2107
2119
  return
2108
2120
  }
2109
2121
  const [offset, align] = offsetInfo
2110
2122
 
2111
- const now = this.now()
2112
- this.scrollState = {
2113
- index,
2114
- align,
2115
- behavior,
2116
- startedAt: now,
2117
- lastTargetOffset: offset,
2118
- stableFrames: 0,
2119
- hasReachedTarget: approxEqual(offset, this.getScrollOffset()),
2120
- startedSmooth: behavior === 'smooth',
2121
- }
2122
-
2123
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2124
-
2125
- this.scheduleScrollReconcile()
2123
+ this._startScroll({ index, align }, offset, behavior, 'absolute')
2126
2124
  }
2127
2125
 
2128
2126
  scrollBy = (
@@ -2133,50 +2131,28 @@ export class Virtualizer<
2133
2131
  // Clamp: a write past either edge that leaves the element where it was
2134
2132
  // fires no scroll event, so nothing would clear an unreachable offset.
2135
2133
  const offset = this.getOffsetForAlignment(
2136
- (this.scrollState?.writtenOffset ?? this.getScrollOffset()) + delta,
2134
+ (this.getCommandWrittenOffset() ?? this.getScrollOffset()) + delta,
2137
2135
  'start',
2138
2136
  )
2139
- const now = this.now()
2140
2137
 
2141
- this.scrollState = {
2142
- index: null,
2143
- align: 'start',
2138
+ this._startScroll(
2139
+ { index: null, align: 'start' },
2140
+ offset,
2144
2141
  behavior,
2145
- startedAt: now,
2146
- lastTargetOffset: offset,
2147
- stableFrames: 0,
2148
- hasReachedTarget: false,
2149
- startedSmooth: behavior === 'smooth',
2150
- }
2151
-
2152
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2153
-
2154
- this.scheduleScrollReconcile()
2142
+ 'relative',
2143
+ )
2155
2144
  }
2156
2145
 
2157
2146
  scrollToEnd = ({ behavior = 'auto' }: ScrollToEndOptions = {}) => {
2158
2147
  if (this.options.count > 0) {
2159
2148
  // Target the browser's max scroll rather than the last item's end-align
2160
2149
  // offset, so paddingEnd is included and isAtEnd() holds afterwards.
2161
- this._iosDeferredAdjustment = 0
2162
-
2163
- const offset = Math.max(this.getMaxScrollOffset(), 0)
2164
-
2165
- this.scrollState = {
2166
- index: this.options.count - 1,
2167
- align: 'end',
2150
+ this._startScroll(
2151
+ { index: this.options.count - 1, align: 'end', toEnd: true },
2152
+ Math.max(this.getMaxScrollOffset(), 0),
2168
2153
  behavior,
2169
- toEnd: true,
2170
- startedAt: this.now(),
2171
- lastTargetOffset: offset,
2172
- stableFrames: 0,
2173
- hasReachedTarget: approxEqual(offset, this.getScrollOffset()),
2174
- startedSmooth: behavior === 'smooth',
2175
- }
2176
-
2177
- this._scrollToOffset(offset, { adjustments: undefined, behavior })
2178
-
2179
- this.scheduleScrollReconcile()
2154
+ 'absolute',
2155
+ )
2180
2156
  return
2181
2157
  }
2182
2158
 
@@ -2185,6 +2161,42 @@ export class Virtualizer<
2185
2161
  })
2186
2162
  }
2187
2163
 
2164
+ // Every scroll command starts here: it becomes the in-flight command,
2165
+ // writes its first target and leaves reconcile to retarget and retire it.
2166
+ //
2167
+ // An absolute command derives its target from current measurements, so
2168
+ // any iOS-deferred compensation still pending is stale by definition —
2169
+ // the command already accounts for the measurements the delta was
2170
+ // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
2171
+ // onto the just-established position. A relative command (scrollBy)
2172
+ // builds on the current offset, so it keeps the deferral.
2173
+ //
2174
+ // An index or end target that is already at its offset starts a smooth
2175
+ // scroll as landed; an offset target never does, so its first scroll
2176
+ // event is read as the user's (see the scroll handler in `_willUpdate`).
2177
+ private _startScroll(
2178
+ target: Pick<ScrollState, 'index' | 'align' | 'toEnd'>,
2179
+ offset: number,
2180
+ behavior: ScrollBehavior,
2181
+ kind: 'absolute' | 'relative',
2182
+ ) {
2183
+ if (kind === 'absolute') {
2184
+ this._iosDeferredAdjustment = 0
2185
+ }
2186
+ this.scrollState = {
2187
+ ...target,
2188
+ startedAt: this.now(),
2189
+ lastTargetOffset: offset,
2190
+ stableFrames: 0,
2191
+ phase: initialScrollPhase(
2192
+ behavior,
2193
+ target.index != null && approxEqual(offset, this.getScrollOffset()),
2194
+ ),
2195
+ }
2196
+ this._scrollToOffset(offset, { adjustments: undefined, behavior })
2197
+ this.scheduleScrollReconcile()
2198
+ }
2199
+
2188
2200
  // Drops the target of an in-flight scrollToIndex / scrollToOffset /
2189
2201
  // scrollBy / scrollToEnd so a user gesture can take over the viewport.
2190
2202
  // The scroll position is left untouched: writing it would stop iOS
@@ -2281,16 +2293,26 @@ export class Virtualizer<
2281
2293
  behavior: ScrollBehavior | undefined
2282
2294
  },
2283
2295
  ) => {
2284
- // Record the intended logical scroll target so the next scroll event
2285
- // can reconcile against subpixel rounding by the browser.
2286
- this._intendedScrollOffset = offset + (adjustments ?? 0)
2287
- if (this.scrollState) {
2288
- this.scrollState.writtenOffset =
2289
- behavior === 'smooth' ? null : this._intendedScrollOffset
2296
+ this.pendingWrite = {
2297
+ target: offset + (adjustments ?? 0),
2298
+ smooth: behavior === 'smooth',
2299
+ adjustments: adjustments ?? this.scrollAdjustments,
2290
2300
  }
2291
2301
  this.options.scrollToFn(offset, { behavior, adjustments }, this)
2292
2302
  }
2293
2303
 
2304
+ // Where the in-flight command's last instant write put the element, until
2305
+ // its scroll event arrives; the rows on screen are still the ones rendered
2306
+ // for the old `scrollOffset`. Null after a smooth write (the element is
2307
+ // somewhere on the way) and without a command, so a write the browser
2308
+ // ignored (no read-back) does not outlive its command.
2309
+ private getCommandWrittenOffset = () =>
2310
+ this.scrollState !== null &&
2311
+ this.pendingWrite !== null &&
2312
+ !this.pendingWrite.smooth
2313
+ ? this.pendingWrite.target
2314
+ : null
2315
+
2294
2316
  measure = () => {
2295
2317
  // Reset pendingMin so the next getMeasurements rebuilds from index 0.
2296
2318
  // Without this, a prior resizeItem() that left pendingMin > 0 would