Skip to content
Source
Sign inSign up
TanStack/virtual

feat(core): implement built-in scroll-scaling for large lists #1172

OpenDivyamUp14(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/1172/headopened

🎯 Changes

Fixes #616

Introduced native scroll-scaling in virtual-core to compress coordinates and bypass the browser's maximum scroll height limitation (~33.5 million pixels) for extremely large lists.

✅ 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

  • New Features

    • Added scroll-scaling for very large virtualized lists
    • New option: maxScrollSize (default 33,000,000; Infinity disables scaling)
    • New property: scale exposes the active compression factor; scroll APIs and anchoring behave transparently during scaling
  • Documentation

    • Clarified capped physical container sizing, virtual vs. physical coordinate semantics, and how to recover real item sizes
  • Tests

    • Added tests for scaling activation, coordinate/reporting behavior, and resize/anchoring under scaling
  • Notes

    • No runtime overhead when scaling is inactive

Review Change Stack

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 Walkthrough

      Walkthrough

      Implements scroll-range compression in Virtualizer: adds maxScrollSize (default 33_000_000) and public scale; converts between physical (DOM) and virtual coordinates for scroll reads/writes, makes reconciliation scale-aware, returns scaled consumer item coordinates when active, updates total-size reporting, and adds tests and docs.

      Changes

      Scroll-Range Scaling Feature

      Layer / File(s)Summary
      Configuration & scale computation
      packages/virtual-core/src/index.ts
      Adds maxScrollSize?: number (default 33_000_000), implements scale computation, and exposes the public scale getter.
      Scroll reading, reconciliation, and DOM writes
      packages/virtual-core/src/index.ts
      Browser read-back offsets are treated as physical; Virtualizer converts to virtual coords for internal state (scrollOffset/direction), reconciliation uses a scale-aware tolerance, and _scrollToOffset() downscales virtual targets to physical values and stores intended physical offsets for subpixel consistency.
      Item geometry, totals, and max-offset mapping
      packages/virtual-core/src/index.ts
      Adds getTotalVirtualSize(); getTotalSize() returns capped physical size (virtual / scale); getVirtualItems() returns original refs when scale === 1 or scaled copies (start/size/end ÷ scale) when active; getMaxScrollOffset() maps DOM max scroll into virtual space.
      Comprehensive test coverage
      packages/virtual-core/tests/index.test.ts
      Adds Vitest cases for scale activation/disabling, custom maxScrollSize, getVirtualItems() semantics and identity behavior, observer offset upscaling, _scrollToOffset downscaling, and resize anchoring under scaling.
      API documentation and release notes
      docs/api/virtualizer.md, .changeset/scroll-scaling.md
      Documents maxScrollSize option and semantics, clarifies getTotalSize() and scrollOffset behavior under scaling, documents scale usage, and updates release notes.

      Sequence Diagram(s):

      sequenceDiagram
        participant Browser
        participant Virtualizer
        participant ScrollFn
        Browser->>Virtualizer: physical scroll event (physicalOffset)
        Virtualizer->>Virtualizer: compute scale, virtualOffset = physicalOffset * scale
        Virtualizer->>Virtualizer: reconcile using scale-aware tolerance
        Virtualizer->>ScrollFn: call _scrollToOffset with physicalOffset = virtualOffset / scale
        ScrollFn->>Browser: perform DOM scroll

      🎯 4 (Complex) | ⏱️ ~45 minutes

      Possibly related PRs

      • TanStack/virtual#1168: Modifies scroll reconciliation and offset handling that interacts with the scaling-aware reconciliation logic.

      Suggested reviewers

      • tannerlinsley
      • piecyk

      "A rabbit hops through bounds so tall, Where pixels once would break and fall, Now scale makes long lists fit the view, Tiny steps become whole and true, Hooray — the scroll keeps going through! 🐇"

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely summarizes the main feature: built-in scroll-scaling for large lists, which is the primary change across all modified files.
      Description check✅ PassedThe description follows the template structure, references the linked issue (#616), explains the core problem and solution, and includes completed checklist items confirming testing and changeset generation.
      Linked Issues check✅ PassedThe PR fully addresses issue #616 by implementing coordinate compression/scroll-scaling to handle lists exceeding the browser's ~33.5 million pixel CSS height limit, enabling scrolling through extremely large lists.
      Out of Scope Changes check✅ PassedAll changes are directly scoped to scroll-scaling implementation: core logic, documentation, changeset note, and comprehensive tests—no unrelated modifications detected.
      Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Warning

      Review ran into problems

      🔥 Problems

      Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


      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 and usage tips.
    2. Actionable comments posted: 1

      🧹 Nitpick comments (1)
      packages/virtual-core/tests/index.test.ts (1)

      2660-2677: ⚡ Quick win

      The scale === 1 zero-overhead test doesn’t verify object identity yet.

      This test currently checks size/scale only, so it won’t fail if getVirtualItems() starts cloning under scale === 1. Assert reference equality between returned items and getMeasurements() entries for visible indexes.

      🤖 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/tests/index.test.ts` around lines 2660 - 2677, The test
      currently only checks scale and total size but doesn't assert object identity;
      update it to ensure getVirtualItems returns actual items (provide a non-null
      scroll element in the Virtualizer config, e.g., a dummy element) when scale ===
      1, call virtualizer.getMeasurements() and virtualizer.getVirtualItems(), then
      for each virtual item assert strict reference equality with the corresponding
      measurements entry (match by item.index) so the test fails if getVirtualItems
      clones objects under scale === 1; keep existing getTotalSize and scale
      assertions.
      🤖 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 `@packages/virtual-core/src/index.ts`:
      - Around line 386-390: The getScale function can divide by invalid
      options.maxScrollSize (0, negative, NaN, Infinity) causing invalid scale values;
      update getScale to validate maxScrollSize before dividing (use Number.isFinite
      and maxScrollSize > 0) and treat any invalid value as a safe fallback (e.g., 1
      or a small positive clamp), keeping the existing behavior of returning
      virtualTotal / max when valid; change references in getScale (and callers like
      getTotalSize/offset conversion/anchoring logic) to rely on this validated result
      so downstream math never sees Infinity/NaN/negative scale.
      
      ---
      
      Nitpick comments:
      In `@packages/virtual-core/tests/index.test.ts`:
      - Around line 2660-2677: The test currently only checks scale and total size but
      doesn't assert object identity; update it to ensure getVirtualItems returns
      actual items (provide a non-null scroll element in the Virtualizer config, e.g.,
      a dummy element) when scale === 1, call virtualizer.getMeasurements() and
      virtualizer.getVirtualItems(), then for each virtual item assert strict
      reference equality with the corresponding measurements entry (match by
      item.index) so the test fails if getVirtualItems clones objects under scale ===
      1; keep existing getTotalSize and scale assertions.
      🪄 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: 2a8f8b85-a408-461b-b026-09188d95fa4e

      📥 Commits

      Reviewing files that changed from the base of the PR and between 949180be8adf66ea8428b326db72ebad42d5b4c3 and bbfc4bfd8604121090a83eefe8a991d5fbebf326.

      📒 Files selected for processing (4)
      • .changeset/scroll-scaling.md
      • docs/api/virtualizer.md
      • packages/virtual-core/src/index.ts
      • packages/virtual-core/tests/index.test.ts
    3. Hi @tannerlinsley, When you have a moment, could you please take a look at my PR? I have raised this PR to fix #616

    4. @DivyamUp14 Thanks for the PR! We’ll take a look as soon as we can.

    5. Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (2)
      packages/virtual-core/src/index.ts (2)

      429-435: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

      Rebase stored offsets when the scale factor changes.

      scrollOffset is stored in virtual units, but scale is derived from mutable totals/options. If count, measured sizes, or maxScrollSize change enough to move the factor from 1 to N (or between two scaled values), the DOM stays at the same physical scroll position while this.scrollOffset stays in the old virtual coordinate system until another scroll event arrives. The very next render can therefore jump to the wrong range or blank space. Please re-read the current physical scroll position, or rebase the stored offset, whenever the scale changes before notifying consumers.

      Also applies to: 641-651, 1569-1578

      🤖 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 429 - 435, getScale can
      change when totals or options mutate, but this.scrollOffset is stored in old
      virtual units and must be rebased when scale changes; detect when getScale()
      returns a different value than the previously-used scale, read the current
      physical scroll position from the same DOM source you use for scrolling (the
      container's scrollTop/scrollLeft), convert that physical position into the new
      virtual units using the new scale and virtual/physical size math (using
      getTotalVirtualSize() and options.maxScrollSize), update this.scrollOffset to
      the rebased value, and only then notify consumers or render; apply this same
      rebase logic in the other scale-sensitive places identified (the scroll
      handling/notification paths around getScale usage) so stored offsets are
      consistent across scale transitions.

      810-815: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

      Keep viewport-length math in virtual space.

      After this callback converts offset into virtual coordinates, any later comparison against viewport length also needs to be virtual. Right now getSize() still returns physical pixels, so calculateRange(), getOffsetForAlignment(), scrollToEnd(), and the smooth-scroll distance check all undercount the visible window by scale when scaling is active. That will render too few items and miscompute alignments/end offsets for the large-list case this feature is meant to fix. A small getVirtualSize() helper would make these call sites consistent.

      🤖 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 810 - 815, The code converts
      a physical scroll offset into virtual coordinates via getScale()/virtualOffset
      but still uses getSize() (physical pixels) elsewhere, causing viewport-length
      math to be undercounted when scaling is active; add a small helper
      getVirtualSize() that returns this.getSize() * this.getScale() (or equivalent
      virtual-space value) and replace uses of getSize() in calculateRange,
      getOffsetForAlignment, scrollToEnd, and the smooth-scroll distance check (and
      any alignment math that compares to viewport length) so all viewport/length
      comparisons occur in virtual space, ensuring consistent rendering and correct
      end/align calculations.
      🧹 Nitpick comments (2)
      docs/api/virtualizer.md (1)

      650-652: ⚡ Quick win

      Clarify "real (unscaled) size" terminology for consistency.

      The term "real (unscaled) size" is ambiguous. Since the maxScrollSize documentation (lines 298, 642) establishes "virtual" vs "physical" terminology, this should use "virtual size" instead for consistency.

      The formula item.size * virtualizer.scale recovers the virtual (pre-compression) size from the physical (scaled-down) size, so "virtual size" would be clearer.

      📝 Suggested rewording
      -You can use this to recover the real (unscaled) size of an item: `realSize = item.size * virtualizer.scale`.
      +You can use this to recover the virtual (unscaled) size of an item: `virtualSize = item.size * virtualizer.scale`.
      🤖 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/api/virtualizer.md` around lines 650 - 652, Update the wording that
      currently uses "real (unscaled) size" to consistently use "virtual size" in the
      virtualizer docs: change the explanatory sentence to state that the formula
      `virtualSize = item.size * virtualizer.scale` recovers the virtual
      (pre-compression) size from the physical (scaled-down) size, and ensure the
      description of `virtualizer.scale` aligns with the existing "virtual" vs
      "physical" terminology used around `maxScrollSize`; reference
      `virtualizer.scale` and `item.size` to locate the sentence to modify.
      packages/virtual-core/src/index.ts (1)

      245-253: ⚡ Quick win

      Avoid widening Virtualizer's public surface for this cache lookup.

      This optimization only needs internal access, but dropping private here makes itemSizeCache part of the exported Virtualizer type. I'd keep the field private and route the fast path through a private helper/getter instead, so this doesn't become an accidental API commitment.

      Also applies to: 415-415

      🤖 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 245 - 253, The code is
      directly accessing instance.itemSizeCache, widening Virtualizer's public API;
      instead, keep itemSizeCache private and add a private Virtualizer helper (e.g.,
      a method like getCachedSize(index) or a private getter on the Virtualizer
      instance) that performs the cache lookup and falls back to options.estimateSize.
      Replace the direct access in this fast-path (the block using
      instance.options.useCachedMeasurements, instance.indexFromElement,
      instance.options.getItemKey, and instance.options.estimateSize) to call that
      private helper so the cache remains internal and the Virtualizer public surface
      is unchanged.
      🤖 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.
      
      Outside diff comments:
      In `@packages/virtual-core/src/index.ts`:
      - Around line 429-435: getScale can change when totals or options mutate, but
      this.scrollOffset is stored in old virtual units and must be rebased when scale
      changes; detect when getScale() returns a different value than the
      previously-used scale, read the current physical scroll position from the same
      DOM source you use for scrolling (the container's scrollTop/scrollLeft), convert
      that physical position into the new virtual units using the new scale and
      virtual/physical size math (using getTotalVirtualSize() and
      options.maxScrollSize), update this.scrollOffset to the rebased value, and only
      then notify consumers or render; apply this same rebase logic in the other
      scale-sensitive places identified (the scroll handling/notification paths around
      getScale usage) so stored offsets are consistent across scale transitions.
      - Around line 810-815: The code converts a physical scroll offset into virtual
      coordinates via getScale()/virtualOffset but still uses getSize() (physical
      pixels) elsewhere, causing viewport-length math to be undercounted when scaling
      is active; add a small helper getVirtualSize() that returns this.getSize() *
      this.getScale() (or equivalent virtual-space value) and replace uses of
      getSize() in calculateRange, getOffsetForAlignment, scrollToEnd, and the
      smooth-scroll distance check (and any alignment math that compares to viewport
      length) so all viewport/length comparisons occur in virtual space, ensuring
      consistent rendering and correct end/align calculations.
      
      ---
      
      Nitpick comments:
      In `@docs/api/virtualizer.md`:
      - Around line 650-652: Update the wording that currently uses "real (unscaled)
      size" to consistently use "virtual size" in the virtualizer docs: change the
      explanatory sentence to state that the formula `virtualSize = item.size *
      virtualizer.scale` recovers the virtual (pre-compression) size from the physical
      (scaled-down) size, and ensure the description of `virtualizer.scale` aligns
      with the existing "virtual" vs "physical" terminology used around
      `maxScrollSize`; reference `virtualizer.scale` and `item.size` to locate the
      sentence to modify.
      
      In `@packages/virtual-core/src/index.ts`:
      - Around line 245-253: The code is directly accessing instance.itemSizeCache,
      widening Virtualizer's public API; instead, keep itemSizeCache private and add a
      private Virtualizer helper (e.g., a method like getCachedSize(index) or a
      private getter on the Virtualizer instance) that performs the cache lookup and
      falls back to options.estimateSize. Replace the direct access in this fast-path
      (the block using instance.options.useCachedMeasurements,
      instance.indexFromElement, instance.options.getItemKey, and
      instance.options.estimateSize) to call that private helper so the cache remains
      internal and the Virtualizer public surface is unchanged.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 5976dcb4-8cb4-40fb-8b6e-eefead37599a

      📥 Commits

      Reviewing files that changed from the base of the PR and between db4a1a72a25d2a779f6a858d63f2595a3eae57b7 and b6bb502270c2f67f6f29d538b45e50da01f95a82.

      📒 Files selected for processing (3)
      • docs/api/virtualizer.md
      • packages/virtual-core/src/index.ts
      • packages/virtual-core/tests/index.test.ts
    6. Hello, I’ve been looking forward to this change for a while. Are there any updates on adding this feature? Or has the decision been made not to implement it?

    7. @DivyamUp14 thanks for taking this on, and sorry it sat for so long. Gave it a proper look today and I think the approach needs a rethink before we can merge it.

      The main problem is that getVirtualItems() divides start, end and size by scale, so the items themselves get shrunk, not just the scroll range. Quick probe on this branch: 100 items × 50px, maxScrollSize: 2000 (scale 2.5), 500px viewport, scrollTop 400. Every item comes back with size: 20, and they only cover 400 to 600 of the 400 to 900 viewport, so most of the screen is empty. If you render them at their real 50px height they overlap, and with measureElement the shrunk size gets measured and written back into the cache.

      What usually works here is to compress only the scroll offset and keep the visible items at their real sizes, shifted by one shared delta, something like physicalStart = virtualStart - (virtualOffset - physicalOffset). Whatever the approach, the two things CodeRabbit flagged outside the diff still need fixing: getSize() is still physical while scrollOffset is virtual (so calculateRange, alignment and scrollToEnd are off), and scrollOffset isn't rebased when scale changes after measurements or a count change.

      A few smaller things:

      • scrollMargin ends up multiplied by scale, so window virtualizers with a header above the list get wrong offsets.
      • imho this should be opt-in for now. 33M as the default turns it on silently for everyone and changes what getTotalSize() and item start/size mean. It also doesn't help Firefox, which caps at around 17.9M.
      • The tests cover the scale math, but nothing checks that the visible items fill the viewport without overlapping. That test would have caught the issue above.

      Also, it needs a rebase, it conflicts with main now. tests/index.test.ts got split into topic files in #1328, and the iOS scroll correction work touched the same _scrollToOffset and scroll event paths.

      @tazalov still on the table, just not in this shape yet 🙂

Sign in to join this conversation.