diff --git a/.changeset/webkit-wheel-prepend-anchor.md b/.changeset/webkit-wheel-prepend-anchor.md new file mode 100644 index 000000000..f016df448 --- /dev/null +++ b/.changeset/webkit-wheel-prepend-anchor.md @@ -0,0 +1,5 @@ +--- +'@tanstack/virtual-core': patch +--- + +Fix wheel scrolling in WebKit losing distance, or the reader's place, when rows are measured or prepended on the way. Scroll corrections are now held for 150ms after a wheel event and written when the wheel rests, or when the element reaches the top of the list. diff --git a/packages/virtual-core/src/index.ts b/packages/virtual-core/src/index.ts index 4bd3531db..3401a951a 100644 --- a/packages/virtual-core/src/index.ts +++ b/packages/virtual-core/src/index.ts @@ -9,7 +9,12 @@ import { flingCaught, flingSpedUp, } from './scroll-classifier' -import { IosGesture, isIOSWebKit, momentumOverridesWrites } from './ios-gesture' +import { + IosGesture, + isIOSWebKit, + isWebKit, + momentumOverridesWrites, +} from './ios-gesture' import type { ScrollPhase, ScrollSample } from './scroll-classifier' export { _resetIOSDetectionForTests } from './ios-gesture' @@ -540,6 +545,12 @@ export class Virtualizer< // `_flushHoldIfReady`: the rows re-render in layout coordinates and the // element moves by the same amount in one paint. private _holdOffset = 0 + // Set in WebKit from a wheel event until 150ms pass without one, whether + // or not that event scrolled this element. Corrections are held meanwhile + // (see `_canWriteScroll`). + private _wheelTimer: number | null = null + // The frame a hold at the top is written in (`_flushHoldAtTop`). + private _edgeFlushFrame: number | null = null // Whether the element's last scroll event reported a position past either // edge (the rubber-band bounce). Judged at report time against the // element's own max, with a 1px tolerance for a fractional scrollTop: a @@ -1087,6 +1098,16 @@ export class Virtualizer< // just removed), deferring every adjustment on the new element until // its next touch cycle. this._holdOffset = 0 + if (this.targetWindow) { + if (this._wheelTimer !== null) { + this.targetWindow.clearTimeout(this._wheelTimer) + } + if (this._edgeFlushFrame !== null) { + this.targetWindow.cancelAnimationFrame(this._edgeFlushFrame) + } + } + this._wheelTimer = null + this._edgeFlushFrame = null this._reportedOverscroll = false this._trailing = 0 // (The gesture was ended with its listeners, in the unsubs above.) @@ -1276,6 +1297,7 @@ export class Virtualizer< // A held correction is written once a write is possible. this._flushHoldIfReady(true) + this._flushHoldAtTop() if (this.scrollState) { this.scheduleScrollReconcile() @@ -1286,9 +1308,24 @@ export class Virtualizer< // Touch event listeners (iOS-aware deferral). if ('addEventListener' in this.scrollElement) { - this.unsubs.push( - this._iosGesture.listen(this.scrollElement as unknown as EventTarget), - ) + const target = this.scrollElement as unknown as EventTarget + this.unsubs.push(this._iosGesture.listen(target)) + if (isWebKit()) { + const onWheel = () => { + const win = this.targetWindow + if (win === null) return + if (this._wheelTimer !== null) win.clearTimeout(this._wheelTimer) + this._wheelTimer = win.setTimeout(() => { + this._wheelTimer = null + this._flushHoldIfReady(true) + this._retryClampedAdjustment() + }, 150) + // At the top the element stops moving, so no scroll event comes. + this._flushHoldAtTop() + } + target.addEventListener('wheel', onWheel, addEventListenerOptions) + this.unsubs.push(() => target.removeEventListener('wheel', onWheel)) + } } this._scrollToOffset(this.getScrollOffset()) @@ -1443,11 +1480,67 @@ export class Virtualizer< // #1307), so a correction is held through the tail on every version; // - not while the element is overscrolled past either edge (the // rubber-band bounce): WebKit discards the write and the bounce can - // stall where it was (#1287). + // stall where it was (#1287); + // - not in WebKit within 150ms of a wheel event: the write lands, but + // WebKit then discards the distance of the next wheel event, and a list + // of rows measured on the way up writes on most frames. In Playwright + // WebKit 26.0 a wheel event per frame lost about a third of its + // distance that way (#1398, #1400); a prepend's anchor write could be + // undone whole. Real Safari and trackpad momentum are not measured. // A write that is unwanted for another reason (a travelling smooth scroll // owns the position) is a separate check at the call sites. private _canWriteScroll = () => - !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll + !(isIOSWebKit() && this._iosGesture.inMotion()) && + !this._reportedOverscroll && + this._wheelTimer === null + + // A hold shifts the rows and leaves the element where it is, so the + // element reaches its top while the layout has `_holdOffset` further to + // go (or, for a negative hold, the layout reaches its top first). Wheel + // input that never pauses would park the reader there, so there the wheel + // hold ends early and the hold is written, two frames later (a prepend's + // anchor written at once can be undone, #1398). The next wheel event + // starts the wheel hold again. Not before the top: while the element + // still moves, WebKit applies the write about two frames after the rows + // have gone back to layout coordinates, and they show `_holdOffset` away + // for those frames (measured with a 1200px and a one-viewport margin, + // #1400). The list's top is `scrollMargin` down the element, where held + // rows would be drawn over what is above the list; the element still + // moves there, so those frames are the lesser evil. Past the top (a + // bounce) the write waits: the next wheel or scroll event tries again. + // The end needs none of this: the total size is exposed short by the + // hold, so the element and the layout reach it together. + private _holdAtTop = () => { + if (this._holdOffset === 0) return false + const offset = this._readElementOffset() + // 1px for a fractional scrollTop. + return ( + offset !== null && + (offset < this.options.scrollMargin + 1 || offset + this._holdOffset < 1) + ) + } + private _flushHoldAtTop = () => { + const win = this.targetWindow + if ( + win === null || + this._wheelTimer === null || + this._edgeFlushFrame !== null || + !this._holdAtTop() + ) { + return + } + this._edgeFlushFrame = win.requestAnimationFrame(() => { + this._edgeFlushFrame = win.requestAnimationFrame(() => { + this._edgeFlushFrame = null + // The reader can have turned back within the two frames. + if (this._wheelTimer === null || !this._holdAtTop()) return + win.clearTimeout(this._wheelTimer) + this._wheelTimer = null + this._flushHoldIfReady(true) + this._retryClampedAdjustment() + }) + }) + } // Write a held correction once a write is possible, from the scroll // handler, the touch tail timer, `_willUpdate` and a resize notify. The diff --git a/packages/virtual-core/src/ios-gesture.ts b/packages/virtual-core/src/ios-gesture.ts index cda397d4a..d803ba982 100644 --- a/packages/virtual-core/src/ios-gesture.ts +++ b/packages/virtual-core/src/ios-gesture.ts @@ -43,9 +43,24 @@ export const iosMomentumOverridesWrites = (): boolean => { export const momentumOverridesWrites = (): boolean => !isIOSWebKit() || iosMomentumOverridesWrites() +// Any WebKit: Safari, a WKWebView app, every browser on iOS. Chromium's +// user agent names AppleWebKit too, and so do jsdom's and happy-dom's, where +// a consumer's test must see the same writes as before. Cached like the iOS +// check; SSR-safe. +let _isWebKitResult: boolean | undefined +export const isWebKit = (): boolean => { + if (_isWebKitResult !== undefined) return _isWebKitResult + if (typeof navigator === 'undefined') return (_isWebKitResult = false) + const ua = navigator.userAgent + return (_isWebKitResult = + /AppleWebKit/.test(ua) && + !/Chrome|Chromium|Android|jsdom|HappyDOM/.test(ua)) +} + // Test hook: reset the iOS detection caches. Not exported. export const _resetIOSDetectionForTests = () => { _isIOSResult = undefined + _isWebKitResult = undefined _iosMomentumOverridesWritesResult = undefined } diff --git a/packages/virtual-core/tests/wheel-hold.test.ts b/packages/virtual-core/tests/wheel-hold.test.ts new file mode 100644 index 000000000..f0a490cda --- /dev/null +++ b/packages/virtual-core/tests/wheel-hold.test.ts @@ -0,0 +1,227 @@ +import { expect, test } from 'vitest' +import { _resetIOSDetectionForTests } from '../src/index' +import { makeDeferralHarness } from './helpers' + +const SAFARI = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15' +const CHROME = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36' + +function withUserAgent(userAgent: string, fn: () => void) { + Object.defineProperty(navigator, 'userAgent', { + value: userAgent, + configurable: true, + }) + _resetIOSDetectionForTests() + try { + fn() + } finally { + delete (navigator as any).userAgent + _resetIOSDetectionForTests() + } +} + +// An end-anchored list at rest at 2000: rows 50px, viewport 200px, the +// element's max 4800. `expireTail` runs the wheel timer: 150ms with no +// wheel event. +function endAnchoredAt2000() { + const h = makeDeferralHarness({ ios: false }) + h.v.setOptions({ ...h.v.options, anchorTo: 'end', getItemKey: (i) => i }) + h.v._willUpdate() + h.v.scrollToOffset(2000) + h.scroll(true) + for (let i = 0; i < 5; i++) h.frame() + h.scroll(false) + h.writes.length = 0 + return h +} + +// 12 rows of 50px above the reader: the anchor write is 600px. +function prepend(h: ReturnType) { + h.v.setOptions({ ...h.v.options, count: 112, getItemKey: (i) => i - 12 }) + h.v._willUpdate() +} + +test('WebKit (#1398): a size correction under wheel input is held until the wheel rests', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.scroll(true, 1900) + const top = h.rowTop(40) + + h.v.resizeItem(0, 70) + expect(h.writes).toEqual([]) + // Row 40 is exposed where the reader sees it. + expect(h.v.getVirtualItems().find((item) => item.index === 40)!.start).toBe( + top + h.el.scrollTop, + ) + + // The wheel carries on: neither a scroll event nor a frame writes. + h.el._dispatch('wheel') + h.scroll(true, 1800) + h.frame() + h.frame() + expect(h.writes).toEqual([]) + + h.expireTail() + expect(h.writes).toEqual([1820]) + expect(h.rowTop(40)).toBe(top + 100) + }) +}) + +test('WebKit (#1398): a prepend under wheel input is held until the wheel rests', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.scroll(true, 1900) + const top = h.rowTop(40) + + prepend(h) + expect(h.writes).toEqual([]) + expect(h.v.getVirtualItems().find((item) => item.index === 52)!.start).toBe( + top + h.el.scrollTop, + ) + + h.expireTail() + expect(h.writes).toEqual([2500]) + expect(h.rowTop(52)).toBe(top) + }) +}) + +test('WebKit: a hold is written two frames after the element reaches the top, the wheel still running', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + prepend(h) + // Not before the edge. + h.scroll(true, 100) + h.frame() + h.frame() + expect(h.writes).toEqual([]) + + h.el._dispatch('wheel') + h.scroll(true, 0) + h.frame() + expect(h.writes).toEqual([]) + h.frame() + expect(h.writes).toEqual([600]) + + // The next wheel event holds what comes after it. + h.writes.length = 0 + h.scroll(true, 600) + h.el._dispatch('wheel') + h.v.resizeItem(0, 70) + expect(h.writes).toEqual([]) + }) +}) + +test('WebKit: a hold at the top is written with no scroll event, from the wheel event', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.scroll(true, 0) + prepend(h) + expect(h.writes).toEqual([]) + h.el._dispatch('wheel') + h.frame() + h.frame() + expect(h.writes).toEqual([600]) + }) +}) + +test('WebKit: a hold is not written when the reader leaves the top within the two frames', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + prepend(h) + h.scroll(true, 0) + h.frame() + h.el._dispatch('wheel') + h.scroll(true, 400) + h.frame() + expect(h.writes).toEqual([]) + + h.expireTail() + expect(h.writes).toEqual([1000]) + }) +}) + +test('WebKit: with a scroll margin a hold is written where the list starts', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.v.setOptions({ ...h.v.options, scrollMargin: 300 }) + h.v._willUpdate() + h.writes.length = 0 + h.el._dispatch('wheel') + prepend(h) + h.scroll(true, 400) + h.frame() + h.frame() + expect(h.writes).toEqual([]) + + // The top of the list: above it held rows would cover the margin. + h.scroll(true, 300) + h.frame() + h.frame() + expect(h.writes).toEqual([900]) + }) +}) + +test('WebKit: a negative hold is written when the layout reaches the top', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.v.resizeItem(0, 20) + expect(h.writes).toEqual([]) + h.scroll(true, 30) + h.frame() + h.frame() + expect(h.writes).toEqual([0]) + }) +}) + +test('WebKit: a correction with no wheel input is written at once', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.v.resizeItem(0, 70) + expect(h.writes).toEqual([2020]) + }) +}) + +test('WebKit: a new scroll element drops the wheel state', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.scroll(true, 0) + prepend(h) + h.el._dispatch('wheel') + expect(h.v['_wheelTimer']).not.toBeNull() + expect(h.v['_edgeFlushFrame']).not.toBeNull() + h.v.setOptions({ ...h.v.options, enabled: false }) + h.v._willUpdate() + expect(h.v['_wheelTimer']).toBeNull() + expect(h.v['_edgeFlushFrame']).toBeNull() + }) +}) + +test('not WebKit: corrections under wheel input are written at once', () => { + withUserAgent(CHROME, () => { + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.v.resizeItem(0, 70) + expect(h.writes).toEqual([2020]) + h.writes.length = 0 + prepend(h) + expect(h.writes).toEqual([2620]) + }) +}) + +test('jsdom is not WebKit: corrections under wheel input are written at once', () => { + // jsdom's own user agent names AppleWebKit. + expect(navigator.userAgent).toMatch(/AppleWebKit.*jsdom/) + _resetIOSDetectionForTests() + const h = endAnchoredAt2000() + h.el._dispatch('wheel') + h.v.resizeItem(0, 70) + expect(h.writes).toEqual([2020]) +})