@tanstack/virtual-core 3.18.0 → 3.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -56,6 +56,11 @@ export interface Range {
56
56
  endIndex: number
57
57
  overscan: number
58
58
  count: number
59
+ /**
60
+ * Lane count of the virtualizer. When greater than 1, `overscan` counts
61
+ * rows of `lanes` items rather than single items.
62
+ */
63
+ lanes?: number
59
64
  }
60
65
 
61
66
  type Key = number | string | bigint
@@ -84,8 +89,13 @@ const getRect = (element: HTMLElement): Rect => {
84
89
  export const defaultKeyExtractor = (index: number) => index
85
90
 
86
91
  export const defaultRangeExtractor = (range: Range) => {
87
- const start = Math.max(range.startIndex - range.overscan, 0)
88
- const end = Math.min(range.endIndex + range.overscan, range.count - 1)
92
+ // With lanes, the visible range is already aligned to whole rows; overscan
93
+ // by whole rows too, so every lane gets the same number of items rendered
94
+ // (and measured). Overscanning single items leaves partial rows, letting one
95
+ // lane collect more measured sizes than the others and drift (#1036).
96
+ const overscan = range.overscan * Math.max(range.lanes ?? 1, 1)
97
+ const start = Math.max(range.startIndex - overscan, 0)
98
+ const end = Math.min(range.endIndex + overscan, range.count - 1)
89
99
  const len = end - start + 1
90
100
 
91
101
  const arr = new Array<number>(len)
@@ -396,6 +406,18 @@ type ScrollState = {
396
406
  stableFrames: number
397
407
  // Keep arrival across measurement-driven retargets so external scrolls can cancel.
398
408
  hasReachedTarget: boolean
409
+ // The command asked for a smooth scroll. Unlike `behavior`, which reconcile
410
+ // switches to 'auto' for the final approach, this stays set: the smooth
411
+ // animation can still deliver scroll events after that switch.
412
+ startedSmooth: boolean
413
+
414
+ // Where our last non-smooth write for this command put the element, until
415
+ // its scroll event arrives. Until then `scrollOffset` still holds the old
416
+ // position, and the rows on screen are the ones rendered for it. A smooth
417
+ // write leaves it null: the element is somewhere between the two offsets.
418
+ // It goes with the scroll state, so a write the browser ignored (no read-back)
419
+ // does not outlive its command.
420
+ writtenOffset?: number | null
399
421
  }
400
422
 
401
423
  type PendingScrollAnchor = [
@@ -505,6 +527,9 @@ export class Virtualizer<
505
527
  instance: Virtualizer<TScrollElement, TItemElement>,
506
528
  ) => boolean)
507
529
  elementsCache = new Map<Key, TItemElement>()
530
+ // Set while a ResizeObserver callback measures its entries; `resizeItem`
531
+ // records the pending notify here instead of firing it per entry.
532
+ private _resizeBatch: { sync: boolean; notify?: boolean } | null = null
508
533
  private now = () => this.targetWindow?.performance?.now?.() ?? Date.now()
509
534
  private observer = (() => {
510
535
  let _ro: ResizeObserver | null = null
@@ -519,46 +544,60 @@ export class Virtualizer<
519
544
  }
520
545
 
521
546
  return (_ro = new this.targetWindow.ResizeObserver((entries) => {
522
- entries.forEach((entry) => {
523
- const run = () => {
524
- const node = entry.target as TItemElement
525
- const index = this.indexFromElement(node)
526
-
527
- if (!node.isConnected) {
528
- this.observer.unobserve(node)
529
- // Find the cache entry pointing to this exact node and remove
530
- // it. We can't call getItemKey(index) here because items may
531
- // have been removed since this node was rendered — the index
532
- // could be stale and out-of-bounds in the user's data array
533
- // (regression test in e2e/.../stale-index.spec.ts, fix #1148).
534
- // The === comparison naturally handles the React-replaced-
535
- // a-node-for-the-same-key case: that entry now points to a
536
- // different node, so this loop won't match.
537
- for (const [cacheKey, cachedNode] of this.elementsCache) {
538
- if (cachedNode === node) {
539
- this.elementsCache.delete(cacheKey)
540
- break
541
- }
542
- }
543
- return
544
- }
545
-
546
- if (!this.isIndexInRange(index)) return
547
-
548
- if (this.shouldMeasureDuringScroll(index)) {
549
- this.resizeItem(
550
- index,
551
- this.options.measureElement(node, entry, this),
552
- )
547
+ const run = () => {
548
+ // Measure every entry before notifying. A notify that adjusted
549
+ // scroll re-renders synchronously, and that render can unmount
550
+ // nodes whose entries are still queued here, leaving them
551
+ // unmeasured. With lanes, a half-measured row lets one lane drift
552
+ // away from the others (#1036).
553
+ const batch: { sync: boolean; notify?: boolean } = { sync: false }
554
+ this._resizeBatch = batch
555
+ try {
556
+ entries.forEach(measureEntry)
557
+ } finally {
558
+ this._resizeBatch = null
559
+ if (batch.notify) {
560
+ this.notify(batch.sync)
561
+ this._retryClampedAdjustment()
553
562
  }
554
563
  }
555
- this.options.useAnimationFrameWithResizeObserver
556
- ? requestAnimationFrame(run)
557
- : run()
558
- })
564
+ }
565
+ this.options.useAnimationFrameWithResizeObserver
566
+ ? requestAnimationFrame(run)
567
+ : run()
559
568
  }))
560
569
  }
561
570
 
571
+ const measureEntry = (entry: ResizeObserverEntry) => {
572
+ const node = entry.target as TItemElement
573
+ const index = this.indexFromElement(node)
574
+
575
+ if (!node.isConnected) {
576
+ this.observer.unobserve(node)
577
+ // Find the cache entry pointing to this exact node and remove
578
+ // it. We can't call getItemKey(index) here because items may
579
+ // have been removed since this node was rendered — the index
580
+ // could be stale and out-of-bounds in the user's data array
581
+ // (regression test in e2e/.../stale-index.spec.ts, fix #1148).
582
+ // The === comparison naturally handles the React-replaced-
583
+ // a-node-for-the-same-key case: that entry now points to a
584
+ // different node, so this loop won't match.
585
+ for (const [cacheKey, cachedNode] of this.elementsCache) {
586
+ if (cachedNode === node) {
587
+ this.elementsCache.delete(cacheKey)
588
+ break
589
+ }
590
+ }
591
+ return
592
+ }
593
+
594
+ if (!this.isIndexInRange(index)) return
595
+
596
+ if (this.shouldMeasureDuringScroll(index)) {
597
+ this.resizeItem(index, this.options.measureElement(node, entry, this))
598
+ }
599
+ }
600
+
562
601
  return {
563
602
  disconnect: () => {
564
603
  get()?.disconnect()
@@ -760,7 +799,11 @@ export class Virtualizer<
760
799
  isIOSWebKit() &&
761
800
  (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
762
801
  ) {
763
- this._iosDeferredAdjustment += delta
802
+ // An index scroll retargets from fresh measurements in reconcileScroll;
803
+ // replaying this delta after it lands would count it twice.
804
+ if (this.scrollState?.index == null) {
805
+ this._iosDeferredAdjustment += delta
806
+ }
764
807
  return false
765
808
  } else {
766
809
  const target = this.getScrollOffset() + this.scrollAdjustments + delta
@@ -930,18 +973,33 @@ export class Virtualizer<
930
973
  offset = this._intendedScrollOffset
931
974
  } else if (
932
975
  this.scrollState?.index != null &&
933
- this.scrollState.hasReachedTarget &&
976
+ // A non-smooth write lands at once, so any other scroll event is
977
+ // the user's, even before reconcile saw the target reached (the
978
+ // target may keep moving, or iOS ignored the write under a
979
+ // finger). A write the browser clamped because the sizer hasn't
980
+ // grown yet reads back at the max, which is also where the fresh
981
+ // target clamps, so the check below keeps it reconciling (#1294).
982
+ // Not when rows above the target shrink before the read-back and
983
+ // pull the target below the new max: the read-back then looks
984
+ // like the user and the scroll stops at the max. That needs the
985
+ // sizer re-rendered before the scroll event, which browsers have
986
+ // not been seen to do (pinned by a `.fails` test).
987
+ // A smooth scroll's own animation events look like a user's, so
988
+ // it only yields once it has reached the target.
989
+ (this.scrollState.hasReachedTarget ||
990
+ !this.scrollState.startedSmooth) &&
934
991
  !approxEqual(offset, this.scrollState.lastTargetOffset) &&
935
992
  !approxEqual(offset, this.getScrollStateTarget(this.scrollState)) &&
936
993
  (this._clampedAdjustment === null ||
937
994
  Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5)
938
995
  ) {
939
- // The index scroll reached its target, but an external scroll moved
940
- // away while we waited for measurements. Our own measurement updates
941
- // (including clamped writes) still need to reconcile.
996
+ // An external scroll moved away from the index scroll's target.
997
+ // Our own measurement updates (including clamped writes) still
998
+ // need to reconcile.
942
999
  this.scrollState = null
943
1000
  }
944
1001
  this._intendedScrollOffset = null
1002
+ if (this.scrollState) this.scrollState.writtenOffset = null
945
1003
 
946
1004
  // A pending clamped compensation write (#1258) survives only its
947
1005
  // own read-back, which the browser reports at the scroll max we
@@ -1192,6 +1250,10 @@ export class Virtualizer<
1192
1250
  return
1193
1251
  }
1194
1252
 
1253
+ // A resize since the last render leaves measurementsCache stale until
1254
+ // something reads getMeasurements(); rebuild it (memoized) so an index
1255
+ // target reflects it even when no render ran in between.
1256
+ this.getMeasurements()
1195
1257
  const targetOffset = this.getScrollStateTarget(this.scrollState)
1196
1258
 
1197
1259
  // Index targets can still depend on cached sizes during the first rAF,
@@ -1610,9 +1672,10 @@ export class Virtualizer<
1610
1672
  this.options.count,
1611
1673
  startIndex,
1612
1674
  endIndex,
1675
+ this.options.lanes,
1613
1676
  ]
1614
1677
  },
1615
- (rangeExtractor, overscan, count, startIndex, endIndex) => {
1678
+ (rangeExtractor, overscan, count, startIndex, endIndex, lanes) => {
1616
1679
  return startIndex === null || endIndex === null
1617
1680
  ? []
1618
1681
  : rangeExtractor({
@@ -1620,6 +1683,7 @@ export class Virtualizer<
1620
1683
  endIndex,
1621
1684
  overscan,
1622
1685
  count,
1686
+ lanes,
1623
1687
  })
1624
1688
  },
1625
1689
  {
@@ -1718,6 +1782,14 @@ export class Virtualizer<
1718
1782
  resizeItem = (index: number, size: number) => {
1719
1783
  if (!this.isIndexInRange(index)) return
1720
1784
 
1785
+ // An earlier entry in this ResizeObserver batch moved `scrollOffset`.
1786
+ // Outside a batch its sync notify would have re-rendered and rebuilt the
1787
+ // caches read below; rebuild them here so the anchoring check compares
1788
+ // this item's current start, not a stale one, against the adjusted
1789
+ // offset (#1218). Without a scroll move, the caches are exactly as stale
1790
+ // as they were before batching, so skip the rebuild.
1791
+ if (this._resizeBatch?.sync) this.getMeasurements()
1792
+
1721
1793
  // Fast field reads. For lanes===1 we read raw start/size from the flat
1722
1794
  // typed array, avoiding a Proxy.get + VirtualItem allocation per call.
1723
1795
  // For lanes>1 we fall back to the cached VirtualItem array.
@@ -1790,13 +1862,33 @@ export class Virtualizer<
1790
1862
  this.itemSizeCache.set(key, size)
1791
1863
  this.itemSizeCacheVersion++
1792
1864
 
1793
- let adjustedSync = false
1794
- if (wasAtEnd) {
1795
- adjustedSync = this.applyScrollAdjustment(
1796
- this.getTotalSize() - prevTotalSize,
1865
+ // A scroll command (or reconcile) wrote a new position that neither a
1866
+ // scroll event nor an eager update has reflected in `scrollOffset` yet.
1867
+ // The rows being measured were rendered for the old position, so
1868
+ // "above the viewport" means nothing against either offset. An index
1869
+ // or end target is retargeted from fresh measurements by
1870
+ // reconcileScroll next frame; an offset target (scrollToOffset,
1871
+ // scrollBy) lands where it was written and the delta is not applied,
1872
+ // since compensating against the stale offset would overwrite the
1873
+ // command. Compensation writes and the prepend anchor sync update
1874
+ // `scrollOffset` eagerly, and the iOS flush writes exactly
1875
+ // `scrollOffset + scrollAdjustments`, so none of them count.
1876
+ const awaitingCommandReadBack =
1877
+ this.scrollState?.writtenOffset != null &&
1878
+ !approxEqual(
1879
+ this.scrollState.writtenOffset,
1880
+ this.getScrollOffset() + this.scrollAdjustments,
1797
1881
  )
1798
- } else if (shouldAdjustScroll) {
1799
- adjustedSync = this.applyScrollAdjustment(delta)
1882
+
1883
+ let adjustedSync = false
1884
+ if (!awaitingCommandReadBack) {
1885
+ if (wasAtEnd) {
1886
+ adjustedSync = this.applyScrollAdjustment(
1887
+ this.getTotalSize() - prevTotalSize,
1888
+ )
1889
+ } else if (shouldAdjustScroll) {
1890
+ adjustedSync = this.applyScrollAdjustment(delta)
1891
+ }
1800
1892
  }
1801
1893
 
1802
1894
  // When we just moved `scrollTop` to compensate for an above-viewport
@@ -1809,6 +1901,13 @@ export class Virtualizer<
1809
1901
  // synchronous notify flushes the render in this same callback, so both
1810
1902
  // land in one paint. When nothing moved (or the write was deferred on
1811
1903
  // iOS), keep the cheaper async notify.
1904
+ if (this._resizeBatch) {
1905
+ // Inside a ResizeObserver callback: notify once after every entry
1906
+ // is measured, synchronously if any of them moved `scrollTop`.
1907
+ this._resizeBatch.notify = true
1908
+ this._resizeBatch.sync ||= adjustedSync
1909
+ return
1910
+ }
1812
1911
  this.notify(adjustedSync)
1813
1912
  // A consumer that grows the sizer synchronously inside `onChange`
1814
1913
  // (direct DOM updates) may never re-render when the range is
@@ -1982,6 +2081,7 @@ export class Virtualizer<
1982
2081
  lastTargetOffset: offset,
1983
2082
  stableFrames: 0,
1984
2083
  hasReachedTarget: false,
2084
+ startedSmooth: behavior === 'smooth',
1985
2085
  }
1986
2086
 
1987
2087
  this._scrollToOffset(offset, { adjustments: undefined, behavior })
@@ -2017,6 +2117,7 @@ export class Virtualizer<
2017
2117
  lastTargetOffset: offset,
2018
2118
  stableFrames: 0,
2019
2119
  hasReachedTarget: approxEqual(offset, this.getScrollOffset()),
2120
+ startedSmooth: behavior === 'smooth',
2020
2121
  }
2021
2122
 
2022
2123
  this._scrollToOffset(offset, { adjustments: undefined, behavior })
@@ -2028,7 +2129,13 @@ export class Virtualizer<
2028
2129
  delta: number,
2029
2130
  { behavior = 'auto' }: ScrollToOffsetOptions = {},
2030
2131
  ) => {
2031
- const offset = this.getScrollOffset() + delta
2132
+ // Build on a position we just wrote even before its scroll event arrives.
2133
+ // Clamp: a write past either edge that leaves the element where it was
2134
+ // fires no scroll event, so nothing would clear an unreachable offset.
2135
+ const offset = this.getOffsetForAlignment(
2136
+ (this.scrollState?.writtenOffset ?? this.getScrollOffset()) + delta,
2137
+ 'start',
2138
+ )
2032
2139
  const now = this.now()
2033
2140
 
2034
2141
  this.scrollState = {
@@ -2039,6 +2146,7 @@ export class Virtualizer<
2039
2146
  lastTargetOffset: offset,
2040
2147
  stableFrames: 0,
2041
2148
  hasReachedTarget: false,
2149
+ startedSmooth: behavior === 'smooth',
2042
2150
  }
2043
2151
 
2044
2152
  this._scrollToOffset(offset, { adjustments: undefined, behavior })
@@ -2063,6 +2171,7 @@ export class Virtualizer<
2063
2171
  lastTargetOffset: offset,
2064
2172
  stableFrames: 0,
2065
2173
  hasReachedTarget: approxEqual(offset, this.getScrollOffset()),
2174
+ startedSmooth: behavior === 'smooth',
2066
2175
  }
2067
2176
 
2068
2177
  this._scrollToOffset(offset, { adjustments: undefined, behavior })
@@ -2175,6 +2284,10 @@ export class Virtualizer<
2175
2284
  // Record the intended logical scroll target so the next scroll event
2176
2285
  // can reconcile against subpixel rounding by the browser.
2177
2286
  this._intendedScrollOffset = offset + (adjustments ?? 0)
2287
+ if (this.scrollState) {
2288
+ this.scrollState.writtenOffset =
2289
+ behavior === 'smooth' ? null : this._intendedScrollOffset
2290
+ }
2178
2291
  this.options.scrollToFn(offset, { behavior, adjustments }, this)
2179
2292
  }
2180
2293