diff --git a/.changeset/smooth-command-wheel-hold.md b/.changeset/smooth-command-wheel-hold.md new file mode 100644 index 000000000..d2b698136 --- /dev/null +++ b/.changeset/smooth-command-wheel-hold.md @@ -0,0 +1,5 @@ +--- +'@tanstack/virtual-core': patch +--- + +Fix a smooth `scrollToIndex` or `scrollToOffset` in WebKit stopping short of its target when rows are prepended or measured during wheel input while it travels. The held correction is now written when the wheel rests, and the scroll continues to its target. diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7f07889e1..bf8d0a8bb 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -30,7 +30,7 @@ jobs: with: main-branch-name: main - name: Install Playwright browsers - run: pnpm exec playwright install chromium + run: pnpm exec playwright install --with-deps chromium webkit - name: Run Checks run: pnpm run test:pr preview: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cb4ed3152..18ebfc1d3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,7 +32,7 @@ jobs: - name: Setup Tools uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Install Playwright browsers - run: pnpm exec playwright install chromium + run: pnpm exec playwright install --with-deps chromium webkit - name: Run Tests run: pnpm run test:ci - name: Run Changesets (version or publish) diff --git a/packages/react-virtual/e2e/app/test/wheel-smooth-prepend.spec.ts b/packages/react-virtual/e2e/app/test/wheel-smooth-prepend.spec.ts new file mode 100644 index 000000000..afd4e658f --- /dev/null +++ b/packages/react-virtual/e2e/app/test/wheel-smooth-prepend.spec.ts @@ -0,0 +1,76 @@ +import { expect, test } from '@playwright/test' +import type { Page } from '@playwright/test' + +// The wheel hold is WebKit only (#1400), so this runs in WebKit. +test.use({ browserName: 'webkit' }) + +const scrollTop = (page: Page) => + page.evaluate(() => document.querySelector('#scroll-container')!.scrollTop) + +// Where row 0 is drawn, relative to the top of the viewport. +const rowZeroTop = (page: Page) => + page.evaluate(() => { + const container = document.querySelector('#scroll-container')! + const row = container.querySelector('[data-index="0"]') + if (!row) return null + return ( + row.getBoundingClientRect().top - + container.getBoundingClientRect().top - + container.clientTop + ) + }) + +// #1406: a smooth scrollToIndex(0) travels, a wheel event comes in, and rows +// are prepended within the wheel's 150ms, so the anchor is held. A real wheel +// does not stop the smooth animation in WebKit, so the element reaches 0 +// while the layout is the held 250px away. The command must still land on +// the new row 0, with the hold written. +test('a prepend held under the wheel does not strand a smooth scrollToIndex', async ({ + page, +}) => { + await page.goto('/smooth-prepend/') + await expect + .poll(() => + page.evaluate(() => { + const c = document.querySelector('#scroll-container')! + return Math.abs(c.scrollHeight - c.scrollTop - c.clientHeight) + }), + ) + .toBeLessThan(1.01) + + // All of it inside one real wheel event, so no round trip has to fit into + // WebKit's ~250ms animation: a capture listener on the window starts the + // smooth command before the virtualizer's own wheel listener opens the + // wheel window, and a listener after it prepends, which is then held. The + // wheel's own scroll lands while the command travels. + await page.evaluate(() => { + const container = document.querySelector('#scroll-container')! + window.addEventListener( + 'wheel', + () => document.querySelector('#smooth-to-0')!.click(), + { capture: true, once: true }, + ) + container.addEventListener( + 'wheel', + () => { + ;(window as any).prependedAt = container.scrollTop + document.querySelector('#prepend')!.click() + }, + { once: true }, + ) + }) + const box = (await page.locator('#scroll-container').boundingBox())! + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await page.mouse.wheel(0, -40) + + // The prepend came while the command was still travelling, not after it. + const prependedAt = await page.evaluate(() => (window as any).prependedAt) + expect(prependedAt).toBeGreaterThan(500) + + await expect.poll(() => rowZeroTop(page), { timeout: 3000 }).toBe(0) + expect(await scrollTop(page)).toBeLessThan(1.01) + await expect(page.locator('[data-index="0"]')).toHaveAttribute( + 'data-message-id', + 'm--5', + ) +}) diff --git a/packages/virtual-core/src/index.ts b/packages/virtual-core/src/index.ts index 033b9fb9e..94de0d995 100644 --- a/packages/virtual-core/src/index.ts +++ b/packages/virtual-core/src/index.ts @@ -1320,7 +1320,7 @@ export class Virtualizer< if (this._wheelTimer !== null) win.clearTimeout(this._wheelTimer) this._wheelTimer = win.setTimeout(() => { this._wheelTimer = null - this._flushHoldIfReady(true) + this._flushHoldIfReady(true, true) this._retryClampedAdjustment() }, 150) // At the top the element stops moving, so no scroll event comes. @@ -1439,14 +1439,31 @@ export class Virtualizer< } // Write the command that `_startScroll` left waiting for the momentum - // tail, against the layout as it is now (rows measured during the fling - // have moved an index target). + // tail. private _writeAwaitingCommand = () => { const state = this.scrollState if (state === null || state.phase !== 'queued') return + this._writeCommand(state) + } + + // Write a command again from where the element is, against the layout as + // it is now (rows measured during a fling have moved an index target). + private _writeCommand = (state: ScrollState) => { const { behavior } = state this.getMeasurements() - const offset = this.getScrollStateTarget(state) + // Clamped to the range the element has now, as for a command issued + // now (`getOffsetForAlignment`). After a hold's flush, a consumer that + // commits the sizer later leaves the element its old max, and a trim + // above can have moved an offset target below 0; reconcile does not + // write an unchanged offset target again. An index or end target is + // already clamped, and reconcile retargets it once the sizer grows. + const offset = Math.max( + Math.min( + this.getScrollStateTarget(state), + Math.max(this.getMaxScrollOffset(), 0), + ), + 0, + ) state.lastTargetOffset = offset // The hold flushed just before can leave a clamp retry (#1258); it // would write its old target over this command. @@ -1543,7 +1560,7 @@ export class Virtualizer< if (this._wheelTimer === null || !this._holdAtTop()) return win.clearTimeout(this._wheelTimer) this._wheelTimer = null - this._flushHoldIfReady(true) + this._flushHoldIfReady(true, true) this._retryClampedAdjustment() }) }) @@ -1559,12 +1576,21 @@ export class Virtualizer< // (`_willUpdate`), where an update it schedules commits before paint // anyway. A command's start passes true, although `_willUpdate` can reach // it too (a follow on append). - private _flushHoldIfReady = (sync: boolean) => { + private _flushHoldIfReady = (sync: boolean, wheelEnded = false) => { if (this._holdOffset === 0) return if (!this.scrollElement || !this.options.enabled) return if (!this._canWriteScroll()) return - // Let a travelling smooth scroll land first (see `_willUpdate`). - if (this.scrollState?.phase === 'smooth') return + // Let a travelling smooth scroll land first (see `_willUpdate`). Not as + // the wheel hold ends: a wheel does not stop the animation (Playwright + // WebKit and Chromium), and one written while the wheel held a + // correction was aimed the hold short, or clamped at the top. It would + // never see its target and would keep the hold until the safety valve + // (#1406). Write the hold, which stops the animation, and the command + // again from there. Other holds keep the wait: a touch stops the + // animation, and the command written again would pull the user back. + const state = this.scrollState + const reaim = wheelEnded && state?.phase === 'smooth' + if (state?.phase === 'smooth' && !reaim) return this._holdOffset = 0 // A held shrink can leave the layout position above the top; the // element clamps that to 0 without an event to say so (#1229). @@ -1572,6 +1598,9 @@ export class Virtualizer< this.scrollOffset = 0 } this.notify(sync) + // `onChange` started another command during the notify: it has written + // its target, and a write here would stop it if it is smooth. + if (this.scrollState !== null && this.scrollState !== state) return // A command whose write has not been reported back yet owns the target: // `scrollOffset` is still the pre-command position until its read-back, // and a command that closes the touch tail makes a write possible with @@ -1581,6 +1610,8 @@ export class Virtualizer< // (#1258). this._clampedAdjustment = this._clampedBy(target) this._scrollToOffset(target) + // Not if `onChange` cancelled the command during the notify. + if (reaim && this.scrollState === state) this._writeCommand(state) } private rafId: number | null = null diff --git a/packages/virtual-core/tests/__snapshots__/scroll-trace.test.ts.snap b/packages/virtual-core/tests/__snapshots__/scroll-trace.test.ts.snap index 4ff59755c..394b92e18 100644 --- a/packages/virtual-core/tests/__snapshots__/scroll-trace.test.ts.snap +++ b/packages/virtual-core/tests/__snapshots__/scroll-trace.test.ts.snap @@ -18,7 +18,7 @@ exports[`scroll behaviour snapshot > anchorEnd ios27 1`] = ` "20: 4c1a00c0 5b17cebe 39f53c48 43b3722d 4c85db64 0d41dbae 319823eb 0cd61d7a ebd8a220 09a1874e", "30: 0224b245 2a263abe beba95dc 6e007e5d 3ab04872 8000f929 a8da8fd8 4acd8bac 3c2c8710 93ac03b2", "40: 351e701d 81b41eab 7e4c0d8a e8e6cf89 0018ede1 ee1edfdf 49ca9103 334646c6 3e95ee0d 8f0a8fe9", - "50: ca6b1fc6 8cc11ea8 90e19d07 7c8d21a0 11d479bb adc56879 e06a8ddb e46aa4df e9fb7a13 a865bfd7", + "50: ca6b1fc6 8cc11ea8 90e19d07 7c8d21a0 13ccf8d1 adc56879 e06a8ddb e46aa4df e9fb7a13 a865bfd7", ] `; diff --git a/packages/virtual-core/tests/wheel-hold.test.ts b/packages/virtual-core/tests/wheel-hold.test.ts index eadc41ac6..77323441f 100644 --- a/packages/virtual-core/tests/wheel-hold.test.ts +++ b/packages/virtual-core/tests/wheel-hold.test.ts @@ -229,6 +229,370 @@ for (const behavior of ['auto', 'smooth'] as const) { }) } +test('WebKit (#1406): a hold made while a smooth command travels is written, and the command lands', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + // A smooth write leaves the element where it is; the test moves it + // along the way as the animation would. + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + }) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + expect(h.writes).toEqual([0]) + h.scroll(true, 1500) + h.frame() + + h.el._dispatch('wheel') + prepend(h) + expect(h.v['_holdOffset']).toBe(600) + + // The animation travels on to where it was aimed, row 0 600px short. + h.scroll(true, 1000) + h.frame() + // Where the reader sees row 34, as exposed. + const shown = () => + h.v.getVirtualItems().find((item) => item.index === 34)!.start - + h.el.scrollTop + const top = shown() + h.writes.length = 0 + + // The wheel rests: the hold is written where the reader is, which stops + // the animation, and the command is written again from there. + h.expireTail() + expect(h.writes).toEqual([1600, 0]) + expect(shown()).toBe(top) + for (const offset of [800, 0]) { + h.scroll(true, offset) + h.frame() + } + h.scroll(false) + for (let i = 0; i < 5; i++) h.frame() + + expect(h.v['_holdOffset']).toBe(0) + expect(h.el.scrollTop).toBe(0) + expect(h.rowTop(0)).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + +test('WebKit (#1406): a smooth command aimed before a wheel hold lands when the element reaches the top under the wheel', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + }) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + h.el._dispatch('wheel') + prepend(h) + h.writes.length = 0 + + // The animation reaches the top, the layout 600px short of row 0. + h.el._dispatch('wheel') + h.scroll(true, 0) + h.frame() + expect(h.writes).toEqual([]) + h.frame() + expect(h.writes).toEqual([600, 0]) + for (const offset of [300, 0]) { + h.scroll(true, offset) + h.frame() + } + h.scroll(false) + for (let i = 0; i < 5; i++) h.frame() + + expect(h.v['_holdOffset']).toBe(0) + expect(h.el.scrollTop).toBe(0) + expect(h.rowTop(0)).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + +test('WebKit (#1406): a smooth command retargeted under the wheel hold lands', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + }) + h.v.scrollToIndex(5, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + h.el._dispatch('wheel') + prepend(h) + expect(h.v['_holdOffset']).toBe(600) + + // A row above the target is measured: reconcile retargets the smooth + // command under the hold, past what the element can reach. + h.v.resizeItem(2, 70) + h.frame() + h.scroll(true, 1000) + h.frame() + + // The animation travels to the last write. + h.expireTail() + h.scroll(true, Math.max(0, h.writes.at(-1)!)) + h.frame() + h.scroll(false) + for (let i = 0; i < 10; i++) { + h.frame() + h.scroll(false) + } + + expect(h.v['_holdOffset']).toBe(0) + expect(h.rowTop(5)).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + +for (const behavior of ['auto', 'smooth'] as const) { + test(`WebKit (#1406): a command (${behavior}) started from the flush's onChange is not overwritten`, () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + let held = false + let started = false + const calls: Array<[number, ScrollBehavior | undefined]> = [] + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior: b }) => { + h.writes.push(offset + adjustments) + calls.push([offset + adjustments, b]) + if (b !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + // The consumer starts a new command while the hold is written. + onChange: (v) => { + if (v['_holdOffset'] !== 0) held = true + else if (held && !started) { + started = true + v.scrollToOffset(3000, { behavior }) + } + }, + }) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + h.el._dispatch('wheel') + prepend(h) + h.scroll(true, 1000) + h.frame() + calls.length = 0 + + h.expireTail() + expect(started).toBe(true) + // Nothing is written after the new command. + expect(calls.at(-1)).toEqual([3000, behavior]) + if (behavior === 'smooth') h.scroll(true, 3000) + h.scroll(false, 3000) + for (let i = 0; i < 5; i++) h.frame() + expect(h.v.scrollOffset).toBe(3000) + expect(h.v.scrollState).toBeNull() + }) + }) +} + +test('WebKit (#1406): a re-aimed scrollToOffset ends at the max a late sizer leaves', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + // The consumer commits the sizer after the notify, not inside `onChange`: + // scrollHeight only moves on commit(). + const max = () => h.el.scrollHeight - h.el.clientHeight + const commit = () => { + h.el.scrollHeight = h.v.getTotalSize() + } + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, max())) + } + }, + }) + h.v.scrollToOffset(4700, { behavior: 'smooth' }) + h.scroll(true, 3000) + h.frame() + h.el._dispatch('wheel') + prepend(h) + commit() + h.scroll(true, 3500) + h.frame() + h.writes.length = 0 + + // The hold is written and the command again, before the sizer has grown + // by the hold: the command is written at the max the element has. + h.expireTail() + expect(h.writes).toEqual([4100, 4800]) + h.scroll(true, 4800) + commit() + h.frame() + h.scroll(false) + for (let i = 0; i < 10; i++) { + h.frame() + h.scroll(false) + } + + expect(h.el.scrollTop).toBe(4800) + expect(h.v.scrollState).toBeNull() + }) +}) + +// A smooth write leaves the element where it is; a test moves it along the +// way as the animation would. An instant write clamps to the range. +function animateSmooth(h: ReturnType) { + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + }) +} + +test('WebKit (#1406): a smooth command is aimed again after each wheel burst', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + animateSmooth(h) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + + h.el._dispatch('wheel') + prepend(h) + h.scroll(true, 1000) + h.frame() + h.writes.length = 0 + h.expireTail() + expect(h.writes).toEqual([1600, 0]) + + // A second burst while the command travels again. + h.scroll(true, 1200) + h.frame() + h.el._dispatch('wheel') + h.v.setOptions({ ...h.v.options, count: 124, getItemKey: (i) => i - 24 }) + h.v._willUpdate() + expect(h.v['_holdOffset']).toBe(600) + h.scroll(true, 800) + h.frame() + h.writes.length = 0 + h.expireTail() + expect(h.writes).toEqual([1400, 0]) + + h.scroll(true, 0) + h.frame() + h.scroll(false) + for (let i = 0; i < 5; i++) h.frame() + expect(h.v['_holdOffset']).toBe(0) + expect(h.rowTop(0)).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + +test('WebKit (#1406): the wheel hold ending in a bounce at the top writes nothing', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + animateSmooth(h) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + h.el._dispatch('wheel') + prepend(h) + h.writes.length = 0 + + // The element bounces past the top: WebKit would drop a write. + h.scroll(true, -20) + h.frame() + h.frame() + h.expireTail() + expect(h.writes).toEqual([]) + expect(h.v['_holdOffset']).toBe(600) + }) +}) + +test('WebKit (#1406): a re-aimed offset target a trim moved below 0 lands at the top', () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + animateSmooth(h) + h.v.scrollToOffset(100, { behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + + // 12 rows of 50px above the reader are trimmed under the wheel: the + // anchor is held, and the offset target moves with it to -500. + h.el._dispatch('wheel') + h.v.setOptions({ ...h.v.options, count: 88, getItemKey: (i) => i + 12 }) + h.v._willUpdate() + expect(h.v['_holdOffset']).toBe(-600) + h.scroll(true, 1000) + h.frame() + h.writes.length = 0 + + h.expireTail() + expect(h.writes).toEqual([400, 0]) + h.scroll(true, 0) + h.frame() + h.scroll(false) + for (let i = 0; i < 5; i++) h.frame() + expect(h.el.scrollTop).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + +test("WebKit (#1406): a command cancelled from the flush's onChange is not written again", () => { + withUserAgent(SAFARI, () => { + const h = endAnchoredAt2000() + let held = false + h.v.setOptions({ + ...h.v.options, + scrollToFn: (offset, { adjustments = 0, behavior }) => { + h.writes.push(offset + adjustments) + if (behavior !== 'smooth') { + h.el.scrollTop = Math.max(0, Math.min(offset + adjustments, 4800)) + } + }, + onChange: (v) => { + if (v['_holdOffset'] !== 0) held = true + else if (held) v.cancelScroll() + }, + }) + h.v.scrollToIndex(0, { align: 'start', behavior: 'smooth' }) + h.scroll(true, 1500) + h.frame() + h.el._dispatch('wheel') + prepend(h) + h.scroll(true, 1000) + h.frame() + h.writes.length = 0 + + // The hold is written where the reader is, and nothing after it. + h.expireTail() + expect(h.writes).toEqual([1600]) + expect(h.v['_holdOffset']).toBe(0) + expect(h.v.scrollState).toBeNull() + }) +}) + test('WebKit: a correction with no wheel input is written at once', () => { withUserAgent(SAFARI, () => { const h = endAnchoredAt2000()