[bug]: MessageScroller: an animated Home/PageUp from the end re-arms follow-bottom and gets pulled back
Describe the bug
With autoScroll on and the reader at the end, pressing Home or PageUp in the viewport can land back at the end, or well short of where the key should have taken the reader. The key scrolls, follow-bottom re-engages partway through the animation, and the next row resize pulls the viewport back to the end.
How often. It depends on timing, because the trigger is a Chromium keyboard-scroll animation whose first frame moves less than scrollEdgeThreshold:
- While the list is still settling after mount (pressing the key right after the transcript opens at the end): every time in headless Chromium, 40 out of 40 presses for both Home and PageUp in the minimal repro below.
- After the list has settled: rare. 0 out of 200 presses per key in the minimal repro (100–1500ms settle, headed and headless, with and without 4× CPU throttling). In our app, which has richer rows (avatars, metadata, varied heights), about 1–3% of presses in headed Chromium (1/30 for Home, 1/30 for PageUp), and once in two PageUp presses in a desktop Chromium browser pane.
- Mouse wheel and ArrowUp: never, in any of our runs. Their first frame moves further than 8px, so the first
scrollevent is already outside the threshold.
It gets worse as a transcript gets longer, because more of the rows the scroll passes are content-visibility placeholders that resize when they're laid out. The registry item applies exactly that ([contain-intrinsic-size:auto_10rem] [content-visibility:auto]), so the default setup is exposed.
What happens
Traced by instrumenting the built package (0.3.1) in Chromium:
- The keydown releases follow.
handleKeyDowncallsuserScrollIntent, which sets the mode tofree-scrolling. - Chromium animates the keyboard scroll. Sometimes the first frame moves only 1–2px, so the first
scrollevent lands insidescrollEdgeThreshold(DEFAULT_SCROLL_EDGE_THRESHOLD = 8). - The commit re-arms follow.
reconcileFollowModeseesautoScrollRef.current && !scrollable.endand sets the mode back tofollowing-bottom. The arm branch doesn't look atscrolledUp, so a scroll that is moving away from the end re-arms as long as it is still within 8px. - A row resize scrolls to the end. As the animation brings
content-visibilityrows into view, they resize from the 10rem estimate to their real height. Each delivery runshandleResize, which seesfollowing-bottomand callsscrollToEnd. - The release gets blocked.
scrollToEndscrolls withautoscrolling: true, which re-arms the 180msautoscrollingflag (AUTOSCROLLING_CLEAR_DELAY). The release branch ofreconcileFollowModerequires!autoscrollingRef.current, so the upward scroll events that follow can't release follow. Every further resize repeats step 4 and re-arms the flag again. - When the animation finishes, the viewport is at the end. Sometimes it is a few hundred pixels short of it, if the last resize came before the last animation frame.
Proposed fix
Don't re-arm follow while the reader is moving away from the end, and learn the direction at the gesture, before the first frame:
- Track which way the last scroll went, and skip the arm when it went up. Measure the direction as a change in distance from the end (
scrollHeight - clientHeight - scrollTop), not asscrollTop. This matters. Our first attempt comparedscrollToplikescrolledUpdoes and still failed: when a row above the viewport grows, scroll anchoring movesscrollTopdown by the same amount without the reader moving, ascrollTopcomparison reads that as "scrolling down", and it re-arms. Distance from the end is unchanged by anchoring. It also leaves the existingscrolledUprelease condition alone, since that is aboutscrollTopmoving up. - Pass a direction to
userScrollIntent. Home, PageUp, ArrowUp, Shift+Space and a wheel withdeltaY < 0count as up. That sets the flag at the keydown, so a resize-triggered commit that runs between the keydown and the first animation frame can't re-arm either. A touch gesture stays direction-less and clears the flag, the same as today.
Roughly, against main (98a1fe6):
// use-message-scroller-controller.ts
+ const movedAwayFromEndRef = React.useRef(false)
+ const lastDistanceFromEndRef = React.useRef(0)
const reconcileFollowMode = React.useCallback(
(scrollable: MessageScrollerScrollable) => {
- const scrollTop = viewportRef.current?.scrollTop ?? 0
+ const viewport = viewportRef.current
+ const scrollTop = viewport?.scrollTop ?? 0
const scrolledUp =
scrollTop < lastScrollTopRef.current - SCROLL_POSITION_EPSILON
lastScrollTopRef.current = scrollTop
+ // Distance from the end, not scrollTop: scroll anchoring moves scrollTop
+ // when rows above resize, without the reader moving.
+ const distanceFromEnd = viewport
+ ? viewport.scrollHeight - viewport.clientHeight - scrollTop
+ : 0
+ if (distanceFromEnd > lastDistanceFromEndRef.current + SCROLL_POSITION_EPSILON) {
+ movedAwayFromEndRef.current = true
+ } else if (distanceFromEnd < lastDistanceFromEndRef.current - SCROLL_POSITION_EPSILON) {
+ movedAwayFromEndRef.current = false
+ }
+ lastDistanceFromEndRef.current = distanceFromEnd
+
if (
autoScrollRef.current &&
!scrollable.end &&
+ !movedAwayFromEndRef.current &&
modeRef.current !== "settling-jump" &&
modeRef.current !== "anchored-to-message"
) {
modeRef.current = "following-bottom"
} else if (- const userScrollIntent = React.useCallback(() => {
+ const userScrollIntent = React.useCallback((direction?: "up" | "down") => {
+ movedAwayFromEndRef.current = direction === "up"
if (// components.tsx
+const UPWARD_SCROLL_KEYS = new Set(["ArrowUp", "Home", "PageUp"])
function handleWheel(event: React.WheelEvent<HTMLDivElement>) {
- userScrollIntent()
+ userScrollIntent(event.deltaY < 0 ? "up" : "down")
onWheel?.(event)
}
function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
if (USER_SCROLL_KEYS.has(event.key)) {
- userScrollIntent()
+ const isUp =
+ UPWARD_SCROLL_KEYS.has(event.key) || (event.key === " " && event.shiftKey)
+ userScrollIntent(isUp ? "up" : "down")
}We've been running the equivalent change as a pnpm patch of the 0.3.1 build.
- Race tests: in Chromium with smooth scrolling on, Home and PageUp from the end went from failing to 0 failures in 50 presses each, pressed immediately after mount. The deterministic replay (below) went from 10/10 failing to 0/10.
- Guard tests: following still resumes after the reader scrolls back to the end with the wheel, and a wheel toward the end while at the end keeps following.
- What I didn't run: the package's own unit and browser suites. I didn't run them against the change.
I'm happy to open a PR with this plus a browser regression test. The test would do what the repro's button does, and it fails on 0.3.1.
Related
- #11223 (the open fix for #11224) already makes the wheel intent direction-aware (
userScrollIntent({ deltaY })) and touches the same lines as the fix above. The fix here could build on it: extend that direction to keyboard intent, and havereconcileFollowModeconsult it before re-arming. I'm happy to base a PR on #11223 if that's preferred. - #11224 is the opposite failure: follow disengaging and never re-arming. This issue is follow re-arming when it shouldn't.
- #11808 (running ResizeObserver handling synchronously, for #11577) changes the timing of step 4, but
handleResizewould still callscrollToEndwhile the mode isfollowing-bottom. It would make the pull-back happen sooner, not stop it. - #11211 (
releaseAutoScroll()) could be called from a consumer's key handler, but the nextscrollevent inside the threshold would re-arm follow just the same, so it can't work around this.
Affected component/components
MessageScroller
How to reproduce
Deterministic, with the repro's button:
- Open the repro (link below) and reload so the list opens at the end.
- Click Replay the race. It dispatches a Home
keydownon the viewport, movesscrollTopup 2px, grows a row above (min-height: 20rem), scrolls up 300px, and grows another row, waiting two frames between steps. That is the sequence Chromium produces when it loses the race. - The log ends at
0px from the end -> BUG: pulled back to the end. Expected: about 300px from the end.
By hand:
- Render a long transcript (the repro has 150 items) with
autoScrollanddefaultScrollPosition="end", and items withcontent-visibility: auto; contain-intrinsic-size: auto 10rem(what the registry item applies). - Reload, focus the viewport and press Home or PageUp straight away, while the list is still settling at the end.
- The viewport ends at, or near, the end instead of at the top (Home) or one page up (PageUp). After the list has settled it still happens, but rarely (see above), so repeat the key press, reloading between tries.
Codesandbox/StackBlitz link
https://github.com/ruisaraiva19/shadcn-message-scroller-home-repro (StackBlitz: https://stackblitz.com/github/ruisaraiva19/shadcn-message-scroller-home-repro)
Logs
# The repro's "Replay the race" log, @shadcn/react 0.3.1, Chromium:
after the 2px first frame: 2px from the end
after a row above resized: 0px from the end
after scrolling up 300px: 300px from the end
after another row resized: 0px from the end -> BUG: pulled back to the end
# The same replay with the proposed fix applied:
after another row resized: 302px from the end -> OK
# Real key presses, Playwright Chromium, smooth scrolling on, 0.3.1:
# (distance from the end after 1.2s; Home should reach scrollTop 0,
# PageUp should end ~438px from the end)
pressed immediately after mount: Home 40/40 failed, PageUp 40/40 failed (e.g. scrollTop 24366 -> 21652, 0px from the end)
pressed after a 100-1500ms settle: Home 0/200, PageUp 0/200 in the minimal repro; ~1/30 each in our app
with --disable-smooth-scrolling: no failures (the first frame is the whole scroll)No console errors or warnings are emitted.
System Info
macOS
Playwright 1.63 Chromium (headed and headless) and a desktop Chromium browser, smooth scrolling on
"@shadcn/react": "0.3.1" (latest; the relevant code is unchanged on main at 98a1fe6)
react 19.2 / 19.3Before submitting
- I've made research efforts and searched the documentation
- I've searched for existing issues
Source: shadcn-ui/ui