Skip to content

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.

How many orders wait for approval?
Three. The oldest is order 4409 from Monday.
Which supplier is late?
Lamivo Metalli. Order 4417 is two days past its delivery date.
Send them a reminder.
Done. I sent the reminder to their purchasing contact.
Show the Verona stock for steel.
Verona holds 40 units of steel, 9 below the minimum.

Installation

pnpm dlx shadcn@latest add @silkware/message-scroller

To 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-react

The scroll button uses the Button, so install it too:

pnpm dlx shadcn@latest add @silkware/button

Then copy the source into components/ui/message-scroller.tsx:

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:

  • MessageScroller fills 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 MessageScrollerContent must be a MessageScrollerItem. 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.

Is Lamivo Metalli late?

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.

Order 4409 needs approval from Giulia.
Order 4417 is two days late.
Order 4421 shipped from Padova.
Order 4430 is waiting for a price check.
Order 4433 has not shipped yet.
Order 4440 was cancelled by the customer.

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.

Monday
Approve order 4409.
Approved by Giulia. I sent it to Lamivo Metalli.
Today
Did they confirm?
Not yet. Their last reply promised Tuesday.

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.

Order 4409 needs approval.
Order 4417 is two days late.
Order 4421 shipped from Padova.
Order 4430 waits for a price check.
Order 4433 has not shipped yet.
Order 4440 was cancelled.
Order 4452 was approved by Giulia.
Order 4458 is in Quality.

Accessibility

KeyAction
TabMoves focus to the transcript, then to the controls inside it and to the scroll button when it is active.
Arrow UpScrolls the focused transcript up.
Arrow DownScrolls the focused transcript down.
Page UpScrolls the focused transcript up by a page.
Page DownScrolls the focused transcript down by a page.
HomeScrolls the focused transcript to the start.
EndScrolls the focused transcript to the end.
EnterPresses 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" and tabIndex={0}, so keyboard users can reach and scroll the transcript.
  • A content element with role="log" and aria-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 exposes data-active="false".
  • The visible name "Scroll to end" or "Scroll to start" on the button, as screen reader text.
  • Rendering with content-visibility on 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-label to MessageScrollerViewport instead of the default "Messages".
  • aria-busy on 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.
Order 4409 needs approval.
Order 4417 is two days late.
Order 4421 shipped from Padova.
Order 4430 waits for a price check.
Order 4433 has not shipped yet.
Order 4440 was cancelled.
Do

Give the scroller a parent with a height, so the transcript scrolls inside it.

Order 4409 needs approval.
Order 4417 is two days late.
Order 4421 shipped from Padova.
Order 4430 waits for a price check.
Order 4433 has not shipped yet.
Order 4440 was cancelled.
Don’t

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.

PropTypeDefaultDescription
autoScroll?booleanfalseFollow 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?number8How close to an edge, in pixels, still counts as being at it.
scrollMargin?number0A margin applied to the edge a jump or an anchor aligns to.
scrollPreviousItemPeek?number64How 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.

PropTypeDefaultDescription
className?stringNoneClasses 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.

PropTypeDefaultDescription
preserveScrollOnPrepend?booleantrueKeeps 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?number0Makes the transcript focusable so it can be scrolled with the keyboard.
className?stringNoneClasses 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.

PropTypeDefaultDescription
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?booleanNoneMarks the live region as busy while a turn streams.
spacerClassName?stringNoneClasses for the spacer that makes room under an anchored row.
className?stringNoneClasses 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.

PropTypeDefaultDescription
messageId?stringNoneA stable id for the row, used by scrollToMessage, visibility tracking and keeping the place on prepend.
scrollAnchor?booleanfalseMarks the row as the start of a turn that a newly added row anchors to.
className?stringNoneClasses 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.

PropTypeDefaultDescription
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?ReactNodeNoneReplaces the arrow icon and the screen reader label.
render?ReactElement | functionNoneReplaces the Button that is rendered.

useMessageScroller, useMessageScrollerScrollable and useMessageScrollerVisibility

Call these from a component inside the provider.

PropTypeDefaultDescription
useMessageScroller()?{ scrollToMessage, scrollToStart, scrollToEnd }NoneCommands 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 }NoneWhether content is hidden before the start or after the end of the viewport.
useMessageScrollerVisibility()?{ currentAnchorId: string | null; visibleMessageIds: string[] }NoneThe current anchored turn and the rows in view, for an outline or an active-turn indicator.