@tanstack/virtual-core 3.17.8 → 3.17.10

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
@@ -1,4 +1,7 @@
1
- import { createLazyMeasurementsView } from './lazy-measurements'
1
+ import {
2
+ createLazyMeasurementsView,
3
+ getMeasurementKey,
4
+ } from './lazy-measurements'
2
5
  import { approxEqual, debounce, memo, notUndefined } from './utils'
3
6
 
4
7
  // Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
@@ -398,6 +401,36 @@ type PendingScrollAnchor = [
398
401
  anchorDelta: number,
399
402
  ]
400
403
 
404
+ function isAppendWithTrim(
405
+ prevCount: number,
406
+ nextCount: number,
407
+ getPreviousKey: (index: number) => Key,
408
+ getNextKey: (index: number) => Key,
409
+ ): boolean {
410
+ if (nextCount === 0) return false
411
+
412
+ const firstKey = getNextKey(0)
413
+ const removedKeys = new Set<Key>()
414
+ let removedCount = 0
415
+ while (removedCount < prevCount) {
416
+ const key = getPreviousKey(removedCount)
417
+ if (key === firstKey) break
418
+ removedKeys.add(key)
419
+ removedCount++
420
+ }
421
+
422
+ const retainedCount = prevCount - removedCount
423
+ if (retainedCount === 0 || retainedCount >= nextCount) return false
424
+
425
+ for (let i = 0; i < retainedCount; i++) {
426
+ if (getNextKey(i) !== getPreviousKey(removedCount + i)) return false
427
+ }
428
+ for (let i = retainedCount; i < nextCount; i++) {
429
+ if (removedKeys.has(getNextKey(i))) return false
430
+ }
431
+ return true
432
+ }
433
+
401
434
  export class Virtualizer<
402
435
  TScrollElement extends Element | Window,
403
436
  TItemElement extends Element,
@@ -409,9 +442,12 @@ export class Virtualizer<
409
442
  isScrolling = false
410
443
  private scrollState: ScrollState | null = null
411
444
  measurementsCache: Array<VirtualItem> = []
412
- // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].
413
- // null until the first single-lane build; reused (and grown) across rebuilds.
414
- private _flatMeasurements: Float64Array | null = null
445
+ // Keys belong to the layout build, even when VirtualItems are read later.
446
+ // The flat [start, size, ...] buffer is reused across builds.
447
+ private _singleLaneMeasurements: {
448
+ flat: Float64Array
449
+ items: Array<Key | VirtualItem>
450
+ } | null = null
415
451
  itemSizeCache = new Map<Key, number>()
416
452
  private itemSizeCacheVersion = 0
417
453
  private laneAssignments = new Map<number, number>() // index → lane cache
@@ -447,6 +483,16 @@ export class Virtualizer<
447
483
  // value when the diff is < 1.5 px, distinguishing it from a real user
448
484
  // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.
449
485
  private _intendedScrollOffset: number | null = null
486
+ // A compensation write from `applyScrollAdjustment` whose target exceeded
487
+ // the element's scroll max at the moment of the write. The browser clamps
488
+ // such a write because the consumer's sizer has not grown yet: an
489
+ // end-anchored item growing at the bottom only extends `scrollHeight` to
490
+ // its own end, so with `paddingEnd > 0` the clamp lands exactly
491
+ // `paddingEnd` short of the target (#1258). `_willUpdate` re-issues the
492
+ // write once the sizer has caught up; the clamped read-back keeps it
493
+ // pending, any other scroll event (a real gesture) cancels it.
494
+ private _clampedAdjustment: { target: number; maxAtWrite: number } | null =
495
+ null
450
496
  shouldAdjustScrollPositionOnItemSizeChange:
451
497
  | undefined
452
498
  | ((
@@ -581,15 +627,11 @@ export class Virtualizer<
581
627
  const prevCount = prevOptions.count
582
628
  const nextCount = merged.count
583
629
  const measurements = this.getMeasurements()
584
- const prevFirstKey =
585
- prevCount > 0
586
- ? (measurements[0]?.key ?? prevOptions.getItemKey(0))
587
- : null
588
- const prevLastKey =
589
- prevCount > 0
590
- ? (measurements[prevCount - 1]?.key ??
591
- prevOptions.getItemKey(prevCount - 1))
592
- : null
630
+ const previousItems = this._singleLaneMeasurements?.items ?? measurements
631
+ const getPreviousKey = (index: number) =>
632
+ getMeasurementKey(previousItems[index]!)
633
+ const prevFirstKey = prevCount > 0 ? getPreviousKey(0) : null
634
+ const prevLastKey = prevCount > 0 ? getPreviousKey(prevCount - 1) : null
593
635
  const didCountChange = nextCount !== prevCount
594
636
  const didEdgeKeysChange =
595
637
  didCountChange ||
@@ -617,11 +659,21 @@ export class Virtualizer<
617
659
 
618
660
  if (
619
661
  behavior &&
620
- nextCount > prevCount &&
662
+ nextCount > 0 &&
621
663
  this.isAtEnd(prevOptions.scrollEndThreshold) &&
622
664
  (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)
623
665
  ) {
624
- followOnAppend = behavior
666
+ if (
667
+ nextCount > prevCount ||
668
+ isAppendWithTrim(
669
+ prevCount,
670
+ nextCount,
671
+ getPreviousKey,
672
+ merged.getItemKey,
673
+ )
674
+ ) {
675
+ followOnAppend = behavior
676
+ }
625
677
  }
626
678
  }
627
679
  }
@@ -662,7 +714,8 @@ export class Virtualizer<
662
714
  // (rubber-band), and a negative tracked offset never self-heals
663
715
  // when the element cannot scroll (#1229).
664
716
  const newOffset = Math.max(0, anchorItem.start + anchorOffset)
665
- if (newOffset !== this.scrollOffset) {
717
+ // A no-op end scroll emits no event to correct a reading-anchor offset.
718
+ if (!followOnAppend && newOffset !== this.scrollOffset) {
666
719
  anchorDelta = newOffset - this.scrollOffset
667
720
  this.scrollOffset = newOffset
668
721
  anchorResolved = true
@@ -706,6 +759,18 @@ export class Virtualizer<
706
759
  this._iosDeferredAdjustment += delta
707
760
  return false
708
761
  } else {
762
+ const target = this.getScrollOffset() + this.scrollAdjustments + delta
763
+ // Guarded so a bare test double without `scrollHeight` / `document`
764
+ // does not crash in `getMaxScrollOffset`.
765
+ const el = this.scrollElement
766
+ const maxAtWrite =
767
+ el !== null && ('scrollHeight' in el || 'document' in el)
768
+ ? this.getMaxScrollOffset()
769
+ : null
770
+ this._clampedAdjustment =
771
+ maxAtWrite !== null && target > maxAtWrite + 0.5
772
+ ? { target, maxAtWrite }
773
+ : null
709
774
  this._scrollToOffset(this.getScrollOffset(), {
710
775
  adjustments: (this.scrollAdjustments += delta),
711
776
  behavior,
@@ -787,6 +852,7 @@ export class Virtualizer<
787
852
  this._iosDeferredAdjustment = 0
788
853
  this._iosTouching = false
789
854
  this._iosJustTouchEnded = false
855
+ this._clampedAdjustment = null
790
856
  this.scrollElement = null
791
857
  this.targetWindow = null
792
858
  }
@@ -861,6 +927,17 @@ export class Virtualizer<
861
927
  }
862
928
  this._intendedScrollOffset = null
863
929
 
930
+ // A pending clamped compensation write (#1258) survives only its
931
+ // own read-back, which the browser reports at the scroll max we
932
+ // saw at write time. Anything else is a real gesture (or the write
933
+ // landing after all), so drop it rather than yank the user later.
934
+ if (
935
+ this._clampedAdjustment !== null &&
936
+ Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5
937
+ ) {
938
+ this._clampedAdjustment = null
939
+ }
940
+
864
941
  this.scrollAdjustments = 0
865
942
  // If the offset hasn't moved, this is the echo of our own
866
943
  // adjustment write — `applyScrollAdjustment` already folded it
@@ -980,6 +1057,39 @@ export class Virtualizer<
980
1057
  this.scrollToEnd({ behavior: followOnAppend })
981
1058
  }
982
1059
  }
1060
+
1061
+ // The consumer has committed the new total size by now, so a clamped
1062
+ // compensation write may have room (#1258).
1063
+ this._retryClampedAdjustment()
1064
+ }
1065
+
1066
+ // Re-issue a compensation write the browser clamped because the sizer had
1067
+ // not grown yet (#1258, #1266). Called after `notify` in `resizeItem`,
1068
+ // which covers consumers that size the container synchronously inside
1069
+ // `onChange` (direct DOM updates, flushSync renders — where no re-render
1070
+ // may follow at all), and from `_willUpdate` for consumers that size it
1071
+ // during an asynchronous render. Both the clamped read-back and the
1072
+ // absence of one leave `_clampedAdjustment` set, so timing does not matter.
1073
+ private _retryClampedAdjustment = () => {
1074
+ if (
1075
+ this._clampedAdjustment === null ||
1076
+ !this.scrollElement ||
1077
+ !this.options.enabled
1078
+ ) {
1079
+ return
1080
+ }
1081
+ const { target, maxAtWrite } = this._clampedAdjustment
1082
+ const max = this.getMaxScrollOffset()
1083
+ if (max > maxAtWrite + 0.5) {
1084
+ // Still short (the sizer grew only partially): stay pending against
1085
+ // the new max so the next opportunity retries.
1086
+ this._clampedAdjustment =
1087
+ target > max + 0.5 ? { target, maxAtWrite: max } : null
1088
+ this._scrollToOffset(target, {
1089
+ adjustments: undefined,
1090
+ behavior: undefined,
1091
+ })
1092
+ }
983
1093
  }
984
1094
 
985
1095
  // Apply any accumulated iOS-deferred scroll adjustment, but only when we're
@@ -1205,6 +1315,7 @@ export class Virtualizer<
1205
1315
  const itemSizeCache = this.itemSizeCache
1206
1316
  if (!enabled) {
1207
1317
  this.measurementsCache = []
1318
+ this._singleLaneMeasurements = null
1208
1319
  this.itemSizeCache.clear()
1209
1320
  this.laneAssignments.clear()
1210
1321
  return []
@@ -1224,6 +1335,7 @@ export class Virtualizer<
1224
1335
  this.lanesChangedFlag = false // Reset immediately
1225
1336
  this.lanesSettling = true // Start settling period
1226
1337
  this.measurementsCache = []
1338
+ this._singleLaneMeasurements = null
1227
1339
  this.itemSizeCache.clear()
1228
1340
  this.laneAssignments.clear() // Clear lane cache for new lane count
1229
1341
  // Force min = 0 on the rebuild
@@ -1253,21 +1365,22 @@ export class Virtualizer<
1253
1365
  // per-item VirtualItem object allocation. We write start/size pairs
1254
1366
  // into a Float64Array and return a Proxy that builds VirtualItem
1255
1367
  // objects on demand (only the indices a consumer actually reads).
1256
- //
1257
- // At n=100k this drops cold-mount cost from ~2.5ms (eager object
1258
- // allocation) to roughly the cost of a single typed-array fill.
1259
1368
  if (lanes === 1) {
1260
1369
  // Reuse flat backing if large enough; else grow (preserving data
1261
1370
  // before `min` to mirror the slice-and-rebuild contract).
1262
1371
  const need = count * 2
1263
- let flat = this._flatMeasurements
1372
+ let flat = this._singleLaneMeasurements?.flat
1264
1373
  if (!flat || flat.length < need) {
1265
1374
  const next = new Float64Array(need)
1266
1375
  if (flat && min > 0) next.set(flat.subarray(0, min * 2))
1267
1376
  flat = next
1268
- this._flatMeasurements = flat
1269
1377
  }
1270
1378
 
1379
+ const items: Array<Key | VirtualItem> =
1380
+ min === 0
1381
+ ? new Array(count)
1382
+ : this._singleLaneMeasurements!.items.slice()
1383
+
1271
1384
  let runningStart: number
1272
1385
  if (min === 0) {
1273
1386
  runningStart = paddingStart + scrollMargin
@@ -1279,6 +1392,7 @@ export class Virtualizer<
1279
1392
 
1280
1393
  for (let i = min; i < count; i++) {
1281
1394
  const key = getItemKey(i)
1395
+ items[i] = key
1282
1396
  const measuredSize = itemSizeCache.get(key)
1283
1397
  const size =
1284
1398
  typeof measuredSize === 'number'
@@ -1289,7 +1403,8 @@ export class Virtualizer<
1289
1403
  runningStart += size + gap
1290
1404
  }
1291
1405
 
1292
- const view = createLazyMeasurementsView(count, flat, getItemKey)
1406
+ this._singleLaneMeasurements = { flat, items }
1407
+ const view = createLazyMeasurementsView(items, flat)
1293
1408
  this.measurementsCache = view
1294
1409
  return view
1295
1410
  }
@@ -1423,8 +1538,8 @@ export class Virtualizer<
1423
1538
  lanes,
1424
1539
  // Pass the typed array so binary search + forward-walk can read
1425
1540
  // start/end directly from Float64Array, skipping the Proxy traps.
1426
- lanes === 1 && this._flatMeasurements != null
1427
- ? this._flatMeasurements
1541
+ lanes === 1 && this._singleLaneMeasurements !== null
1542
+ ? this._singleLaneMeasurements.flat
1428
1543
  : null,
1429
1544
  )
1430
1545
  return this.range
@@ -1560,8 +1675,8 @@ export class Virtualizer<
1560
1675
  let cachedSize: number
1561
1676
  let itemStart: number
1562
1677
  let key: Key
1563
- const flat = this._flatMeasurements
1564
- if (this.options.lanes === 1 && flat !== null) {
1678
+ const flat = this._singleLaneMeasurements?.flat
1679
+ if (this.options.lanes === 1 && flat != null) {
1565
1680
  key = this.options.getItemKey(index)
1566
1681
  itemStart = flat[index * 2]!
1567
1682
  cachedSize = flat[index * 2 + 1]!
@@ -1646,6 +1761,11 @@ export class Virtualizer<
1646
1761
  // land in one paint. When nothing moved (or the write was deferred on
1647
1762
  // iOS), keep the cheaper async notify.
1648
1763
  this.notify(adjustedSync)
1764
+ // A consumer that grows the sizer synchronously inside `onChange`
1765
+ // (direct DOM updates) may never re-render when the range is
1766
+ // unchanged, so retry a clamped write here rather than only in
1767
+ // `_willUpdate` (#1266).
1768
+ this._retryClampedAdjustment()
1649
1769
  }
1650
1770
  }
1651
1771
 
@@ -1677,7 +1797,7 @@ export class Virtualizer<
1677
1797
  // Same fast-path as calculateRange: read start values directly from the
1678
1798
  // typed array during binary search to skip the Proxy.get materialization
1679
1799
  // per probe.
1680
- const flat = this._flatMeasurements
1800
+ const flat = this._singleLaneMeasurements?.flat
1681
1801
  const useFlat = this.options.lanes === 1 && flat != null
1682
1802
  const idx = findNearestBinarySearch(
1683
1803
  0,
@@ -1897,7 +2017,7 @@ export class Virtualizer<
1897
2017
  // when available; avoids a Proxy.get + VirtualItem materialization
1898
2018
  // just to call getTotalSize (which React renders trigger every commit).
1899
2019
  const lastIdx = measurements.length - 1
1900
- const flat = this._flatMeasurements
2020
+ const flat = this._singleLaneMeasurements?.flat
1901
2021
  if (flat != null) {
1902
2022
  end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!
1903
2023
  } else {
@@ -1,19 +1,22 @@
1
1
  // Lazy materialization for the lanes===1 fast path. Backed by a
2
2
  // Float64Array (stride 2: start, size, …); VirtualItems are constructed on
3
- // first indexed read and cached. Saves the per-item object allocation at
4
- // large list counts where most items are never visible.
3
+ // first indexed read, replacing the stored key. Saves the per-item object
4
+ // allocation at large list counts where most items are never visible.
5
5
 
6
6
  import type { VirtualItem } from './index'
7
7
 
8
- type Key = number | string | bigint
8
+ export function getMeasurementKey(
9
+ item: VirtualItem | VirtualItem['key'],
10
+ ): VirtualItem['key'] {
11
+ return typeof item === 'object' ? item.key : item
12
+ }
9
13
 
10
14
  export function createLazyMeasurementsView(
11
- count: number,
15
+ cache: Array<VirtualItem | VirtualItem['key']>,
12
16
  flat: Float64Array,
13
- getItemKey: (i: number) => Key,
14
17
  ): Array<VirtualItem> {
15
- const cache: Array<VirtualItem | undefined> = new Array(count)
16
- return new Proxy(cache as any, {
18
+ const count = cache.length
19
+ return new Proxy(cache, {
17
20
  get(target, prop, receiver) {
18
21
  if (typeof prop === 'string') {
19
22
  // Cheap digit-prefix sniff before number coerce.
@@ -21,12 +24,12 @@ export function createLazyMeasurementsView(
21
24
  if (c >= 48 && c <= 57) {
22
25
  const i = +prop
23
26
  if (Number.isInteger(i) && i >= 0 && i < count) {
24
- let v = target[i]
25
- if (!v) {
27
+ let v = target[i]!
28
+ if (typeof v !== 'object') {
26
29
  const s = flat[i * 2]!
27
30
  v = target[i] = {
28
31
  index: i,
29
- key: getItemKey(i),
32
+ key: v,
30
33
  start: s,
31
34
  size: flat[i * 2 + 1]!,
32
35
  end: s + flat[i * 2 + 1]!,