@tanstack/virtual-core 3.17.9 → 3.17.11

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
@@ -196,7 +199,7 @@ const observeOffset = <T extends Element | Window>(
196
199
  ? null
197
200
  : debounce(
198
201
  targetWindow,
199
- () => cb(offset, false),
202
+ () => cb(readOffset(element), false),
200
203
  instance.options.isScrollingResetDelay,
201
204
  )
202
205
 
@@ -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
@@ -591,15 +627,11 @@ export class Virtualizer<
591
627
  const prevCount = prevOptions.count
592
628
  const nextCount = merged.count
593
629
  const measurements = this.getMeasurements()
594
- const prevFirstKey =
595
- prevCount > 0
596
- ? (measurements[0]?.key ?? prevOptions.getItemKey(0))
597
- : null
598
- const prevLastKey =
599
- prevCount > 0
600
- ? (measurements[prevCount - 1]?.key ??
601
- prevOptions.getItemKey(prevCount - 1))
602
- : 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
603
635
  const didCountChange = nextCount !== prevCount
604
636
  const didEdgeKeysChange =
605
637
  didCountChange ||
@@ -627,11 +659,21 @@ export class Virtualizer<
627
659
 
628
660
  if (
629
661
  behavior &&
630
- nextCount > prevCount &&
662
+ nextCount > 0 &&
631
663
  this.isAtEnd(prevOptions.scrollEndThreshold) &&
632
664
  (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)
633
665
  ) {
634
- followOnAppend = behavior
666
+ if (
667
+ nextCount > prevCount ||
668
+ isAppendWithTrim(
669
+ prevCount,
670
+ nextCount,
671
+ getPreviousKey,
672
+ merged.getItemKey,
673
+ )
674
+ ) {
675
+ followOnAppend = behavior
676
+ }
635
677
  }
636
678
  }
637
679
  }
@@ -672,7 +714,8 @@ export class Virtualizer<
672
714
  // (rubber-band), and a negative tracked offset never self-heals
673
715
  // when the element cannot scroll (#1229).
674
716
  const newOffset = Math.max(0, anchorItem.start + anchorOffset)
675
- 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) {
676
719
  anchorDelta = newOffset - this.scrollOffset
677
720
  this.scrollOffset = newOffset
678
721
  anchorResolved = true
@@ -1002,6 +1045,21 @@ export class Virtualizer<
1002
1045
  if (anchorDelta !== 0) {
1003
1046
  this._iosDeferredAdjustment += anchorDelta
1004
1047
  }
1048
+ } else if (
1049
+ this.scrollState?.behavior === 'smooth' &&
1050
+ !approxEqual(
1051
+ this.getScrollOffset() - anchorDelta,
1052
+ this.scrollState.lastTargetOffset,
1053
+ )
1054
+ ) {
1055
+ // A smooth programmatic scroll is still travelling. Writing scrollTop
1056
+ // here would cancel the browser's animation, and Chromium drops a
1057
+ // smooth request re-issued in the frame right after that cancel, so
1058
+ // the journey would be stranded. The target is index-based and
1059
+ // recomputes against the new layout in reconcileScroll, so let the
1060
+ // animation run; the next scroll event re-syncs the tracked offset.
1061
+ // A smooth scroll that has already landed (offset at its target,
1062
+ // reconcile not yet retired it) still gets the anchor sync.
1005
1063
  } else {
1006
1064
  this._scrollToOffset(this.getScrollOffset(), {
1007
1065
  adjustments: undefined,
@@ -1272,6 +1330,7 @@ export class Virtualizer<
1272
1330
  const itemSizeCache = this.itemSizeCache
1273
1331
  if (!enabled) {
1274
1332
  this.measurementsCache = []
1333
+ this._singleLaneMeasurements = null
1275
1334
  this.itemSizeCache.clear()
1276
1335
  this.laneAssignments.clear()
1277
1336
  return []
@@ -1291,6 +1350,7 @@ export class Virtualizer<
1291
1350
  this.lanesChangedFlag = false // Reset immediately
1292
1351
  this.lanesSettling = true // Start settling period
1293
1352
  this.measurementsCache = []
1353
+ this._singleLaneMeasurements = null
1294
1354
  this.itemSizeCache.clear()
1295
1355
  this.laneAssignments.clear() // Clear lane cache for new lane count
1296
1356
  // Force min = 0 on the rebuild
@@ -1320,21 +1380,22 @@ export class Virtualizer<
1320
1380
  // per-item VirtualItem object allocation. We write start/size pairs
1321
1381
  // into a Float64Array and return a Proxy that builds VirtualItem
1322
1382
  // objects on demand (only the indices a consumer actually reads).
1323
- //
1324
- // At n=100k this drops cold-mount cost from ~2.5ms (eager object
1325
- // allocation) to roughly the cost of a single typed-array fill.
1326
1383
  if (lanes === 1) {
1327
1384
  // Reuse flat backing if large enough; else grow (preserving data
1328
1385
  // before `min` to mirror the slice-and-rebuild contract).
1329
1386
  const need = count * 2
1330
- let flat = this._flatMeasurements
1387
+ let flat = this._singleLaneMeasurements?.flat
1331
1388
  if (!flat || flat.length < need) {
1332
1389
  const next = new Float64Array(need)
1333
1390
  if (flat && min > 0) next.set(flat.subarray(0, min * 2))
1334
1391
  flat = next
1335
- this._flatMeasurements = flat
1336
1392
  }
1337
1393
 
1394
+ const items: Array<Key | VirtualItem> =
1395
+ min === 0
1396
+ ? new Array(count)
1397
+ : this._singleLaneMeasurements!.items.slice()
1398
+
1338
1399
  let runningStart: number
1339
1400
  if (min === 0) {
1340
1401
  runningStart = paddingStart + scrollMargin
@@ -1346,6 +1407,7 @@ export class Virtualizer<
1346
1407
 
1347
1408
  for (let i = min; i < count; i++) {
1348
1409
  const key = getItemKey(i)
1410
+ items[i] = key
1349
1411
  const measuredSize = itemSizeCache.get(key)
1350
1412
  const size =
1351
1413
  typeof measuredSize === 'number'
@@ -1356,7 +1418,8 @@ export class Virtualizer<
1356
1418
  runningStart += size + gap
1357
1419
  }
1358
1420
 
1359
- const view = createLazyMeasurementsView(count, flat, getItemKey)
1421
+ this._singleLaneMeasurements = { flat, items }
1422
+ const view = createLazyMeasurementsView(items, flat)
1360
1423
  this.measurementsCache = view
1361
1424
  return view
1362
1425
  }
@@ -1490,8 +1553,8 @@ export class Virtualizer<
1490
1553
  lanes,
1491
1554
  // Pass the typed array so binary search + forward-walk can read
1492
1555
  // start/end directly from Float64Array, skipping the Proxy traps.
1493
- lanes === 1 && this._flatMeasurements != null
1494
- ? this._flatMeasurements
1556
+ lanes === 1 && this._singleLaneMeasurements !== null
1557
+ ? this._singleLaneMeasurements.flat
1495
1558
  : null,
1496
1559
  )
1497
1560
  return this.range
@@ -1627,8 +1690,8 @@ export class Virtualizer<
1627
1690
  let cachedSize: number
1628
1691
  let itemStart: number
1629
1692
  let key: Key
1630
- const flat = this._flatMeasurements
1631
- if (this.options.lanes === 1 && flat !== null) {
1693
+ const flat = this._singleLaneMeasurements?.flat
1694
+ if (this.options.lanes === 1 && flat != null) {
1632
1695
  key = this.options.getItemKey(index)
1633
1696
  itemStart = flat[index * 2]!
1634
1697
  cachedSize = flat[index * 2 + 1]!
@@ -1749,7 +1812,7 @@ export class Virtualizer<
1749
1812
  // Same fast-path as calculateRange: read start values directly from the
1750
1813
  // typed array during binary search to skip the Proxy.get materialization
1751
1814
  // per probe.
1752
- const flat = this._flatMeasurements
1815
+ const flat = this._singleLaneMeasurements?.flat
1753
1816
  const useFlat = this.options.lanes === 1 && flat != null
1754
1817
  const idx = findNearestBinarySearch(
1755
1818
  0,
@@ -1969,7 +2032,7 @@ export class Virtualizer<
1969
2032
  // when available; avoids a Proxy.get + VirtualItem materialization
1970
2033
  // just to call getTotalSize (which React renders trigger every commit).
1971
2034
  const lastIdx = measurements.length - 1
1972
- const flat = this._flatMeasurements
2035
+ const flat = this._singleLaneMeasurements?.flat
1973
2036
  if (flat != null) {
1974
2037
  end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!
1975
2038
  } 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]!,