Skip to content
Source
Sign inSign up
TanStack/virtual

refactor(virtual-core): describe an in-flight scroll command by one phase #1311

Mergedpiecykmerged 3 commits intomain fromrefs/pull/1311/headmerged by piecyk

piecykcommented

Stacked on #1310 (itself on #1309). This branch contains both of their commits; review only the last commit, refactor(virtual-core): describe an in-flight scroll command by one phase. I'll rebase and mark it ready once they merge.

🎯 Changes

No behaviour change. ScrollState described an in-flight scroll command's lifecycle through three fields: behavior (switched from 'smooth' to 'auto' by reconcile for the final approach, which also re-enables size compensation), hasReachedTarget, and startedSmooth (added in #1310 because WebKit keeps delivering smooth-animation events after that switch). Each fix in this area had added one. Their combinations encode four situations the code tells apart, so they become one field:

 type ScrollState = {
   index, align, toEnd, startedAt, lastTargetOffset, stableFrames,
-  behavior: ScrollBehavior
-  hasReachedTarget: boolean
-  startedSmooth: boolean
+  phase: 'smooth' | 'smoothLanded' | 'smoothFinishing' | 'instant'
 }
smooth           a smooth animation is travelling to the target
smoothLanded     a smooth scroll is at its target, waiting to retire
smoothFinishing  a smooth scroll switched to instant writes for the final
                 approach; its animation can still report positions
instant          instant writes

Two helpers replace the flag combinations:

HelperUsed byEquivalent to before
isSmoothScroll (smooth | smoothLanded)size compensation, the prepend anchor sync, shouldMeasureDuringScrollbehavior === 'smooth'
isAnimating (smooth | smoothFinishing)the scroll handler: a non-read-back event may not be the user!hasReachedTarget && startedSmooth

reconcileScroll moves the phase where it used to flip the flags: at the target, smooth → smoothLanded and smoothFinishing → instant; on a retarget, a far smooth retarget → smooth, otherwise smooth → smoothFinishing and smoothLanded → instant.

Evidence

  • Differential check against the parent: 3,000 random event sequences (auto, smooth and instant commands, animation steps, resizes, drags, frames, cancelScroll, prepends with anchorTo: 'end', the 5s safety valve, iOS UA, lanes, scrollPaddingStart) produce identical traces before and after: writes, scrollTop, tracked offset, scroll state, and shouldMeasureDuringScroll for sample rows at every step. Breaking any single transition or helper on purpose is caught. A separate independent probe (600 seeds, including useAnimationFrameWithResizeObserver and lanes: 2) also found zero mismatches and exercised every transition.
  • virtual-core: 233 passed + 5 expected failures; types and lint clean. One test that matched scrollState on behavior: 'smooth' now matches phase: 'smooth'.
  • react-virtual cached-measurements, smooth-scroll, smooth-prepend, scroll in Chromium, Firefox and WebKit; react e2e 39/39; Marko chat "does NOT follow appends while reading history" 15/15 interleaved against the parent; pnpm run test:pr green.
  • The ios-deferral diagnostic page (#1308) logged scrollState.hasReachedTarget; it now logs phase.

Merge Danger

Door: two-way. Private state only; no public API or option changes.

Blast Radius: none intended. Every reader of the removed fields is in virtual-core/src and maps onto a phase helper; no adapter, test or doc reads them.

Part of the plan in #1307 (step 2a), ahead of reworking the iOS deferral state.

✅ 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).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved scrolling when content measurements change during an ongoing smooth scroll. Large shifts in the destination continue to use smooth movement, while smaller adjustments settle immediately.
    • Scrolling now accounts for animation events throughout the transition, helping maintain consistent positioning as items are added or measured and reducing abrupt interruptions.
    • Scroll behavior now transitions more reliably between smooth movement and immediate adjustments, including when a scroll target is already reached.
    1. 🦋 Changeset detected

      Latest commit: a8561b3a9f35d58920931775c385c69dcf13e58d

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 9 packages
      NameType
      @tanstack/virtual-corePatch
      @tanstack/angular-virtualPatch
      @tanstack/lit-virtualPatch
      @tanstack/marko-virtualPatch
      @tanstack/react-virtualPatch
      @tanstack/solid-virtualPatch
      @tanstack/svelte-virtualPatch
      @tanstack/vue-virtualPatch
      @tanstack/virtual-benchmarksPatch

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: defaults
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: c2e96db2-907b-463d-84ed-d33e69ac8226

      📥 Commits

      Reviewing files that changed from the base of the PR and between c67f8d634400b8faa8e15a4e097baa7a19465839 and a8561b3a9f35d58920931775c385c69dcf13e58d.


      📒 Files selected for processing (1)
      • .changeset/scroll-state-phase.md

      Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.



      📝 Walkthrough
      📝 Walkthrough

      Walkthrough

      The virtualizer replaces separate scroll behavior and target-arrival fields with a phase lifecycle. Scroll commands initialize phases, and reconciliation and retargeting update them. Scroll-event detection, anchor synchronization, measurement, and scroll compensation use phase checks.

      Changes

      Scroll Phase Lifecycle

      Layer / File(s)Summary
      Define phases and initialize scroll commands
      packages/virtual-core/src/index.ts
      A ScrollPhase field and helpers replace separate behavior and arrival flags. Scroll commands initialize phases based on behavior and target arrival.
      Advance phases during scrolling
      packages/virtual-core/src/index.ts
      Reconciliation and retargeting update phases based on target arrival and distance. External-scroll detection uses the new phases.
      Use phases in measurement and validation
      packages/virtual-core/src/index.ts, packages/virtual-core/tests/index.test.ts, packages/react-virtual/e2e/app/ios-deferral/main.tsx, .changeset/scroll-state-phase.md
      Anchor synchronization, measurement gating, and scroll compensation use phase checks. The test assertion and iOS deferral log record the phase. A changeset requests a patch release.

      Priority: ⬇️ Low

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Refactor


      Merge Risk: ⚪ Minimal · up to a8561

      The phase-based scroll refactor is reported to preserve behavior; no concrete merge-blocking risk is identified, so it appears ready after normal checks.

      Pre-merge checks | Passed 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Docstring CoveragePassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3…
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Title checkPassedThe title clearly and concisely identifies the main change: replacing multiple in-flight scroll state fields with one phase.
      Description checkPassedThe description follows the required template. It explains the change and motivation, marks both checklist items complete, and records the generated changeset for published code. It also provides deta…

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Thanks 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

      Comment `@coderabbitai help` to get the list of available commands.
    3. View your CI Pipeline Execution ↗ for commit c67f8d634400b8faa8e15a4e097baa7a19465839

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded4m 17sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded20sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-10-12 11:04:44 UTC

    4. More templates

      @tanstack/angular-virtual

      npm i https://pkg.pr.new/@tanstack/angular-virtual@1311

      @tanstack/lit-virtual

      npm i https://pkg.pr.new/@tanstack/lit-virtual@1311

      @tanstack/marko-virtual

      npm i https://pkg.pr.new/@tanstack/marko-virtual@1311

      @tanstack/react-virtual

      npm i https://pkg.pr.new/@tanstack/react-virtual@1311

      @tanstack/solid-virtual

      npm i https://pkg.pr.new/@tanstack/solid-virtual@1311

      @tanstack/svelte-virtual

      npm i https://pkg.pr.new/@tanstack/svelte-virtual@1311

      @tanstack/virtual-core

      npm i https://pkg.pr.new/@tanstack/virtual-core@1311

      @tanstack/vue-virtual

      npm i https://pkg.pr.new/@tanstack/vue-virtual@1311

      commit: a8561b3

    5. Reviewed the last commit at 113f9b4d against its parent 2b7ac8b4. I could not find a behaviour difference.

      Differential run, written independently of yours. Same seeded event script on both revisions, full trace compared at every step: every scrollToFn call, scrollTop, scrollOffset, scrollAdjustments, isScrolling, direction, scroll state fields, _intendedScrollOffset, _lastWrittenOffset, _iosDeferredAdjustment, _clampedAdjustment, shouldMeasureDuringScroll for sample rows, range and total size.

      SeedsTrace stepsMismatches
      full traces5,000340,6540
      trace hashes50,0003,408,1890

      Events: all four scroll commands with auto / smooth / instant, read-backs delivered, rounded, clamped and dropped, animation steps including stale ones after the switch to instant writes, user scrolls, resizes, frames, clock jumps past the safety valve, cancelScroll, prepends and appends with and without anchorTo: 'end', touch events with and without an iOS UA, lanes, gap, paddings, scrollMargin, rAF-deferred ResizeObserver, a custom adjust predicate.

      Coverage. All four phases and every transition were reached (5,000-seed run: smooth→smoothLanded 2,283, smooth→smoothFinishing 867, smoothFinishing→instant 217, smoothLanded→instant 130, smoothLanded→smooth 103). The parent's (behavior, hasReachedTarget, startedSmooth) mapped onto a phase equals phase at every step. The only two flag combinations never seen are smooth behavior with startedSmooth false, which the old code cannot reach either.

      Sensitivity. Each of these, applied alone to this branch, is caught:

      MutationMismatching seeds / 5,000
      isAnimating true only for smooth253
      isSmoothScroll true only for smooth2,267
      no smoothFinishing → instant at the target21
      retarget sends smoothLanded to smoothFinishing34
      initialScrollPhase ignores atTarget369

      Static. No reader of behavior, hasReachedTarget or startedSmooth on the scroll state is left anywhere in the repo; tsc and eslint ./src are clean. The ios-deferral page logging phase is fine by me.

      E2E. Nothing that separates it from #1310. One WebKit failure of scroll.spec.ts › scrolls to last item (received 14, expected < 1.01) did not reproduce in 30 more repetitions (30/30 here, 30/30 on main).

      Limits: the differential run uses a simulated scroll element, and it did not exercise horizontal, a window scroller, isRtl or more than two lanes.

      Nit: the changeset is a patch with a changelog line for a change with no behaviour change. Up to you whether that entry is wanted.

    6. piecyk merged thiscb510cb

    7. piecyk closed this

Sign in to join this conversation.