@tanstack/virtual-core 3.19.4 → 3.19.6

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.
@@ -0,0 +1,229 @@
1
+ // Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
2
+ // during a momentum-scroll cancel the momentum on iOS WebKit, so we defer
3
+ // scroll-position adjustments triggered by mid-scroll resizes until the
4
+ // scroll settles. SSR-safe (returns false when navigator is unavailable).
5
+ let _isIOSResult: boolean | undefined
6
+ export const isIOSWebKit = (): boolean => {
7
+ if (_isIOSResult !== undefined) return _isIOSResult
8
+ if (typeof navigator === 'undefined') return (_isIOSResult = false)
9
+ if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)
10
+ // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.
11
+ const mtp = (navigator as Navigator & { maxTouchPoints?: number })
12
+ .maxTouchPoints
13
+ return (_isIOSResult =
14
+ navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)
15
+ }
16
+
17
+ // iOS 27 changed what a scrollTop write does to a fling: it no longer stops
18
+ // the momentum, the fling carries on along its own path and the write shows
19
+ // for one frame (measured on the 27.0 simulator in #1307, device check still
20
+ // open). WebKit shipped `overflow-anchor` in the same release, so that is
21
+ // the feature check; iOS 26 and earlier report false. Cached like the iOS
22
+ // check; SSR-safe.
23
+ let _iosMomentumOverridesWritesResult: boolean | undefined
24
+ export const iosMomentumOverridesWrites = (): boolean => {
25
+ if (_iosMomentumOverridesWritesResult !== undefined) {
26
+ return _iosMomentumOverridesWritesResult
27
+ }
28
+ return (_iosMomentumOverridesWritesResult =
29
+ isIOSWebKit() &&
30
+ typeof CSS !== 'undefined' &&
31
+ typeof CSS.supports === 'function' &&
32
+ CSS.supports('overflow-anchor: auto'))
33
+ }
34
+
35
+ // Test hook: reset the iOS detection caches. Not exported.
36
+ export const _resetIOSDetectionForTests = () => {
37
+ _isIOSResult = undefined
38
+ _iosMomentumOverridesWritesResult = undefined
39
+ }
40
+
41
+ // Touch listeners on the scroll element run in the capture phase, so a row
42
+ // that stops a touch event's propagation cannot hide the gesture from the
43
+ // iOS deferral.
44
+ const touchListenerOptions = {
45
+ capture: true,
46
+ passive: true,
47
+ }
48
+
49
+ // The touch gesture in progress. iOS WebKit ignores a scrollTop write while
50
+ // a finger drags the content (one resting on it does not stop the write)
51
+ // and cancels momentum on one after it, so adjustments are deferred through
52
+ // the whole gesture: `down` from touchstart to touchend/touchcancel, then
53
+ // `tail` while momentum runs. iOS fires no touch events during momentum, so
54
+ // every scroll event re-arms the tail and it closes ~150ms after the last
55
+ // one. Null between gestures, and after touchend on non-iOS, which arms no
56
+ // tail. The tail record owns its timer: every replacement of the state goes
57
+ // through `end`, which clears it, so a live timer always has its record.
58
+ //
59
+ // `moved`: the content moved under or after the finger other than by our
60
+ // own write's read-back. While `down`, a scroll event that changed the
61
+ // position sets it: the finger is dragging. The tail inherits it from the
62
+ // drag, and any other scroll event re-arming the tail sets it: a fling can
63
+ // be running. A tap's tail has it unset.
64
+ //
65
+ // `awaitingFling`: the tail follows a drag whose fling has not reported
66
+ // yet. The first frame of a fling can come 150–250ms after touchend when
67
+ // the main thread is busy (27.0 simulator, #1307); if the tail closes
68
+ // first, `lateFling` waits until `until` for that frame to reopen it. It
69
+ // defers nothing: other scroll events with no touch before them must not
70
+ // defer corrections (#1250).
71
+ type IosTouch =
72
+ | { phase: 'down'; moved: boolean }
73
+ | { phase: 'tail'; moved: boolean; awaitingFling: boolean; timerId: number }
74
+ | { phase: 'lateFling'; until: number }
75
+ | null
76
+
77
+ type TimerWindow = Pick<Window, 'setTimeout' | 'clearTimeout'>
78
+
79
+ export class IosGesture {
80
+ private _touch: IosTouch = null
81
+
82
+ constructor(
83
+ private readonly host: {
84
+ // The scroll element's window, which runs the tail timer; null when
85
+ // there is no element.
86
+ getWindow: () => TimerWindow | null
87
+ now: () => number
88
+ // Asked when the tail's timer fires: true keeps it open another
89
+ // 150ms (the fling still moves between scroll events).
90
+ tailStillMoving: () => boolean
91
+ // The tail closed on its own: a write is possible again.
92
+ onTailClosed: () => void
93
+ },
94
+ ) {}
95
+
96
+ get touch(): IosTouch {
97
+ return this._touch
98
+ }
99
+
100
+ // A touch gesture owns the scroll: on iOS a write now would be ignored or
101
+ // would cancel the momentum, so adjustments wait for the tail to close.
102
+ // `isScrolling` is not part of it: any scroll event sets it, including
103
+ // the read-back of our own write, and a programmatic scroll has no
104
+ // momentum to protect (#1250).
105
+ inMotion = () => this._touch !== null && this._touch.phase !== 'lateFling'
106
+
107
+ // A finger is dragging the content, so iOS ignores our writes and no
108
+ // read-back will come. A resting finger does not: the write lands.
109
+ dragging = () => this._touch?.phase === 'down' && this._touch.moved
110
+
111
+ // The open tail, if any: after a tap, or after a drag or fling. On iOS 27
112
+ // a fling's momentum overrides a write within a frame (see
113
+ // `iosMomentumOverridesWrites`).
114
+ tail = (): 'tap' | 'fling' | null =>
115
+ this._touch?.phase === 'tail' ? (this._touch.moved ? 'fling' : 'tap') : null
116
+
117
+ // A scroll event reached the handler. `ownReadBack`: it is our own
118
+ // write's read-back; `moved`: it changed the layout position; `external`:
119
+ // the user or a fling moved it (not our write nor our smooth animation).
120
+ // Returns whether it shows a finger dragging the content.
121
+ onScroll = ({
122
+ isScrolling,
123
+ ownReadBack,
124
+ moved,
125
+ external,
126
+ }: {
127
+ isScrolling: boolean
128
+ ownReadBack: boolean
129
+ moved: boolean
130
+ external: boolean
131
+ }): boolean => {
132
+ // Momentum after touchend fires a scroll event per frame but no touch
133
+ // events, so each one re-arms the tail to span the fling. Only an open
134
+ // tail is extended: a scroll event with no touch before it (our own
135
+ // write's read-back) never opens one.
136
+ if (isScrolling && this._touch?.phase === 'tail') {
137
+ this._openTail(this._touch.moved || !ownReadBack, false)
138
+ } else if (this._touch?.phase === 'lateFling') {
139
+ // A drag's fling reporting after its tail closed reopens it.
140
+ if (this.host.now() > this._touch.until) {
141
+ this._touch = null
142
+ } else if (external && isScrolling && moved) {
143
+ this._openTail(true, false)
144
+ }
145
+ }
146
+ // A finger that moved the content is dragging. Our own write landing
147
+ // under a resting finger is not, and neither is a report at rest that
148
+ // leaves the position where it was.
149
+ if (!ownReadBack && isScrolling && moved && this._touch?.phase === 'down') {
150
+ this._touch.moved = true
151
+ return true
152
+ }
153
+ return false
154
+ }
155
+
156
+ touchStart = () => {
157
+ // A finger back down inside the grace window cancels its tail.
158
+ this.end()
159
+ this._touch = { phase: 'down', moved: false }
160
+ }
161
+
162
+ touchEnd = () => {
163
+ const moved = this._touch?.phase === 'down' && this._touch.moved
164
+ this.end()
165
+ this._openTail(moved, moved)
166
+ }
167
+
168
+ // Drop the gesture, and the tail's timer with it.
169
+ end = () => {
170
+ const win = this.host.getWindow()
171
+ if (this._touch?.phase === 'tail' && win != null) {
172
+ win.clearTimeout(this._touch.timerId)
173
+ }
174
+ this._touch = null
175
+ }
176
+
177
+ // Follow the touch events on `target`; the returned function stops and
178
+ // drops the gesture. Listening is unconditional: the listeners are
179
+ // passive and cheap, and on non-touch devices they never fire. The gating
180
+ // by `isIOSWebKit()` lives where a write is decided.
181
+ listen = (target: EventTarget) => {
182
+ const onTouchStart = () => this.touchStart()
183
+ const onTouchEnd = () => this.touchEnd()
184
+ target.addEventListener('touchstart', onTouchStart, touchListenerOptions)
185
+ target.addEventListener('touchend', onTouchEnd, touchListenerOptions)
186
+ // Same handler as touchend: iOS can end a touch with touchcancel (system
187
+ // gesture, interrupted scroll) and never fire touchend.
188
+ target.addEventListener('touchcancel', onTouchEnd, touchListenerOptions)
189
+ return () => {
190
+ target.removeEventListener(
191
+ 'touchstart',
192
+ onTouchStart,
193
+ touchListenerOptions,
194
+ )
195
+ target.removeEventListener('touchend', onTouchEnd, touchListenerOptions)
196
+ target.removeEventListener(
197
+ 'touchcancel',
198
+ onTouchEnd,
199
+ touchListenerOptions,
200
+ )
201
+ this.end()
202
+ }
203
+ }
204
+
205
+ // (Re)open the tail after the finger lifts, closing ~150ms after the last
206
+ // touchend or momentum frame. On non-iOS there is nothing to protect.
207
+ private _openTail = (moved: boolean, awaitingFling: boolean) => {
208
+ const win = this.host.getWindow()
209
+ if (!isIOSWebKit() || win == null) return
210
+ this.end()
211
+ const tail = {
212
+ phase: 'tail' as const,
213
+ moved,
214
+ awaitingFling,
215
+ // Only fires while this tail is current: `end` clears it otherwise.
216
+ timerId: win.setTimeout(() => {
217
+ if (this.host.tailStillMoving()) {
218
+ this._openTail(tail.moved, tail.awaitingFling)
219
+ return
220
+ }
221
+ this._touch = tail.awaitingFling
222
+ ? { phase: 'lateFling', until: this.host.now() + 1000 }
223
+ : null
224
+ this.host.onTailClosed()
225
+ }, 150),
226
+ }
227
+ this._touch = tail
228
+ }
229
+ }
@@ -0,0 +1,232 @@
1
+ import { approxEqual } from './utils'
2
+
3
+ // Why a scroll event arrived, decided from the virtualizer's state as it was
4
+ // before the event, before the scroll handler mutates anything. The first
5
+ // match in this order wins:
6
+ // spurious Safari/Firefox re-emit at the position we hold, nothing
7
+ // pending
8
+ // readBack our last write reporting back (within 1.5px of its
9
+ // target)
10
+ // clampedReadBack our last non-smooth write, clamped at the element's
11
+ // current max or at a smaller max the layout passed
12
+ // through since the write
13
+ // clampedEcho a compensation write the browser clamped (#1258)
14
+ // reporting at the max seen at write time
15
+ // external anything else: the user, a fling, a smooth animation
16
+ // frame
17
+ type ScrollEventKind =
18
+ | 'spurious'
19
+ | 'readBack'
20
+ | 'clampedReadBack'
21
+ | 'clampedEcho'
22
+ | 'external'
23
+
24
+ export interface ScrollEventInput {
25
+ // The reported position in layout coordinates (the element's offset plus
26
+ // the held correction and a pending prepend anchor's delta).
27
+ offset: number
28
+ isScrolling: boolean
29
+ // The element's own scroll max, read only while scrolling (null otherwise
30
+ // or where it cannot be read).
31
+ elementMax: number | null
32
+ // How far the element sits behind the layout while a correction is held.
33
+ holdOffset: number
34
+ // The layout position the virtualizer holds.
35
+ scrollOffset: number | null
36
+ // Our last write to the element, until a scroll event reports it, with
37
+ // the scroll maxima below its target the element had since (see
38
+ // `lowMaxes` on `pendingWrite` in the virtualizer).
39
+ pendingWrite: {
40
+ target: number
41
+ smooth: boolean
42
+ lowMaxes?: Array<number>
43
+ } | null
44
+ // The element's max when a clamped compensation write was made (#1258),
45
+ // or null when none is pending.
46
+ clampedMaxAtWrite: number | null
47
+ }
48
+
49
+ export function classifyScrollEvent({
50
+ offset,
51
+ isScrolling,
52
+ elementMax,
53
+ holdOffset,
54
+ scrollOffset,
55
+ pendingWrite,
56
+ clampedMaxAtWrite,
57
+ }: ScrollEventInput): ScrollEventKind {
58
+ // A scroll event that reports movement but lands on the offset we already
59
+ // hold — and isn't a self-write read-back — is a spurious no-op re-emit
60
+ // that Safari/Firefox fire after a re-render's layout (Chrome doesn't).
61
+ // Treating it as scrolling re-arms `isScrolling`, which forces a render
62
+ // that triggers another such event: an infinite re-render loop.
63
+ if (isScrolling && pendingWrite === null && offset === scrollOffset) {
64
+ return 'spurious'
65
+ }
66
+ if (pendingWrite !== null && Math.abs(offset - pendingWrite.target) < 1.5) {
67
+ return 'readBack'
68
+ }
69
+ // A non-smooth write past the element's max reads back at the max: ours,
70
+ // clamped because the sizer shrank between the write and the report (rows
71
+ // above the target measured smaller in a same-task render, #1310). The
72
+ // element is where it says. A finger that drags to the max while such a
73
+ // write is pending (iOS ignored it) is read the same way; the command then
74
+ // retires at the next frame, its target clamped to the same max.
75
+ if (
76
+ pendingWrite !== null &&
77
+ !pendingWrite.smooth &&
78
+ elementMax !== null &&
79
+ pendingWrite.target > elementMax + holdOffset + 0.5 &&
80
+ Math.abs(offset - (elementMax + holdOffset)) < 1.5
81
+ ) {
82
+ return 'clampedReadBack'
83
+ }
84
+ // The same, clamped to a smaller max than the element's current one: the
85
+ // sizer shrank below the target after the write (rows measured smaller,
86
+ // a count change) and the browser clamped there, then it grew back, all
87
+ // before the report. The clamp lands on one of those maxima; a position
88
+ // between them is not one.
89
+ if (
90
+ pendingWrite !== null &&
91
+ !pendingWrite.smooth &&
92
+ pendingWrite.lowMaxes?.some((max) => Math.abs(offset - max) < 1.5)
93
+ ) {
94
+ return 'clampedReadBack'
95
+ }
96
+ if (
97
+ clampedMaxAtWrite !== null &&
98
+ Math.abs(offset - clampedMaxAtWrite) < 1.5
99
+ ) {
100
+ return 'clampedEcho'
101
+ }
102
+ return 'external'
103
+ }
104
+
105
+ // Where an in-flight scroll command is in its lifecycle, which decides how
106
+ // its scroll events and measurements are read:
107
+ // queued the first write waits for the momentum tail to close
108
+ // (iOS 27, see `_startScroll`). Nothing has been written:
109
+ // the fling's scroll events do not retire the command, a
110
+ // drag does, and reconcile only keeps the safety valve
111
+ // smooth a smooth animation is travelling to the target
112
+ // smoothLanded a smooth scroll is at its target, waiting to retire
113
+ // smoothFinishing a smooth scroll switched to instant writes for the
114
+ // final approach; its animation can still report positions
115
+ // instant instant writes
116
+ export type ScrollPhase =
117
+ | 'queued'
118
+ | 'smooth'
119
+ | 'smoothLanded'
120
+ | 'smoothFinishing'
121
+ | 'instant'
122
+
123
+ // The smooth animation may still be reporting positions, so a scroll event
124
+ // that isn't the read-back of our own write may not be the user.
125
+ const isAnimating = (phase: ScrollPhase) =>
126
+ phase === 'smooth' || phase === 'smoothFinishing'
127
+
128
+ export interface RetireInput {
129
+ kind: ScrollEventKind
130
+ // The reported position in layout coordinates, as classified.
131
+ offset: number
132
+ // The in-flight scroll command, or null.
133
+ command: {
134
+ index: number | null
135
+ phase: ScrollPhase
136
+ lastTargetOffset: number
137
+ } | null
138
+ // The command's target recomputed against the current layout. Called
139
+ // only once every cheaper clause has passed, and at most once.
140
+ target: () => number
141
+ }
142
+
143
+ // Whether a scroll event that is not the read-back of our own write retires
144
+ // the in-flight index command: an external scroll moved away from its
145
+ // target. Our own measurement updates (including clamped writes) still need
146
+ // to reconcile.
147
+ export function externalRetiresCommand({
148
+ kind,
149
+ offset,
150
+ command,
151
+ target,
152
+ }: RetireInput): boolean {
153
+ return (
154
+ kind !== 'spurious' &&
155
+ kind !== 'readBack' &&
156
+ // Our own write, clamped (`clampedReadBack`, #1310): the command is not
157
+ // retired by it, and reconcile retargets below the new max.
158
+ kind !== 'clampedReadBack' &&
159
+ command?.index != null &&
160
+ // Nothing has been written for a command waiting for the tail; these
161
+ // are the fling's events.
162
+ command.phase !== 'queued' &&
163
+ // A non-smooth write lands at once, so any other scroll event is the
164
+ // user's, even before reconcile saw the target reached (the target may
165
+ // keep moving, or iOS ignored the write under a finger). A write the
166
+ // browser clamped because the sizer hasn't grown yet reads back at the
167
+ // max, which is also where the fresh target clamps, so the check below
168
+ // keeps it reconciling (#1294). While a smooth scroll's animation may
169
+ // still report, its events look like a user's, so it yields only once it
170
+ // has landed.
171
+ !isAnimating(command.phase) &&
172
+ !approxEqual(offset, command.lastTargetOffset) &&
173
+ !approxEqual(offset, target()) &&
174
+ // A compensation write's clamped echo (#1258) keeps the command. The
175
+ // order is deliberate, not tidiness: this clause stays after `target()`
176
+ // (and `clampedReadBack` before it) because `target()` can rebuild the
177
+ // measurements, so it must run for exactly the events it always did.
178
+ kind !== 'clampedEcho'
179
+ )
180
+ }
181
+
182
+ // A scroll position reported at a time, in the element's own coordinates.
183
+ export interface ScrollSample {
184
+ t: number
185
+ offset: number
186
+ }
187
+
188
+ const FLING_WINDOW_MS = 40
189
+
190
+ // Whether the scroll sped up: a finger flicked again or dragged on during a
191
+ // fling. iOS fires no touch events for a touch that lands on a fling
192
+ // (#1307), so this, and a turn against the fling, is all that shows it.
193
+ // Momentum only slows down. Scroll events arrive 7–26ms apart and some
194
+ // carry two frames, so one event can read 2–3× faster than its neighbours;
195
+ // the speed is taken over the last 40ms and compared with the 40ms before.
196
+ // On an iPhone (27.0.1) the flicks read 2.4–6× faster than the window before
197
+ // and at least 1.5px/ms more, momentum alone at most 1.7× (#1307).
198
+ export function flingSpedUp(samples: ReadonlyArray<ScrollSample>): boolean {
199
+ const last = samples[samples.length - 1]
200
+ if (last === undefined) return false
201
+ let j = samples.length - 2
202
+ while (j >= 0 && last.t - samples[j]!.t < FLING_WINDOW_MS) j--
203
+ if (j < 0) return false
204
+ const mid = samples[j]!
205
+ let k = j - 1
206
+ while (k >= 0 && mid.t - samples[k]!.t < FLING_WINDOW_MS) k--
207
+ if (k < 0) return false
208
+ const first = samples[k]!
209
+ const recent = (last.offset - mid.offset) / (last.t - mid.t)
210
+ const before = (mid.offset - first.offset) / (mid.t - first.t)
211
+ return (
212
+ recent * before >= 0 &&
213
+ Math.abs(recent) >= 2 * Math.abs(before) &&
214
+ Math.abs(recent) - Math.abs(before) >= 0.8
215
+ )
216
+ }
217
+
218
+ // Whether a fling that sent its last scroll event was still going at
219
+ // 0.05px/ms or more over its last 40ms: a finger caught it. A fling that
220
+ // ends on its own fades to at most 0.015px/ms first; taps stopped one at
221
+ // 0.21–1.43px/ms (iPhones on 27.0.1, #1307). The finger stays down with no
222
+ // touch events, and iOS undoes a write made under it. A tap in the last
223
+ // pixels of a fling reads as its end.
224
+ export function flingCaught(samples: ReadonlyArray<ScrollSample>): boolean {
225
+ const last = samples[samples.length - 1]
226
+ if (last === undefined) return false
227
+ let j = samples.length - 2
228
+ while (j >= 0 && last.t - samples[j]!.t < FLING_WINDOW_MS) j--
229
+ if (j < 0) return false
230
+ const from = samples[j]!
231
+ return Math.abs(last.offset - from.offset) / (last.t - from.t) >= 0.05
232
+ }