@tanstack/virtual-core 3.19.4 → 3.19.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,19 +1,11 @@
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
- const { offsetWidth, offsetHeight } = element;
16
- return { width: offsetWidth, height: offsetHeight };
7
+ const { clientWidth, clientHeight } = element;
8
+ return { width: clientWidth, height: clientHeight };
17
9
  };
18
10
  const createFrameQueue = (targetWindow) => {
19
11
  const ids = /* @__PURE__ */ new Set();
@@ -62,21 +54,13 @@ const observeElementRect = (instance, cb) => {
62
54
  };
63
55
  }
64
56
  const frames = createFrameQueue(targetWindow);
65
- const observer = new targetWindow.ResizeObserver((entries) => {
57
+ const observer = new targetWindow.ResizeObserver(() => {
66
58
  const run = () => {
67
- const entry = entries[0];
68
- if (entry == null ? void 0 : entry.borderBoxSize) {
69
- const box = entry.borderBoxSize[0];
70
- if (box) {
71
- handler({ width: box.inlineSize, height: box.blockSize });
72
- return;
73
- }
74
- }
75
59
  handler(getRect(element));
76
60
  };
77
61
  instance.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
78
62
  });
79
- observer.observe(element, { box: "border-box" });
63
+ observer.observe(element, { box: "content-box" });
80
64
  return () => {
81
65
  observer.unobserve(element);
82
66
  frames.cancel();
@@ -183,7 +167,6 @@ const windowScroll = scrollWithAdjustments;
183
167
  const elementScroll = scrollWithAdjustments;
184
168
  const initialScrollPhase = (behavior, atTarget) => behavior === "smooth" ? atTarget ? "smoothLanded" : "smooth" : "instant";
185
169
  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
170
  function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
188
171
  if (nextCount === 0) return false;
189
172
  const firstKey = getNextKey(0);
@@ -225,8 +208,40 @@ class Virtualizer {
225
208
  this.scrollRect = null;
226
209
  this.scrollOffset = null;
227
210
  this.scrollDirection = null;
228
- this._iosDeferredAdjustment = 0;
229
- this._iosTouch = null;
211
+ this._holdOffset = 0;
212
+ this._reportedOverscroll = false;
213
+ this._iosGesture = new IosGesture({
214
+ getWindow: () => this.targetWindow,
215
+ now: () => this.now(),
216
+ // The end of a fling can move less than a pixel per scroll event, so
217
+ // events can stop for 150ms while the fling is still running (seen on
218
+ // an iPhone, 27.0.1). A command waiting for it would then be written
219
+ // into the fling and overridden. The element having moved since the
220
+ // last event means it has not ended: wait again. Not while our own
221
+ // write has yet to report: that moved it.
222
+ tailStillMoving: () => {
223
+ const state = this.scrollState;
224
+ if ((state == null ? void 0 : state.phase) !== "queued" || this.pendingWrite !== null) {
225
+ return false;
226
+ }
227
+ const now = this._readElementOffset();
228
+ if (now === null || this._lastElementOffset === null || Math.abs(now - this._lastElementOffset) < 1) {
229
+ return false;
230
+ }
231
+ this._lastElementOffset = now;
232
+ state.samples = [...state.samples ?? [], { t: this.now(), offset: now }];
233
+ return true;
234
+ },
235
+ onTailClosed: () => {
236
+ const state = this.scrollState;
237
+ if ((state == null ? void 0 : state.phase) === "queued" && flingCaught(state.samples ?? [])) {
238
+ this.scrollState = null;
239
+ }
240
+ this._flushHoldIfReady(true);
241
+ this._writeAwaitingCommand();
242
+ }
243
+ });
244
+ this._lastElementOffset = null;
230
245
  this.pendingWrite = null;
231
246
  this._clampedAdjustment = null;
232
247
  this.elementsCache = /* @__PURE__ */ new Map();
@@ -257,6 +272,8 @@ class Virtualizer {
257
272
  this._resizeBatch = null;
258
273
  if (batch.notify) {
259
274
  this.notify(batch.sync);
275
+ this._noteClampMax();
276
+ this._flushHoldIfReady(true);
260
277
  this._retryClampedAdjustment();
261
278
  }
262
279
  }
@@ -377,7 +394,7 @@ class Virtualizer {
377
394
  this.itemSizeCacheVersion++;
378
395
  }
379
396
  let anchorDelta = null;
380
- if (anchor && this.scrollOffset !== null) {
397
+ if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
381
398
  const [anchorKey, anchorOffset] = anchor;
382
399
  const newMeasurements = this.getMeasurements();
383
400
  const { count, getItemKey } = this.options;
@@ -399,7 +416,12 @@ class Virtualizer {
399
416
  if (followOnAppend) {
400
417
  this.pendingScrollAnchor = { kind: "follow", behavior: followOnAppend };
401
418
  } else if (anchorDelta !== null) {
402
- this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
419
+ if (this._canWriteScroll()) {
420
+ this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
421
+ } else {
422
+ this._holdOffset += anchorDelta;
423
+ this._followOffsetTarget(anchorDelta);
424
+ }
403
425
  }
404
426
  };
405
427
  this.notify = (sync) => {
@@ -429,6 +451,7 @@ class Virtualizer {
429
451
  }
430
452
  );
431
453
  this.cleanup = () => {
454
+ var _a;
432
455
  this.unsubs.filter(Boolean).forEach((d) => d());
433
456
  this.unsubs = [];
434
457
  this.observer.disconnect();
@@ -437,10 +460,12 @@ class Virtualizer {
437
460
  this.rafId = null;
438
461
  }
439
462
  this.scrollState = null;
463
+ (_a = this._momentumStop) == null ? void 0 : _a.restore();
464
+ this._momentumStop = null;
440
465
  this.isScrolling = false;
441
466
  this.scrollDirection = null;
442
- this._iosDeferredAdjustment = 0;
443
- this._endIosTouch();
467
+ this._holdOffset = 0;
468
+ this._reportedOverscroll = false;
444
469
  this._clampedAdjustment = null;
445
470
  this.pendingWrite = null;
446
471
  this.scrollElement = null;
@@ -477,27 +502,30 @@ class Virtualizer {
477
502
  );
478
503
  this.unsubs.push(
479
504
  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)) {
505
+ var _a2, _b, _c, _d;
506
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null;
507
+ const wasOverscrolled = this._reportedOverscroll;
508
+ this._reportedOverscroll = offset < 0 || elementMax !== null && offset > elementMax + 1;
509
+ const elementOffset = offset;
510
+ this._lastElementOffset = elementOffset;
511
+ offset = this._toLayoutOffset(offset);
512
+ const kind = this._classifyScrollEvent(
513
+ offset,
514
+ isScrolling,
515
+ elementMax
516
+ );
517
+ if (kind === "spurious") return;
518
+ if (kind === "readBack") {
519
+ offset = this.pendingWrite.target;
520
+ } else if (kind === "clampedReadBack" && ((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // Not `elementMax`: an adapter can report the read-back at rest.
521
+ offset < this.getMaxScrollOffset() - 1.5) {
522
+ this.scrollState.lastTargetOffset = offset;
523
+ } else if (externalRetiresCommand({
524
+ kind,
525
+ offset,
526
+ command: this.scrollState,
527
+ target: () => this.getScrollStateTarget(this.scrollState)
528
+ })) {
501
529
  this.scrollState = null;
502
530
  }
503
531
  this.pendingWrite = null;
@@ -505,10 +533,40 @@ class Virtualizer {
505
533
  this._clampedAdjustment = null;
506
534
  }
507
535
  const prevOffset = this.getScrollOffset();
536
+ const prevDirection = this.scrollDirection;
508
537
  this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? "forward" : "backward" : null;
509
538
  this.scrollOffset = offset;
510
539
  this.isScrolling = isScrolling;
511
- this._flushIosDeferredIfReady();
540
+ const queued = this.scrollState;
541
+ if ((queued == null ? void 0 : queued.phase) === "queued" && kind === "external" && isScrolling) {
542
+ if (wasOverscrolled || this._reportedOverscroll) {
543
+ queued.samples = [];
544
+ } else {
545
+ const t = this.now();
546
+ queued.samples = [
547
+ ...(queued.samples ?? []).filter(
548
+ (sample) => t - sample.t <= 200
549
+ ),
550
+ { t, offset: elementOffset }
551
+ ];
552
+ if (prevDirection !== null && this.scrollDirection !== prevDirection || flingSpedUp(queued.samples)) {
553
+ this.scrollState = null;
554
+ }
555
+ }
556
+ }
557
+ if (this._iosGesture.onScroll({
558
+ isScrolling,
559
+ ownReadBack: kind === "readBack",
560
+ moved: offset !== prevOffset,
561
+ // Neither our write's read-back nor a frame of our smooth
562
+ // animation: the user or a fling moved it.
563
+ external: kind === "external" && ((_b = this.scrollState) == null ? void 0 : _b.phase) !== "smooth" && ((_c = this.scrollState) == null ? void 0 : _c.phase) !== "smoothFinishing"
564
+ }) && // The user scrolls: a command still waiting for the tail is
565
+ // theirs to override, like a written one would be.
566
+ ((_d = this.scrollState) == null ? void 0 : _d.phase) === "queued") {
567
+ this.scrollState = null;
568
+ }
569
+ this._flushHoldIfReady(true);
512
570
  if (this.scrollState) {
513
571
  this.scheduleScrollReconcile();
514
572
  }
@@ -516,74 +574,48 @@ class Virtualizer {
516
574
  })
517
575
  );
518
576
  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
577
+ this.unsubs.push(
578
+ this._iosGesture.listen(this.scrollElement)
542
579
  );
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
580
  }
560
- this._scrollToOffset(this.getScrollOffset(), {
561
- adjustments: void 0,
562
- behavior: void 0
563
- });
581
+ this._scrollToOffset(this.getScrollOffset());
564
582
  }
583
+ this._noteClampMax();
565
584
  const anchor = this.pendingScrollAnchor;
566
585
  this.pendingScrollAnchor = null;
567
586
  if (anchor && this.scrollElement && this.options.enabled) {
568
587
  if (anchor.kind === "anchor") {
569
- if (isIOSWebKit() && this._iosInMotion()) {
570
- this._iosDeferredAdjustment += anchor.delta;
588
+ if (!this._canWriteScroll()) {
589
+ this._holdOffset += anchor.delta;
590
+ this._followOffsetTarget(anchor.delta);
591
+ this.notify(false);
571
592
  } else if (isSmoothScroll(this.scrollState) && !approxEqual(
572
593
  this.getScrollOffset() - anchor.delta,
573
594
  this.scrollState.lastTargetOffset
574
595
  )) ;
575
596
  else {
576
- this._scrollToOffset(this.getScrollOffset(), {
577
- adjustments: void 0,
578
- behavior: void 0
579
- });
597
+ this._followOffsetTarget(anchor.delta);
598
+ this._scrollToOffset(this.getScrollOffset());
580
599
  }
581
600
  } else {
582
601
  this.scrollToEnd({ behavior: anchor.behavior });
583
602
  }
584
603
  }
604
+ this._flushHoldIfReady(false);
585
605
  this._retryClampedAdjustment();
586
606
  };
607
+ this._classifyScrollEvent = (offset, isScrolling, elementMax) => {
608
+ var _a;
609
+ return classifyScrollEvent({
610
+ offset,
611
+ isScrolling,
612
+ elementMax,
613
+ holdOffset: this._holdOffset,
614
+ scrollOffset: this.scrollOffset,
615
+ pendingWrite: this.pendingWrite,
616
+ clampedMaxAtWrite: ((_a = this._clampedAdjustment) == null ? void 0 : _a.maxAtWrite) ?? null
617
+ });
618
+ };
587
619
  this._retryClampedAdjustment = () => {
588
620
  if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled) {
589
621
  return;
@@ -592,36 +624,51 @@ class Virtualizer {
592
624
  const max = this.getMaxScrollOffset();
593
625
  if (max > maxAtWrite + 0.5) {
594
626
  this._clampedAdjustment = target > max + 0.5 ? { target, maxAtWrite: max } : null;
595
- this._scrollToOffset(target, {
596
- adjustments: void 0,
597
- behavior: void 0
598
- });
627
+ this._scrollToOffset(target);
599
628
  }
600
629
  };
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);
630
+ this._writeAwaitingCommand = () => {
631
+ const state = this.scrollState;
632
+ if (state === null || state.phase !== "queued") return;
633
+ const { behavior } = state;
634
+ this.getMeasurements();
635
+ const offset = this.getScrollStateTarget(state);
636
+ state.lastTargetOffset = offset;
637
+ this._clampedAdjustment = null;
638
+ state.phase = initialScrollPhase(
639
+ behavior,
640
+ state.index != null && approxEqual(offset, this.getScrollOffset())
641
+ );
642
+ this._scrollToOffset(offset, { behavior });
643
+ this.scheduleScrollReconcile();
644
+ };
645
+ this._readElementOffset = () => {
646
+ const el = this.scrollElement;
647
+ if (el == null) return null;
648
+ const { horizontal, isRtl } = this.options;
649
+ if (typeof el.scrollTop === "number") {
650
+ return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
651
+ }
652
+ if (typeof el.scrollY === "number") {
653
+ return horizontal ? el.scrollX : el.scrollY;
606
654
  }
607
- this._iosTouch = null;
655
+ return null;
608
656
  };
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;
657
+ this._canWriteScroll = () => !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll;
658
+ this._flushHoldIfReady = (sync) => {
659
+ var _a;
660
+ if (this._holdOffset === 0) return;
661
+ if (!this.scrollElement || !this.options.enabled) return;
662
+ if (!this._canWriteScroll()) return;
663
+ if (((_a = this.scrollState) == null ? void 0 : _a.phase) === "smooth") return;
664
+ this._holdOffset = 0;
665
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
666
+ this.scrollOffset = 0;
618
667
  }
619
- const delta = this._iosDeferredAdjustment;
620
- this._iosDeferredAdjustment = 0;
621
- this._scrollToOffset(cur, {
622
- adjustments: this.scrollAdjustments + delta,
623
- behavior: void 0
624
- });
668
+ this.notify(sync);
669
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
670
+ this._clampedAdjustment = this._clampedBy(target);
671
+ this._scrollToOffset(target);
625
672
  };
626
673
  this.rafId = null;
627
674
  this.getSize = () => {
@@ -964,14 +1011,14 @@ class Virtualizer {
964
1011
  const delta = size - itemSize;
965
1012
  if (delta !== 0) {
966
1013
  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;
1014
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
1015
+ const scrollOffset = this.getScrollOffset();
969
1016
  const isFirstMeasure = !this.itemSizeCache.has(key);
970
1017
  const defaultShouldAdjust = isFirstMeasure ? (
971
1018
  // First measurement: compensate any item whose top sits above the
972
1019
  // fold — the estimate→actual delta must be corrected regardless of
973
1020
  // scroll direction, since the whole estimated block was above it.
974
- itemStart < scrollOffsetWithAdj
1021
+ itemStart < scrollOffset
975
1022
  ) : (
976
1023
  // Re-measurement: only compensate an item that is ENTIRELY above the
977
1024
  // fold. An item that merely *spans* the fold (top above, bottom
@@ -980,7 +1027,7 @@ class Virtualizer {
980
1027
  // delta would drag the viewport downward on every growth (#1218).
981
1028
  // Also skip during backward scroll to avoid the "items jump while
982
1029
  // scrolling up" cascade.
983
- itemStart + itemSize <= scrollOffsetWithAdj && this.scrollDirection !== "backward"
1030
+ itemStart + itemSize <= scrollOffset && this.scrollDirection !== "backward"
984
1031
  );
985
1032
  const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(
986
1033
  // The callback expects a VirtualItem; build one lazily only
@@ -1001,16 +1048,11 @@ class Virtualizer {
1001
1048
  }
1002
1049
  this.itemSizeCache.set(key, size);
1003
1050
  this.itemSizeCacheVersion++;
1004
- const writtenOffset = this.getCommandWrittenOffset();
1005
- const awaitingCommandReadBack = writtenOffset !== null && !approxEqual(
1006
- writtenOffset,
1007
- this.getScrollOffset() + this.scrollAdjustments
1008
- );
1009
1051
  let adjustedSync = false;
1010
- if (!awaitingCommandReadBack) {
1052
+ if (!this._awaitingCommandReadBack()) {
1011
1053
  if (wasAtEnd) {
1012
1054
  adjustedSync = this.applyScrollAdjustment(
1013
- this.getTotalSize() - prevTotalSize
1055
+ this._getLayoutTotalSize() - prevTotalSize
1014
1056
  );
1015
1057
  } else if (shouldAdjustScroll) {
1016
1058
  adjustedSync = this.applyScrollAdjustment(delta);
@@ -1022,17 +1064,25 @@ class Virtualizer {
1022
1064
  return;
1023
1065
  }
1024
1066
  this.notify(adjustedSync);
1067
+ this._noteClampMax();
1068
+ this._flushHoldIfReady(true);
1025
1069
  this._retryClampedAdjustment();
1026
1070
  }
1027
1071
  };
1028
1072
  this.getVirtualItems = memo(
1029
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1030
- (indexes, measurements) => {
1073
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
1074
+ (indexes, measurements, hold) => {
1031
1075
  const virtualItems = [];
1032
1076
  for (let k = 0, len = indexes.length; k < len; k++) {
1033
1077
  const i = indexes[k];
1034
1078
  const measurement = measurements[i];
1035
- virtualItems.push(measurement);
1079
+ virtualItems.push(
1080
+ hold === 0 ? measurement : {
1081
+ ...measurement,
1082
+ start: measurement.start - hold,
1083
+ end: measurement.end - hold
1084
+ }
1085
+ );
1036
1086
  }
1037
1087
  return virtualItems;
1038
1088
  },
@@ -1057,18 +1107,83 @@ class Virtualizer {
1057
1107
  );
1058
1108
  return notUndefined(measurements[idx]);
1059
1109
  };
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;
1110
+ this._noteClampMax = () => {
1111
+ if (!this._awaitingCommandReadBack()) return;
1112
+ const elementMax = this._elementMaxScrollOffset();
1113
+ if (elementMax === null) return;
1114
+ const write = this.pendingWrite;
1115
+ const max = Math.max(elementMax, 0) + this._holdOffset;
1116
+ if (max >= write.target) return;
1117
+ const lowMaxes = write.lowMaxes ?? (write.lowMaxes = []);
1118
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max);
1119
+ };
1120
+ this.getMaxScrollOffset = () => (this._elementMaxScrollOffset() ?? 0) + this._holdOffset;
1121
+ this._toLayoutOffset = (elementOffset) => {
1122
+ var _a;
1123
+ let offset = elementOffset + this._holdOffset;
1124
+ if (((_a = this.pendingScrollAnchor) == null ? void 0 : _a.kind) === "anchor") {
1125
+ offset += this.pendingScrollAnchor.delta;
1067
1126
  }
1127
+ return offset;
1128
+ };
1129
+ this._elementMaxScrollOffset = () => {
1130
+ const el = this.scrollElement;
1131
+ if (el === null) return null;
1132
+ if ("scrollHeight" in el) {
1133
+ return this.options.horizontal ? el.scrollWidth - el.clientWidth : el.scrollHeight - el.clientHeight;
1134
+ }
1135
+ if ("document" in el) {
1136
+ const doc = el.document.documentElement;
1137
+ return this.options.horizontal ? doc.scrollWidth - el.innerWidth : doc.scrollHeight - el.innerHeight;
1138
+ }
1139
+ return null;
1140
+ };
1141
+ this._momentumStop = null;
1142
+ this._stopMomentum = (done) => {
1143
+ const el = this.scrollElement;
1144
+ const win = this.targetWindow;
1145
+ if (el === null || win === null) return;
1146
+ const scroller = "document" in el ? el.document.scrollingElement : el;
1147
+ if (!(scroller == null ? void 0 : scroller.style)) return;
1148
+ if (this._momentumStop) {
1149
+ this._momentumStop.done = done;
1150
+ return;
1151
+ }
1152
+ const { style } = scroller;
1153
+ const property = this.options.horizontal ? "overflow-x" : "overflow-y";
1154
+ const value = style.getPropertyValue(property);
1155
+ const priority = style.getPropertyPriority(property);
1156
+ style.setProperty(property, "hidden", "important");
1157
+ const stop = {
1158
+ // False when the app replaced the hidden value: the fling may not
1159
+ // have stopped.
1160
+ restore: () => {
1161
+ if (style.getPropertyValue(property) !== "hidden" || style.getPropertyPriority(property) !== "important") {
1162
+ return false;
1163
+ }
1164
+ style.setProperty(property, value, priority);
1165
+ return true;
1166
+ },
1167
+ done
1168
+ };
1169
+ this._momentumStop = stop;
1170
+ win.requestAnimationFrame(
1171
+ () => win.requestAnimationFrame(() => {
1172
+ if (this._momentumStop !== stop) return;
1173
+ this._momentumStop = null;
1174
+ if (stop.restore()) stop.done();
1175
+ })
1176
+ );
1177
+ };
1178
+ this._clampedBy = (target) => {
1179
+ const elementMax = this._elementMaxScrollOffset();
1180
+ if (elementMax === null) return null;
1181
+ const maxAtWrite = elementMax + this._holdOffset;
1182
+ return target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1068
1183
  };
1069
1184
  this.getVirtualDistanceFromEnd = () => {
1070
1185
  return Math.max(
1071
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
1186
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
1072
1187
  0
1073
1188
  );
1074
1189
  };
@@ -1133,10 +1248,7 @@ class Virtualizer {
1133
1248
  } = {}) => {
1134
1249
  index = Math.max(0, Math.min(index, this.options.count - 1));
1135
1250
  const offsetInfo = this.getOffsetForIndex(index, initialAlign);
1136
- if (!offsetInfo) {
1137
- this._iosDeferredAdjustment = 0;
1138
- return;
1139
- }
1251
+ if (!offsetInfo) return;
1140
1252
  const [offset, align] = offsetInfo;
1141
1253
  this._startScroll({ index, align }, offset, behavior, "absolute");
1142
1254
  };
@@ -1173,7 +1285,8 @@ class Virtualizer {
1173
1285
  }
1174
1286
  this.scrollState = null;
1175
1287
  };
1176
- this.getTotalSize = () => {
1288
+ this.getTotalSize = () => Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
1289
+ this._getLayoutTotalSize = () => {
1177
1290
  var _a, _b;
1178
1291
  const measurements = this.getMeasurements();
1179
1292
  let end;
@@ -1225,15 +1338,29 @@ class Virtualizer {
1225
1338
  this._scrollToOffset = (offset, {
1226
1339
  adjustments,
1227
1340
  behavior
1228
- }) => {
1229
- this.pendingWrite = {
1341
+ } = {}) => {
1342
+ const write = {
1230
1343
  target: offset + (adjustments ?? 0),
1231
- smooth: behavior === "smooth",
1232
- adjustments: adjustments ?? this.scrollAdjustments
1344
+ smooth: behavior === "smooth"
1233
1345
  };
1234
- this.options.scrollToFn(offset, { behavior, adjustments }, this);
1346
+ this.pendingWrite = write;
1347
+ this.options.scrollToFn(
1348
+ offset - this._holdOffset,
1349
+ { behavior, adjustments },
1350
+ this
1351
+ );
1352
+ return write;
1235
1353
  };
1236
1354
  this.getCommandWrittenOffset = () => this.scrollState !== null && this.pendingWrite !== null && !this.pendingWrite.smooth ? this.pendingWrite.target : null;
1355
+ this._awaitingCommandReadBack = () => {
1356
+ const writtenOffset = this.getCommandWrittenOffset();
1357
+ return !(isIOSWebKit() && this._iosGesture.dragging()) && writtenOffset !== null && !approxEqual(writtenOffset, this.getScrollOffset());
1358
+ };
1359
+ this._followOffsetTarget = (delta) => {
1360
+ if (this.scrollState !== null && this.scrollState.index == null) {
1361
+ this.scrollState.lastTargetOffset += delta;
1362
+ }
1363
+ };
1237
1364
  this.measure = () => {
1238
1365
  this.pendingMin = null;
1239
1366
  this.itemSizeCache.clear();
@@ -1243,41 +1370,38 @@ class Virtualizer {
1243
1370
  };
1244
1371
  this.setOptions(opts);
1245
1372
  }
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.
1373
+ /**
1374
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
1375
+ * at once, so there is never an outstanding adjustment to add to it. Read
1376
+ * `scrollOffset` alone.
1377
+ */
1249
1378
  get scrollAdjustments() {
1250
- var _a;
1251
- return ((_a = this.pendingWrite) == null ? void 0 : _a.adjustments) ?? 0;
1379
+ return 0;
1252
1380
  }
1253
1381
  // Returns `true` when it performed a synchronous `scrollTop` write this
1254
1382
  // tick, `false` when the delta was zero or the write was deferred (iOS).
1255
1383
  // `resizeItem` uses that to decide whether the follow-up `notify` must be
1256
1384
  // synchronous so the grown transforms commit in the same paint (#1227).
1257
1385
  applyScrollAdjustment(delta, behavior) {
1258
- var _a;
1259
1386
  if (delta === 0) return false;
1260
1387
  if (process.env.NODE_ENV !== "production" && this.options.debug) {
1261
1388
  console.info("correction", delta);
1262
1389
  }
1263
- if (isIOSWebKit() && this._iosInMotion()) {
1264
- if (((_a = this.scrollState) == null ? void 0 : _a.index) == null) {
1265
- this._iosDeferredAdjustment += delta;
1266
- }
1267
- return false;
1390
+ this._followOffsetTarget(delta);
1391
+ if (!this._canWriteScroll()) {
1392
+ this._holdOffset += delta;
1393
+ if (this.scrollOffset !== null) this.scrollOffset += delta;
1394
+ return true;
1268
1395
  } 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,
1396
+ const offset = this.getScrollOffset();
1397
+ this._clampedAdjustment = this._clampedBy(offset + delta);
1398
+ const write = this._scrollToOffset(offset, {
1399
+ adjustments: delta,
1275
1400
  behavior
1276
1401
  });
1277
1402
  if (this.scrollOffset !== null) {
1278
- this.scrollOffset += this.scrollAdjustments;
1403
+ if (this.pendingWrite === write) this.scrollOffset += delta;
1279
1404
  if (this.scrollOffset < 0) this.scrollOffset = 0;
1280
- if (this.pendingWrite) this.pendingWrite.adjustments = 0;
1281
1405
  }
1282
1406
  return true;
1283
1407
  }
@@ -1306,6 +1430,10 @@ class Virtualizer {
1306
1430
  this.scrollState = null;
1307
1431
  return;
1308
1432
  }
1433
+ if (this.scrollState.phase === "queued") {
1434
+ this.scheduleScrollReconcile();
1435
+ return;
1436
+ }
1309
1437
  this.getMeasurements();
1310
1438
  const targetOffset = this.getScrollStateTarget(this.scrollState);
1311
1439
  const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
@@ -1319,10 +1447,7 @@ class Virtualizer {
1319
1447
  this.scrollState.stableFrames++;
1320
1448
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1321
1449
  if (this.getScrollOffset() !== targetOffset) {
1322
- this._scrollToOffset(targetOffset, {
1323
- adjustments: void 0,
1324
- behavior: "auto"
1325
- });
1450
+ this._scrollToOffset(targetOffset, { behavior: "auto" });
1326
1451
  }
1327
1452
  this.scrollState = null;
1328
1453
  return;
@@ -1342,7 +1467,6 @@ class Virtualizer {
1342
1467
  this.scrollState.phase = "instant";
1343
1468
  }
1344
1469
  this._scrollToOffset(targetOffset, {
1345
- adjustments: void 0,
1346
1470
  behavior: keepSmooth ? "smooth" : "auto"
1347
1471
  });
1348
1472
  }
@@ -1352,31 +1476,58 @@ class Virtualizer {
1352
1476
  // Every scroll command starts here: it becomes the in-flight command,
1353
1477
  // writes its first target and leaves reconcile to retarget and retire it.
1354
1478
  //
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.
1479
+ // Targets are layout offsets. A held correction is not dropped by a
1480
+ // command: the write lands the element `_holdOffset` short of the target,
1481
+ // under the rows exposed shifted by the same amount, and the flush moves
1482
+ // both together once a write is possible.
1361
1483
  //
1362
1484
  // An index or end target that is already at its offset starts a smooth
1363
1485
  // scroll as landed; an offset target never does, so its first scroll
1364
1486
  // event is read as the user's (see the scroll handler in `_willUpdate`).
1365
1487
  _startScroll(target, offset, behavior, kind) {
1366
- if (kind === "absolute") {
1367
- this._iosDeferredAdjustment = 0;
1488
+ const tail = this._iosGesture.tail();
1489
+ if (kind === "absolute" && tail !== null) {
1490
+ if (tail === "fling" && iosMomentumOverridesWrites()) {
1491
+ this._stopMomentum(() => {
1492
+ const state = this.scrollState;
1493
+ if ((state == null ? void 0 : state.phase) !== "queued" || // A finger came down: it owns the scroll until it lifts.
1494
+ this._iosGesture.tail() !== "fling" || // In a bounce WebKit can drop the write (#1287): the tail
1495
+ // decides, as without the stop. (Not `flingCaught`: our stop
1496
+ // also ends the fling at speed, so a slow frame would read as
1497
+ // a catch and the tail would drop the command.)
1498
+ this._reportedOverscroll) {
1499
+ return;
1500
+ }
1501
+ this._iosGesture.end();
1502
+ this._flushHoldIfReady(true);
1503
+ this._writeAwaitingCommand();
1504
+ });
1505
+ this.scrollState = {
1506
+ ...target,
1507
+ startedAt: this.now(),
1508
+ lastTargetOffset: offset,
1509
+ stableFrames: 0,
1510
+ phase: "queued",
1511
+ behavior,
1512
+ samples: []
1513
+ };
1514
+ this.scheduleScrollReconcile();
1515
+ return;
1516
+ }
1517
+ this._iosGesture.end();
1368
1518
  }
1369
1519
  this.scrollState = {
1370
1520
  ...target,
1371
1521
  startedAt: this.now(),
1372
1522
  lastTargetOffset: offset,
1373
1523
  stableFrames: 0,
1524
+ behavior,
1374
1525
  phase: initialScrollPhase(
1375
1526
  behavior,
1376
1527
  target.index != null && approxEqual(offset, this.getScrollOffset())
1377
1528
  )
1378
1529
  };
1379
- this._scrollToOffset(offset, { adjustments: void 0, behavior });
1530
+ this._scrollToOffset(offset, { behavior });
1380
1531
  this.scheduleScrollReconcile();
1381
1532
  }
1382
1533
  }