Message Scroller
Scrolls a conversation the way readers expect, following new messages only when they are at the end and never moving them against their intent.
Installation
pnpm dlx shadcn@latest add @silkware/message-scrollerTo copy the component by hand, install its dependencies. The scroll behaviour comes from the headless @shadcn/react package; the component only adds the styles.
pnpm add @shadcn/react cn lucide-reactThe scroll button uses the Button, so install it too:
pnpm dlx shadcn@latest add @silkware/buttonThen copy the source into components/ui/message-scroller.tsx:
"use client"
import * as React from "react"import { MessageScroller as MessageScrollerPrimitive, useMessageScroller, useMessageScrollerScrollable, useMessageScrollerVisibility,} from "@shadcn/react/message-scroller"import { cn } from "cn"
import { Button } from "@/components/ui/button"import { ArrowDownIcon } from "lucide-react"
function MessageScrollerProvider( props: React.ComponentProps<typeof MessageScrollerPrimitive.Provider>) { return <MessageScrollerPrimitive.Provider {...props} />}
function MessageScroller({ className, ...props}: React.ComponentProps<typeof MessageScrollerPrimitive.Root>) { return ( <MessageScrollerPrimitive.Root data-slot="message-scroller" className={cn( "group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden", className )} {...props} /> )}
function MessageScrollerViewport({ className, ...props}: React.ComponentProps<typeof MessageScrollerPrimitive.Viewport>) { return ( <MessageScrollerPrimitive.Viewport data-slot="message-scroller-viewport" className={cn( "size-full min-h-0 min-w-0 scroll-fade-b scrollbar-thin scrollbar-gutter-stable overflow-y-auto overscroll-contain contain-content data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent data-pending-scroll:invisible", className )} {...props} /> )}
function MessageScrollerContent({ className, ...props}: React.ComponentProps<typeof MessageScrollerPrimitive.Content>) { return ( <MessageScrollerPrimitive.Content data-slot="message-scroller-content" className={cn("flex h-max min-h-full flex-col gap-8", className)} {...props} /> )}
function MessageScrollerItem({ className, scrollAnchor = false, ...props}: React.ComponentProps<typeof MessageScrollerPrimitive.Item>) { return ( <MessageScrollerPrimitive.Item data-slot="message-scroller-item" scrollAnchor={scrollAnchor} className={cn( "min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto] nth-last-[-n+3]:[content-visibility:visible]", className )} {...props} /> )}
function MessageScrollerButton({ direction = "end", className, children, render, variant = "secondary", size = "icon-sm", ...props}: React.ComponentProps<typeof MessageScrollerPrimitive.Button> & Pick<React.ComponentProps<typeof Button>, "variant" | "size">) { return ( <MessageScrollerPrimitive.Button data-slot="message-scroller-button" data-direction={direction} data-variant={variant} data-size={size} direction={direction} className={cn( "absolute inset-s-1/2 -translate-x-1/2 border-border bg-background text-foreground transition-[translate,scale,opacity] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-150 data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180", className )} render={render ?? <Button variant={variant} size={size} />} {...props} > {children ?? ( <> <ArrowDownIcon /> <span className="sr-only"> {direction === "end" ? "Scroll to end" : "Scroll to start"} </span> </> )} </MessageScrollerPrimitive.Button> )}
export { MessageScrollerProvider, MessageScroller, MessageScrollerViewport, MessageScrollerContent, MessageScrollerItem, MessageScrollerButton, useMessageScroller, useMessageScrollerScrollable, useMessageScrollerVisibility,}Usage
import { MessageScroller, MessageScrollerButton, MessageScrollerContent, MessageScrollerItem, MessageScrollerProvider, MessageScrollerViewport,} from "@/components/ui/message-scroller"<div className="h-96"> <MessageScrollerProvider> <MessageScroller> <MessageScrollerViewport> <MessageScrollerContent> {turns.map((turn) => ( <MessageScrollerItem key={turn.id} messageId={turn.id} scrollAnchor={turn.from === "user"} > <Message /> </MessageScrollerItem> ))} </MessageScrollerContent> </MessageScrollerViewport> <MessageScrollerButton /> </MessageScroller> </MessageScrollerProvider></div>Three things people get wrong:
MessageScrollerfills its parent, so the parent needs a height. In an element with no height the transcript grows with its content and never scrolls.- Every direct child of
MessageScrollerContentmust be aMessageScrollerItem. Messages, Marker rows and a typing line are all items. The scroller measures items to anchor, follow and keep the reader's place. - Give each item a stable
messageId. Jumping, visibility tracking and keeping the place when earlier messages are added depend on it.
The scroller does not hold messages, state or a connection. You render the rows with Message, Bubble and Trace. The whole conversation is assembled in Chat. To use the behaviour without these styles, import the parts from @shadcn/react/message-scroller as MessageScroller.Provider, MessageScroller.Root and so on.
Examples
Anchoring a turn
Mark the row that starts a turn with scrollAnchor, usually the person's message. When a new anchor is added, the viewport moves it near the top and keeps a strip of the previous row above it, so the answer can grow into the space below instead of pushing the question away. Send the questions below and watch where the new turn settles.
Following a stream
Set autoScroll on the provider to follow new content while the reader is at the end of the transcript. If the reader scrolls away from the end, it stops following until they return to the end. Pass aria-busy to the content while a turn streams, so assistive technology waits for the finished row.
Jumping to a message
useMessageScroller returns scrollToMessage, scrollToStart and scrollToEnd. Call them from any component inside the provider, for a search result, an unread marker or a link to a message. scrollToMessage takes an align of start, center, end or nearest.
Markers as rows
A date, a break or a joined line is a row too. Wrap it in a MessageScrollerItem like a message, and add scrollAnchor to it if it starts a turn. defaultScrollPosition sets where the transcript opens: end (the default), start, or last-anchor to open at the last turn.
The scroll button
MessageScrollerButton scrolls to the end, or to the start with direction="start". It fades in when there is content beyond the edge and is inert when there is not. Its default label is "Scroll to end" for screen readers, and it renders a secondary icon button. Add a second button with direction="start" to return to the top.
Accessibility
| Key | Action |
|---|---|
| Tab | Moves focus to the transcript, then to the controls inside it and to the scroll button when it is active. |
| Arrow Up | Scrolls the focused transcript up. |
| Arrow Down | Scrolls the focused transcript down. |
| Page Up | Scrolls the focused transcript up by a page. |
| Page Down | Scrolls the focused transcript down by a page. |
| Home | Scrolls the focused transcript to the start. |
| End | Scrolls the focused transcript to the end. |
| Enter | Presses the scroll button when it has focus. |
The scroll keys are the browser's own keys for a scrollable region. The primitive makes the viewport focusable so they work.
The primitive provides:
- A viewport with
role="region",aria-label="Messages"andtabIndex={0}, so keyboard users can reach and scroll the transcript. - A content element with
role="log"andaria-relevant="additions", a live region that announces new rows and not every change to text inside a row. - A scroll button that is a real button. When there is nothing to scroll toward, it is
inert, leaves the tab order and exposesdata-active="false". - The visible name "Scroll to end" or "Scroll to start" on the button, as screen reader text.
- Rendering with
content-visibilityon rows far from the viewport, which keeps the rows in the DOM for find in page, selection and assistive technology.
You provide:
- A name for the region when the page has more than one: pass
aria-labeltoMessageScrollerViewportinstead of the default "Messages". aria-busyon the content while a turn streams, when you want announcements to wait for the finished message.- The sender of each row, in text, such as a
MessageHeader. - A height on the parent. Without one the region cannot scroll and the keys do nothing.
Guidelines
When to use
- For a conversation with an agent or between people, where messages arrive over time and older ones scroll away.
- For any feed that grows at the end and that people read while it grows, such as a log of agent steps.
When not to use
- For a list of records that people sort, filter or page through. Use a Table.
- For a short list with a fixed height. Use a Scroll Area.
- For content with no live end, such as a document. Let the page scroll.
- For the conversation rows themselves. Compose Message and Bubble inside it.
Behaviour
- Never move the reader against their intent. Do not scroll to the end in your own code when a message arrives; leave that to
autoScroll, which stops when the reader scrolls away. - Anchor the person's message, not the agent's reply, so the question stays visible while the answer streams.
- Keep the scroll button. It is how a reader who scrolled away returns to the latest message.
- Let people jump: with a marker, a search or a link to a message id.
Content
- Keep a row to one message or one marker. A row that holds a whole turn cannot be jumped to in parts.
- Show who sent a row in text, not only by side or colour.
- Do not add a typing row that never ends. Remove it when the turn is done.
Give the scroller a parent with a height, so the transcript scrolls inside it.
Don’t put it in an element with no height. The transcript grows with its content, nothing scrolls, and the scroll button has no work to do.
API reference
The props, data attributes and hooks of every part are the same for the styled component and the headless primitive. The full reference is in the @shadcn/react message scroller docs.
MessageScrollerProvider
The headless root. It owns the scroll state and renders no element. Put it around the scroller and around anything that calls the hooks.
| Prop | Type | Default | Description |
|---|---|---|---|
autoScroll? | boolean | false | Follow new content while the reader is at the end. Wheel, touch, keyboard scrolling and jumps release it. |
defaultScrollPosition? | "start" | "end" | "last-anchor" | "end" | Where the transcript opens on its first non-empty render. last-anchor opens at the last row marked as an anchor. |
scrollEdgeThreshold? | number | 8 | How close to an edge, in pixels, still counts as being at it. |
scrollMargin? | number | 0 | A margin applied to the edge a jump or an anchor aligns to. |
scrollPreviousItemPeek? | number | 64 | How much of the previous row stays visible above a newly added anchor, in pixels. |
MessageScroller
Renders the frame, a <div> that fills its parent and clips its content. It accepts every prop of a div and mirrors the scroll state as data attributes such as data-scrollable.
| Prop | Type | Default | Description |
|---|---|---|---|
className? | string | None | Classes merged after the frame classes. |
MessageScrollerViewport
Renders the scrolling <div>. It keeps the visible row in place when older rows are added above it, and hides itself until the opening position is applied.
| Prop | Type | Default | Description |
|---|---|---|---|
preserveScrollOnPrepend? | boolean | true | Keeps the first visible row stable when older rows are added above it. |
role? | string | "region" | The landmark role of the transcript. |
aria-label? | string | "Messages" | The name of the transcript. |
tabIndex? | number | 0 | Makes the transcript focusable so it can be scrolled with the keyboard. |
className? | string | None | Classes merged after the viewport classes. |
MessageScrollerContent
Renders the column of rows. It is the live region of the transcript. Every direct child must be a MessageScrollerItem.
| Prop | Type | Default | Description |
|---|---|---|---|
role? | string | "log" | The ARIA role of the list of rows. |
aria-relevant? | string | "additions" | Which updates are announced. The default announces new rows only. |
aria-busy? | boolean | None | Marks the live region as busy while a turn streams. |
spacerClassName? | string | None | Classes for the spacer that makes room under an anchored row. |
className? | string | None | Classes merged after the content classes. |
MessageScrollerItem
Renders one row. It is measured for anchoring, following, visibility and jumps, and it renders lazily when it is far from the viewport.
| Prop | Type | Default | Description |
|---|---|---|---|
messageId? | string | None | A stable id for the row, used by scrollToMessage, visibility tracking and keeping the place on prepend. |
scrollAnchor? | boolean | false | Marks the row as the start of a turn that a newly added row anchors to. |
className? | string | None | Classes merged after the item classes. |
MessageScrollerButton
Renders a Button that scrolls to an edge of the transcript. It is positioned at the centre of that edge, fades in when there is content beyond it and is inert when there is not.
| Prop | Type | Default | Description |
|---|---|---|---|
direction? | "start" | "end" | "end" | The edge it scrolls toward. |
behavior? | ScrollBehavior | "smooth" | The native scroll behaviour used when it scrolls. |
variant? | ButtonProps variant | "secondary" | The Button variant. |
size? | ButtonProps size | "icon-sm" | The Button size. |
children? | ReactNode | None | Replaces the arrow icon and the screen reader label. |
render? | ReactElement | function | None | Replaces the Button that is rendered. |
useMessageScroller, useMessageScrollerScrollable and useMessageScrollerVisibility
Call these from a component inside the provider.
| Prop | Type | Default | Description |
|---|---|---|---|
useMessageScroller()? | { scrollToMessage, scrollToStart, scrollToEnd } | None | Commands that scroll the transcript. Each returns false when it could not run. scrollToMessage(id, options) takes align, behavior and scrollMargin. |
useMessageScrollerScrollable()? | { start: boolean; end: boolean } | None | Whether content is hidden before the start or after the end of the viewport. |
useMessageScrollerVisibility()? | { currentAnchorId: string | null; visibleMessageIds: string[] } | None | The current anchored turn and the rows in view, for an outline or an active-turn indicator. |