feat(core): implement built-in scroll-scaling for large lists #1172
main fromrefs/pull/1172/head·opened 🎯 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
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/virtual-core/tests/index.test.ts (1)
2660-2677: ⚡ Quick winThe
scale === 1zero-overhead test doesn’t verify object identity yet.This test currently checks size/scale only, so it won’t fail if
getVirtualItems()starts cloning underscale === 1. Assert reference equality between returned items andgetMeasurements()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.mddocs/api/virtualizer.mdpackages/virtual-core/src/index.tspackages/virtual-core/tests/index.test.ts
packages/virtual-core/src/index.ts lines 429 to 435Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -378,3 +382,9 @@378382 scrollOffset: number | null = null379383 scrollDirection: ScrollDirection | null = null380384 private scrollAdjustments = 0385+386+ private getScale = (): number => {387+ const virtualTotal = this.getTotalVirtualSize()388+ const max = this.options.maxScrollSize389+ return virtualTotal > max ? virtualTotal / max : 1390+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Guard
maxScrollSizeagainst invalid values to avoid broken scale math.Line 388/389 currently allows
0, negative, orNaN, which can produceInfinity/negative scale and breakgetTotalSize(), offset conversion, and anchoring logic. Add a validation guard before division.Suggested fix
private getScale = (): number => { const virtualTotal = this.getTotalVirtualSize() const max = this.options.maxScrollSize + // Invalid values disable scaling to keep math stable. + if (!Number.isFinite(max) || max <= 0) return 1 return virtualTotal > max ? virtualTotal / max : 1 }🤖 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 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.✅ Addressed in commit 431a45e
Hi @tannerlinsley, When you have a moment, could you please take a look at my PR? I have raised this PR to fix #616
@DivyamUp14 Thanks for the PR! We’ll take a look as soon as we can.
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 liftRebase stored offsets when the scale factor changes.
scrollOffsetis stored in virtual units, butscaleis derived from mutable totals/options. Ifcount, measured sizes, ormaxScrollSizechange enough to move the factor from1toN(or between two scaled values), the DOM stays at the same physical scroll position whilethis.scrollOffsetstays 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 liftKeep viewport-length math in virtual space.
After this callback converts
offsetinto virtual coordinates, any later comparison against viewport length also needs to be virtual. Right nowgetSize()still returns physical pixels, socalculateRange(),getOffsetForAlignment(),scrollToEnd(), and the smooth-scroll distance check all undercount the visible window byscalewhen 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 smallgetVirtualSize()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 winClarify "real (unscaled) size" terminology for consistency.
The term "real (unscaled) size" is ambiguous. Since the
maxScrollSizedocumentation (lines 298, 642) establishes "virtual" vs "physical" terminology, this should use "virtual size" instead for consistency.The formula
item.size * virtualizer.scalerecovers 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 winAvoid widening
Virtualizer's public surface for this cache lookup.This optimization only needs internal access, but dropping
privatehere makesitemSizeCachepart of the exportedVirtualizertype. 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.mdpackages/virtual-core/src/index.tspackages/virtual-core/tests/index.test.ts
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?
@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()dividesstart,endandsizebyscale, 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 withsize: 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 withmeasureElementthe 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 whilescrollOffsetis virtual (socalculateRange, alignment andscrollToEndare off), andscrollOffsetisn't rebased whenscalechanges after measurements or acountchange.A few smaller things:
scrollMarginends up multiplied byscale, 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 itemstart/sizemean. 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.tsgot split into topic files in #1328, and the iOS scroll correction work touched the same_scrollToOffsetand scroll event paths.@tazalov still on the table, just not in this shape yet 🙂
DivyamUp14(GitHub profile, opens in a new tab) linked this to fix #616
Sign in to join this conversation.
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_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
Implements scroll-range compression in Virtualizer: adds
maxScrollSize(default 33_000_000) and publicscale; 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
packages/virtual-core/src/index.tsmaxScrollSize?: number(default33_000_000), implements scale computation, and exposes the publicscalegetter.packages/virtual-core/src/index.tsscrollOffset/direction), reconciliation uses a scale-aware tolerance, and_scrollToOffset()downscales virtual targets to physical values and stores intended physical offsets for subpixel consistency.packages/virtual-core/src/index.tsgetTotalVirtualSize();getTotalSize()returns capped physical size (virtual / scale);getVirtualItems()returns original refs whenscale === 1or scaled copies (start/size/end ÷ scale) when active;getMaxScrollOffset()maps DOM max scroll into virtual space.packages/virtual-core/tests/index.test.tsmaxScrollSize,getVirtualItems()semantics and identity behavior, observer offset upscaling,_scrollToOffsetdownscaling, and resize anchoring under scaling.docs/api/virtualizer.md,.changeset/scroll-scaling.mdmaxScrollSizeoption and semantics, clarifiesgetTotalSize()andscrollOffsetbehavior under scaling, documentsscaleusage, and updates release notes.Sequence Diagram(s):
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#616), explains the core problem and solution, and includes completed checklist items confirming testing and changeset generation.#616by 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.✨ Finishing Touches
🧪 Generate unit tests (beta)
Warning
Review ran into problems#
🔥 Problems
Git: Failed to clone repository. Please run the
@coderabbitai full reviewcommand to re-trigger a full review. If the issue persists, setpath_filtersto 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