Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wild-chairs-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/virtual-core': patch
---

fix(virtual-core): scroll to last index properly
1 change: 1 addition & 0 deletions examples/react/dynamic/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ function RowVirtualizerDynamic() {
width: 400,
overflowY: 'auto',
contain: 'strict',
overflowAnchor: 'none',
}}
>
<div
Expand Down
31 changes: 29 additions & 2 deletions packages/virtual-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -972,11 +972,30 @@ export class Virtualizer<
)
}

private getMaxScrollOffset = () => {
if (!this.scrollElement) return 0

if ('scrollHeight' in this.scrollElement) {
// Element
return this.options.horizontal
? this.scrollElement.scrollWidth - this.scrollElement.clientWidth
: this.scrollElement.scrollHeight - this.scrollElement.clientHeight
} else {
// Window
const doc = this.scrollElement.document.documentElement
return this.options.horizontal
? doc.scrollWidth - this.scrollElement.innerWidth
: doc.scrollHeight - this.scrollElement.innerHeight
}
}

getOffsetForAlignment = (
toOffset: number,
align: ScrollAlignment,
itemSize = 0,
) => {
if (!this.scrollElement) return 0

const size = this.getSize()
const scrollOffset = this.getScrollOffset()

Expand All @@ -992,7 +1011,7 @@ export class Virtualizer<
toOffset -= size
}

const maxOffset = this.getTotalSize() + this.options.scrollMargin - size
const maxOffset = this.getMaxScrollOffset()

return Math.max(Math.min(maxOffset, toOffset), 0)
}
Expand All @@ -1014,10 +1033,18 @@ export class Virtualizer<
} else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {
align = 'start'
} else {
return [scrollOffset, align] as const
// Item is already visible, return current position with concrete alignment
// to avoid infinite retry loop if measurements change
return [scrollOffset, 'start'] as const
}
}

// For the last item with 'end' alignment, use browser's actual max scroll
// to account for borders/padding that aren't in our measurements
if (align === 'end' && index === this.options.count - 1) {
return [this.getMaxScrollOffset(), align] as const
}

const toOffset =
align === 'end'
? item.end + this.options.scrollPaddingEnd
Expand Down
Loading