@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.
@@ -2,21 +2,28 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const lazyMeasurements = require("./lazy-measurements.cjs");
4
4
  const utils = require("./utils.cjs");
5
- let _isIOSResult;
6
- const isIOSWebKit = () => {
7
- if (_isIOSResult !== void 0) return _isIOSResult;
8
- if (typeof navigator === "undefined") return _isIOSResult = false;
9
- if (/iP(hone|od|ad)/.test(navigator.userAgent)) return _isIOSResult = true;
10
- const mtp = navigator.maxTouchPoints;
11
- return _isIOSResult = navigator.platform === "MacIntel" && mtp !== void 0 && mtp > 0;
12
- };
13
- const _resetIOSDetectionForTests = () => {
14
- _isIOSResult = void 0;
15
- };
5
+ const scrollClassifier = require("./scroll-classifier.cjs");
6
+ const iosGesture = require("./ios-gesture.cjs");
16
7
  const getRect = (element) => {
17
8
  const { offsetWidth, offsetHeight } = element;
18
9
  return { width: offsetWidth, height: offsetHeight };
19
10
  };
11
+ const createFrameQueue = (targetWindow) => {
12
+ const ids = /* @__PURE__ */ new Set();
13
+ return {
14
+ schedule: (fn) => {
15
+ const id = targetWindow.requestAnimationFrame(() => {
16
+ ids.delete(id);
17
+ fn();
18
+ });
19
+ ids.add(id);
20
+ },
21
+ cancel: () => {
22
+ ids.forEach((id) => targetWindow.cancelAnimationFrame(id));
23
+ ids.clear();
24
+ }
25
+ };
26
+ };
20
27
  const defaultKeyExtractor = (index) => index;
21
28
  const defaultRangeExtractor = (range) => {
22
29
  const overscan = range.overscan * Math.max(range.lanes ?? 1, 1);
@@ -47,6 +54,7 @@ const observeElementRect = (instance, cb) => {
47
54
  return () => {
48
55
  };
49
56
  }
57
+ const frames = createFrameQueue(targetWindow);
50
58
  const observer = new targetWindow.ResizeObserver((entries) => {
51
59
  const run = () => {
52
60
  const entry = entries[0];
@@ -59,11 +67,12 @@ const observeElementRect = (instance, cb) => {
59
67
  }
60
68
  handler(getRect(element));
61
69
  };
62
- instance.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
70
+ instance.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
63
71
  });
64
72
  observer.observe(element, { box: "border-box" });
65
73
  return () => {
66
74
  observer.unobserve(element);
75
+ frames.cancel();
67
76
  };
68
77
  };
69
78
  const addEventListenerOptions = {
@@ -167,7 +176,6 @@ const windowScroll = scrollWithAdjustments;
167
176
  const elementScroll = scrollWithAdjustments;
168
177
  const initialScrollPhase = (behavior, atTarget) => behavior === "smooth" ? atTarget ? "smoothLanded" : "smooth" : "instant";
169
178
  const isSmoothScroll = (state) => (state == null ? void 0 : state.phase) === "smooth" || (state == null ? void 0 : state.phase) === "smoothLanded";
170
- const isAnimating = (state) => state.phase === "smooth" || state.phase === "smoothFinishing";
171
179
  function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
172
180
  if (nextCount === 0) return false;
173
181
  const firstKey = getNextKey(0);
@@ -209,8 +217,40 @@ class Virtualizer {
209
217
  this.scrollRect = null;
210
218
  this.scrollOffset = null;
211
219
  this.scrollDirection = null;
212
- this._iosDeferredAdjustment = 0;
213
- this._iosTouch = null;
220
+ this._holdOffset = 0;
221
+ this._reportedOverscroll = false;
222
+ this._iosGesture = new iosGesture.IosGesture({
223
+ getWindow: () => this.targetWindow,
224
+ now: () => this.now(),
225
+ // The end of a fling can move less than a pixel per scroll event, so
226
+ // events can stop for 150ms while the fling is still running (seen on
227
+ // an iPhone, 27.0.1). A command waiting for it would then be written
228
+ // into the fling and overridden. The element having moved since the
229
+ // last event means it has not ended: wait again. Not while our own
230
+ // write has yet to report: that moved it.
231
+ tailStillMoving: () => {
232
+ const state = this.scrollState;
233
+ if ((state == null ? void 0 : state.phase) !== "queued" || this.pendingWrite !== null) {
234
+ return false;
235
+ }
236
+ const now = this._readElementOffset();
237
+ if (now === null || this._lastElementOffset === null || Math.abs(now - this._lastElementOffset) < 1) {
238
+ return false;
239
+ }
240
+ this._lastElementOffset = now;
241
+ state.samples = [...state.samples ?? [], { t: this.now(), offset: now }];
242
+ return true;
243
+ },
244
+ onTailClosed: () => {
245
+ const state = this.scrollState;
246
+ if ((state == null ? void 0 : state.phase) === "queued" && scrollClassifier.flingCaught(state.samples ?? [])) {
247
+ this.scrollState = null;
248
+ }
249
+ this._flushHoldIfReady(true);
250
+ this._writeAwaitingCommand();
251
+ }
252
+ });
253
+ this._lastElementOffset = null;
214
254
  this.pendingWrite = null;
215
255
  this._clampedAdjustment = null;
216
256
  this.elementsCache = /* @__PURE__ */ new Map();
@@ -221,14 +261,17 @@ class Virtualizer {
221
261
  };
222
262
  this.observer = /* @__PURE__ */ (() => {
223
263
  let _ro = null;
264
+ let _frames = null;
224
265
  const get = () => {
225
266
  if (_ro) {
226
267
  return _ro;
227
268
  }
228
- if (!this.targetWindow || !this.targetWindow.ResizeObserver) {
269
+ const targetWindow = this.targetWindow;
270
+ if (!targetWindow || !targetWindow.ResizeObserver) {
229
271
  return null;
230
272
  }
231
- return _ro = new this.targetWindow.ResizeObserver((entries) => {
273
+ const frames = _frames = createFrameQueue(targetWindow);
274
+ return _ro = new targetWindow.ResizeObserver((entries) => {
232
275
  const run = () => {
233
276
  const batch = { sync: false };
234
277
  this._resizeBatch = batch;
@@ -238,11 +281,13 @@ class Virtualizer {
238
281
  this._resizeBatch = null;
239
282
  if (batch.notify) {
240
283
  this.notify(batch.sync);
284
+ this._noteClampMax();
285
+ this._flushHoldIfReady(true);
241
286
  this._retryClampedAdjustment();
242
287
  }
243
288
  }
244
289
  };
245
- this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
290
+ this.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
246
291
  });
247
292
  };
248
293
  const measureEntry = (entry) => {
@@ -267,7 +312,9 @@ class Virtualizer {
267
312
  disconnect: () => {
268
313
  var _a;
269
314
  (_a = get()) == null ? void 0 : _a.disconnect();
315
+ _frames == null ? void 0 : _frames.cancel();
270
316
  _ro = null;
317
+ _frames = null;
271
318
  },
272
319
  observe: (target) => {
273
320
  var _a;
@@ -356,7 +403,7 @@ class Virtualizer {
356
403
  this.itemSizeCacheVersion++;
357
404
  }
358
405
  let anchorDelta = null;
359
- if (anchor && this.scrollOffset !== null) {
406
+ if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
360
407
  const [anchorKey, anchorOffset] = anchor;
361
408
  const newMeasurements = this.getMeasurements();
362
409
  const { count, getItemKey } = this.options;
@@ -378,7 +425,12 @@ class Virtualizer {
378
425
  if (followOnAppend) {
379
426
  this.pendingScrollAnchor = { kind: "follow", behavior: followOnAppend };
380
427
  } else if (anchorDelta !== null) {
381
- this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
428
+ if (this._canWriteScroll()) {
429
+ this.pendingScrollAnchor = { kind: "anchor", delta: anchorDelta };
430
+ } else {
431
+ this._holdOffset += anchorDelta;
432
+ this._followOffsetTarget(anchorDelta);
433
+ }
382
434
  }
383
435
  };
384
436
  this.notify = (sync) => {
@@ -408,6 +460,7 @@ class Virtualizer {
408
460
  }
409
461
  );
410
462
  this.cleanup = () => {
463
+ var _a;
411
464
  this.unsubs.filter(Boolean).forEach((d) => d());
412
465
  this.unsubs = [];
413
466
  this.observer.disconnect();
@@ -416,10 +469,12 @@ class Virtualizer {
416
469
  this.rafId = null;
417
470
  }
418
471
  this.scrollState = null;
472
+ (_a = this._momentumStop) == null ? void 0 : _a.restore();
473
+ this._momentumStop = null;
419
474
  this.isScrolling = false;
420
475
  this.scrollDirection = null;
421
- this._iosDeferredAdjustment = 0;
422
- this._endIosTouch();
476
+ this._holdOffset = 0;
477
+ this._reportedOverscroll = false;
423
478
  this._clampedAdjustment = null;
424
479
  this.pendingWrite = null;
425
480
  this.scrollElement = null;
@@ -456,27 +511,30 @@ class Virtualizer {
456
511
  );
457
512
  this.unsubs.push(
458
513
  this.options.observeElementOffset(this, (offset, isScrolling) => {
459
- var _a2;
460
- if (isScrolling && this.pendingWrite === null && offset === this.scrollOffset) {
461
- return;
462
- }
463
- const pending = this.pendingWrite;
464
- if (pending !== null && Math.abs(offset - pending.target) < 1.5) {
465
- offset = pending.target;
466
- } else if (((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // A non-smooth write lands at once, so any other scroll event is
467
- // the user's, even before reconcile saw the target reached (the
468
- // target may keep moving, or iOS ignored the write under a
469
- // finger). A write the browser clamped because the sizer hasn't
470
- // grown yet reads back at the max, which is also where the fresh
471
- // target clamps, so the check below keeps it reconciling (#1294).
472
- // Not when rows above the target shrink before the read-back and
473
- // pull the target below the new max: the read-back then looks
474
- // like the user and the scroll stops at the max. That needs the
475
- // sizer re-rendered before the scroll event, which browsers have
476
- // not been seen to do (pinned by a `.fails` test).
477
- // While a smooth scroll's animation may still report, its events
478
- // look like a user's, so it yields only once it has landed.
479
- !isAnimating(this.scrollState) && !utils.approxEqual(offset, this.scrollState.lastTargetOffset) && !utils.approxEqual(offset, this.getScrollStateTarget(this.scrollState)) && (this._clampedAdjustment === null || Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5)) {
514
+ var _a2, _b, _c, _d;
515
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null;
516
+ const wasOverscrolled = this._reportedOverscroll;
517
+ this._reportedOverscroll = offset < 0 || elementMax !== null && offset > elementMax + 1;
518
+ const elementOffset = offset;
519
+ this._lastElementOffset = elementOffset;
520
+ offset = this._toLayoutOffset(offset);
521
+ const kind = this._classifyScrollEvent(
522
+ offset,
523
+ isScrolling,
524
+ elementMax
525
+ );
526
+ if (kind === "spurious") return;
527
+ if (kind === "readBack") {
528
+ offset = this.pendingWrite.target;
529
+ } else if (kind === "clampedReadBack" && ((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && // Not `elementMax`: an adapter can report the read-back at rest.
530
+ offset < this.getMaxScrollOffset() - 1.5) {
531
+ this.scrollState.lastTargetOffset = offset;
532
+ } else if (scrollClassifier.externalRetiresCommand({
533
+ kind,
534
+ offset,
535
+ command: this.scrollState,
536
+ target: () => this.getScrollStateTarget(this.scrollState)
537
+ })) {
480
538
  this.scrollState = null;
481
539
  }
482
540
  this.pendingWrite = null;
@@ -484,10 +542,40 @@ class Virtualizer {
484
542
  this._clampedAdjustment = null;
485
543
  }
486
544
  const prevOffset = this.getScrollOffset();
545
+ const prevDirection = this.scrollDirection;
487
546
  this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? "forward" : "backward" : null;
488
547
  this.scrollOffset = offset;
489
548
  this.isScrolling = isScrolling;
490
- this._flushIosDeferredIfReady();
549
+ const queued = this.scrollState;
550
+ if ((queued == null ? void 0 : queued.phase) === "queued" && kind === "external" && isScrolling) {
551
+ if (wasOverscrolled || this._reportedOverscroll) {
552
+ queued.samples = [];
553
+ } else {
554
+ const t = this.now();
555
+ queued.samples = [
556
+ ...(queued.samples ?? []).filter(
557
+ (sample) => t - sample.t <= 200
558
+ ),
559
+ { t, offset: elementOffset }
560
+ ];
561
+ if (prevDirection !== null && this.scrollDirection !== prevDirection || scrollClassifier.flingSpedUp(queued.samples)) {
562
+ this.scrollState = null;
563
+ }
564
+ }
565
+ }
566
+ if (this._iosGesture.onScroll({
567
+ isScrolling,
568
+ ownReadBack: kind === "readBack",
569
+ moved: offset !== prevOffset,
570
+ // Neither our write's read-back nor a frame of our smooth
571
+ // animation: the user or a fling moved it.
572
+ external: kind === "external" && ((_b = this.scrollState) == null ? void 0 : _b.phase) !== "smooth" && ((_c = this.scrollState) == null ? void 0 : _c.phase) !== "smoothFinishing"
573
+ }) && // The user scrolls: a command still waiting for the tail is
574
+ // theirs to override, like a written one would be.
575
+ ((_d = this.scrollState) == null ? void 0 : _d.phase) === "queued") {
576
+ this.scrollState = null;
577
+ }
578
+ this._flushHoldIfReady(true);
491
579
  if (this.scrollState) {
492
580
  this.scheduleScrollReconcile();
493
581
  }
@@ -495,74 +583,48 @@ class Virtualizer {
495
583
  })
496
584
  );
497
585
  if ("addEventListener" in this.scrollElement) {
498
- const scrollEl = this.scrollElement;
499
- const onTouchStart = () => {
500
- this._endIosTouch();
501
- this._iosTouch = { phase: "down" };
502
- };
503
- const onTouchEnd = () => {
504
- this._endIosTouch();
505
- if (!isIOSWebKit() || this.targetWindow == null) {
506
- return;
507
- }
508
- const tail = {
509
- phase: "tail",
510
- timerId: this.targetWindow.setTimeout(() => {
511
- if (this._iosTouch === tail) this._iosTouch = null;
512
- this._flushIosDeferredIfReady();
513
- }, 150)
514
- };
515
- this._iosTouch = tail;
516
- };
517
- scrollEl.addEventListener(
518
- "touchstart",
519
- onTouchStart,
520
- addEventListenerOptions
586
+ this.unsubs.push(
587
+ this._iosGesture.listen(this.scrollElement)
521
588
  );
522
- scrollEl.addEventListener(
523
- "touchend",
524
- onTouchEnd,
525
- addEventListenerOptions
526
- );
527
- scrollEl.addEventListener(
528
- "touchcancel",
529
- onTouchEnd,
530
- addEventListenerOptions
531
- );
532
- this.unsubs.push(() => {
533
- scrollEl.removeEventListener("touchstart", onTouchStart);
534
- scrollEl.removeEventListener("touchend", onTouchEnd);
535
- scrollEl.removeEventListener("touchcancel", onTouchEnd);
536
- this._endIosTouch();
537
- });
538
589
  }
539
- this._scrollToOffset(this.getScrollOffset(), {
540
- adjustments: void 0,
541
- behavior: void 0
542
- });
590
+ this._scrollToOffset(this.getScrollOffset());
543
591
  }
592
+ this._noteClampMax();
544
593
  const anchor = this.pendingScrollAnchor;
545
594
  this.pendingScrollAnchor = null;
546
595
  if (anchor && this.scrollElement && this.options.enabled) {
547
596
  if (anchor.kind === "anchor") {
548
- if (isIOSWebKit() && this._iosInMotion()) {
549
- this._iosDeferredAdjustment += anchor.delta;
597
+ if (!this._canWriteScroll()) {
598
+ this._holdOffset += anchor.delta;
599
+ this._followOffsetTarget(anchor.delta);
600
+ this.notify(false);
550
601
  } else if (isSmoothScroll(this.scrollState) && !utils.approxEqual(
551
602
  this.getScrollOffset() - anchor.delta,
552
603
  this.scrollState.lastTargetOffset
553
604
  )) ;
554
605
  else {
555
- this._scrollToOffset(this.getScrollOffset(), {
556
- adjustments: void 0,
557
- behavior: void 0
558
- });
606
+ this._followOffsetTarget(anchor.delta);
607
+ this._scrollToOffset(this.getScrollOffset());
559
608
  }
560
609
  } else {
561
610
  this.scrollToEnd({ behavior: anchor.behavior });
562
611
  }
563
612
  }
613
+ this._flushHoldIfReady(false);
564
614
  this._retryClampedAdjustment();
565
615
  };
616
+ this._classifyScrollEvent = (offset, isScrolling, elementMax) => {
617
+ var _a;
618
+ return scrollClassifier.classifyScrollEvent({
619
+ offset,
620
+ isScrolling,
621
+ elementMax,
622
+ holdOffset: this._holdOffset,
623
+ scrollOffset: this.scrollOffset,
624
+ pendingWrite: this.pendingWrite,
625
+ clampedMaxAtWrite: ((_a = this._clampedAdjustment) == null ? void 0 : _a.maxAtWrite) ?? null
626
+ });
627
+ };
566
628
  this._retryClampedAdjustment = () => {
567
629
  if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled) {
568
630
  return;
@@ -571,36 +633,51 @@ class Virtualizer {
571
633
  const max = this.getMaxScrollOffset();
572
634
  if (max > maxAtWrite + 0.5) {
573
635
  this._clampedAdjustment = target > max + 0.5 ? { target, maxAtWrite: max } : null;
574
- this._scrollToOffset(target, {
575
- adjustments: void 0,
576
- behavior: void 0
577
- });
636
+ this._scrollToOffset(target);
578
637
  }
579
638
  };
580
- this._iosInMotion = () => this.isScrolling || this._iosTouch !== null;
581
- this._endIosTouch = () => {
582
- var _a;
583
- if (((_a = this._iosTouch) == null ? void 0 : _a.phase) === "tail" && this.targetWindow != null) {
584
- this.targetWindow.clearTimeout(this._iosTouch.timerId);
639
+ this._writeAwaitingCommand = () => {
640
+ const state = this.scrollState;
641
+ if (state === null || state.phase !== "queued") return;
642
+ const { behavior } = state;
643
+ this.getMeasurements();
644
+ const offset = this.getScrollStateTarget(state);
645
+ state.lastTargetOffset = offset;
646
+ this._clampedAdjustment = null;
647
+ state.phase = initialScrollPhase(
648
+ behavior,
649
+ state.index != null && utils.approxEqual(offset, this.getScrollOffset())
650
+ );
651
+ this._scrollToOffset(offset, { behavior });
652
+ this.scheduleScrollReconcile();
653
+ };
654
+ this._readElementOffset = () => {
655
+ const el = this.scrollElement;
656
+ if (el == null) return null;
657
+ const { horizontal, isRtl } = this.options;
658
+ if (typeof el.scrollTop === "number") {
659
+ return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
660
+ }
661
+ if (typeof el.scrollY === "number") {
662
+ return horizontal ? el.scrollX : el.scrollY;
585
663
  }
586
- this._iosTouch = null;
664
+ return null;
587
665
  };
588
- this._flushIosDeferredIfReady = () => {
589
- if (this._iosDeferredAdjustment === 0) return;
590
- if (this._iosInMotion()) return;
591
- const cur = this.getScrollOffset();
592
- const max = this.getMaxScrollOffset();
593
- if (cur < 0 || cur > max) return;
594
- if (this._iosDeferredAdjustment < 0 && cur >= max - 1) {
595
- this._iosDeferredAdjustment = 0;
596
- return;
666
+ this._canWriteScroll = () => !(iosGesture.isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll;
667
+ this._flushHoldIfReady = (sync) => {
668
+ var _a;
669
+ if (this._holdOffset === 0) return;
670
+ if (!this.scrollElement || !this.options.enabled) return;
671
+ if (!this._canWriteScroll()) return;
672
+ if (((_a = this.scrollState) == null ? void 0 : _a.phase) === "smooth") return;
673
+ this._holdOffset = 0;
674
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
675
+ this.scrollOffset = 0;
597
676
  }
598
- const delta = this._iosDeferredAdjustment;
599
- this._iosDeferredAdjustment = 0;
600
- this._scrollToOffset(cur, {
601
- adjustments: this.scrollAdjustments + delta,
602
- behavior: void 0
603
- });
677
+ this.notify(sync);
678
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
679
+ this._clampedAdjustment = this._clampedBy(target);
680
+ this._scrollToOffset(target);
604
681
  };
605
682
  this.rafId = null;
606
683
  this.getSize = () => {
@@ -943,14 +1020,14 @@ class Virtualizer {
943
1020
  const delta = size - itemSize;
944
1021
  if (delta !== 0) {
945
1022
  const wasAtEnd = this.options.anchorTo === "end" && !isSmoothScroll(this.scrollState) && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
946
- const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0;
947
- const scrollOffsetWithAdj = this.getScrollOffset() + this.scrollAdjustments;
1023
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
1024
+ const scrollOffset = this.getScrollOffset();
948
1025
  const isFirstMeasure = !this.itemSizeCache.has(key);
949
1026
  const defaultShouldAdjust = isFirstMeasure ? (
950
1027
  // First measurement: compensate any item whose top sits above the
951
1028
  // fold — the estimate→actual delta must be corrected regardless of
952
1029
  // scroll direction, since the whole estimated block was above it.
953
- itemStart < scrollOffsetWithAdj
1030
+ itemStart < scrollOffset
954
1031
  ) : (
955
1032
  // Re-measurement: only compensate an item that is ENTIRELY above the
956
1033
  // fold. An item that merely *spans* the fold (top above, bottom
@@ -959,7 +1036,7 @@ class Virtualizer {
959
1036
  // delta would drag the viewport downward on every growth (#1218).
960
1037
  // Also skip during backward scroll to avoid the "items jump while
961
1038
  // scrolling up" cascade.
962
- itemStart + itemSize <= scrollOffsetWithAdj && this.scrollDirection !== "backward"
1039
+ itemStart + itemSize <= scrollOffset && this.scrollDirection !== "backward"
963
1040
  );
964
1041
  const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(
965
1042
  // The callback expects a VirtualItem; build one lazily only
@@ -980,16 +1057,11 @@ class Virtualizer {
980
1057
  }
981
1058
  this.itemSizeCache.set(key, size);
982
1059
  this.itemSizeCacheVersion++;
983
- const writtenOffset = this.getCommandWrittenOffset();
984
- const awaitingCommandReadBack = writtenOffset !== null && !utils.approxEqual(
985
- writtenOffset,
986
- this.getScrollOffset() + this.scrollAdjustments
987
- );
988
1060
  let adjustedSync = false;
989
- if (!awaitingCommandReadBack) {
1061
+ if (!this._awaitingCommandReadBack()) {
990
1062
  if (wasAtEnd) {
991
1063
  adjustedSync = this.applyScrollAdjustment(
992
- this.getTotalSize() - prevTotalSize
1064
+ this._getLayoutTotalSize() - prevTotalSize
993
1065
  );
994
1066
  } else if (shouldAdjustScroll) {
995
1067
  adjustedSync = this.applyScrollAdjustment(delta);
@@ -1001,17 +1073,25 @@ class Virtualizer {
1001
1073
  return;
1002
1074
  }
1003
1075
  this.notify(adjustedSync);
1076
+ this._noteClampMax();
1077
+ this._flushHoldIfReady(true);
1004
1078
  this._retryClampedAdjustment();
1005
1079
  }
1006
1080
  };
1007
1081
  this.getVirtualItems = utils.memo(
1008
- () => [this.getVirtualIndexes(), this.getMeasurements()],
1009
- (indexes, measurements) => {
1082
+ () => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset],
1083
+ (indexes, measurements, hold) => {
1010
1084
  const virtualItems = [];
1011
1085
  for (let k = 0, len = indexes.length; k < len; k++) {
1012
1086
  const i = indexes[k];
1013
1087
  const measurement = measurements[i];
1014
- virtualItems.push(measurement);
1088
+ virtualItems.push(
1089
+ hold === 0 ? measurement : {
1090
+ ...measurement,
1091
+ start: measurement.start - hold,
1092
+ end: measurement.end - hold
1093
+ }
1094
+ );
1015
1095
  }
1016
1096
  return virtualItems;
1017
1097
  },
@@ -1036,18 +1116,83 @@ class Virtualizer {
1036
1116
  );
1037
1117
  return utils.notUndefined(measurements[idx]);
1038
1118
  };
1039
- this.getMaxScrollOffset = () => {
1040
- if (!this.scrollElement) return 0;
1041
- if ("scrollHeight" in this.scrollElement) {
1042
- return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;
1043
- } else {
1044
- const doc = this.scrollElement.document.documentElement;
1045
- return this.options.horizontal ? doc.scrollWidth - this.scrollElement.innerWidth : doc.scrollHeight - this.scrollElement.innerHeight;
1119
+ this._noteClampMax = () => {
1120
+ if (!this._awaitingCommandReadBack()) return;
1121
+ const elementMax = this._elementMaxScrollOffset();
1122
+ if (elementMax === null) return;
1123
+ const write = this.pendingWrite;
1124
+ const max = Math.max(elementMax, 0) + this._holdOffset;
1125
+ if (max >= write.target) return;
1126
+ const lowMaxes = write.lowMaxes ?? (write.lowMaxes = []);
1127
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max);
1128
+ };
1129
+ this.getMaxScrollOffset = () => (this._elementMaxScrollOffset() ?? 0) + this._holdOffset;
1130
+ this._toLayoutOffset = (elementOffset) => {
1131
+ var _a;
1132
+ let offset = elementOffset + this._holdOffset;
1133
+ if (((_a = this.pendingScrollAnchor) == null ? void 0 : _a.kind) === "anchor") {
1134
+ offset += this.pendingScrollAnchor.delta;
1046
1135
  }
1136
+ return offset;
1137
+ };
1138
+ this._elementMaxScrollOffset = () => {
1139
+ const el = this.scrollElement;
1140
+ if (el === null) return null;
1141
+ if ("scrollHeight" in el) {
1142
+ return this.options.horizontal ? el.scrollWidth - el.clientWidth : el.scrollHeight - el.clientHeight;
1143
+ }
1144
+ if ("document" in el) {
1145
+ const doc = el.document.documentElement;
1146
+ return this.options.horizontal ? doc.scrollWidth - el.innerWidth : doc.scrollHeight - el.innerHeight;
1147
+ }
1148
+ return null;
1149
+ };
1150
+ this._momentumStop = null;
1151
+ this._stopMomentum = (done) => {
1152
+ const el = this.scrollElement;
1153
+ const win = this.targetWindow;
1154
+ if (el === null || win === null) return;
1155
+ const scroller = "document" in el ? el.document.scrollingElement : el;
1156
+ if (!(scroller == null ? void 0 : scroller.style)) return;
1157
+ if (this._momentumStop) {
1158
+ this._momentumStop.done = done;
1159
+ return;
1160
+ }
1161
+ const { style } = scroller;
1162
+ const property = this.options.horizontal ? "overflow-x" : "overflow-y";
1163
+ const value = style.getPropertyValue(property);
1164
+ const priority = style.getPropertyPriority(property);
1165
+ style.setProperty(property, "hidden", "important");
1166
+ const stop = {
1167
+ // False when the app replaced the hidden value: the fling may not
1168
+ // have stopped.
1169
+ restore: () => {
1170
+ if (style.getPropertyValue(property) !== "hidden" || style.getPropertyPriority(property) !== "important") {
1171
+ return false;
1172
+ }
1173
+ style.setProperty(property, value, priority);
1174
+ return true;
1175
+ },
1176
+ done
1177
+ };
1178
+ this._momentumStop = stop;
1179
+ win.requestAnimationFrame(
1180
+ () => win.requestAnimationFrame(() => {
1181
+ if (this._momentumStop !== stop) return;
1182
+ this._momentumStop = null;
1183
+ if (stop.restore()) stop.done();
1184
+ })
1185
+ );
1186
+ };
1187
+ this._clampedBy = (target) => {
1188
+ const elementMax = this._elementMaxScrollOffset();
1189
+ if (elementMax === null) return null;
1190
+ const maxAtWrite = elementMax + this._holdOffset;
1191
+ return target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1047
1192
  };
1048
1193
  this.getVirtualDistanceFromEnd = () => {
1049
1194
  return Math.max(
1050
- this.getTotalSize() - this.getSize() - this.getScrollOffset(),
1195
+ this._getLayoutTotalSize() - this.getSize() - this.getScrollOffset(),
1051
1196
  0
1052
1197
  );
1053
1198
  };
@@ -1112,10 +1257,7 @@ class Virtualizer {
1112
1257
  } = {}) => {
1113
1258
  index = Math.max(0, Math.min(index, this.options.count - 1));
1114
1259
  const offsetInfo = this.getOffsetForIndex(index, initialAlign);
1115
- if (!offsetInfo) {
1116
- this._iosDeferredAdjustment = 0;
1117
- return;
1118
- }
1260
+ if (!offsetInfo) return;
1119
1261
  const [offset, align] = offsetInfo;
1120
1262
  this._startScroll({ index, align }, offset, behavior, "absolute");
1121
1263
  };
@@ -1152,7 +1294,8 @@ class Virtualizer {
1152
1294
  }
1153
1295
  this.scrollState = null;
1154
1296
  };
1155
- this.getTotalSize = () => {
1297
+ this.getTotalSize = () => Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
1298
+ this._getLayoutTotalSize = () => {
1156
1299
  var _a, _b;
1157
1300
  const measurements = this.getMeasurements();
1158
1301
  let end;
@@ -1204,15 +1347,29 @@ class Virtualizer {
1204
1347
  this._scrollToOffset = (offset, {
1205
1348
  adjustments,
1206
1349
  behavior
1207
- }) => {
1208
- this.pendingWrite = {
1350
+ } = {}) => {
1351
+ const write = {
1209
1352
  target: offset + (adjustments ?? 0),
1210
- smooth: behavior === "smooth",
1211
- adjustments: adjustments ?? this.scrollAdjustments
1353
+ smooth: behavior === "smooth"
1212
1354
  };
1213
- this.options.scrollToFn(offset, { behavior, adjustments }, this);
1355
+ this.pendingWrite = write;
1356
+ this.options.scrollToFn(
1357
+ offset - this._holdOffset,
1358
+ { behavior, adjustments },
1359
+ this
1360
+ );
1361
+ return write;
1214
1362
  };
1215
1363
  this.getCommandWrittenOffset = () => this.scrollState !== null && this.pendingWrite !== null && !this.pendingWrite.smooth ? this.pendingWrite.target : null;
1364
+ this._awaitingCommandReadBack = () => {
1365
+ const writtenOffset = this.getCommandWrittenOffset();
1366
+ return !(iosGesture.isIOSWebKit() && this._iosGesture.dragging()) && writtenOffset !== null && !utils.approxEqual(writtenOffset, this.getScrollOffset());
1367
+ };
1368
+ this._followOffsetTarget = (delta) => {
1369
+ if (this.scrollState !== null && this.scrollState.index == null) {
1370
+ this.scrollState.lastTargetOffset += delta;
1371
+ }
1372
+ };
1216
1373
  this.measure = () => {
1217
1374
  this.pendingMin = null;
1218
1375
  this.itemSizeCache.clear();
@@ -1222,41 +1379,38 @@ class Virtualizer {
1222
1379
  };
1223
1380
  this.setOptions(opts);
1224
1381
  }
1225
- // Size compensation written to the element but not yet reflected in
1226
- // `scrollOffset`: the element is expected at `scrollOffset +
1227
- // scrollAdjustments` until the next scroll event reports it.
1382
+ /**
1383
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
1384
+ * at once, so there is never an outstanding adjustment to add to it. Read
1385
+ * `scrollOffset` alone.
1386
+ */
1228
1387
  get scrollAdjustments() {
1229
- var _a;
1230
- return ((_a = this.pendingWrite) == null ? void 0 : _a.adjustments) ?? 0;
1388
+ return 0;
1231
1389
  }
1232
1390
  // Returns `true` when it performed a synchronous `scrollTop` write this
1233
1391
  // tick, `false` when the delta was zero or the write was deferred (iOS).
1234
1392
  // `resizeItem` uses that to decide whether the follow-up `notify` must be
1235
1393
  // synchronous so the grown transforms commit in the same paint (#1227).
1236
1394
  applyScrollAdjustment(delta, behavior) {
1237
- var _a;
1238
1395
  if (delta === 0) return false;
1239
1396
  if (process.env.NODE_ENV !== "production" && this.options.debug) {
1240
1397
  console.info("correction", delta);
1241
1398
  }
1242
- if (isIOSWebKit() && this._iosInMotion()) {
1243
- if (((_a = this.scrollState) == null ? void 0 : _a.index) == null) {
1244
- this._iosDeferredAdjustment += delta;
1245
- }
1246
- return false;
1399
+ this._followOffsetTarget(delta);
1400
+ if (!this._canWriteScroll()) {
1401
+ this._holdOffset += delta;
1402
+ if (this.scrollOffset !== null) this.scrollOffset += delta;
1403
+ return true;
1247
1404
  } else {
1248
- const target = this.getScrollOffset() + this.scrollAdjustments + delta;
1249
- const el = this.scrollElement;
1250
- const maxAtWrite = el !== null && ("scrollHeight" in el || "document" in el) ? this.getMaxScrollOffset() : null;
1251
- this._clampedAdjustment = maxAtWrite !== null && target > maxAtWrite + 0.5 ? { target, maxAtWrite } : null;
1252
- this._scrollToOffset(this.getScrollOffset(), {
1253
- adjustments: this.scrollAdjustments + delta,
1405
+ const offset = this.getScrollOffset();
1406
+ this._clampedAdjustment = this._clampedBy(offset + delta);
1407
+ const write = this._scrollToOffset(offset, {
1408
+ adjustments: delta,
1254
1409
  behavior
1255
1410
  });
1256
1411
  if (this.scrollOffset !== null) {
1257
- this.scrollOffset += this.scrollAdjustments;
1412
+ if (this.pendingWrite === write) this.scrollOffset += delta;
1258
1413
  if (this.scrollOffset < 0) this.scrollOffset = 0;
1259
- if (this.pendingWrite) this.pendingWrite.adjustments = 0;
1260
1414
  }
1261
1415
  return true;
1262
1416
  }
@@ -1285,6 +1439,10 @@ class Virtualizer {
1285
1439
  this.scrollState = null;
1286
1440
  return;
1287
1441
  }
1442
+ if (this.scrollState.phase === "queued") {
1443
+ this.scheduleScrollReconcile();
1444
+ return;
1445
+ }
1288
1446
  this.getMeasurements();
1289
1447
  const targetOffset = this.getScrollStateTarget(this.scrollState);
1290
1448
  const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
@@ -1298,10 +1456,7 @@ class Virtualizer {
1298
1456
  this.scrollState.stableFrames++;
1299
1457
  if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1300
1458
  if (this.getScrollOffset() !== targetOffset) {
1301
- this._scrollToOffset(targetOffset, {
1302
- adjustments: void 0,
1303
- behavior: "auto"
1304
- });
1459
+ this._scrollToOffset(targetOffset, { behavior: "auto" });
1305
1460
  }
1306
1461
  this.scrollState = null;
1307
1462
  return;
@@ -1321,7 +1476,6 @@ class Virtualizer {
1321
1476
  this.scrollState.phase = "instant";
1322
1477
  }
1323
1478
  this._scrollToOffset(targetOffset, {
1324
- adjustments: void 0,
1325
1479
  behavior: keepSmooth ? "smooth" : "auto"
1326
1480
  });
1327
1481
  }
@@ -1331,31 +1485,58 @@ class Virtualizer {
1331
1485
  // Every scroll command starts here: it becomes the in-flight command,
1332
1486
  // writes its first target and leaves reconcile to retarget and retire it.
1333
1487
  //
1334
- // An absolute command derives its target from current measurements, so
1335
- // any iOS-deferred compensation still pending is stale by definition —
1336
- // the command already accounts for the measurements the delta was
1337
- // compensating for. Drop it so _flushIosDeferredIfReady doesn't replay it
1338
- // onto the just-established position. A relative command (scrollBy)
1339
- // builds on the current offset, so it keeps the deferral.
1488
+ // Targets are layout offsets. A held correction is not dropped by a
1489
+ // command: the write lands the element `_holdOffset` short of the target,
1490
+ // under the rows exposed shifted by the same amount, and the flush moves
1491
+ // both together once a write is possible.
1340
1492
  //
1341
1493
  // An index or end target that is already at its offset starts a smooth
1342
1494
  // scroll as landed; an offset target never does, so its first scroll
1343
1495
  // event is read as the user's (see the scroll handler in `_willUpdate`).
1344
1496
  _startScroll(target, offset, behavior, kind) {
1345
- if (kind === "absolute") {
1346
- this._iosDeferredAdjustment = 0;
1497
+ const tail = this._iosGesture.tail();
1498
+ if (kind === "absolute" && tail !== null) {
1499
+ if (tail === "fling" && iosGesture.iosMomentumOverridesWrites()) {
1500
+ this._stopMomentum(() => {
1501
+ const state = this.scrollState;
1502
+ if ((state == null ? void 0 : state.phase) !== "queued" || // A finger came down: it owns the scroll until it lifts.
1503
+ this._iosGesture.tail() !== "fling" || // In a bounce WebKit can drop the write (#1287): the tail
1504
+ // decides, as without the stop. (Not `flingCaught`: our stop
1505
+ // also ends the fling at speed, so a slow frame would read as
1506
+ // a catch and the tail would drop the command.)
1507
+ this._reportedOverscroll) {
1508
+ return;
1509
+ }
1510
+ this._iosGesture.end();
1511
+ this._flushHoldIfReady(true);
1512
+ this._writeAwaitingCommand();
1513
+ });
1514
+ this.scrollState = {
1515
+ ...target,
1516
+ startedAt: this.now(),
1517
+ lastTargetOffset: offset,
1518
+ stableFrames: 0,
1519
+ phase: "queued",
1520
+ behavior,
1521
+ samples: []
1522
+ };
1523
+ this.scheduleScrollReconcile();
1524
+ return;
1525
+ }
1526
+ this._iosGesture.end();
1347
1527
  }
1348
1528
  this.scrollState = {
1349
1529
  ...target,
1350
1530
  startedAt: this.now(),
1351
1531
  lastTargetOffset: offset,
1352
1532
  stableFrames: 0,
1533
+ behavior,
1353
1534
  phase: initialScrollPhase(
1354
1535
  behavior,
1355
1536
  target.index != null && utils.approxEqual(offset, this.getScrollOffset())
1356
1537
  )
1357
1538
  };
1358
- this._scrollToOffset(offset, { adjustments: void 0, behavior });
1539
+ this._scrollToOffset(offset, { behavior });
1359
1540
  this.scheduleScrollReconcile();
1360
1541
  }
1361
1542
  }
@@ -1439,8 +1620,8 @@ exports.approxEqual = utils.approxEqual;
1439
1620
  exports.debounce = utils.debounce;
1440
1621
  exports.memo = utils.memo;
1441
1622
  exports.notUndefined = utils.notUndefined;
1623
+ exports._resetIOSDetectionForTests = iosGesture._resetIOSDetectionForTests;
1442
1624
  exports.Virtualizer = Virtualizer;
1443
- exports._resetIOSDetectionForTests = _resetIOSDetectionForTests;
1444
1625
  exports.defaultKeyExtractor = defaultKeyExtractor;
1445
1626
  exports.defaultRangeExtractor = defaultRangeExtractor;
1446
1627
  exports.elementScroll = elementScroll;