feat(virtual-core): iOS momentum-safe scroll adjustments via CSS offset #1189
main fromrefs/pull/1189/head·opened On iOS WebKit, writing scrollTop during momentum scroll cancels the in-flight scroll. Instead of writing scrollTop, we now apply a negative marginTop on the container element to visually compensate for above-viewport size changes. The CSS offset is flushed to a real scrollTop write once momentum fully settles.
- Defer scroll adjustments during iOS touch and momentum phases using CSS offset (
marginTop/marginLeft) - Force-flush CSS offset before programmatic scroll operations (
scrollToIndex,scrollToOffset,scrollBy) - Compensate
scrollOffsetfor active CSS offset in range calculations - Guard against Safari elastic overscroll (rubber-band) during flush
- Clean up CSS offset on unmount
- Refine backward-scroll suppression: first measurements always adjust regardless of direction; re-measurements skip during backward scroll to avoid the
scrollTopcascade jank
🎯 Changes#
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
Improvements
- Smoother iOS Safari momentum scrolling via deferred CSS-based offset compensation and safer flush handling.
- Programmatic scrolling now forces resolution of any active iOS deferred offsets before performing scrolls.
Behavior
- Refined resize-scroll adjustments: always apply the first backward-scroll measurement, skip redundant re-measurement adjustments, and keep offset calculations consistent during deferral.
Documentation
- Chat/virtualization guidance now requires stable item keys and recommends disabling scroll anchoring.
Tests
- Updated tests to match refined forward/backward resize-adjustment behavior.
- 1
View your CI Pipeline Execution ↗ for commit dfe7dc9705e105a9df1e2d559590134d21a2b809
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 2m 36s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded 17s View ↗ 💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗
☁️ Nx Cloud last updated this comment at
2026-06-08 15:23:42UTCMore templates
- @tanstack/virtual-example-angular-dynamic
- @tanstack/virtual-example-angular-fixed
- @tanstack/virtual-example-angular-infinite-scroll
- @tanstack/virtual-example-angular-padding
- @tanstack/virtual-example-angular-smooth-scroll
- @tanstack/virtual-example-angular-sticky
- @tanstack/virtual-example-angular-table
- @tanstack/virtual-example-angular-variable
- @tanstack/virtual-example-angular-window
- tanstack-lit-virtual-example-dynamic
- tanstack-lit-virtual-example-fixed
- tanstack-react-virtual-example-chat
- tanstack-react-virtual-example-dynamic
- tanstack-react-virtual-example-fixed
- tanstack-react-virtual-example-infinite-scroll
- tanstack-react-virtual-example-padding
- tanstack-react-virtual-example-pretext
- tanstack-react-virtual-example-scroll-padding
- tanstack-react-virtual-example-smooth-scroll
- tanstack-react-virtual-example-sticky
- tanstack-react-virtual-example-table
- tanstack-react-virtual-example-variable
- tanstack-react-virtual-example-window
- tanstack-svelte-virtual-example-dynamic
- tanstack-svelte-virtual-example-fixed
- tanstack-svelte-virtual-example-infinite-scroll
- tanstack-svelte-virtual-example-smooth-scroll
- tanstack-svelte-virtual-example-sticky
- tanstack-svelte-virtual-example-table
- tanstack-vue-virtual-example-dynamic
- tanstack-vue-virtual-example-fixed
- tanstack-vue-virtual-example-infinite-scroll
- tanstack-vue-virtual-example-padding
- tanstack-vue-virtual-example-scroll-padding
- tanstack-vue-virtual-example-smooth-scroll
- tanstack-vue-virtual-example-sticky
- tanstack-vue-virtual-example-table
- tanstack-vue-virtual-example-variable
@tanstack/angular-virtual
npm i https://pkg.pr.new/@tanstack/angular-virtual@1189@tanstack/lit-virtual
npm i https://pkg.pr.new/@tanstack/lit-virtual@1189@tanstack/react-virtual
npm i https://pkg.pr.new/@tanstack/react-virtual@1189@tanstack/solid-virtual
npm i https://pkg.pr.new/@tanstack/solid-virtual@1189@tanstack/svelte-virtual
npm i https://pkg.pr.new/@tanstack/svelte-virtual@1189@tanstack/virtual-core
npm i https://pkg.pr.new/@tanstack/virtual-core@1189@tanstack/vue-virtual
npm i https://pkg.pr.new/@tanstack/vue-virtual@1189commit:
1e6c48d🧹 Nitpick comments (1)
packages/virtual-core/src/index.ts (1)
742-756: 💤 Low valueConsider edge case:
scrollOffsetis null when force-flushing.In
_forceFlushIosDeviation, ifscrollOffsetisnulland_iosDeferredAdjustmentis non-zero,rawBrowserScrollwould compute as a negative value (0 - adjustment). While this scenario is unlikely in practice (deviation is only accumulated after scroll events setscrollOffset), a defensive guard would prevent unexpected behavior if the invariant is violated.🛡️ Optional defensive guard
private _forceFlushIosDeviation = () => { if (this._iosDeferredAdjustment === 0) return + if (this.scrollOffset === null) { + // No scroll offset yet; just clear the deviation state + this._iosDeferredAdjustment = 0 + this._applyIosDeviation() + return + } const rawBrowserScroll = (this.scrollOffset ?? 0) - this._iosDeferredAdjustment🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/virtual-core/src/index.ts` around lines 742 - 756, If this._iosDeferredAdjustment is non-zero but this.scrollOffset is null, computing rawBrowserScroll yields an incorrect value; add a defensive guard at the top of _forceFlushIosDeviation to handle null scrollOffset (e.g. if this.scrollOffset == null then clear _iosDeferredAdjustment and call _applyIosDeviation and return) so you don't call _scrollToOffset with an invalid rawBrowserScroll; reference the method name _forceFlushIosDeviation and the fields scrollOffset, _iosDeferredAdjustment and the helpers _applyIosDeviation and _scrollToOffset when making the change.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/virtual-core/src/index.ts`: - Around line 742-756: If this._iosDeferredAdjustment is non-zero but this.scrollOffset is null, computing rawBrowserScroll yields an incorrect value; add a defensive guard at the top of _forceFlushIosDeviation to handle null scrollOffset (e.g. if this.scrollOffset == null then clear _iosDeferredAdjustment and call _applyIosDeviation and return) so you don't call _scrollToOffset with an invalid rawBrowserScroll; reference the method name _forceFlushIosDeviation and the fields scrollOffset, _iosDeferredAdjustment and the helpers _applyIosDeviation and _scrollToOffset when making the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e304110e-eb8c-4e87-8cfc-e899b4dc56ce📥 Commits
Reviewing files that changed from the base of the PR and between 932c3588a00c8fd31ebe239ea10295bb0e65aac1 and d9919d9afb1611ed6f5bc55134a278a76ff95714.
📒 Files selected for processing (5)
.changeset/ios-momentum-scroll.mddocs/chat.mdexamples/react/chat/src/index.csspackages/virtual-core/src/index.tspackages/virtual-core/tests/index.test.ts
piecyk changed the title
piecyk changed the title
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/chat.md`: - Line 58: Update the rationale to explain that useCallback is applied to getItemKey to stabilize its function reference so memoized values that include getItemKey (such as getMeasurements which depends on this.getMeasurementOptions()) don't treat measurement options as changed on every render; specifically mention wrapping getItemKey in useCallback to keep a stable reference, how passing a new getItemKey identity each render can invalidate getMeasurements/getMeasurementOptions memoization and cause unnecessary measurement rebuilds/cache invalidation, and note this keeps the virtualizer from triggering extra recomputation while clarifying that edge-key change detection itself is based on returned key values.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
77b40f76-f2ad-4786-be9a-e5b0ed7c5cee📥 Commits
Reviewing files that changed from the base of the PR and between d9919d9afb1611ed6f5bc55134a278a76ff95714 and dfe7dc9705e105a9df1e2d559590134d21a2b809.
📒 Files selected for processing (5)
.changeset/ios-momentum-scroll.mddocs/chat.mdexamples/react/chat/src/index.csspackages/virtual-core/src/index.tspackages/virtual-core/tests/index.test.ts
✅ Files skipped from review due to trivial changes (2)
- examples/react/chat/src/index.css
- .changeset/ios-momentum-scroll.md
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/virtual-core/src/index.ts
- packages/virtual-core/tests/index.test.ts
@@ -46,6 +49,10 @@4649 Stable keys are required for this to work:47504851 ```tsx49-getItemKey: (index) => messages[index]!.id52+getItemKey: React.useCallback(53+ (index: number) => messages[index]!.id,54+ [messages],55+),5056 ```515758+Wrap `getItemKey` in `useCallback` so the virtualizer sees a stable reference between renders. Without it, every render creates a new function and the virtualizer cannot detect which edge keys changed.⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check how getItemKey reference is used in edge detection and memoization # Look for getItemKey comparison logic rg -n -A5 -B5 'getItemKey.*!==|prevOptions.*getItemKey' packages/virtual-core/src/index.ts # Check for function reference equality checks on getItemKey rg -n -P 'getItemKey\s*!==.*getItemKey|prevOptions\.getItemKey\s*!==|options\.getItemKey\s*!==' packages/virtual-core/src/index.ts # Look for memoization or caching logic that depends on options rg -n -A3 'itemSizeCacheVersion|getMeasurements.*memo' packages/virtual-core/src/index.tsRepository: TanStack/virtual
Length of output: 2647
Fix the rationale for
useCallbackongetItemKeyThe virtualizer’s edge-key change detection is based on the returned key values from
getItemKey(0)/getItemKey(nextCount - 1), not on the function reference identity. WhatuseCallbackhelps with is memo/caching:getMeasurementsis memoized and includesthis.getMeasurementOptions()in its dependency, so passing a newgetItemKeyfunction each render can cause the measurement options to be treated as changed and trigger unnecessary recomputation/cache invalidation.Suggested rewrite:
Wrap
getItemKeyinuseCallbackso the virtualizer maintains a stablegetItemKeyreference. Without it, a new function identity can cause memoized measurement options to be recomputed, leading to unnecessary measurement rebuilds/cache invalidation. [minor fixes required]🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/chat.md` at line 58, Update the rationale to explain that useCallback is applied to getItemKey to stabilize its function reference so memoized values that include getItemKey (such as getMeasurements which depends on this.getMeasurementOptions()) don't treat measurement options as changed on every render; specifically mention wrapping getItemKey in useCallback to keep a stable reference, how passing a new getItemKey identity each render can invalidate getMeasurements/getMeasurementOptions memoization and cause unnecessary measurement rebuilds/cache invalidation, and note this keeps the virtualizer from triggering extra recomputation while clarifying that edge-key change detection itself is based on returned key values.Closing as superseded. The deferral approach that landed on
maincovers #884 without the CSSmarginTopoffset, and #1280 fixes its remaining over-reach (#1250) by gating the deferral on touch provenance rather thanisScrolling. The rubber-band guard and the force-flush-before-programmatic-scroll ideas from this branch both live on in that path.piecyk closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
56258643-ddf2-488c-b4d0-d37d48d9ed64📥 Commits
Reviewing files that changed from the base of the PR and between dfe7dc9705e105a9df1e2d559590134d21a2b809 and 1e6c48dd3f9a2968873c9ad9b42b196b6788db90.
📒 Files selected for processing (5)
.changeset/ios-momentum-scroll.mddocs/chat.mdexamples/react/chat/src/index.csspackages/virtual-core/src/index.tspackages/virtual-core/tests/index.test.ts✅ Files skipped from review due to trivial changes (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 Walkthrough
Walkthrough#
Defers visual scroll adjustments on iOS WebKit into a CSS margin offset during touch/momentum, folds the deferred delta into offset reads, flushes the compensation when safe or before programmatic scrolls, refines backward-scroll resize adjustment based on measurement cache, and updates tests, docs, example CSS, and a changeset.
Changes#
iOS Momentum Scroll Safety and Adjustment Refinement
packages/virtual-core/src/index.ts(690–717,742–763,970–979)_iosDeferredAdjustment,_applyIosCssOffset, and flush logic that computes raw browser scroll by subtracting the deferred delta, guards against Safari elastic overscroll when flushing, clears the deferred delta, removes CSS compensation, and ensures cleanup on unmount.packages/virtual-core/src/index.ts(831–838,929–940,1745–1798)_iosDeferredAdjustmentand applies the CSS offset immediately; folds the deferred delta into reported scroll offsets for range calculations; and_forceFlushIosCssOffsetis called beforescrollToOffset,scrollToIndex, andscrollBy.packages/virtual-core/src/index.ts(1579–1587)shouldAdjustScrollPositionOnItemSizeChangestill adjusts for above-viewport resizes, but during backward scroll it allows the first (uncached) measurement to adjust and skips adjustments for re-measurements when the item key exists initemSizeCache.packages/virtual-core/tests/index.test.ts(2069–2072,2090–2151,2186).changeset/ios-momentum-scroll.md(1–14),docs/chat.md(14–17,52–59,138–154),examples/react/chat/src/index.css(73)getItemKeyto be stable viaReact.useCallback, recommendoverflow-anchor: none, add an "iOS Safari" section describing the CSS margin workaround for momentum, update example CSS, and include a changeset note.Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs#
_iosDeferredAdjustment/anchor delta handling), overlapping with this PR.Suggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Warning
There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
packages/virtual-core/tests/index.test.ts
Parsing error: "parserOptions.project" has been provided for
@typescript-eslint/parser. The file was not found in any of the provided project(s): packages/virtual-core/tests/index.test.tsThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share