diff --git a/.changeset/pending-scroll-offset.md b/.changeset/pending-scroll-offset.md new file mode 100644 index 000000000..2aceeb12b --- /dev/null +++ b/.changeset/pending-scroll-offset.md @@ -0,0 +1,14 @@ +--- +'@tanstack/virtual-core': minor +--- + +Add `isScrollPending()`. It is `true` while a scroll command has written a position that no scroll event has reported back yet. + +Until that read-back, `scrollOffset`, `range` and `getVirtualItems()` still describe the position before the command. A consumer that acts on the position in `onChange` can use this to tell those notifies apart, and wait for the one the read-back brings. + +If the element never reports a command's write, the virtualizer now notifies when reconcile gives up on the command or `cancelScroll` ends it. A consumer waiting for the read-back is not left waiting. + +Two corrections that the browser clamps without a scroll event no longer leave `scrollOffset` wrong: + +- A correction past the top. The recorded write now matches the clamp, as `scrollOffset` already did. +- A correction on a list that fits its viewport, where the only position is 0. `scrollOffset` used to keep the clamped target until an unrelated scroll event. A later command to 0 also looked unreported for its whole lifetime. diff --git a/docs/api/virtualizer.md b/docs/api/virtualizer.md index a5715fbc1..f0f306f4a 100644 --- a/docs/api/virtualizer.md +++ b/docs/api/virtualizer.md @@ -471,6 +471,18 @@ Cancels an in-flight `scrollToIndex`, `scrollToOffset`, `scrollBy` or `scrollToE The current scroll position is not changed. It does nothing when no scroll is in flight. +### `isScrollPending` + +```tsx +isScrollPending: () => boolean +``` + +Whether a scroll command (`scrollToIndex`, `scrollToOffset`, `scrollBy`, `scrollToEnd`) has written a position that no scroll event has reported back yet. + +While it has, `scrollOffset`, `range`, `getVirtualItems()` and `isAtEnd()` still describe the position before the command. An `onChange` fired in between, by a row being measured or the scroll element resizing, pairs the current sizes with that old position. A consumer that acts on the position in `onChange`, for example to report which rows are on screen, can skip a notify while this is `true`. The read-back always brings another, and so does the command being given up on. + +It is `false` for a smooth scroll, whose scroll events keep `scrollOffset` current while it travels, and for a scroll correction, which is folded into `scrollOffset` at once. + ### `getDistanceFromEnd` ```tsx diff --git a/packages/virtual-core/src/index.ts b/packages/virtual-core/src/index.ts index bd6e7cb23..9239bdf22 100644 --- a/packages/virtual-core/src/index.ts +++ b/packages/virtual-core/src/index.ts @@ -998,6 +998,12 @@ export class Virtualizer< adjustments: delta, behavior, }) + // A write past the top is clamped to 0 by the browser, and from an + // element already there no scroll event follows (#1229): record what + // the element can report back, as `scrollOffset` is clamped below, or + // the write would look like an unreported one for as long as a + // command is in flight. + if (write.target < 0) write.target = 0 // Eagerly carry the intended target in `scrollOffset` so callers that // read it before the next scroll event — notably the next `resizeItem` // tick's `getVirtualDistanceFromEnd()` / `wasAtEnd` check — see the @@ -1325,7 +1331,7 @@ export class Virtualizer< this._flushHoldIfReady(false) // The consumer has committed the new total size by now, so a clamped // compensation write may have room (#1258). - this._retryClampedAdjustment() + this._retryClampedAdjustment(true) } // Classify a scroll event (see `ScrollEventKind`) from the state as it was @@ -1356,7 +1362,7 @@ export class Virtualizer< // absence of one leave `_clampedAdjustment` set, so timing does not matter. // While the element cannot take a write (`_canWriteScroll`) the record is // kept for the next opportunity, the latest being the tail closing. - private _retryClampedAdjustment = () => { + private _retryClampedAdjustment = (committed = false) => { if ( this._clampedAdjustment === null || !this.scrollElement || @@ -1373,6 +1379,24 @@ export class Virtualizer< this._clampedAdjustment = target > max + 0.5 ? { target, maxAtWrite: max } : null this._scrollToOffset(target) + } else if (committed && this._isUnscrollable()) { + // The sizer is committed and did not grow, nor will it: the layout + // fits the viewport, so the element's one position is 0. The browser clamped the write + // there and, from an element already at 0, reported no scroll event + // (#1229 at the other edge). Adopt it: otherwise `scrollOffset` keeps + // the clamped target until some unrelated scroll event, and a command + // written to 0 afterwards can never read back, its target being where + // the element already is. + this._clampedAdjustment = null + if (this.scrollOffset !== null && this.scrollOffset > 0) { + this.scrollOffset = 0 + } + if ( + this.pendingWrite !== null && + approxEqual(this.pendingWrite.target, target) + ) { + this.pendingWrite.target = 0 + } } } @@ -1478,7 +1502,19 @@ export class Virtualizer< : undefined return offsetInfo ? offsetInfo[0] : state.lastTargetOffset } + // A write the element never reports (clamped where it already was, or + // dropped) stays pending until reconcile retargets or retires its command. + // That ends the pending position with no scroll event to say so, so a + // consumer that waited for the read-back to act on the position is told. private reconcileScroll() { + const wasPending = this.isScrollPending() + this._reconcileScrollStep() + if (wasPending && !this.isScrollPending()) { + this.notify(false) + } + } + + private _reconcileScrollStep() { if (!this.scrollState) return const el = this.scrollElement @@ -2346,6 +2382,16 @@ export class Virtualizer< ) } + // The layout fits the viewport and the element has no scroll range: its + // one position is 0, and no scroll event will ever report another. + private _isUnscrollable = () => { + const layoutMax = + this._getLayoutTotalSize() + this.options.scrollMargin - this.getSize() + if (layoutMax > 0) return false + const elementMax = this._elementMaxScrollOffset() + return elementMax !== null && elementMax <= 0.5 + } + // A compensation write past the element's current max (the sizer has not // grown yet) is clamped by the browser; record it for the retry (#1258). private _clampedBy = (target: number) => { @@ -2614,7 +2660,10 @@ export class Virtualizer< this.targetWindow.cancelAnimationFrame(this.rafId) this.rafId = null } + const wasPending = this.isScrollPending() this.scrollState = null + // See `reconcileScroll`: the pending position ends with the command. + if (wasPending) this.notify(false) } // The size the consumer gives the container: the layout's total, short by @@ -2734,6 +2783,23 @@ export class Virtualizer< ? this.pendingWrite.target : null + /** + * Whether a scroll command (`scrollToIndex`, `scrollToOffset`, `scrollBy`, + * `scrollToEnd`) has written a position that no scroll event has reported + * back yet. While it has, `scrollOffset`, `range`, `getVirtualItems()` and + * `isAtEnd()` still describe the position before the command. An + * `onChange` fired in between (a row measured, the scroll element resized) + * pairs the current sizes with that old position. A consumer that acts on + * the position in `onChange` can skip such a notify: the read-back always + * brings another. + * + * `false` for a smooth write, whose scroll events keep `scrollOffset` + * current, and for a correction, which is folded into `scrollOffset` at + * once. A write the element never reports stops being pending when + * reconcile retargets or gives up on the command, with a notify. + */ + isScrollPending = (): boolean => this._awaitingCommandReadBack() + // A scroll command (or reconcile) wrote a new position that neither a // scroll event nor an eager update has reflected in `scrollOffset` yet. // The rows on screen were rendered for the old position, so "above the diff --git a/packages/virtual-core/tests/scroll-commands.test.ts b/packages/virtual-core/tests/scroll-commands.test.ts index f7eaacaae..c7f5e7b10 100644 --- a/packages/virtual-core/tests/scroll-commands.test.ts +++ b/packages/virtual-core/tests/scroll-commands.test.ts @@ -2026,3 +2026,152 @@ test.each([ expect(v.getVirtualItems().at(-1)!.index).toBeGreaterThanOrEqual(54) }, ) + +test('isScrollPending reports a command’s write until its scroll event', () => { + const { v, el, scroll } = setupHandDrivenScroll() + + expect(v.isScrollPending()).toBe(false) + v.scrollToOffset(1000) + expect(el.scrollTop).toBe(1000) + // Written, not yet reported: the position the instance exposes is the old one. + expect(v.isScrollPending()).toBe(true) + expect(v.scrollOffset).toBe(0) + expect(v.range).toMatchObject({ startIndex: 0 }) + + scroll(1000, true) + expect(v.isScrollPending()).toBe(false) + expect(v.scrollOffset).toBe(1000) + expect(v.range).toMatchObject({ startIndex: 20 }) +}) + +test('an onChange between a command’s write and its read-back can be told apart', () => { + const onChange = vi.fn() + const { v, scroll } = setupHandDrivenScroll({ onChange }) + onChange.mockClear() + + v.scrollToOffset(1000) + // A row measured before the scroll event: sizes are current, the position is not. + v.resizeItem(0, 70) + expect(onChange).toHaveBeenCalled() + const duringWrite = onChange.mock.calls.map(([instance]) => + instance.isScrollPending(), + ) + expect(duringWrite.every(Boolean)).toBe(true) + + onChange.mockClear() + scroll(1020, true) + // The read-back notifies, and by then nothing is pending. + expect(onChange).toHaveBeenCalled() + expect(onChange.mock.calls[0][0].isScrollPending()).toBe(false) +}) + +test('a smooth write and a scroll correction are not pending', () => { + const { v, el, scroll } = setupHandDrivenScroll() + el.scrollTop = 2000 + scroll(2000, false) + + v.scrollToOffset(1000, { behavior: 'smooth' }) + expect(v.isScrollPending()).toBe(false) + v.cancelScroll() + scroll(2000, false) + + // A row above the viewport grows: the correction is folded into scrollOffset at once. + v.resizeItem(0, 100) + expect(el.scrollTop).toBe(2050) + expect(v.scrollOffset).toBe(2050) + expect(v.isScrollPending()).toBe(false) +}) + +test('a write the element never reports is retired with a notify', () => { + vi.useFakeTimers() + try { + const onChange = vi.fn() + const { v, browser, frames } = setupHandDrivenScroll({ onChange }) + browser.ignoreWrites = true + onChange.mockClear() + + v.scrollToOffset(1000) + expect(v.isScrollPending()).toBe(true) + frames(3) + expect(v.isScrollPending()).toBe(true) + expect(onChange).not.toHaveBeenCalled() + + // Reconcile gives up on the command after its safety valve. + vi.advanceTimersByTime(5001) + frames(1) + expect(v.scrollState).toBeNull() + expect(v.isScrollPending()).toBe(false) + expect(onChange).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } +}) + +test('a correction clamped at the top during a command leaves nothing pending', () => { + // Three rows estimated at 100px in a 400px viewport, anchored to the end: + // the list fits, so it is at the end at offset 0. A row measuring smaller + // keeps the end pinned with a write to -8, which the browser clamps to 0 + // from an element already there, so no scroll event reports it. + const { v, el } = setupHandDrivenScroll({ + count: 3, + estimateSize: () => 100, + anchorTo: 'end', + observeElementRect: (_inst, cb) => { + cb({ width: 400, height: 400 }) + return () => {} + }, + }) + el.clientHeight = 400 + el.scrollHeight = 400 + + v.scrollToIndex(2, { align: 'end' }) + expect(el.scrollTop).toBe(0) + expect(v.isScrollPending()).toBe(false) + + v.resizeItem(0, 92) + expect(el.scrollTop).toBe(0) + expect(v.scrollOffset).toBe(0) + expect(v.isScrollPending()).toBe(false) +}) + +test('cancelScroll ends a pending write with a notify', () => { + const onChange = vi.fn() + const { v, browser } = setupHandDrivenScroll({ onChange }) + browser.ignoreWrites = true + onChange.mockClear() + + v.scrollToOffset(1000) + expect(v.isScrollPending()).toBe(true) + v.cancelScroll() + expect(v.isScrollPending()).toBe(false) + expect(onChange).toHaveBeenCalledTimes(1) +}) + +test('a correction on a list that fits its viewport keeps the offset at 0, so a later command is not pending', () => { + // Three rows estimated at 100px in a 400px viewport, anchored to the end. + // The last row grows by 24px: the end stays pinned with a write to 24, + // which the browser clamps to 0 from an element already there, so no + // scroll event reports it and the sizer never grows past the viewport. + const { v, el } = setupHandDrivenScroll({ + count: 3, + estimateSize: () => 100, + anchorTo: 'end', + observeElementRect: (_inst, cb) => { + cb({ width: 400, height: 400 }) + return () => {} + }, + }) + el.clientHeight = 400 + el.scrollHeight = 400 + + v.resizeItem(2, 124) + expect(el.scrollTop).toBe(0) + // The consumer renders: the sizer is committed, still shorter than the viewport. + v._willUpdate() + expect(v.scrollOffset).toBe(0) + expect(v.isScrollPending()).toBe(false) + + // A command to the end writes 0, where the element already is. + v.scrollToIndex(2, { align: 'end' }) + expect(v.isScrollPending()).toBe(false) +})