@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/dist/esm/index.js CHANGED
@@ -1,16 +1,8 @@
1
1
  import { createLazyMeasurementsView, getMeasurementKey } from "./lazy-measurements.js";
2
2
  import { memo, approxEqual, notUndefined, debounce } from "./utils.js";
3
- let _isIOSResult;
4
- const isIOSWebKit = () => {
5
- if (_isIOSResult !== void 0) return _isIOSResult;
6
- if (typeof navigator === "undefined") return _isIOSResult = false;
7
- if (/iP(hone|od|ad)/.test(navigator.userAgent)) return _isIOSResult = true;
8
- const mtp = navigator.maxTouchPoints;
9
- return _isIOSResult = navigator.platform === "MacIntel" && mtp !== void 0 && mtp > 0;
10
- };
11
- const _resetIOSDetectionForTests = () => {
12
- _isIOSResult = void 0;
13
- };
3
+ import { flingCaught, externalRetiresCommand, flingSpedUp, classifyScrollEvent } from "./scroll-classifier.js";
4
+ import { IosGesture, isIOSWebKit, iosMomentumOverridesWrites } from "./ios-gesture.js";
5
+ import { _resetIOSDetectionForTests } from "./ios-gesture.js";
14
6
  const getRect = (element) => {
15
7
  const { offsetWidth, offsetHeight } = element;
16
8
  return { width: offsetWidth, height: offsetHeight };
@@ -183,7 +175,6 @@ const windowScroll = scrollWithAdjustments;
183
175
  const elementScroll = scrollWithAdjustments;
184
176
  const initialScrollPhase = (behavior, atTarget) => behavior === "smooth" ? atTarget ? "smoothLanded" : "smooth" : "instant";
185
177
  const isSmoothScroll = (state) => (state == null ? void 0 : state.phase) === "smooth" || (state == null ? void 0 : state.phase) === "smoothLanded";
186
- const isAnimating = (state) => state.phase === "smooth" || state.phase === "smoothFinishing";
187
178
  function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
188
179
  if (nextCount === 0) return false;
189
180
  const firstKey = getNextKey(0);
@@ -225,8 +216,40 @@ class Virtualizer {
225
216
  this.scrollRect = null;
226
217
  this.scrollOffset = null;
227
218
  this.scrollDirection = null;
228
- this._iosDeferredAdjustment = 0;
229
- this._iosTouch = null;
219
+ this._holdOffset = 0;
220
+ this._reportedOverscroll = false;
221
+ this._iosGesture = new IosGesture({
222
+ getWindow: () => this.targetWindow,
223
+ now: () => this.now(),
224
+ // The end of a fling can move less than a pixel per scroll event, so
225
+ // events can stop for 150ms while the fling is still running (seen on
226
+ // an iPhone, 27.0.1). A command waiting for it would then be written
227
+ // into the fling and overridden. The element having moved since the
228
+ // last event means it has not ended: wait again. Not while our own
229
+ // write has yet to report: that moved it.
230
+ tailStillMoving: () => {
231
+ const state = this.scrollState;
232
+ if ((state == null ? void 0 : state.phase) !== "queued" || this.pendingWrite !== null) {
233
+ return false;
234
+ }
235
+ const now = this._readElementOffset();
236
+ if (now === null || this._lastElementOffset === null || Math.abs(now - this._lastElementOffset) < 1) {
237
+ return false;
238
+ }
239
+ this._lastElementOffset = now;
240
+ state.samples = [...state.samples ?? [], { t: this.now(), offset: now }];
241
+ return true;
242
+ },
243
+ onTailClosed: () => {
244
+ const state = this.scrollState;
245
+ if ((state == null ? void 0 : state.phase) === "queued" && flingCaught(state.samples ?? [])) {
246
+ this.scrollState = null;
247
+ }
248
+ this._flushHoldIfReady(true);
249
+ this._writeAwaitingCommand();
250
+ }
251
+ });
252
+ this._lastElementOffset = null;
230
253
  this.pendingWrite = null;
231
254
  this._clampedAdjustment = null;
232
255
  this.elementsCache = /* @__PURE__ */ new Map();
@@ -257,6 +280,8 @@ class Virtualizer {
257
280
  this._resizeBatch = null;
258
281
  if (batch.notify) {
259
282
  this.notify(batch.sync);
283
+ this._noteClampMax();
284
+ this._flushHoldIfReady(true);
260
285
  this._retryClampedAdjustment();
261
286
  }
262
287
  }
@@ -377,7 +402,7 @@ class Virtualizer {
377
402
  this.itemSizeCacheVersion++;
378
403
  }
379
404
  let anchorDelta = null;
380
- if (anchor && this.scrollOffset !== null) {
405
+ if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
381
406
  const [anchorKey, anchorOffset] = anchor;
382
407
  const newMeasurements = this.getMeasurements();
383
408
  const { count, getItemKey } = this.options;
@@ -399,7 +424,12 @@ class Virtualizer {
399
424
  if (followOnAppend) {
400
425
  this.pendingScrollAnchor = { kind: "follow", behavior: followOnAppend };
401
426
  } else if (anchorDelta !== null) {
402
- this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
427
+ if (this._canWriteScroll()) {
428
+ this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
429
+ } else {
430
+ this._holdOffset += anchorDelta;
431
+ this._followOffsetTarget(anchorDelta);
432
+ }
403
433
  }
404
434
  };
405
435
  this.notify = (sync) => {
@@ -429,6 +459,7 @@ class Virtualizer {
429
459
  }
430
460
  );
431
461
  this.cleanup = () => {
462
+ var _a;
432
463
  this.unsubs.filter(Boolean).forEach((d) => d());
433
464
  this.unsubs = [];
434
465
  this.observer.disconnect();
@@ -437,10 +468,12 @@ class Virtualizer {
437
468
  this.rafId = null;
438
469
  }
439
470
  this.scrollState = null;
471
+ (_a = this._momentumStop) == null ? void 0 : _a.restore();
472
+ this._momentumStop = null;
440
473
  this.isScrolling = false;
441
474
  this.scrollDirection = null;
442
- this._iosDeferredAdjustment = 0;
443
- this._endIosTouch();
475
+ this._holdOffset = 0;
476
+ this._reportedOverscroll = false;
444
477
  this._clampedAdjustment = null;
445
478
  this.pendingWrite = null;
446
479
  this.scrollElement = null;
@@ -477,27 +510,30 @@ class Virtualizer {
477
510
  );
478
511
  this.unsubs.push(
479
512
  this.options.observeElementOffset(this, (offset, isScrolling) => {
480
- var _a2;
481
- if (isScrolling && this.pendingWrite === null && offset === this.scrollOffset) {
482
- return;
483
- }
484
- const pending = this.pendingWrite;
485
- if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
486
- offset = pending.target;
487
- } else if (((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // A non-smooth write lands at once, so any other scroll event is
488
- // the user's, even before reconcile saw the target reached (the
489
- // target may keep moving, or iOS ignored the write under a
490
- // finger). A write the browser clamped because the sizer hasn't
491
- // grown yet reads back at the max, which is also where the fresh
492
- // target clamps, so the check below keeps it reconciling (#1294).
493
- // Not when rows above the target shrink before the read-back and
494
- // pull the target below the new max: the read-back then looks
495
- // like the user and the scroll stops at the max. That needs the
496
- // sizer re-rendered before the scroll event, which browsers have
497
- // not been seen to do (pinned by a `.fails` test).
498
- // While a smooth scroll's animation may still report, its events
499
- // look like a user's, so it yields only once it has landed.
500
- !isAnimating(this.scrollState) && !approxEqual(offset, this.scrollState.lastTargetOffset) && !approxEqual(offset, this.getScrollStateTarget(this.scrollState)) && (this._clampedAdjustment === null || Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5)) {
513
+ var _a2, _b, _c, _d;
514
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null;
515
+ const wasOverscrolled = this._reportedOverscroll;
516
+ this._reportedOverscroll = offset < 0 || elementMax !== null && offset > elementMax + 1;
517
+ const elementOffset = offset;
518
+ this._lastElementOffset = elementOffset;
519
+ offset = this._toLayoutOffset(offset);
520
+ const kind = this._classifyScrollEvent(
521
+ offset,
522
+ isScrolling,
523
+ elementMax
524
+ );
525
+ if (kind === "spurious") return;
526
+ if (kind === "readBack") {
527
+ offset = this.pendingWrite.target;
528
+ } else if (kind === "clampedReadBack" && ((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // Not `elementMax`: an adapter can report the read-back at rest.
529
+ offset < this.getMaxScrollOffset() - 1.5) {
530
+ this.scrollState.lastTargetOffset = offset;
531
+ } else if (externalRetiresCommand({
532
+ kind,
533
+ offset,
534
+ command: this.scrollState,
535
+ target: () => this.getScrollStateTarget(this.scrollState)
536
+ })) {
501
537
  this.scrollState = null;
502
538
  }
503
539
  this.pendingWrite = null;
@@ -505,10 +541,40 @@ class Virtualizer {
505
541
  this._clampedAdjustment = null;
506
542
  }
507
543
  const prevOffset = this.getScrollOffset();
544
+ const prevDirection = this.scrollDirection;
508
545
  this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? "forward" : "backward" : null;
509
546
  this.scrollOffset = offset;
510
547
  this.isScrolling = isScrolling;
511
- this._flushIosDeferredIfReady();
548
+ const queued = this.scrollState;
549
+ if ((queued == null ? void 0 : queued.phase) === "queued" && kind === "external" && isScrolling) {
550
+ if (wasOverscrolled || this._reportedOverscroll) {
551
+ queued.samples = [];
552
+ } else {
553
+ const t = this.now();
554
+ queued.samples = [
555
+ ...(queued.samples ?? []).filter(
556
+ (sample) => t - sample.t <= 200
557
+ ),
558
+ { t, offset: elementOffset }
559
+ ];
560
+ if (prevDirection !== null && this.scrollDirection !== prevDirection || flingSpedUp(queued.samples)) {
561
+ this.scrollState = null;
562
+ }
563
+ }
564
+ }
565
+ if (this._iosGesture.onScroll({
566
+ isScrolling,
567
+ ownReadBack: kind === "readBack",
568
+ moved: offset !== prevOffset,
569
+ // Neither our write's read-back nor a frame of our smooth
570
+ // animation: the user or a fling moved it.
571
+ external: kind === "external" && ((_b = this.scrollState) == null ? void 0 : _b.phase) !== "smooth" && ((_c = this.scrollState) == null ? void 0 : _c.phase) !== "smoothFinishing"
572
+ }) && // The user scrolls: a command still waiting for the tail is
573
+ // theirs to override, like a written one would be.
574
+ ((_d = this.scrollState) == null ? void 0 : _d.phase) === "queued") {
575
+ this.scrollState = null;
576
+ }
577
+ this._flushHoldIfReady(true);
512
578
  if (this.scrollState) {
513
579
  this.scheduleScrollReconcile();
514
580
  }
@@ -516,74 +582,48 @@ class Virtualizer {
516
582
  })
517
583
  );
518
584
  if ("addEventListener" in this.scrollElement) {
519
- const scrollEl = this.scrollElement;
520
- const onTouchStart = () => {
521
- this._endIosTouch();
522
- this._iosTouch = { phase: "down" };
523
- };
524
- const onTouchEnd = () => {
525
- this._endIosTouch();
526
- if (!isIOSWebKit() || this.targetWindow == null) {
527
- return;
528
- }
529
- const tail = {
530
- phase: "tail",
531
- timerId: this.targetWindow.setTimeout(() => {
532
- if (this._iosTouch === tail) this._iosTouch = null;
533
- this._flushIosDeferredIfReady();
534
- }, 150)
535
- };
536
- this._iosTouch = tail;
537
- };
538
- scrollEl.addEventListener(
539
- "touchstart",
540
- onTouchStart,
541
- addEventListenerOptions
585
+ this.unsubs.push(
586
+ this._iosGesture.listen(this.scrollElement)
542
587
  );
543
- scrollEl.addEventListener(
544
- "touchend",
545
- onTouchEnd,
546
- addEventListenerOptions
547
- );
548
- scrollEl.addEventListener(
549
- "touchcancel",
550
- onTouchEnd,
551
- addEventListenerOptions
552
- );
553
- this.unsubs.push(() => {
554
- scrollEl.removeEventListener("touchstart", onTouchStart);
555
- scrollEl.removeEventListener("touchend", onTouchEnd);
556
- scrollEl.removeEventListener("touchcancel", onTouchEnd);
557
- this._endIosTouch();
558
- });
559
588
  }
560
- this._scrollToOffset(this.getScrollOffset(), {
561
- adjustments: void 0,
562
- behavior: void 0
563
- });
589
+ this._scrollToOffset(this.getScrollOffset());
564
590
  }
591
+ this._noteClampMax();
565
592
  const anchor = this.pendingScrollAnchor;
566
593
  this.pendingScrollAnchor = null;
567
594
  if (anchor && this.scrollElement && this.options.enabled) {
568
595
  if (anchor.kind === "anchor") {
569
- if (isIOSWebKit() && this._iosInMotion()) {
570
- this._iosDeferredAdjustment += anchor.delta;
596
+ if (!this._canWriteScroll()) {
597
+ this._holdOffset += anchor.delta;
598
+ this._followOffsetTarget(anchor.delta);
599
+ this.notify(false);
571
600
  } else if (isSmoothScroll(this.scrollState) && !approxEqual(
572
601
  this.getScrollOffset() - anchor.delta,
573
602
  this.scrollState.lastTargetOffset
574
603
  )) ;
575
604
  else {
576
- this._scrollToOffset(this.getScrollOffset(), {
577
- adjustments: void 0,
578
- behavior: void 0
579
- });
605
+ this._followOffsetTarget(anchor.delta);
606
+ this._scrollToOffset(this.getScrollOffset());
580
607
  }
581
608
  } else {
582
609
  this.scrollToEnd({ behavior: anchor.behavior });
583
610
  }
584
611
  }
612
+ this._flushHoldIfReady(false);
585
613
  this._retryClampedAdjustment();
586
614
  };
615
+ this._classifyScrollEvent = (offset, isScrolling, elementMax) => {
616
+ var _a;
617
+ return classifyScrollEvent({
618
+ offset,
619
+ isScrolling,
620
+ elementMax,
621
+ holdOffset: this._holdOffset,
622
+ scrollOffset: this.scrollOffset,
623
+ pendingWrite: this.pendingWrite,
624
+ clampedMaxAtWrite: ((_a = this._clampedAdjustment) == null ? void 0 : _a.maxAtWrite) ?? null
625
+ });
626
+ };
587
627
  this._retryClampedAdjustment = () => {
588
628
  if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled) {
589
629
  return;
@@ -592,36 +632,51 @@ class Virtualizer {
592
632
  const max = this.getMaxScrollOffset();
593
633
  if (max > maxAtWrite + 0.5) {
594
634
  this._clampedAdjustment = target > max + 0.5 ? { target, maxAtWrite: max } : null;
595
- this._scrollToOffset(target, {
596
- adjustments: void 0,
597
- behavior: void 0
598
- });
635
+ this._scrollToOffset(target);
599
636
  }
600
637
  };
601
- this._iosInMotion = () => this.isScrolling || this._iosTouch !== null;
602
- this._endIosTouch = () => {
603
- var _a;
604
- if (((_a = this._iosTouch) == null ? void 0 : _a.phase) === "tail" && this.targetWindow != null) {
605
- this.targetWindow.clearTimeout(this._iosTouch.timerId);
638
+ this._writeAwaitingCommand = () => {
639
+ const state = this.scrollState;
640
+ if (state === null || state.phase !== "queued") return;
641
+ const { behavior } = state;
642
+ this.getMeasurements();
643
+ const offset = this.getScrollStateTarget(state);
644
+ state.lastTargetOffset = offset;
645
+ this._clampedAdjustment = null;
646
+ state.phase = initialScrollPhase(
647
+ behavior,
648
+ state.index != null && approxEqual(offset, this.getScrollOffset())
649
+ );
650
+ this._scrollToOffset(offset, { behavior });
651
+ this.scheduleScrollReconcile();
652
+ };
653
+ this._readElementOffset = () => {
654
+ const el = this.scrollElement;
655
+ if (el == null) return null;
656
+ const { horizontal, isRtl } = this.options;
657
+ if (typeof el.scrollTop === "number") {
658
+ return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
606
659
  }
607
- this._iosTouch = null;
660
+ if (typeof el.scrollY === "number") {
661
+ return horizontal ? el.scrollX : el.scrollY;
662
+ }
663
+ return null;
608
664
  };
609
- this._flushIosDeferredIfReady = () => {
610
- if (this._iosDeferredAdjustment === 0) return;
611
- if (this._iosInMotion()) return;
612
- const cur = this.getScrollOffset();
613
- const max = this.getMaxScrollOffset();
614
- if (cur < 0 || cur > max) return;
615
- if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {
616
- this._iosDeferredAdjustment = 0;
617
- return;
665
+ this._canWriteScroll = () => !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll;
666
+ this._flushHoldIfReady = (sync) => {
667
+ var _a;
668
+ if (this._holdOffset === 0) return;
669
+ if (!this.scrollElement || !this.options.enabled) return;
670
+ if (!this._canWriteScroll()) return;
671
+ if (((_a = this.scrollState) == null ? void 0 : _a.phase) === "smooth") return;
672
+ this._holdOffset = 0;
673
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
674
+ this.scrollOffset = 0;
618
675
  }
619
- const delta = this._iosDeferredAdjustment;
620
- this._iosDeferredAdjustment = 0;
621
- this._scrollToOffset(cur, {
622
- adjustments: this.scrollAdjustments + delta,
623
- behavior: void 0
624
- });
676
+ this.notify(sync);
677
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
678
+ this._clampedAdjustment = this._clampedBy(target);
679
+ this._scrollToOffset(target);
625
680
  };
626
681
  this.rafId = null;
627
682
  this.getSize = () => {
@@ -964,14 +1019,14 @@ class Virtualizer {
964
1019
  const delta = size - itemSize;
965
1020
  if (delta !== 0) {
966
1021
  const wasAtEnd = this.options.anchorTo === "end" && !isSmoothScroll(this.scrollState) && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
967
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0;
968
- const scrollOffsetWithAdj = this.getScrollOffset() + this.scrollAdjustments;
1022
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
1023
+ const scrollOffset = this.getScrollOffset();
969
1024
  const isFirstMeasure = !this.itemSizeCache.has(key);
970
1025
  const defaultShouldAdjust = isFirstMeasure ? (
971
1026
  // First measurement: compensate any item whose top sits above the
972
1027
  // fold — the estimate→actual delta must be corrected regardless of
973
1028
  // scroll direction, since the whole estimated block was above it.
974
- itemStart < scrollOffsetWithAdj
1029
+ itemStart < scrollOffset
975
1030
  ) : (
976
1031
  // Re-measurement: only compensate an item that is ENTIRELY above the
977
1032
  // fold. An item that merely *spans* the fold (top above, bottom
@@ -980,7 +1035,7 @@ class Virtualizer {
980
1035
  // delta would drag the viewport downward on every growth (#1218).
981
1036
  // Also skip during backward scroll to avoid the "items jump while
982
1037
  // scrolling up" cascade.
983
- itemStart + itemSize <= scrollOffsetWithAdj && this.scrollDirection !== "backward"
1038
+ itemStart + itemSize <= scrollOffset && this.scrollDirection !== "backward"
984
1039
  );
985
1040
  const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(
986
1041
  // The callback expects a VirtualItem; build one lazily only
@@ -1001,16 +1056,11 @@ class Virtualizer {
1001
1056
  }
1002
1057
  this.itemSizeCache.set(key, size);
1003
1058
  this.itemSizeCacheVersion++;
1004
- const writtenOffset = this.getCommandWrittenOffset();
1005
- const awaitingCommandReadBack = writtenOffset !== null && !approxEqual(
1006
- writtenOffset,
1007
- this.getScrollOffset() + this.scrollAdjustments
1008
- );
1009
1059
  let adjustedSync = false;
1010
- if (!awaitingCommandReadBack) {
1060
+ if (!this._awaitingCommandReadBack()) {
1011
1061
  if (wasAtEnd) {
1012
1062
  adjustedSync = this.applyScrollAdjustment(
1013
- this.getTotalSize() - prevTotalSize
1063
+ this._getLayoutTotalSize() - prevTotalSize
1014
1064
  );
1015
1065
  } else if (shouldAdjustScroll) {
1016
1066
  adjustedSync = this.applyScrollAdjustment(delta);
@@ -1022,17 +1072,25 @@ class Virtualizer {
1022
1072
  return;
1023
1073
  }
1024
1074
  this.notify(adjustedSync);
1075
+ this._noteClampMax();
1076
+ this._flushHoldIfReady(true);
1025
1077
  this._retryClampedAdjustment();
1026
1078
  }
1027
1079
  };
1028
1080
  this.getVirtualItems = memo(
1029
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1030
- (indexes, measurements) => {
1081
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
1082
+ (indexes, measurements, hold) => {
1031
1083
  const virtualItems = [];
1032
1084
  for (let k = 0, len = indexes.length; k < len; k++) {
1033
1085
  const i = indexes[k];
1034
1086
  const measurement = measurements[i];
1035
- virtualItems.push(measurement);
1087
+ virtualItems.push(
1088
+ hold === 0 ? measurement : {
1089
+ ...measurement,
1090
+ start: measurement.start - hold,
1091
+ end: measurement.end - hold
1092
+ }
1093
+ );
1036
1094
  }
1037
1095
  return virtualItems;
1038
1096
  },
@@ -1057,18 +1115,83 @@ class Virtualizer {
1057
1115
  );
1058
1116
  return notUndefined(measurements[idx]);
1059
1117
  };
1060
- this.getMaxScrollOffset = () => {
1061
- if (!this.scrollElement) return 0;
1062
- if ("scrollHeight" in this.scrollElement) {
1063
- return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;
1064
- } else {
1065
- const doc = this.scrollElement.document.documentElement;
1066
- return this.options.horizontal ? doc.scrollWidth - this.scrollElement.innerWidth : doc.scrollHeight - this.scrollElement.innerHeight;
1118
+ this._noteClampMax = () => {
1119
+ if (!this._awaitingCommandReadBack()) return;
1120
+ const elementMax = this._elementMaxScrollOffset();
1121
+ if (elementMax === null) return;
1122
+ const write = this.pendingWrite;
1123
+ const max = Math.max(elementMax, 0) + this._holdOffset;
1124
+ if (max >= write.target) return;
1125
+ const lowMaxes = write.lowMaxes ?? (write.lowMaxes = []);
1126
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max);
1127
+ };
1128
+ this.getMaxScrollOffset = () => (this._elementMaxScrollOffset() ?? 0) + this._holdOffset;
1129
+ this._toLayoutOffset = (elementOffset) => {
1130
+ var _a;
1131
+ let offset = elementOffset + this._holdOffset;
1132
+ if (((_a = this.pendingScrollAnchor) == null ? void 0 : _a.kind) === "anchor") {
1133
+ offset += this.pendingScrollAnchor.delta;
1134
+ }
1135
+ return offset;
1136
+ };
1137
+ this._elementMaxScrollOffset = () => {
1138
+ const el = this.scrollElement;
1139
+ if (el === null) return null;
1140
+ if ("scrollHeight" in el) {
1141
+ return this.options.horizontal ? el.scrollWidth - el.clientWidth : el.scrollHeight - el.clientHeight;
1067
1142
  }
1143
+ if ("document" in el) {
1144
+ const doc = el.document.documentElement;
1145
+ return this.options.horizontal ? doc.scrollWidth - el.innerWidth : doc.scrollHeight - el.innerHeight;
1146
+ }
1147
+ return null;
1148
+ };
1149
+ this._momentumStop = null;
1150
+ this._stopMomentum = (done) => {
1151
+ const el = this.scrollElement;
1152
+ const win = this.targetWindow;
1153
+ if (el === null || win === null) return;
1154
+ const scroller = "document" in el ? el.document.scrollingElement : el;
1155
+ if (!(scroller == null ? void 0 : scroller.style)) return;
1156
+ if (this._momentumStop) {
1157
+ this._momentumStop.done = done;
1158
+ return;
1159
+ }
1160
+ const { style } = scroller;
1161
+ const property = this.options.horizontal ? "overflow-x" : "overflow-y";
1162
+ const value = style.getPropertyValue(property);
1163
+ const priority = style.getPropertyPriority(property);
1164
+ style.setProperty(property, "hidden", "important");
1165
+ const stop = {
1166
+ // False when the app replaced the hidden value: the fling may not
1167
+ // have stopped.
1168
+ restore: () => {
1169
+ if (style.getPropertyValue(property) !== "hidden" || style.getPropertyPriority(property) !== "important") {
1170
+ return false;
1171
+ }
1172
+ style.setProperty(property, value, priority);
1173
+ return true;
1174
+ },
1175
+ done
1176
+ };
1177
+ this._momentumStop = stop;
1178
+ win.requestAnimationFrame(
1179
+ () => win.requestAnimationFrame(() => {
1180
+ if (this._momentumStop !== stop) return;
1181
+ this._momentumStop = null;
1182
+ if (stop.restore()) stop.done();
1183
+ })
1184
+ );
1185
+ };
1186
+ this._clampedBy = (target) => {
1187
+ const elementMax = this._elementMaxScrollOffset();
1188
+ if (elementMax === null) return null;
1189
+ const maxAtWrite = elementMax + this._holdOffset;
1190
+ return target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1068
1191
  };
1069
1192
  this.getVirtualDistanceFromEnd = () => {
1070
1193
  return Math.max(
1071
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
1194
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
1072
1195
  0
1073
1196
  );
1074
1197
  };
@@ -1133,10 +1256,7 @@ class Virtualizer {
1133
1256
  } = {}) => {
1134
1257
  index = Math.max(0, Math.min(index, this.options.count - 1));
1135
1258
  const offsetInfo = this.getOffsetForIndex(index, initialAlign);
1136
- if (!offsetInfo) {
1137
- this._iosDeferredAdjustment = 0;
1138
- return;
1139
- }
1259
+ if (!offsetInfo) return;
1140
1260
  const [offset, align] = offsetInfo;
1141
1261
  this._startScroll({ index, align }, offset, behavior, "absolute");
1142
1262
  };
@@ -1173,7 +1293,8 @@ class Virtualizer {
1173
1293
  }
1174
1294
  this.scrollState = null;
1175
1295
  };
1176
- this.getTotalSize = () => {
1296
+ this.getTotalSize = () => Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
1297
+ this._getLayoutTotalSize = () => {
1177
1298
  var _a, _b;
1178
1299
  const measurements = this.getMeasurements();
1179
1300
  let end;
@@ -1225,15 +1346,29 @@ class Virtualizer {
1225
1346
  this._scrollToOffset = (offset, {
1226
1347
  adjustments,
1227
1348
  behavior
1228
- }) => {
1229
- this.pendingWrite = {
1349
+ } = {}) => {
1350
+ const write = {
1230
1351
  target: offset + (adjustments ?? 0),
1231
- smooth: behavior === "smooth",
1232
- adjustments: adjustments ?? this.scrollAdjustments
1352
+ smooth: behavior === "smooth"
1233
1353
  };
1234
- this.options.scrollToFn(offset, { behavior, adjustments }, this);
1354
+ this.pendingWrite = write;
1355
+ this.options.scrollToFn(
1356
+ offset - this._holdOffset,
1357
+ { behavior, adjustments },
1358
+ this
1359
+ );
1360
+ return write;
1235
1361
  };
1236
1362
  this.getCommandWrittenOffset = () => this.scrollState !== null && this.pendingWrite !== null && !this.pendingWrite.smooth ? this.pendingWrite.target : null;
1363
+ this._awaitingCommandReadBack = () => {
1364
+ const writtenOffset = this.getCommandWrittenOffset();
1365
+ return !(isIOSWebKit() && this._iosGesture.dragging()) && writtenOffset !== null && !approxEqual(writtenOffset, this.getScrollOffset());
1366
+ };
1367
+ this._followOffsetTarget = (delta) => {
1368
+ if (this.scrollState !== null && this.scrollState.index == null) {
1369
+ this.scrollState.lastTargetOffset += delta;
1370
+ }
1371
+ };
1237
1372
  this.measure = () => {
1238
1373
  this.pendingMin = null;
1239
1374
  this.itemSizeCache.clear();
@@ -1243,41 +1378,38 @@ class Virtualizer {
1243
1378
  };
1244
1379
  this.setOptions(opts);
1245
1380
  }
1246
- // Size compensation written to the element but not yet reflected in
1247
- // `scrollOffset`: the element is expected at `scrollOffset +
1248
- // scrollAdjustments` until the next scroll event reports it.
1381
+ /**
1382
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
1383
+ * at once, so there is never an outstanding adjustment to add to it. Read
1384
+ * `scrollOffset` alone.
1385
+ */
1249
1386
  get scrollAdjustments() {
1250
- var _a;
1251
- return ((_a = this.pendingWrite) == null ? void 0 : _a.adjustments) ?? 0;
1387
+ return 0;
1252
1388
  }
1253
1389
  // Returns `true` when it performed a synchronous `scrollTop` write this
1254
1390
  // tick, `false` when the delta was zero or the write was deferred (iOS).
1255
1391
  // `resizeItem` uses that to decide whether the follow-up `notify` must be
1256
1392
  // synchronous so the grown transforms commit in the same paint (#1227).
1257
1393
  applyScrollAdjustment(delta, behavior) {
1258
- var _a;
1259
1394
  if (delta === 0) return false;
1260
1395
  if (process.env.NODE_ENV !== "production" && this.options.debug) {
1261
1396
  console.info("correction", delta);
1262
1397
  }
1263
- if (isIOSWebKit() && this._iosInMotion()) {
1264
- if (((_a = this.scrollState) == null ? void 0 : _a.index) == null) {
1265
- this._iosDeferredAdjustment += delta;
1266
- }
1267
- return false;
1398
+ this._followOffsetTarget(delta);
1399
+ if (!this._canWriteScroll()) {
1400
+ this._holdOffset += delta;
1401
+ if (this.scrollOffset !== null) this.scrollOffset += delta;
1402
+ return true;
1268
1403
  } else {
1269
- const target = this.getScrollOffset() + this.scrollAdjustments + delta;
1270
- const el = this.scrollElement;
1271
- const maxAtWrite = el !== null && ("scrollHeight" in el || "document" in el) ? this.getMaxScrollOffset() : null;
1272
- this._clampedAdjustment = maxAtWrite !== null && target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1273
- this._scrollToOffset(this.getScrollOffset(), {
1274
- adjustments: this.scrollAdjustments + delta,
1404
+ const offset = this.getScrollOffset();
1405
+ this._clampedAdjustment = this._clampedBy(offset + delta);
1406
+ const write = this._scrollToOffset(offset, {
1407
+ adjustments: delta,
1275
1408
  behavior
1276
1409
  });
1277
1410
  if (this.scrollOffset !== null) {
1278
- this.scrollOffset += this.scrollAdjustments;
1411
+ if (this.pendingWrite === write) this.scrollOffset += delta;
1279
1412
  if (this.scrollOffset < 0) this.scrollOffset = 0;
1280
- if (this.pendingWrite) this.pendingWrite.adjustments = 0;
1281
1413
  }
1282
1414
  return true;
1283
1415
  }
@@ -1306,6 +1438,10 @@ class Virtualizer {
1306
1438
  this.scrollState = null;
1307
1439
  return;
1308
1440
  }
1441
+ if (this.scrollState.phase === "queued") {
1442
+ this.scheduleScrollReconcile();
1443
+ return;
1444
+ }
1309
1445
  this.getMeasurements();
1310
1446
  const targetOffset = this.getScrollStateTarget(this.scrollState);
1311
1447
  const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
@@ -1319,10 +1455,7 @@ class Virtualizer {
1319
1455
  this.scrollState.stableFrames++;
1320
1456
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1321
1457
  if (this.getScrollOffset() !== targetOffset) {
1322
- this._scrollToOffset(targetOffset, {
1323
- adjustments: void 0,
1324
- behavior: "auto"
1325
- });
1458
+ this._scrollToOffset(targetOffset, { behavior: "auto" });
1326
1459
  }
1327
1460
  this.scrollState = null;
1328
1461
  return;
@@ -1342,7 +1475,6 @@ class Virtualizer {
1342
1475
  this.scrollState.phase = "instant";
1343
1476
  }
1344
1477
  this._scrollToOffset(targetOffset, {
1345
- adjustments: void 0,
1346
1478
  behavior: keepSmooth ? "smooth" : "auto"
1347
1479
  });
1348
1480
  }
@@ -1352,31 +1484,58 @@ class Virtualizer {
1352
1484
  // Every scroll command starts here: it becomes the in-flight command,
1353
1485
  // writes its first target and leaves reconcile to retarget and retire it.
1354
1486
  //
1355
- // An absolute command derives its target from current measurements, so
1356
- // any iOS-deferred compensation still pending is stale by definition —
1357
- // the command already accounts for the measurements the delta was
1358
- // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
1359
- // onto the just-established position. A relative command (scrollBy)
1360
- // builds on the current offset, so it keeps the deferral.
1487
+ // Targets are layout offsets. A held correction is not dropped by a
1488
+ // command: the write lands the element `_holdOffset` short of the target,
1489
+ // under the rows exposed shifted by the same amount, and the flush moves
1490
+ // both together once a write is possible.
1361
1491
  //
1362
1492
  // An index or end target that is already at its offset starts a smooth
1363
1493
  // scroll as landed; an offset target never does, so its first scroll
1364
1494
  // event is read as the user's (see the scroll handler in `_willUpdate`).
1365
1495
  _startScroll(target, offset, behavior, kind) {
1366
- if (kind === "absolute") {
1367
- this._iosDeferredAdjustment = 0;
1496
+ const tail = this._iosGesture.tail();
1497
+ if (kind === "absolute" && tail !== null) {
1498
+ if (tail === "fling" && iosMomentumOverridesWrites()) {
1499
+ this._stopMomentum(() => {
1500
+ const state = this.scrollState;
1501
+ if ((state == null ? void 0 : state.phase) !== "queued" || // A finger came down: it owns the scroll until it lifts.
1502
+ this._iosGesture.tail() !== "fling" || // In a bounce WebKit can drop the write (#1287): the tail
1503
+ // decides, as without the stop. (Not `flingCaught`: our stop
1504
+ // also ends the fling at speed, so a slow frame would read as
1505
+ // a catch and the tail would drop the command.)
1506
+ this._reportedOverscroll) {
1507
+ return;
1508
+ }
1509
+ this._iosGesture.end();
1510
+ this._flushHoldIfReady(true);
1511
+ this._writeAwaitingCommand();
1512
+ });
1513
+ this.scrollState = {
1514
+ ...target,
1515
+ startedAt: this.now(),
1516
+ lastTargetOffset: offset,
1517
+ stableFrames: 0,
1518
+ phase: "queued",
1519
+ behavior,
1520
+ samples: []
1521
+ };
1522
+ this.scheduleScrollReconcile();
1523
+ return;
1524
+ }
1525
+ this._iosGesture.end();
1368
1526
  }
1369
1527
  this.scrollState = {
1370
1528
  ...target,
1371
1529
  startedAt: this.now(),
1372
1530
  lastTargetOffset: offset,
1373
1531
  stableFrames: 0,
1532
+ behavior,
1374
1533
  phase: initialScrollPhase(
1375
1534
  behavior,
1376
1535
  target.index != null && approxEqual(offset, this.getScrollOffset())
1377
1536
  )
1378
1537
  };
1379
- this._scrollToOffset(offset, { adjustments: void 0, behavior });
1538
+ this._scrollToOffset(offset, { behavior });
1380
1539
  this.scheduleScrollReconcile();
1381
1540
  }
1382
1541
  }