FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Auto-Scroll Pinning and User-Controlled Reading

Keep a streaming chat at its newest output while the reader is pinned, then preserve their position and offer a clear return-to-latest control.

Freshness: current•12 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Auto-scroll pinning treats following the newest output as a user-controlled mode. A chat view follows each rendered growth only while its distance from the bottom stays within a small tolerance; once the reader moves upward, the client preserves that viewport and exposes a deliberate jump-to-latest control. Reaching the bottom or activating that control restores follow mode.

The stream protocol delivers incremental message parts, but a UI should not issue a scroll command for every token. Layout may update several times before a frame is painted. Observe the transcript's rendered size and coalesce follow-up work to one animation frame. Keep the scroll container stable across UI rerenders so the scroll position and mode belong to the same object.

A stream part extends the transcript
ResizeObserver sees new content height
Pinned mode queues one frame update
Scroll position moves to the end
Reader input restores or pauses following
Conceptual teaching model synthesized from:css-scroll-anchoring-spec,cssom-view-spec,vercel-ai-sdk-ui-stream-protocol

Theory

For a normal top-to-bottom scroll container, define its distance from the end as:

g=H−V−yg = H - V - y

Here, HH is scrollHeight in CSS pixels, VV is clientHeight in CSS pixels, and yy is scrollTop in CSS pixels. Clamp small negative results to zero because subpixel positions and browser rounding can put the measured bottom a fraction of a pixel past the calculated end. The view is pinned when g≤ϵg \le \epsilon, where ϵ\epsilon is a small pixel tolerance such as 56 px. Choose it from interaction testing; it is not a model-latency threshold.

This explicit mode matters because distance alone is not enough. As chunks append below an old reading position, the gap grows. The user has already indicated that they are reading older output, so the client must not chase that growing gap. If the reader scrolls back close to the end, or presses the return control, following becomes active again.

CSS scroll anchoring addresses a related but different problem. When content above the viewport changes size, a browser may adjust the scroll position to keep an anchor node visually stable. That behavior protects the current reading position; it does not mean “follow the newest message.” Let normal anchoring handle layout changes while the reader is paused, and avoid adding a second global correction that fights it. When following, an explicit write to scrollTop after the transcript grows has a clear owner and purpose.

For example, a transcript with H=2,160H=2{,}160 px, a viewport of V=640V=640 px, and y=1,462y=1{,}462 px has g=58g=58 px. With ϵ=64\epsilon=64 px, it is close enough to be considered pinned. If a streamed paragraph adds 320 px, one coalesced update sets the position to the new end, y=1,840y=1{,}840 px. If the reader instead scrolls upward to y=1,210y=1{,}210 px, the gap becomes 630 px and the follow mode pauses. A “Latest response” button gives the reader a predictable way to resume.

Trade-offs

ChoiceWhen it fitsCost to watch
Follow every layout changeA response is short and the reader stays at the endRepeated smooth animations can lag behind tokens and make the viewport feel slippery
Follow only while pinnedLong answers, code blocks, or citations can move older content out of viewNeeds a visible return control and careful resume behavior
Browser scroll anchoringImages or earlier messages can resize above a paused viewportIt preserves an anchor; it does not select the newest message for the user

Use instant position correction during token streaming. Smooth scrolling on every chunk can continuously restart an animation, so the viewport may never arrive at the target. Reserve smooth motion for an intentional “jump to latest” action if that motion is acceptable and does not fight reduced-motion preferences. The button should be a real keyboard-focusable button with a label; visual placement at the bottom alone is not an accessible interaction.

The code below assumes a normal vertical scroll container, a stable transcript element, and an accessible notice button already present in the UI. It measures upward movement to pause, resumes when the measured gap is small, and coalesces content-resize updates. The scrollport should be focusable if the application expects Page Up or Home to control it.

Implementation pattern

typescript
export function bindStreamFollower(
scrollport: HTMLElement,
transcript: HTMLElement,
latestButton: HTMLButtonElement,
thresholdPx = 56,
) {
let following = false;
let frame = 0;
let previousTop = scrollport.scrollTop;
const gapToEnd = () =>
Math.max(0, scrollport.scrollHeight - scrollport.clientHeight - scrollport.scrollTop);
const revealLatest = () => {
following = true;
latestButton.hidden = true;
scrollport.scrollTop = scrollport.scrollHeight;
};
const pauseFollowing = () => {
following = false;
latestButton.hidden = false;
};
const scheduleFollow = () => {
if (!following || frame !== 0) return;
frame = requestAnimationFrame(() => {
frame = 0;
scrollport.scrollTop = scrollport.scrollHeight;
});
};
const onScroll = () => {
if (gapToEnd() <= thresholdPx) following = true;
else if (scrollport.scrollTop < previousTop - 1) pauseFollowing();
latestButton.hidden = following;
previousTop = scrollport.scrollTop;
};
const onWheel = (event: WheelEvent) => {
if (event.deltaY < 0) pauseFollowing();
};
const onKeyDown = (event: KeyboardEvent) => {
if (["PageUp", "Home", "ArrowUp"].includes(event.key)) pauseFollowing();
};
const observer = new ResizeObserver(scheduleFollow);
observer.observe(transcript);
scrollport.addEventListener("scroll", onScroll, { passive: true });
scrollport.addEventListener("wheel", onWheel, { passive: true });
scrollport.addEventListener("keydown", onKeyDown);
latestButton.addEventListener("click", revealLatest);
revealLatest();
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
scrollport.removeEventListener("scroll", onScroll);
scrollport.removeEventListener("wheel", onWheel);
scrollport.removeEventListener("keydown", onKeyDown);
latestButton.removeEventListener("click", revealLatest);
};
}

Failure modes and misconceptions

  • The transcript is replaced on each token. Recreating the scrollport resets its geometry and can drop focus. Keep the scrollport stable and append or reconcile content inside it.
  • New content arrives while the reader is paused. Do not move the viewport. Keep the return button visible, and ensure its action scrolls to the current end rather than to the position captured when the button first appeared.
  • A smooth scroll is restarted for every token. Use one frame-coalesced instant write while following; use motion only for a discrete user action.
  • A reverse flex column or nested scroller is used. The simple distance formula assumes normal vertical flow and the measured element must be the actual scroll owner. Verify the relevant geometry for any reversed layout or nested panel.
  • Scroll anchoring is disabled globally to make the view “stable.” That can make images or earlier messages jump while the reader is paused. Change anchoring only for a demonstrated local conflict, then test the saved reading position.

Test a long response while the reader remains pinned, scroll upward during generation, resize an image in an earlier message, use Page Up and the return button, and unmount the component. Assert that a paused viewport does not move, a pinned viewport ends at the latest content, and cleanup disconnects both listeners and the observer.

Decision scenario

A user has scrolled 500 px above the end of a long answer when a tool result adds a large table. The product requirement says new answers should be easy to find without hiding the paragraph being read. Keep follow mode paused, preserve the browser's anchor behavior, and show the “Latest response” control. Resume only after the user returns near the end or activates the button.

Learning outcomes

  • Compute distance to the end from scrollHeight, clientHeight, and scrollTop.
  • Separate browser anchoring, which protects the viewport, from product follow mode, which tracks new output.
  • Coalesce resize-driven scroll writes and pause them when the reader moves upward.
  • Verify keyboard return controls, resize behavior, and cleanup as part of the chat interaction.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next