@tanstack/virtual-core 3.19.3 → 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,20 +1,28 @@
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 };
17
9
  };
10
+ const createFrameQueue = (targetWindow) => {
11
+ const ids = /* @__PURE__ */ new Set();
12
+ return {
13
+ schedule: (fn) => {
14
+ const id = targetWindow.requestAnimationFrame(() => {
15
+ ids.delete(id);
16
+ fn();
17
+ });
18
+ ids.add(id);
19
+ },
20
+ cancel: () => {
21
+ ids.forEach((id) => targetWindow.cancelAnimationFrame(id));
22
+ ids.clear();
23
+ }
24
+ };
25
+ };
18
26
  const defaultKeyExtractor = (index) => index;
19
27
  const defaultRangeExtractor = (range) => {
20
28
  const overscan = range.overscan * Math.max(range.lanes ?? 1, 1);
@@ -45,6 +53,7 @@ const observeElementRect = (instance, cb) => {
45
53
  return () => {
46
54
  };
47
55
  }
56
+ const frames = createFrameQueue(targetWindow);
48
57
  const observer = new targetWindow.ResizeObserver((entries) => {
49
58
  const run = () => {
50
59
  const entry = entries[0];
@@ -57,11 +66,12 @@ const observeElementRect = (instance, cb) => {
57
66
  }
58
67
  handler(getRect(element));
59
68
  };
60
- instance.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
69
+ instance.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
61
70
  });
62
71
  observer.observe(element, { box: "border-box" });
63
72
  return () => {
64
73
  observer.unobserve(element);
74
+ frames.cancel();
65
75
  };
66
76
  };
67
77
  const addEventListenerOptions = {
@@ -165,7 +175,6 @@ const windowScroll = scrollWithAdjustments;
165
175
  const elementScroll = scrollWithAdjustments;
166
176
  const initialScrollPhase = (behavior, atTarget) => behavior === "smooth" ? atTarget ? "smoothLanded" : "smooth" : "instant";
167
177
  const isSmoothScroll = (state) => (state == null ? void 0 : state.phase) === "smooth" || (state == null ? void 0 : state.phase) === "smoothLanded";
168
- const isAnimating = (state) => state.phase === "smooth" || state.phase === "smoothFinishing";
169
178
  function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
170
179
  if (nextCount === 0) return false;
171
180
  const firstKey = getNextKey(0);
@@ -207,8 +216,40 @@ class Virtualizer {
207
216
  this.scrollRect = null;
208
217
  this.scrollOffset = null;
209
218
  this.scrollDirection = null;
210
- this._iosDeferredAdjustment = 0;
211
- 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;
212
253
  this.pendingWrite = null;
213
254
  this._clampedAdjustment = null;
214
255
  this.elementsCache = /* @__PURE__ */ new Map();
@@ -219,14 +260,17 @@ class Virtualizer {
219
260
  };
220
261
  this.observer = /* @__PURE__ */ (() => {
221
262
  let _ro = null;
263
+ let _frames = null;
222
264
  const get = () => {
223
265
  if (_ro) {
224
266
  return _ro;
225
267
  }
226
- if (!this.targetWindow || !this.targetWindow.ResizeObserver) {
268
+ const targetWindow = this.targetWindow;
269
+ if (!targetWindow || !targetWindow.ResizeObserver) {
227
270
  return null;
228
271
  }
229
- return _ro = new this.targetWindow.ResizeObserver((entries) => {
272
+ const frames = _frames = createFrameQueue(targetWindow);
273
+ return _ro = new targetWindow.ResizeObserver((entries) => {
230
274
  const run = () => {
231
275
  const batch = { sync: false };
232
276
  this._resizeBatch = batch;
@@ -236,11 +280,13 @@ class Virtualizer {
236
280
  this._resizeBatch = null;
237
281
  if (batch.notify) {
238
282
  this.notify(batch.sync);
283
+ this._noteClampMax();
284
+ this._flushHoldIfReady(true);
239
285
  this._retryClampedAdjustment();
240
286
  }
241
287
  }
242
288
  };
243
- this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
289
+ this.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
244
290
  });
245
291
  };
246
292
  const measureEntry = (entry) => {
@@ -265,7 +311,9 @@ class Virtualizer {
265
311
  disconnect: () => {
266
312
  var _a;
267
313
  (_a = get()) == null ? void 0 : _a.disconnect();
314
+ _frames == null ? void 0 : _frames.cancel();
268
315
  _ro = null;
316
+ _frames = null;
269
317
  },
270
318
  observe: (target) => {
271
319
  var _a;
@@ -354,7 +402,7 @@ class Virtualizer {
354
402
  this.itemSizeCacheVersion++;
355
403
  }
356
404
  let anchorDelta = null;
357
- if (anchor && this.scrollOffset !== null) {
405
+ if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
358
406
  const [anchorKey, anchorOffset] = anchor;
359
407
  const newMeasurements = this.getMeasurements();
360
408
  const { count, getItemKey } = this.options;
@@ -376,7 +424,12 @@ class Virtualizer {
376
424
  if (followOnAppend) {
377
425
  this.pendingScrollAnchor = { kind: "follow", behavior: followOnAppend };
378
426
  } else if (anchorDelta !== null) {
379
- 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
+ }
380
433
  }
381
434
  };
382
435
  this.notify = (sync) => {
@@ -406,6 +459,7 @@ class Virtualizer {
406
459
  }
407
460
  );
408
461
  this.cleanup = () => {
462
+ var _a;
409
463
  this.unsubs.filter(Boolean).forEach((d) => d());
410
464
  this.unsubs = [];
411
465
  this.observer.disconnect();
@@ -414,10 +468,12 @@ class Virtualizer {
414
468
  this.rafId = null;
415
469
  }
416
470
  this.scrollState = null;
471
+ (_a = this._momentumStop) == null ? void 0 : _a.restore();
472
+ this._momentumStop = null;
417
473
  this.isScrolling = false;
418
474
  this.scrollDirection = null;
419
- this._iosDeferredAdjustment = 0;
420
- this._endIosTouch();
475
+ this._holdOffset = 0;
476
+ this._reportedOverscroll = false;
421
477
  this._clampedAdjustment = null;
422
478
  this.pendingWrite = null;
423
479
  this.scrollElement = null;
@@ -454,27 +510,30 @@ class Virtualizer {
454
510
  );
455
511
  this.unsubs.push(
456
512
  this.options.observeElementOffset(this, (offset, isScrolling) => {
457
- var _a2;
458
- if (isScrolling && this.pendingWrite === null && offset === this.scrollOffset) {
459
- return;
460
- }
461
- const pending = this.pendingWrite;
462
- if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
463
- offset = pending.target;
464
- } else if (((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // A non-smooth write lands at once, so any other scroll event is
465
- // the user's, even before reconcile saw the target reached (the
466
- // target may keep moving, or iOS ignored the write under a
467
- // finger). A write the browser clamped because the sizer hasn't
468
- // grown yet reads back at the max, which is also where the fresh
469
- // target clamps, so the check below keeps it reconciling (#1294).
470
- // Not when rows above the target shrink before the read-back and
471
- // pull the target below the new max: the read-back then looks
472
- // like the user and the scroll stops at the max. That needs the
473
- // sizer re-rendered before the scroll event, which browsers have
474
- // not been seen to do (pinned by a `.fails` test).
475
- // While a smooth scroll's animation may still report, its events
476
- // look like a user's, so it yields only once it has landed.
477
- !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
+ })) {
478
537
  this.scrollState = null;
479
538
  }
480
539
  this.pendingWrite = null;
@@ -482,10 +541,40 @@ class Virtualizer {
482
541
  this._clampedAdjustment = null;
483
542
  }
484
543
  const prevOffset = this.getScrollOffset();
544
+ const prevDirection = this.scrollDirection;
485
545
  this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? "forward" : "backward" : null;
486
546
  this.scrollOffset = offset;
487
547
  this.isScrolling = isScrolling;
488
- 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);
489
578
  if (this.scrollState) {
490
579
  this.scheduleScrollReconcile();
491
580
  }
@@ -493,74 +582,48 @@ class Virtualizer {
493
582
  })
494
583
  );
495
584
  if ("addEventListener" in this.scrollElement) {
496
- const scrollEl = this.scrollElement;
497
- const onTouchStart = () => {
498
- this._endIosTouch();
499
- this._iosTouch = { phase: "down" };
500
- };
501
- const onTouchEnd = () => {
502
- this._endIosTouch();
503
- if (!isIOSWebKit() || this.targetWindow == null) {
504
- return;
505
- }
506
- const tail = {
507
- phase: "tail",
508
- timerId: this.targetWindow.setTimeout(() => {
509
- if (this._iosTouch === tail) this._iosTouch = null;
510
- this._flushIosDeferredIfReady();
511
- }, 150)
512
- };
513
- this._iosTouch = tail;
514
- };
515
- scrollEl.addEventListener(
516
- "touchstart",
517
- onTouchStart,
518
- addEventListenerOptions
585
+ this.unsubs.push(
586
+ this._iosGesture.listen(this.scrollElement)
519
587
  );
520
- scrollEl.addEventListener(
521
- "touchend",
522
- onTouchEnd,
523
- addEventListenerOptions
524
- );
525
- scrollEl.addEventListener(
526
- "touchcancel",
527
- onTouchEnd,
528
- addEventListenerOptions
529
- );
530
- this.unsubs.push(() => {
531
- scrollEl.removeEventListener("touchstart", onTouchStart);
532
- scrollEl.removeEventListener("touchend", onTouchEnd);
533
- scrollEl.removeEventListener("touchcancel", onTouchEnd);
534
- this._endIosTouch();
535
- });
536
588
  }
537
- this._scrollToOffset(this.getScrollOffset(), {
538
- adjustments: void 0,
539
- behavior: void 0
540
- });
589
+ this._scrollToOffset(this.getScrollOffset());
541
590
  }
591
+ this._noteClampMax();
542
592
  const anchor = this.pendingScrollAnchor;
543
593
  this.pendingScrollAnchor = null;
544
594
  if (anchor && this.scrollElement && this.options.enabled) {
545
595
  if (anchor.kind === "anchor") {
546
- if (isIOSWebKit() && this._iosInMotion()) {
547
- this._iosDeferredAdjustment += anchor.delta;
596
+ if (!this._canWriteScroll()) {
597
+ this._holdOffset += anchor.delta;
598
+ this._followOffsetTarget(anchor.delta);
599
+ this.notify(false);
548
600
  } else if (isSmoothScroll(this.scrollState) && !approxEqual(
549
601
  this.getScrollOffset() - anchor.delta,
550
602
  this.scrollState.lastTargetOffset
551
603
  )) ;
552
604
  else {
553
- this._scrollToOffset(this.getScrollOffset(), {
554
- adjustments: void 0,
555
- behavior: void 0
556
- });
605
+ this._followOffsetTarget(anchor.delta);
606
+ this._scrollToOffset(this.getScrollOffset());
557
607
  }
558
608
  } else {
559
609
  this.scrollToEnd({ behavior: anchor.behavior });
560
610
  }
561
611
  }
612
+ this._flushHoldIfReady(false);
562
613
  this._retryClampedAdjustment();
563
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
+ };
564
627
  this._retryClampedAdjustment = () => {
565
628
  if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled) {
566
629
  return;
@@ -569,36 +632,51 @@ class Virtualizer {
569
632
  const max = this.getMaxScrollOffset();
570
633
  if (max > maxAtWrite + 0.5) {
571
634
  this._clampedAdjustment = target > max + 0.5 ? { target, maxAtWrite: max } : null;
572
- this._scrollToOffset(target, {
573
- adjustments: void 0,
574
- behavior: void 0
575
- });
635
+ this._scrollToOffset(target);
576
636
  }
577
637
  };
578
- this._iosInMotion = () => this.isScrolling || this._iosTouch !== null;
579
- this._endIosTouch = () => {
580
- var _a;
581
- if (((_a = this._iosTouch) == null ? void 0 : _a.phase) === "tail" && this.targetWindow != null) {
582
- 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;
659
+ }
660
+ if (typeof el.scrollY === "number") {
661
+ return horizontal ? el.scrollX : el.scrollY;
583
662
  }
584
- this._iosTouch = null;
663
+ return null;
585
664
  };
586
- this._flushIosDeferredIfReady = () => {
587
- if (this._iosDeferredAdjustment === 0) return;
588
- if (this._iosInMotion()) return;
589
- const cur = this.getScrollOffset();
590
- const max = this.getMaxScrollOffset();
591
- if (cur < 0 || cur > max) return;
592
- if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {
593
- this._iosDeferredAdjustment = 0;
594
- 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;
595
675
  }
596
- const delta = this._iosDeferredAdjustment;
597
- this._iosDeferredAdjustment = 0;
598
- this._scrollToOffset(cur, {
599
- adjustments: this.scrollAdjustments + delta,
600
- behavior: void 0
601
- });
676
+ this.notify(sync);
677
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
678
+ this._clampedAdjustment = this._clampedBy(target);
679
+ this._scrollToOffset(target);
602
680
  };
603
681
  this.rafId = null;
604
682
  this.getSize = () => {
@@ -941,14 +1019,14 @@ class Virtualizer {
941
1019
  const delta = size - itemSize;
942
1020
  if (delta !== 0) {
943
1021
  const wasAtEnd = this.options.anchorTo === "end" && !isSmoothScroll(this.scrollState) && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
944
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0;
945
- const scrollOffsetWithAdj = this.getScrollOffset() + this.scrollAdjustments;
1022
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
1023
+ const scrollOffset = this.getScrollOffset();
946
1024
  const isFirstMeasure = !this.itemSizeCache.has(key);
947
1025
  const defaultShouldAdjust = isFirstMeasure ? (
948
1026
  // First measurement: compensate any item whose top sits above the
949
1027
  // fold — the estimate→actual delta must be corrected regardless of
950
1028
  // scroll direction, since the whole estimated block was above it.
951
- itemStart < scrollOffsetWithAdj
1029
+ itemStart < scrollOffset
952
1030
  ) : (
953
1031
  // Re-measurement: only compensate an item that is ENTIRELY above the
954
1032
  // fold. An item that merely *spans* the fold (top above, bottom
@@ -957,7 +1035,7 @@ class Virtualizer {
957
1035
  // delta would drag the viewport downward on every growth (#1218).
958
1036
  // Also skip during backward scroll to avoid the "items jump while
959
1037
  // scrolling up" cascade.
960
- itemStart + itemSize <= scrollOffsetWithAdj && this.scrollDirection !== "backward"
1038
+ itemStart + itemSize <= scrollOffset && this.scrollDirection !== "backward"
961
1039
  );
962
1040
  const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(
963
1041
  // The callback expects a VirtualItem; build one lazily only
@@ -978,16 +1056,11 @@ class Virtualizer {
978
1056
  }
979
1057
  this.itemSizeCache.set(key, size);
980
1058
  this.itemSizeCacheVersion++;
981
- const writtenOffset = this.getCommandWrittenOffset();
982
- const awaitingCommandReadBack = writtenOffset !== null && !approxEqual(
983
- writtenOffset,
984
- this.getScrollOffset() + this.scrollAdjustments
985
- );
986
1059
  let adjustedSync = false;
987
- if (!awaitingCommandReadBack) {
1060
+ if (!this._awaitingCommandReadBack()) {
988
1061
  if (wasAtEnd) {
989
1062
  adjustedSync = this.applyScrollAdjustment(
990
- this.getTotalSize() - prevTotalSize
1063
+ this._getLayoutTotalSize() - prevTotalSize
991
1064
  );
992
1065
  } else if (shouldAdjustScroll) {
993
1066
  adjustedSync = this.applyScrollAdjustment(delta);
@@ -999,17 +1072,25 @@ class Virtualizer {
999
1072
  return;
1000
1073
  }
1001
1074
  this.notify(adjustedSync);
1075
+ this._noteClampMax();
1076
+ this._flushHoldIfReady(true);
1002
1077
  this._retryClampedAdjustment();
1003
1078
  }
1004
1079
  };
1005
1080
  this.getVirtualItems = memo(
1006
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1007
- (indexes, measurements) => {
1081
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
1082
+ (indexes, measurements, hold) => {
1008
1083
  const virtualItems = [];
1009
1084
  for (let k = 0, len = indexes.length; k < len; k++) {
1010
1085
  const i = indexes[k];
1011
1086
  const measurement = measurements[i];
1012
- virtualItems.push(measurement);
1087
+ virtualItems.push(
1088
+ hold === 0 ? measurement : {
1089
+ ...measurement,
1090
+ start: measurement.start - hold,
1091
+ end: measurement.end - hold
1092
+ }
1093
+ );
1013
1094
  }
1014
1095
  return virtualItems;
1015
1096
  },
@@ -1034,18 +1115,83 @@ class Virtualizer {
1034
1115
  );
1035
1116
  return notUndefined(measurements[idx]);
1036
1117
  };
1037
- this.getMaxScrollOffset = () => {
1038
- if (!this.scrollElement) return 0;
1039
- if ("scrollHeight" in this.scrollElement) {
1040
- return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;
1041
- } else {
1042
- const doc = this.scrollElement.document.documentElement;
1043
- 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;
1044
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;
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;
1045
1191
  };
1046
1192
  this.getVirtualDistanceFromEnd = () => {
1047
1193
  return Math.max(
1048
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
1194
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
1049
1195
  0
1050
1196
  );
1051
1197
  };
@@ -1110,10 +1256,7 @@ class Virtualizer {
1110
1256
  } = {}) => {
1111
1257
  index = Math.max(0, Math.min(index, this.options.count - 1));
1112
1258
  const offsetInfo = this.getOffsetForIndex(index, initialAlign);
1113
- if (!offsetInfo) {
1114
- this._iosDeferredAdjustment = 0;
1115
- return;
1116
- }
1259
+ if (!offsetInfo) return;
1117
1260
  const [offset, align] = offsetInfo;
1118
1261
  this._startScroll({ index, align }, offset, behavior, "absolute");
1119
1262
  };
@@ -1150,7 +1293,8 @@ class Virtualizer {
1150
1293
  }
1151
1294
  this.scrollState = null;
1152
1295
  };
1153
- this.getTotalSize = () => {
1296
+ this.getTotalSize = () => Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
1297
+ this._getLayoutTotalSize = () => {
1154
1298
  var _a, _b;
1155
1299
  const measurements = this.getMeasurements();
1156
1300
  let end;
@@ -1202,15 +1346,29 @@ class Virtualizer {
1202
1346
  this._scrollToOffset = (offset, {
1203
1347
  adjustments,
1204
1348
  behavior
1205
- }) => {
1206
- this.pendingWrite = {
1349
+ } = {}) => {
1350
+ const write = {
1207
1351
  target: offset + (adjustments ?? 0),
1208
- smooth: behavior === "smooth",
1209
- adjustments: adjustments ?? this.scrollAdjustments
1352
+ smooth: behavior === "smooth"
1210
1353
  };
1211
- 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;
1212
1361
  };
1213
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
+ };
1214
1372
  this.measure = () => {
1215
1373
  this.pendingMin = null;
1216
1374
  this.itemSizeCache.clear();
@@ -1220,41 +1378,38 @@ class Virtualizer {
1220
1378
  };
1221
1379
  this.setOptions(opts);
1222
1380
  }
1223
- // Size compensation written to the element but not yet reflected in
1224
- // `scrollOffset`: the element is expected at `scrollOffset +
1225
- // 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
+ */
1226
1386
  get scrollAdjustments() {
1227
- var _a;
1228
- return ((_a = this.pendingWrite) == null ? void 0 : _a.adjustments) ?? 0;
1387
+ return 0;
1229
1388
  }
1230
1389
  // Returns `true` when it performed a synchronous `scrollTop` write this
1231
1390
  // tick, `false` when the delta was zero or the write was deferred (iOS).
1232
1391
  // `resizeItem` uses that to decide whether the follow-up `notify` must be
1233
1392
  // synchronous so the grown transforms commit in the same paint (#1227).
1234
1393
  applyScrollAdjustment(delta, behavior) {
1235
- var _a;
1236
1394
  if (delta === 0) return false;
1237
1395
  if (process.env.NODE_ENV !== "production" && this.options.debug) {
1238
1396
  console.info("correction", delta);
1239
1397
  }
1240
- if (isIOSWebKit() && this._iosInMotion()) {
1241
- if (((_a = this.scrollState) == null ? void 0 : _a.index) == null) {
1242
- this._iosDeferredAdjustment += delta;
1243
- }
1244
- 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;
1245
1403
  } else {
1246
- const target = this.getScrollOffset() + this.scrollAdjustments + delta;
1247
- const el = this.scrollElement;
1248
- const maxAtWrite = el !== null && ("scrollHeight" in el || "document" in el) ? this.getMaxScrollOffset() : null;
1249
- this._clampedAdjustment = maxAtWrite !== null && target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1250
- this._scrollToOffset(this.getScrollOffset(), {
1251
- 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,
1252
1408
  behavior
1253
1409
  });
1254
1410
  if (this.scrollOffset !== null) {
1255
- this.scrollOffset += this.scrollAdjustments;
1411
+ if (this.pendingWrite === write) this.scrollOffset += delta;
1256
1412
  if (this.scrollOffset < 0) this.scrollOffset = 0;
1257
- if (this.pendingWrite) this.pendingWrite.adjustments = 0;
1258
1413
  }
1259
1414
  return true;
1260
1415
  }
@@ -1283,6 +1438,10 @@ class Virtualizer {
1283
1438
  this.scrollState = null;
1284
1439
  return;
1285
1440
  }
1441
+ if (this.scrollState.phase === "queued") {
1442
+ this.scheduleScrollReconcile();
1443
+ return;
1444
+ }
1286
1445
  this.getMeasurements();
1287
1446
  const targetOffset = this.getScrollStateTarget(this.scrollState);
1288
1447
  const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
@@ -1296,10 +1455,7 @@ class Virtualizer {
1296
1455
  this.scrollState.stableFrames++;
1297
1456
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1298
1457
  if (this.getScrollOffset() !== targetOffset) {
1299
- this._scrollToOffset(targetOffset, {
1300
- adjustments: void 0,
1301
- behavior: "auto"
1302
- });
1458
+ this._scrollToOffset(targetOffset, { behavior: "auto" });
1303
1459
  }
1304
1460
  this.scrollState = null;
1305
1461
  return;
@@ -1319,7 +1475,6 @@ class Virtualizer {
1319
1475
  this.scrollState.phase = "instant";
1320
1476
  }
1321
1477
  this._scrollToOffset(targetOffset, {
1322
- adjustments: void 0,
1323
1478
  behavior: keepSmooth ? "smooth" : "auto"
1324
1479
  });
1325
1480
  }
@@ -1329,31 +1484,58 @@ class Virtualizer {
1329
1484
  // Every scroll command starts here: it becomes the in-flight command,
1330
1485
  // writes its first target and leaves reconcile to retarget and retire it.
1331
1486
  //
1332
- // An absolute command derives its target from current measurements, so
1333
- // any iOS-deferred compensation still pending is stale by definition —
1334
- // the command already accounts for the measurements the delta was
1335
- // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
1336
- // onto the just-established position. A relative command (scrollBy)
1337
- // 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.
1338
1491
  //
1339
1492
  // An index or end target that is already at its offset starts a smooth
1340
1493
  // scroll as landed; an offset target never does, so its first scroll
1341
1494
  // event is read as the user's (see the scroll handler in `_willUpdate`).
1342
1495
  _startScroll(target, offset, behavior, kind) {
1343
- if (kind === "absolute") {
1344
- 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();
1345
1526
  }
1346
1527
  this.scrollState = {
1347
1528
  ...target,
1348
1529
  startedAt: this.now(),
1349
1530
  lastTargetOffset: offset,
1350
1531
  stableFrames: 0,
1532
+ behavior,
1351
1533
  phase: initialScrollPhase(
1352
1534
  behavior,
1353
1535
  target.index != null && approxEqual(offset, this.getScrollOffset())
1354
1536
  )
1355
1537
  };
1356
- this._scrollToOffset(offset, { adjustments: void 0, behavior });
1538
+ this._scrollToOffset(offset, { behavior });
1357
1539
  this.scheduleScrollReconcile();
1358
1540
  }
1359
1541
  }