# Message Scroller

The scroll container for a chat transcript. It anchors each turn, opens a saved thread where you choose, follows a streaming reply, keeps your place while history loads and scrolls to any message.

```tsx
import { useEffect, useRef, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { VStack } from "@/components/ui/stack"
import { color, leading, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"
import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const script = [
  {
    prompt:
      "The transcript keeps shifting while a reply streams in. What should own the scroll position?",
    reply:
      "Wrap the list in MessageScroller. It owns the scroll position, so the rows you render stay presentational.\n\nMark the user's message with scrollAnchor. When a new turn arrives, the scroller settles that message near the top and lets the reply grow into the space below it.",
  },
  {
    prompt: "What happens if I scroll up while a reply is still arriving?",
    reply:
      "Then nothing moves. A wheel, a touch drag, a scroll key or the scrollbar all release the view, and new text keeps arriving out of sight.\n\nThe button at the bottom appears once there is something below. Pressing it brings the reader back to the latest message.",
  },
  {
    prompt: "Does the previous turn disappear when the new one anchors?",
    reply:
      "No. A slice of the turn above stays in view, 64 pixels by default, so the new question reads as part of the same thread rather than a fresh page.",
  },
  {
    prompt: "How does a screen reader hear the new messages?",
    reply:
      'The content is a log with aria-relevant="additions", so new rows are announced and token-by-token edits are not. The viewport is a labelled region you can focus and scroll with the keyboard.',
  },
]

const initialMessages: ChatMessage[] = script.slice(0, 1).flatMap((turn) => [
  { id: "user-0", role: "user" as const, text: turn.prompt },
  { id: "assistant-0", role: "assistant" as const, text: turn.reply },
])

const styles = stylex.create({
  card: { height: "34rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { columnGap: space.s3, alignItems: "flex-end" },
  prompt: {
    flexGrow: 1,
    minWidth: 0,
    minHeight: `calc(2 * ${leading.sm} * ${text.sm})`,
    fontSize: text.sm,
    lineHeight: leading.sm,
    color: color.mutedForeground,
  },
})

function useScriptedChat() {
  const [messages, setMessages] = useState(initialMessages)
  const [turn, setTurn] = useState(1)
  const [streaming, setStreaming] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => () => clearTimeout(timer.current), [])

  function send() {
    const next = script[turn]
    if (!next || streaming) return
    const replyId = `assistant-${turn}`
    const words = next.reply.split(/(?=\s)/)
    let count = 0

    setMessages((current) => [...current, { id: `user-${turn}`, role: "user", text: next.prompt }])
    setTurn(turn + 1)
    setStreaming(true)

    const tick = () => {
      count += 2
      const reply: ChatMessage = {
        id: replyId,
        role: "assistant",
        text: words.slice(0, count).join(""),
      }
      setMessages((current) =>
        current.some((message) => message.id === replyId)
          ? current.map((message) => (message.id === replyId ? reply : message))
          : [...current, reply],
      )
      if (count < words.length) {
        timer.current = setTimeout(tick, 40)
      } else {
        setStreaming(false)
      }
    }

    timer.current = setTimeout(tick, 500)
  }

  function reset() {
    clearTimeout(timer.current)
    setMessages(initialMessages)
    setTurn(1)
    setStreaming(false)
  }

  return { messages, next: script[turn], streaming, send, reset }
}

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={isUser}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>
              {isUser ? (
                message.text
              ) : (
                <VStack gap={3}>
                  {message.text.split("\n\n").map((paragraph, index) => (
                    <p key={index}>{paragraph}</p>
                  ))}
                </VStack>
              )}
            </BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerDemo() {
  const { messages, next, streaming, send, reset } = useScriptedChat()

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>New chat</CardTitle>
        <CardDescription>Press send to stream the next turn.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset conversation"
            disabled={streaming || messages.length === initialMessages.length}
            onClick={reset}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent aria-busy={streaming}>
                {messages.map((message) => (
                  <Turn key={message.id} message={message} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter xstyle={styles.footer}>
        <p {...stylex.props(styles.prompt)}>
          {next ? next.prompt : "Nothing left to send. Reset the conversation."}
        </p>
        <Button size="icon" aria-label="Send" disabled={!next || streaming} onClick={send}>
          <ArrowUpIcon />
        </Button>
      </CardFooter>
    </Card>
  )
}
```

A streamed reply changes the transcript while someone may be reading it. The
scroller keeps the reader's place through that: it moves the view only when the
reader asked to move, starts each new turn near the top with part of the last
one still in view, follows a reply only while the reader is at the live edge,
and keeps the visible row in place when layout above it changes.

It owns the scroll viewport and nothing else. Messages, model state, transport
and persistence stay in your code. The behaviour comes from the headless
`@shadcn/react/message-scroller` package; this component adds arene's frame,
scrollbar, edge fade and jump button on top.

## Installation

**Command**

```bash
npx shadcn@latest add @arene/message-scroller
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @shadcn/react @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` from the same page,
   which hides the jump button's screen-reader label and draws the focus ring.
   The viewport also needs `interop.css`, whose `scroll-fade-y` mask fades the transcript at the
   edge it can scroll toward, and which sizes the button's icon.

3. Add [Button](https://www.arene.style/docs/components/button). The jump button renders it.

4. Paste this source into the file named in its title.

   ```tsx title="components/ui/message-scroller.tsx"
   "use client"

   import type { ComponentProps, FocusEvent } from "react"
   import { useState } from "react"
   import {
     MessageScroller as MessageScrollerPrimitive,
     useMessageScroller,
     useMessageScrollerScrollable,
     useMessageScrollerVisibility,
     type MessageScrollerDefaultScrollPosition,
     type MessageScrollerScrollAlign,
     type MessageScrollerScrollOptions,
     type MessageScrollerScrollable,
     type MessageScrollerVisibilityState,
   } from "@shadcn/react/message-scroller"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { ArrowDownIcon } from "@phosphor-icons/react/dist/csr/ArrowDown"
   import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

   import { Button } from "@/components/ui/button"
   import { states } from "@/theme/states"
   import { color, duration, ease, shadow, space } from "@/theme/tokens.stylex"

   const scrollbarThumb = `color-mix(in oklab, ${color.mutedForeground} 35%, transparent)`

   const styles = stylex.create({
     root: {
       position: "relative",
       display: "flex",
       flexDirection: "column",
       width: "100%",
       height: "100%",
       minHeight: 0,
       overflow: "hidden",
     },
     viewport: {
       width: "100%",
       height: "100%",
       minWidth: 0,
       minHeight: 0,
       overflowY: "auto",
       overscrollBehavior: "contain",
       contain: "content",
       borderRadius: "inherit",
       outlineStyle: "none",
       scrollbarWidth: "thin",
       scrollbarGutter: "stable",
       scrollbarColor: {
         default: `${scrollbarThumb} transparent`,
         ":is([data-autoscrolling])": "transparent transparent",
       },
       visibility: { default: null, ":is([data-pending-scroll])": "hidden" },
     },
     content: {
       display: "flex",
       flexDirection: "column",
       rowGap: space.s6,
       height: "max-content",
       minHeight: "100%",
       padding: space.s4,
     },
     item: {
       minWidth: 0,
       flexShrink: 0,
     },
     skipOffscreen: {
       contentVisibility: "auto",
       containIntrinsicSize: "auto 10rem",
     },
     button: {
       position: "absolute",
       left: "50%",
       translate: "-50% 0",
       scale: 1,
       boxShadow: {
         default: shadow.popup,
         ":focus-visible": `${shadow.popup}, ${shadow.ring}`,
       },
       transitionProperty:
         "color, background-color, border-color, box-shadow, opacity, transform, translate, scale",
       transitionDuration: {
         default: duration.move,
         "@media (prefers-reduced-motion: reduce)": "0s",
       },
       transitionTimingFunction: ease.decelerate,
     },
     buttonInactive: {
       opacity: 0,
       scale: 0.95,
       pointerEvents: "none",
     },
   })

   const directions = stylex.create({
     end: { insetBlockEnd: space.s4 },
     start: { insetBlockStart: space.s4 },
   })

   const inactiveDirections = stylex.create({
     end: { translate: "-50% 100%" },
     start: { translate: "-50% -100%" },
   })

   const messageScrollerStyles = {
     root: styles.root,
     focused: states.fieldFocusedInset,
     viewport: styles.viewport,
     content: styles.content,
     item: styles.item,
     skipOffscreen: styles.skipOffscreen,
     button: styles.button,
     buttonInactive: styles.buttonInactive,
     directions,
     inactiveDirections,
   }

   type MessageScrollerButtonDirection = keyof typeof directions

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type ButtonProps = ComponentProps<typeof Button>

   const MessageScrollerProvider = MessageScrollerPrimitive.Provider

   type MessageScrollerProps = Omit<
     ComponentProps<typeof MessageScrollerPrimitive.Root>,
     "className" | "ref"
   > &
     Overrides

   function isViewport(target: EventTarget) {
     return target instanceof Element && target.matches('[data-slot="message-scroller-viewport"]')
   }

   function MessageScroller({
     xstyle,
     className,
     style,
     onFocus,
     onBlur,
     ...props
   }: MessageScrollerProps) {
     const [focused, setFocused] = useState(false)
     const sx = stylex.props(styles.root, focused && states.fieldFocusedInset, xstyle)
     return (
       <MessageScrollerPrimitive.Root
         data-slot="message-scroller"
         {...sx}
         {...props}
         onFocus={(event: FocusEvent<HTMLDivElement>) => {
           if (isViewport(event.target)) setFocused(event.target.matches(":focus-visible"))
           onFocus?.(event)
         }}
         onBlur={(event: FocusEvent<HTMLDivElement>) => {
           if (isViewport(event.target)) setFocused(false)
           onBlur?.(event)
         }}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type MessageScrollerViewportProps = Omit<
     ComponentProps<typeof MessageScrollerPrimitive.Viewport>,
     "className"
   > &
     Overrides

   function MessageScrollerViewport({
     xstyle,
     className,
     style,
     ...props
   }: MessageScrollerViewportProps) {
     const sx = stylex.props(styles.viewport, xstyle)
     return (
       <MessageScrollerPrimitive.Viewport
         data-slot="message-scroller-viewport"
         {...sx}
         {...props}
         className={clsx("scroll-fade-y", sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type MessageScrollerContentProps = Omit<
     ComponentProps<typeof MessageScrollerPrimitive.Content>,
     "className"
   > &
     Overrides

   function MessageScrollerContent({
     xstyle,
     className,
     style,
     ...props
   }: MessageScrollerContentProps) {
     const sx = stylex.props(styles.content, xstyle)
     return (
       <MessageScrollerPrimitive.Content
         data-slot="message-scroller-content"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type MessageScrollerItemProps = Omit<
     ComponentProps<typeof MessageScrollerPrimitive.Item>,
     "className"
   > &
     Overrides

   function MessageScrollerItem({ xstyle, className, style, ...props }: MessageScrollerItemProps) {
     const sx = stylex.props(styles.item, xstyle)
     return (
       <MessageScrollerPrimitive.Item
         data-slot="message-scroller-item"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   type MessageScrollerButtonProps = Omit<
     ComponentProps<typeof MessageScrollerPrimitive.Button>,
     "className" | "render" | "direction"
   > &
     Pick<ButtonProps, "variant" | "size" | "render" | "nativeButton"> &
     Overrides & { direction?: MessageScrollerButtonDirection }

   function MessageScrollerButton({
     direction = "end",
     variant = "outline",
     size = "icon-sm",
     render,
     nativeButton,
     xstyle,
     className,
     children,
     ...props
   }: MessageScrollerButtonProps) {
     const Icon = direction === "end" ? ArrowDownIcon : ArrowUpIcon
     return (
       <MessageScrollerPrimitive.Button
         data-slot="message-scroller-button"
         direction={direction}
         {...props}
         render={(buttonProps, state) => (
           <Button
             {...buttonProps}
             data-slot="message-scroller-button"
             variant={variant}
             size={size}
             render={render}
             nativeButton={nativeButton}
             xstyle={[
               styles.button,
               directions[direction],
               !state.active && styles.buttonInactive,
               !state.active && inactiveDirections[direction],
               xstyle,
             ]}
             className={className}
           />
         )}
       >
         {children ?? (
           <>
             <Icon aria-hidden="true" />
             <span {...stylex.props(states.srOnly)}>
               {direction === "end" ? "Scroll to latest" : "Scroll to start"}
             </span>
           </>
         )}
       </MessageScrollerPrimitive.Button>
     )
   }

   export {
     MessageScroller,
     MessageScrollerButton,
     MessageScrollerContent,
     MessageScrollerItem,
     MessageScrollerProvider,
     messageScrollerStyles,
     MessageScrollerViewport,
     useMessageScroller,
     useMessageScrollerScrollable,
     useMessageScrollerVisibility,
     type MessageScrollerButtonDirection,
     type MessageScrollerDefaultScrollPosition,
     type MessageScrollerScrollable,
     type MessageScrollerScrollAlign,
     type MessageScrollerScrollOptions,
     type MessageScrollerVisibilityState,
   }
   ```

5. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
```

```tsx
<MessageScrollerProvider>
  <MessageScroller>
    <MessageScrollerViewport>
      <MessageScrollerContent>
        {messages.map((message) => (
          <MessageScrollerItem
            key={message.id}
            messageId={message.id}
            scrollAnchor={message.role === "user"}
          >
            {message.text}
          </MessageScrollerItem>
        ))}
      </MessageScrollerContent>
    </MessageScrollerViewport>
    <MessageScrollerButton />
  </MessageScroller>
</MessageScrollerProvider>
```

A row can hold anything. The examples on this page draw each turn as a
[Message](https://www.arene.style/docs/components/message) with a [Bubble](https://www.arene.style/docs/components/bubble)
in it, but the scroller does not depend on either.

`MessageScroller` fills its parent, so put it in a box with a fixed or
flex-constrained height. Inside a [Card](https://www.arene.style/docs/components/card), give the
`CardContent` around it `flexGrow: 1`, `minHeight: 0` and no inline padding;
`MessageScrollerContent` brings its own.

## Composition

```text
MessageScrollerProvider
└── MessageScroller
    ├── MessageScrollerViewport
    │   └── MessageScrollerContent
    │       └── MessageScrollerItem
    └── MessageScrollerButton
```

- `MessageScrollerProvider` renders nothing. It holds the scroll state and the
  behaviour props, and the hooks read from it, so a control outside the frame,
  in a card header or a toolbar, can drive the transcript as long as it sits
  inside the provider.
- `MessageScroller` is the frame. It lays out the viewport and positions the
  button.
- `MessageScrollerViewport` is the element that scrolls. It keeps the visible
  row in place when older rows are prepended.
- `MessageScrollerContent` is the transcript column, a live region that
  announces new rows.
- `MessageScrollerItem` is one row. Wrap every direct child of the content in
  one, whether it is a message, a date marker or a typing row, so the scroller
  can measure it, anchor to it and jump to it.
- `MessageScrollerButton` scrolls to the latest message, or to the start with
  `direction="start"`. It shows only while there is something to scroll to.

## Anchoring turns

An anchor is the row a new turn starts from. Give it `scrollAnchor`. When an
anchored row is appended, the viewport scrolls it to near the top and the
reply fills in underneath it. The view does not snap to the bottom.

An appended row without `scrollAnchor` moves nothing. Switch the anchor to the
assistant below and send: the question arrives without moving the view, and
the reply is what settles at the top.

```tsx
import { useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"
import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

type Role = "user" | "assistant"

type ChatMessage = { id: string; role: Role; text: string }

const OPENING_COUNT = 2

const script: ChatMessage[] = [
  {
    id: "user-1",
    role: "user",
    text: "Where does a new turn land when I send a message?",
  },
  {
    id: "assistant-1",
    role: "assistant",
    text: "Wherever the anchored row is. With User selected, your message settles near the top of the view and this reply fills the space under it.",
  },
  {
    id: "user-2",
    role: "user",
    text: "And if I pick Assistant as the anchor instead?",
  },
  {
    id: "assistant-2",
    role: "assistant",
    text: "Your message is added without moving the view. The reply is what settles near the top, with the end of your question still visible above it. That suits a product where the answer is what people come back to read.",
  },
  {
    id: "user-3",
    role: "user",
    text: "Does the anchor have to be a message at all?",
  },
  {
    id: "assistant-3",
    role: "assistant",
    text: "No. Any row can take scrollAnchor: a date marker, a join event, a handoff to a person. The scroller only needs to know which row starts the turn.",
  },
]

const styles = stylex.create({
  card: { height: "32rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { justifyContent: "space-between" },
})

function Turn({ message, anchor }: { message: ChatMessage; anchor: boolean }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={anchor}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>{message.text}</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerAnchoring() {
  const [anchorRole, setAnchorRole] = useState<Role>("user")
  const [count, setCount] = useState(OPENING_COUNT)
  const [thread, setThread] = useState(0)
  const next = script[count]

  function restart(role: Role) {
    setAnchorRole(role)
    setCount(OPENING_COUNT)
    setThread((current) => current + 1)
  }

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Anchoring</CardTitle>
        <CardDescription>Choose the role that starts a turn, then send.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset conversation"
            disabled={count === OPENING_COUNT}
            onClick={() => restart(anchorRole)}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider key={thread}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {script.slice(0, count).map((message) => (
                  <Turn key={message.id} message={message} anchor={message.role === anchorRole} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter xstyle={styles.footer}>
        <ToggleGroup
          aria-label="Anchor role"
          size="sm"
          spacing={0}
          value={[anchorRole]}
          onValueChange={([role]) => role && restart(role)}
        >
          <ToggleGroupItem value="user">User</ToggleGroupItem>
          <ToggleGroupItem value="assistant">Assistant</ToggleGroupItem>
        </ToggleGroup>
        <Button
          size="icon"
          aria-label="Send next message"
          disabled={!next}
          onClick={() => setCount(count + 1)}
        >
          <ArrowUpIcon />
        </Button>
      </CardFooter>
    </Card>
  )
}
```

## Group chat

Anchoring is not tied to a role. Put it on the row that starts a turn in your
product. That can be the message the model answers, an "Emmy joined" marker or
a handoff to a person. Typing indicators and history controls should not
anchor.

```tsx
<MessageScrollerItem messageId="emmy-joined" scrollAnchor>
  <Marker variant="separator">
    <MarkerContent>Emmy joined the chat</MarkerContent>
  </Marker>
</MessageScrollerItem>
```

```tsx
import { useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent, type BubbleVariant } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Marker, MarkerContent } from "@/components/ui/marker"
import { Message, MessageContent, MessageHeader } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"

type ChatItem =
  | { kind: "marker"; id: string; text: string }
  | { kind: "message"; id: string; sender: string; agent?: boolean; text: string }

const currentUser = "Grace"

const initialItems: ChatItem[] = [
  {
    kind: "message",
    id: "grace-1",
    sender: "Grace",
    text: "@atlas, how long did last night's simulation run take?",
  },
  {
    kind: "message",
    id: "atlas-1",
    sender: "Atlas",
    agent: true,
    text: "It finished in 6 h 12 min, about 40 minutes slower than last week. Most of the extra time went into mesh refinement. Emmy wrote that step, if you want a second opinion.",
  },
  {
    kind: "message",
    id: "grace-2",
    sender: "Grace",
    text: "Good idea. Adding her now.",
  },
]

const arrivals: ChatItem[] = [
  { kind: "marker", id: "emmy-joined", text: "Emmy joined the chat" },
  {
    kind: "message",
    id: "emmy-1",
    sender: "Emmy",
    text: "The refinement threshold changed on Monday, so the mesh has more cells near the boundary. I'll rerun it with the old threshold and post both timings here within the hour.",
  },
]

const actions = ["Add Emmy", "Send as Emmy"]

const styles = stylex.create({
  card: { height: "32rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  send: { width: "100%" },
})

function bubbleVariant(item: Extract<ChatItem, { kind: "message" }>): BubbleVariant {
  if (item.sender === currentUser) return "secondary"
  return item.agent ? "ghost" : "outline"
}

function Row({ item }: { item: ChatItem }) {
  if (item.kind === "marker") {
    return (
      <MessageScrollerItem messageId={item.id} scrollAnchor>
        <Marker variant="separator">
          <MarkerContent>{item.text}</MarkerContent>
        </Marker>
      </MessageScrollerItem>
    )
  }

  const isCurrentUser = item.sender === currentUser
  return (
    <MessageScrollerItem messageId={item.id}>
      <Message align={isCurrentUser ? "end" : "start"}>
        <MessageContent>
          {!isCurrentUser && <MessageHeader>{item.sender}</MessageHeader>}
          <Bubble variant={bubbleVariant(item)}>
            <BubbleContent>{item.text}</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerGroupChat() {
  const [arrived, setArrived] = useState(0)
  const [thread, setThread] = useState(0)
  const items = [...initialItems, ...arrivals.slice(0, arrived)]
  const action = actions[arrived]

  function reset() {
    setArrived(0)
    setThread((current) => current + 1)
  }

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Group chat</CardTitle>
        <CardDescription>The join marker starts the next turn.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset conversation"
            disabled={arrived === 0}
            onClick={reset}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider key={thread}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {items.map((item) => (
                  <Row key={item.id} item={item} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter>
        <Button
          variant="secondary"
          disabled={!action}
          onClick={() => setArrived((current) => current + 1)}
          xstyle={styles.send}
        >
          {action ?? "Emmy replied"}
        </Button>
      </CardFooter>
    </Card>
  )
}
```

## Showing the previous turn

`scrollPreviousItemPeek` keeps a slice of the previous row in view above a new
anchor, so the question still reads as part of the same thread. The default is
`64` pixels, added to `scrollMargin`.

```tsx
import { useEffect, useRef, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { VStack } from "@/components/ui/stack"
import { Slider } from "@/components/ui/slider"
import { color, font, leading, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"
import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const DEFAULT_PEEK = 64

const script = [
  {
    prompt: "What should the release notes lead with?",
    reply:
      "Lead with the sync engine. It is the change every user notices, because edits from teammates now arrive in under a second.\n\nOffline editing comes second. It matters most to the people who travel, and they will read past the first paragraph to find it.",
  },
  {
    prompt: "Should the export change go in the same post?",
    reply:
      "Yes, but at the end. The legacy format only affects a few workspaces, and they were emailed last month. A short paragraph with a link to the migration guide is enough.",
  },
  {
    prompt: "Who should sign it?",
    reply:
      "The engineering lead for sync. A name on the post makes the reliability claims easier to believe, and it gives readers someone to reply to.",
  },
]

const initialMessages: ChatMessage[] = script.slice(0, 1).flatMap((turn) => [
  { id: "user-0", role: "user" as const, text: turn.prompt },
  { id: "assistant-0", role: "assistant" as const, text: turn.reply },
])

const styles = stylex.create({
  card: { height: "34rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { columnGap: space.s3 },
  slider: { flexGrow: 1 },
  value: {
    minWidth: "3rem",
    fontFamily: font.mono,
    fontSize: text.xs,
    lineHeight: leading.xs,
    fontVariantNumeric: "tabular-nums",
    color: color.mutedForeground,
  },
})

function useScriptedChat() {
  const [messages, setMessages] = useState(initialMessages)
  const [turn, setTurn] = useState(1)
  const [streaming, setStreaming] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => () => clearTimeout(timer.current), [])

  function send() {
    const next = script[turn]
    if (!next || streaming) return
    const replyId = `assistant-${turn}`
    const words = next.reply.split(/(?=\s)/)
    let count = 0

    setMessages((current) => [...current, { id: `user-${turn}`, role: "user", text: next.prompt }])
    setTurn(turn + 1)
    setStreaming(true)

    const tick = () => {
      count += 2
      const reply: ChatMessage = {
        id: replyId,
        role: "assistant",
        text: words.slice(0, count).join(""),
      }
      setMessages((current) =>
        current.some((message) => message.id === replyId)
          ? current.map((message) => (message.id === replyId ? reply : message))
          : [...current, reply],
      )
      if (count < words.length) {
        timer.current = setTimeout(tick, 40)
      } else {
        setStreaming(false)
      }
    }

    timer.current = setTimeout(tick, 500)
  }

  function reset() {
    clearTimeout(timer.current)
    setMessages(initialMessages)
    setTurn(1)
    setStreaming(false)
  }

  return { messages, next: script[turn], streaming, send, reset }
}

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={isUser}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>
              {isUser ? (
                message.text
              ) : (
                <VStack gap={3}>
                  {message.text.split("\n\n").map((paragraph, index) => (
                    <p key={index}>{paragraph}</p>
                  ))}
                </VStack>
              )}
            </BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerPreviousContext() {
  const [peek, setPeek] = useState(DEFAULT_PEEK)
  const { messages, next, streaming, send, reset } = useScriptedChat()

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Previous context</CardTitle>
        <CardDescription>Set the peek, then send the next turn.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset conversation"
            disabled={streaming || messages.length === initialMessages.length}
            onClick={reset}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider scrollMargin={16} scrollPreviousItemPeek={peek}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent aria-busy={streaming}>
                {messages.map((message) => (
                  <Turn key={message.id} message={message} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter xstyle={styles.footer}>
        <Slider
          aria-label="Previous context peek"
          value={[peek]}
          min={0}
          max={160}
          step={8}
          disabled={streaming}
          onValueChange={(value) =>
            setPeek((Array.isArray(value) ? value[0] : value) ?? DEFAULT_PEEK)
          }
          xstyle={styles.slider}
        />
        <span {...stylex.props(styles.value)}>{peek}px</span>
        <Button size="icon" aria-label="Send" disabled={!next || streaming} onClick={send}>
          <ArrowUpIcon />
        </Button>
      </CardFooter>
    </Card>
  )
}
```

## Following a stream

With `autoScroll`, a reply that is streaming stays in view while the reader is
at the live edge. A wheel, a touch drag, a scroll key or the scrollbar releases
it, and so does a jump to a message. New text then arrives without moving
the reader. `MessageScrollerButton` and `scrollToEnd` start following again.

`autoScroll` works with anchoring. The anchored question settles near the top,
the reply streams into the room below it, and once the reply fills the
viewport the view follows it.

```tsx
import { useEffect, useRef, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScrollerScrollable,
} from "@/components/ui/message-scroller"
import { VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import { color, leading, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"
import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const script = [
  {
    prompt: "Write up the launch for the changelog.",
    reply:
      "Version 2.0 ships today. The headline is the new sync engine, which replaces polling with a single long-lived connection per workspace. Edits from other people now arrive in under a second, and the client no longer refetches whole documents when one field changes.\n\nOffline editing is the second half of the release. Changes made without a connection are queued locally, merged when the connection returns, and shown with a small marker until the server confirms them. Conflicts that cannot be merged open a side-by-side view instead of silently picking a winner.\n\nWe also removed the legacy export format. Workspaces that still use it were emailed last month, and the importer keeps reading it until the end of the year.\n\nThanks to everyone who tested the beta. Most of the bugs fixed in the last two weeks came from your reports.",
  },
  {
    prompt: "Now a shorter version for the in-app banner.",
    reply:
      "Sync is now instant and works offline. Edits from your team arrive in under a second, and anything you change without a connection is saved and merged when you are back online.\n\nThe legacy export format has been retired. Read the changelog for the details.",
  },
]

const styles = stylex.create({
  card: { height: "28rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { columnGap: space.s3, alignItems: "flex-end" },
  prompt: {
    flexGrow: 1,
    minWidth: 0,
    fontSize: text.sm,
    lineHeight: leading.sm,
    color: color.mutedForeground,
  },
})

function useScriptedChat() {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [turn, setTurn] = useState(0)
  const [streaming, setStreaming] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => () => clearTimeout(timer.current), [])

  function send() {
    const next = script[turn]
    if (!next || streaming) return
    const replyId = `assistant-${turn}`
    const words = next.reply.split(/(?=\s)/)
    let count = 0

    setMessages((current) => [...current, { id: `user-${turn}`, role: "user", text: next.prompt }])
    setTurn(turn + 1)
    setStreaming(true)

    const tick = () => {
      count += 1
      const reply: ChatMessage = {
        id: replyId,
        role: "assistant",
        text: words.slice(0, count).join(""),
      }
      setMessages((current) =>
        current.some((message) => message.id === replyId)
          ? current.map((message) => (message.id === replyId ? reply : message))
          : [...current, reply],
      )
      if (count < words.length) {
        timer.current = setTimeout(tick, 45)
      } else {
        setStreaming(false)
      }
    }

    timer.current = setTimeout(tick, 500)
  }

  function reset() {
    clearTimeout(timer.current)
    setMessages([])
    setTurn(0)
    setStreaming(false)
  }

  return { messages, next: script[turn], streaming, send, reset }
}

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={isUser}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>
              {isUser ? (
                message.text
              ) : (
                <VStack gap={3}>
                  {message.text.split("\n\n").map((paragraph, index) => (
                    <p key={index}>{paragraph}</p>
                  ))}
                </VStack>
              )}
            </BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

function FollowStatus({ streaming }: { streaming: boolean }) {
  const { end } = useMessageScrollerScrollable()
  const status = !streaming ? "Idle" : end ? "Paused. New text is arriving below." : "Following"
  return (
    <Text size="xs" tone="muted" aria-live="polite">
      {status}
    </Text>
  )
}

export default function MessageScrollerStreaming() {
  const { messages, next, streaming, send, reset } = useScriptedChat()

  return (
    <MessageScrollerProvider autoScroll>
      <Card xstyle={[widths.sm, styles.card]}>
        <CardHeader>
          <CardTitle>Streaming</CardTitle>
          <CardDescription>
            <FollowStatus streaming={streaming} />
          </CardDescription>
          <CardAction>
            <Button
              variant="outline"
              size="icon-sm"
              aria-label="Reset stream"
              disabled={streaming || messages.length === 0}
              onClick={reset}
            >
              <ArrowCounterClockwiseIcon />
            </Button>
          </CardAction>
        </CardHeader>
        <CardContent xstyle={styles.body}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent aria-busy={streaming}>
                {messages.map((message) => (
                  <Turn key={message.id} message={message} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </CardContent>
        <CardFooter xstyle={styles.footer}>
          <p {...stylex.props(styles.prompt)}>
            {next ? next.prompt : "Nothing left to send. Reset the stream."}
          </p>
          <Button size="icon" aria-label="Send" disabled={!next || streaming} onClick={send}>
            <ArrowUpIcon />
          </Button>
        </CardFooter>
      </Card>
    </MessageScrollerProvider>
  )
}
```

The status in that card reads `end` from `useMessageScrollerScrollable`. It is
`false` while the view follows, because following keeps the reader at the
bottom, and `true` once the reader scrolls away and text keeps arriving below.

Pass `aria-busy` to `MessageScrollerContent` while a turn streams. The log
announces a reply's row when it is added, which is when it holds only its first
words; while the content is busy, a screen reader that supports `aria-busy`
waits and reads the finished row.

## Opening position

`defaultScrollPosition` sets where a saved thread opens, once, on the first
render that has rows. `"last-anchor"` opens at the last anchored row with its
reply below, which is usually where the reader left off. It falls back to
`"end"` when there is no anchor or the last turn already fits. `"end"`, the
default, opens at the bottom and `"start"` at the top.

```tsx
import { useEffect, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  type MessageScrollerDefaultScrollPosition,
} from "@/components/ui/message-scroller"
import { VStack } from "@/components/ui/stack"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { widths } from "@/theme/widths"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const positions: { value: MessageScrollerDefaultScrollPosition; label: string }[] = [
  { value: "start", label: "Start" },
  { value: "last-anchor", label: "Last anchor" },
  { value: "end", label: "End" },
]

const transcript: ChatMessage[] = [
  { id: "user-1", role: "user", text: "What did the reviewers say about the draft?" },
  {
    id: "assistant-1",
    role: "assistant",
    text: "Both reviewers accept the main result. The first wants the proof of the second lemma written out in full instead of cited.\n\nThe second asks for a comparison with the earlier bound in section four.",
  },
  { id: "user-2", role: "user", text: "Which change takes the most work?" },
  {
    id: "assistant-2",
    role: "assistant",
    text: "The comparison. The earlier bound is stated with a different constant, so every table has to be recomputed before the two can be read side by side.",
  },
  { id: "user-3", role: "user", text: "Can we still send the revision this week?" },
  {
    id: "assistant-3",
    role: "assistant",
    text: "Yes, if the tables are done by Wednesday. The lemma proof is already in the appendix of the preprint and only needs to move into the main text.\n\nThe tables are the risk. Each one takes about an hour to recompute, and the two largest cases should be checked by hand against the earlier paper.\n\nI will open a branch for the revision and copy both reviews into the tracking issue, so every comment has an owner and a status.\n\nIf a recomputed value disagrees with the earlier bound by more than rounding, stop and flag it in the issue rather than adjusting the text around it.\n\nOnce the tables are in, I will draft the response letter: a short summary, then each comment quoted with the change it led to. The letter should also say why the lemma was cited before, since the first reviewer will ask.\n\nThe draft should be ready for Thursday's meeting. Reply here if you want anything else covered in it.",
  },
]

const styles = stylex.create({
  card: { height: "34rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  tabs: { width: "100%" },
  list: { width: "100%" },
})

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={isUser}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>
              {isUser ? (
                message.text
              ) : (
                <VStack gap={3}>
                  {message.text.split("\n\n").map((paragraph, index) => (
                    <p key={index}>{paragraph}</p>
                  ))}
                </VStack>
              )}
            </BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

function SavedThread() {
  const [messages, setMessages] = useState<ChatMessage[]>([])

  useEffect(() => {
    const timer = setTimeout(() => setMessages(transcript), 400)
    return () => clearTimeout(timer)
  }, [])

  return (
    <MessageScroller>
      <MessageScrollerViewport>
        <MessageScrollerContent>
          {messages.map((message) => (
            <Turn key={message.id} message={message} />
          ))}
        </MessageScrollerContent>
      </MessageScrollerViewport>
      <MessageScrollerButton direction="start" />
      <MessageScrollerButton />
    </MessageScroller>
  )
}

export default function MessageScrollerOpeningPosition() {
  const [position, setPosition] = useState<MessageScrollerDefaultScrollPosition>("last-anchor")

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Opening position</CardTitle>
        <CardDescription>Choose where a saved thread opens.</CardDescription>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider key={position} defaultScrollPosition={position}>
          <SavedThread />
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter>
        <Tabs
          value={position}
          onValueChange={(value: MessageScrollerDefaultScrollPosition) => setPosition(value)}
          xstyle={styles.tabs}
        >
          <TabsList xstyle={styles.list}>
            {positions.map((option) => (
              <TabsTrigger key={option.value} value={option.value}>
                {option.label}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>
      </CardFooter>
    </Card>
  )
}
```

The demo loads its transcript after a short delay, the way a saved thread
arrives from a request, and the position applies when the rows do. Remount the
provider with a new `key` to open a different thread.

A scroll container always paints at its top before script runs. For `"end"`
and `"last-anchor"`, the viewport carries `data-pending-scroll` until the
opening position is applied, and the component hides it while that attribute
is there, so the first frame shows the empty frame rather than the oldest
messages followed by a jump. A prerendered page needs nothing more: the
attribute is in the HTML, and the viewport shows once the page has hydrated.
`"start"` never hides the viewport.

To show a prerendered transcript at its end before hydration, put a script
right after the viewport that scrolls it to the bottom and removes the
attribute itself.

```tsx
const id = useId()

<MessageScroller>
  <MessageScrollerViewport id={id} suppressHydrationWarning>
    <MessageScrollerContent>{/* transcript */}</MessageScrollerContent>
  </MessageScrollerViewport>
  <script
    dangerouslySetInnerHTML={{
      __html: `(() => {
        const viewport = document.getElementById(${JSON.stringify(id)})
        if (!viewport) return
        viewport.scrollTop = viewport.scrollHeight
        viewport.removeAttribute("data-pending-scroll")
      })()`,
    }}
  />
  <MessageScrollerButton />
</MessageScroller>
```

The script only runs from the server's HTML, so it covers the first load and
not a client navigation, where the attribute does the work as before. It is
only for `"end"`: it scrolls to the bottom, so with `"last-anchor"` the view
would show the end and then jump to the anchor. Leave it out when the rows
load on the client. Under a Content Security Policy, give the script a `nonce`.

## Loading history

When rows are prepended, the viewport keeps the first visible message where it
was, so the reader stays on the same line while history loads above. Give rows
stable `messageId` values: that is the row the viewport holds still. Pass
`preserveScrollOnPrepend={false}` to the viewport to turn this off.

```tsx
import { useEffect, useRef, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Marker, MarkerContent } from "@/components/ui/marker"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { Spinner } from "@/components/ui/spinner"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const PAGE_SIZE = 4

const pairs: [string, string][] = [
  [
    "What did the overnight benchmark find?",
    "The matrix solver is 18% slower on the largest inputs. Small inputs did not change.",
  ],
  [
    "Did any results change?",
    "No. Every output matched the reference values to the last stored digit, on all three machines.",
  ],
  [
    "Which commit caused the slowdown?",
    "The one that moved the solver to double-precision accumulators.",
  ],
  [
    "Why would that cost 18%?",
    "The wider values no longer fit in cache for the largest matrices, so each pass reads more memory.",
  ],
  [
    "Should we revert it?",
    "Not yet. The precision fix closed two open bug reports, so it is worth keeping.",
  ],
  [
    "Try blocking the loop so each tile fits in cache.",
    "I will rerun the benchmark with 64-row tiles and post the numbers here.",
  ],
]

const history: ChatMessage[] = pairs.flatMap(([prompt, reply], index) => [
  { id: `user-${index}`, role: "user" as const, text: prompt },
  { id: `assistant-${index}`, role: "assistant" as const, text: reply },
])

const styles = stylex.create({
  card: { height: "30rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  load: { width: "100%" },
})

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id}>
      <Message align={isUser ? "end" : "start"}>
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>{message.text}</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerLoadHistory() {
  const [count, setCount] = useState(PAGE_SIZE)
  const [loading, setLoading] = useState(false)
  const [thread, setThread] = useState(0)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)
  const hasMore = count < history.length

  useEffect(() => () => clearTimeout(timer.current), [])

  function loadEarlier() {
    setLoading(true)
    timer.current = setTimeout(() => {
      setCount((current) => Math.min(current + PAGE_SIZE, history.length))
      setLoading(false)
    }, 800)
  }

  function reset() {
    clearTimeout(timer.current)
    setCount(PAGE_SIZE)
    setLoading(false)
    setThread((current) => current + 1)
  }

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Load history</CardTitle>
        <CardDescription>Earlier messages load above without moving you.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset history"
            disabled={loading || count === PAGE_SIZE}
            onClick={reset}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider key={thread}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {!hasMore && (
                  <MessageScrollerItem>
                    <Marker variant="separator">
                      <MarkerContent>Start of conversation</MarkerContent>
                    </Marker>
                  </MessageScrollerItem>
                )}
                {history.slice(-count).map((message) => (
                  <Turn key={message.id} message={message} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter>
        <Button
          variant="secondary"
          iconPosition={loading ? "start" : undefined}
          disabled={loading || !hasMore}
          onClick={loadEarlier}
          xstyle={styles.load}
        >
          {loading && <Spinner aria-hidden="true" />}
          {loading ? "Loading" : hasMore ? "Load earlier messages" : "History loaded"}
        </Button>
      </CardFooter>
    </Card>
  )
}
```

> **Note**
>
> Keep the "load earlier" control out of `MessageScrollerContent`, or at least
> out of its first row. The viewport recognises a prepend by its old first row
> moving down. A control that stays first while history is inserted after it
> hides the prepend, and the view jumps.

## Entrance animations

A row can animate in. Put the entrance on the message inside
`MessageScrollerItem`, not on the item: the scroller places a row by its
measured box, and a transform on the item moves that box while the scroller
is measuring it. Animate `transform` and `opacity` only. Height, margin and
padding change the layout the scroller is positioning.

```tsx
const rise = stylex.keyframes({
  from: { opacity: 0, transform: `translateY(${space.s6})` },
  to: { opacity: 1, transform: "none" },
})

const styles = stylex.create({
  enter: {
    animationName: rise,
    animationDuration: {
      default: duration.panel,
      "@media (prefers-reduced-motion: reduce)": "0s",
    },
    animationTimingFunction: ease.decelerate,
  },
})

<MessageScrollerItem messageId={message.id} scrollAnchor>
  <Message align="end" xstyle={styles.enter}>
    {/* bubble */}
  </Message>
</MessageScrollerItem>
```

```tsx
import { useEffect, useRef, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"
import { Text } from "@/components/ui/text"
import { duration, ease, space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { ArrowCounterClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise"
import { ArrowUpIcon } from "@phosphor-icons/react/dist/csr/ArrowUp"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const script = [
  {
    prompt: "Can my message animate in while the scroller keeps its place?",
    reply:
      "Yes. Animate transform and opacity on the message inside the row, and leave the row itself alone. The scroller measures the row, so its position stays exact while the bubble moves.",
  },
  {
    prompt: "Why not animate the row?",
    reply:
      "A transform moves the box the scroller measures. Measured mid-slide, the row would be placed by where it was at that moment rather than where it comes to rest.",
  },
  {
    prompt: "And for people who turn animation off?",
    reply:
      "The entrance drops to zero seconds under prefers-reduced-motion. The message appears in place, and scrolling behaves exactly the same.",
  },
]

const initialMessages: ChatMessage[] = script.slice(0, 1).flatMap((turn) => [
  { id: "user-0", role: "user" as const, text: turn.prompt },
  { id: "assistant-0", role: "assistant" as const, text: turn.reply },
])

const initialIds = new Set(initialMessages.map((message) => message.id))

const rise = stylex.keyframes({
  from: { opacity: 0, transform: `translateY(${space.s6})` },
  to: { opacity: 1, transform: "none" },
})

const styles = stylex.create({
  card: { height: "32rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { columnGap: space.s3 },
  prompt: { flexGrow: 1, minWidth: 0 },
  enter: {
    animationName: rise,
    animationDuration: {
      default: duration.panel,
      "@media (prefers-reduced-motion: reduce)": "0s",
    },
    animationTimingFunction: ease.decelerate,
  },
})

function useScriptedChat() {
  const [messages, setMessages] = useState(initialMessages)
  const [turn, setTurn] = useState(1)
  const [streaming, setStreaming] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => () => clearTimeout(timer.current), [])

  function send() {
    const next = script[turn]
    if (!next || streaming) return
    const replyId = `assistant-${turn}`
    const words = next.reply.split(/(?=\s)/)
    let count = 0

    setMessages((current) => [...current, { id: `user-${turn}`, role: "user", text: next.prompt }])
    setTurn(turn + 1)
    setStreaming(true)

    const tick = () => {
      count += 2
      const reply: ChatMessage = {
        id: replyId,
        role: "assistant",
        text: words.slice(0, count).join(""),
      }
      setMessages((current) =>
        current.some((message) => message.id === replyId)
          ? current.map((message) => (message.id === replyId ? reply : message))
          : [...current, reply],
      )
      if (count < words.length) {
        timer.current = setTimeout(tick, 40)
      } else {
        setStreaming(false)
      }
    }

    timer.current = setTimeout(tick, 600)
  }

  function reset() {
    clearTimeout(timer.current)
    setMessages(initialMessages)
    setTurn(1)
    setStreaming(false)
  }

  return { messages, next: script[turn], streaming, send, reset }
}

function Turn({ message }: { message: ChatMessage }) {
  const isUser = message.role === "user"
  return (
    <MessageScrollerItem messageId={message.id} scrollAnchor={isUser}>
      <Message
        align={isUser ? "end" : "start"}
        xstyle={isUser && !initialIds.has(message.id) && styles.enter}
      >
        <MessageContent>
          <Bubble variant={isUser ? "secondary" : "ghost"}>
            <BubbleContent>{message.text}</BubbleContent>
          </Bubble>
        </MessageContent>
      </Message>
    </MessageScrollerItem>
  )
}

export default function MessageScrollerAnimation() {
  const { messages, next, streaming, send, reset } = useScriptedChat()

  return (
    <Card xstyle={[widths.sm, styles.card]}>
      <CardHeader>
        <CardTitle>Entrance</CardTitle>
        <CardDescription>Sent messages rise in from the bottom edge.</CardDescription>
        <CardAction>
          <Button
            variant="outline"
            size="icon-sm"
            aria-label="Reset conversation"
            disabled={streaming || messages.length === initialMessages.length}
            onClick={reset}
          >
            <ArrowCounterClockwiseIcon />
          </Button>
        </CardAction>
      </CardHeader>
      <CardContent xstyle={styles.body}>
        <MessageScrollerProvider>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent aria-busy={streaming}>
                {messages.map((message) => (
                  <Turn key={message.id} message={message} />
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </CardContent>
      <CardFooter xstyle={styles.footer}>
        <Text render={<p />} tone="muted" xstyle={styles.prompt}>
          {next ? next.prompt : "Nothing left to send. Reset the conversation."}
        </Text>
        <Button size="icon" aria-label="Send" disabled={!next || streaming} onClick={send}>
          <ArrowUpIcon />
        </Button>
      </CardFooter>
    </Card>
  )
}
```

An animation runs whenever its element mounts, including in the first render
of a saved thread, so the demo animates only the messages sent after the page
loaded.

## Jumping to messages

`useMessageScroller` returns `scrollToMessage`, `scrollToStart` and
`scrollToEnd`, for search results, permalinks, outlines and toolbar buttons.

```tsx
const { scrollToMessage, scrollToStart, scrollToEnd } = useMessageScroller()

scrollToMessage("user-3", { align: "start", behavior: "smooth" })
```

```tsx
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScroller,
} from "@/components/ui/message-scroller"
import { space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { CaretDownIcon } from "@phosphor-icons/react/dist/csr/CaretDown"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const pairs: [string, string][] = [
  [
    "How should we name the new plan?",
    "Something short that says who it is for. Team works better than Pro Plus.",
  ],
  [
    "What should it cost?",
    "Twelve dollars per seat per month, billed yearly, with a fifteen dollar monthly option.",
  ],
  [
    "Which features belong in it?",
    "Shared workspaces, admin roles, audit history and priority support.",
  ],
  [
    "How do we move existing customers?",
    "Grandfather current prices for a year and email every owner a month before the change.",
  ],
  [
    "When can it launch?",
    "The billing work is done. Pricing pages and the email need about two weeks.",
  ],
  [
    "Who signs off?",
    "Finance on the price, legal on the terms, and the product lead on the feature list.",
  ],
]

const messages: ChatMessage[] = pairs.flatMap(([prompt, reply], index) => [
  { id: `user-${index}`, role: "user" as const, text: prompt },
  { id: `assistant-${index}`, role: "assistant" as const, text: reply },
])

const prompts = messages.filter((message) => message.role === "user")

const styles = stylex.create({
  card: { height: "32rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  menu: { width: "16rem" },
  footer: { columnGap: space.s2 },
})

function JumpMenu() {
  const { scrollToMessage } = useMessageScroller()
  return (
    <DropdownMenu>
      <DropdownMenuTrigger render={<Button variant="outline" size="sm" iconPosition="end" />}>
        Jump to
        <CaretDownIcon />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" xstyle={styles.menu}>
        <DropdownMenuGroup>
          <DropdownMenuLabel>Questions</DropdownMenuLabel>
          {prompts.map((message) => (
            <DropdownMenuItem
              key={message.id}
              onClick={() => scrollToMessage(message.id, { behavior: "smooth" })}
            >
              {message.text}
            </DropdownMenuItem>
          ))}
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function EdgeCommands() {
  const { scrollToStart, scrollToEnd } = useMessageScroller()
  return (
    <>
      <Button variant="outline" size="sm" onClick={() => scrollToStart({ behavior: "smooth" })}>
        First message
      </Button>
      <Button variant="outline" size="sm" onClick={() => scrollToEnd({ behavior: "smooth" })}>
        Latest
      </Button>
    </>
  )
}

export default function MessageScrollerCommands() {
  return (
    <MessageScrollerProvider>
      <Card xstyle={[widths.sm, styles.card]}>
        <CardHeader>
          <CardTitle>Commands</CardTitle>
          <CardDescription>Drive the transcript from outside it.</CardDescription>
          <CardAction>
            <JumpMenu />
          </CardAction>
        </CardHeader>
        <CardContent xstyle={styles.body}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {messages.map((message) => {
                  const isUser = message.role === "user"
                  return (
                    <MessageScrollerItem
                      key={message.id}
                      messageId={message.id}
                      scrollAnchor={isUser}
                    >
                      <Message align={isUser ? "end" : "start"}>
                        <MessageContent>
                          <Bubble variant={isUser ? "secondary" : "ghost"}>
                            <BubbleContent>{message.text}</BubbleContent>
                          </Bubble>
                        </MessageContent>
                      </Message>
                    </MessageScrollerItem>
                  )
                })}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </CardContent>
        <CardFooter xstyle={styles.footer}>
          <EdgeCommands />
        </CardFooter>
      </Card>
    </MessageScrollerProvider>
  )
}
```

`scrollToMessage` targets the `messageId` on an item. It returns `true` when
the scroll ran or was queued, not when the row is in view. Called before the
rows mount, it queues the target, which covers a permalink resolved on the
client. Once rows have mounted, an unknown id returns `false`.

## Tracking what is on screen

`useMessageScrollerVisibility` returns `currentAnchorId`, the anchored turn the
reader is in, and `visibleMessageIds`, the rows on screen in document order.
`currentAnchorId` stays set after its row scrolls above the viewport, so it
answers "which question am I reading the answer to".

```tsx
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScroller,
  useMessageScrollerVisibility,
} from "@/components/ui/message-scroller"
import { Text } from "@/components/ui/text"
import { font, space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const pairs: [string, string][] = [
  [
    "How should we name the new plan?",
    "Something short that says who it is for. Team works better than Pro Plus, because it names the buyer instead of ranking the plan against the others.",
  ],
  [
    "What should it cost?",
    "Twelve dollars per seat per month, billed yearly, with a fifteen dollar monthly option. That keeps it under the per-seat price of the two closest competitors.",
  ],
  [
    "Which features belong in it?",
    "Shared workspaces, admin roles, audit history and priority support. Single sign-on stays in Enterprise, since it is the main reason larger companies upgrade.",
  ],
  [
    "How do we move existing customers?",
    "Grandfather current prices for a year and email every owner a month before the change, with a link that shows their new price.",
  ],
  [
    "When can it launch?",
    "The billing work is done. Pricing pages, the migration email and the help center articles need about two weeks.",
  ],
]

const messages: ChatMessage[] = pairs.flatMap(([prompt, reply], index) => [
  { id: `user-${index}`, role: "user" as const, text: prompt },
  { id: `assistant-${index}`, role: "assistant" as const, text: reply },
])

const prompts = messages.filter((message) => message.role === "user")

const styles = stylex.create({
  card: { height: "32rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
  footer: { justifyContent: "space-between", columnGap: space.s3 },
  outline: { display: "flex", columnGap: space.s1 },
  mono: { fontFamily: font.mono },
})

function CurrentTurn() {
  const { currentAnchorId } = useMessageScrollerVisibility()
  const index = prompts.findIndex((message) => message.id === currentAnchorId)
  return index === -1 ? "Scroll to read" : `Question ${index + 1} of ${prompts.length}`
}

function Outline() {
  const { scrollToMessage } = useMessageScroller()
  const { currentAnchorId, visibleMessageIds } = useMessageScrollerVisibility()
  return (
    <>
      <nav aria-label="Questions" {...stylex.props(styles.outline)}>
        {prompts.map((message, index) => {
          const current = message.id === currentAnchorId
          return (
            <Button
              key={message.id}
              variant={current ? "secondary" : "ghost"}
              size="icon-xs"
              aria-label={`${index + 1}. ${message.text}`}
              aria-current={current ? "location" : undefined}
              onClick={() => scrollToMessage(message.id, { behavior: "smooth" })}
            >
              {index + 1}
            </Button>
          )
        })}
      </nav>
      <Text size="xs" tone="muted" xstyle={styles.mono}>
        {visibleMessageIds.length} on screen
      </Text>
    </>
  )
}

export default function MessageScrollerVisibility() {
  return (
    <MessageScrollerProvider scrollMargin={12} defaultScrollPosition="start">
      <Card xstyle={[widths.sm, styles.card]}>
        <CardHeader>
          <CardTitle>Transcript outline</CardTitle>
          <CardDescription>
            <CurrentTurn />
          </CardDescription>
        </CardHeader>
        <CardContent xstyle={styles.body}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {messages.map((message) => {
                  const isUser = message.role === "user"
                  return (
                    <MessageScrollerItem
                      key={message.id}
                      messageId={message.id}
                      scrollAnchor={isUser}
                    >
                      <Message align={isUser ? "end" : "start"}>
                        <MessageContent>
                          <Bubble variant={isUser ? "secondary" : "ghost"}>
                            <BubbleContent>{message.text}</BubbleContent>
                          </Bubble>
                        </MessageContent>
                      </Message>
                    </MessageScrollerItem>
                  )
                })}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </CardContent>
        <CardFooter xstyle={styles.footer}>
          <Outline />
        </CardFooter>
      </Card>
    </MessageScrollerProvider>
  )
}
```

Visibility is tracked only while something subscribes to the hook, and only
rows with a `messageId` take part.

## Reading scroll state

`useMessageScrollerScrollable` returns `{ start, end }`, the edges the viewport
can still scroll toward. The reader is at the top when `start` is `false`, at
the latest message when `end` is `false`, and everything fits when both are.
While `autoScroll` follows a stream, `end` stays `false`. To style the scroller
from this state, read `data-scrollable` instead.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Message, MessageContent } from "@/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScrollerScrollable,
  type MessageScrollerScrollable,
} from "@/components/ui/message-scroller"
import { Text } from "@/components/ui/text"
import { widths } from "@/theme/widths"

type ChatMessage = { id: string; role: "user" | "assistant"; text: string }

const messages: ChatMessage[] = Array.from({ length: 6 }, (_, index) => [
  { id: `user-${index}`, role: "user" as const, text: `Check step ${index + 1} of the migration.` },
  {
    id: `assistant-${index}`,
    role: "assistant" as const,
    text: `Step ${index + 1} is done. The rows it touched are verified, and the next step can start whenever you are ready.`,
  },
]).flat()

const styles = stylex.create({
  card: { height: "28rem" },
  body: { flexGrow: 1, minHeight: 0, paddingInline: 0 },
})

function describe({ start, end }: MessageScrollerScrollable) {
  if (start && end) return "Earlier messages above, later ones below."
  if (end) return "At the first message. Scroll down for the rest."
  if (start) return "At the latest message. Scroll up for earlier ones."
  return "Every message fits."
}

function ScrollStatus() {
  const scrollable = useMessageScrollerScrollable()
  return <Text tone="muted">{describe(scrollable)}</Text>
}

export default function MessageScrollerScrollableDemo() {
  return (
    <MessageScrollerProvider defaultScrollPosition="start">
      <Card xstyle={[widths.sm, styles.card]}>
        <CardHeader>
          <CardTitle>Scroll state</CardTitle>
          <CardDescription>Scroll the transcript to update the footer.</CardDescription>
        </CardHeader>
        <CardContent xstyle={styles.body}>
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent>
                {messages.map((message) => {
                  const isUser = message.role === "user"
                  return (
                    <MessageScrollerItem
                      key={message.id}
                      messageId={message.id}
                      scrollAnchor={isUser}
                    >
                      <Message align={isUser ? "end" : "start"}>
                        <MessageContent>
                          <Bubble variant={isUser ? "secondary" : "ghost"}>
                            <BubbleContent>{message.text}</BubbleContent>
                          </Bubble>
                        </MessageContent>
                      </Message>
                    </MessageScrollerItem>
                  )
                })}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </CardContent>
        <CardFooter>
          <ScrollStatus />
        </CardFooter>
      </Card>
    </MessageScrollerProvider>
  )
}
```

## Virtualization

The scroller renders every row as real DOM, so selection, find-in-page and
screen readers reach all of it, and `skipOffscreen` lets the browser skip the
rows far from view. For a transcript too long for that, let a virtualizer such
as TanStack Virtual own the rows, with the viewport as its scroll element.

`MessageScrollerContent` spaces its rows with a `1.5rem` `rowGap` and pads
them with `1rem`. Under a virtualizer its only child is the list, and each row
sits at an offset the virtualizer computes, so neither reaches the rows. Pass
the gap to the virtualizer as `gap`. Move the block padding into it as well:
remove it through `xstyle` and pass it as `paddingStart` and `paddingEnd`, so
the visible range and `scrollToIndex` are computed from where the rows are
drawn.

```tsx
import { useRef, type ReactNode } from "react"
import * as stylex from "@stylexjs/stylex"
import { useVirtualizer } from "@tanstack/react-virtual"

import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller"

const styles = stylex.create({
  content: { paddingBlock: 0 },
  list: { position: "relative", width: "100%" },
  listHeight: (height: number) => ({ height: `${height}px` }),
  row: { position: "absolute", insetBlockStart: 0, insetInlineStart: 0, width: "100%" },
  rowOffset: (start: number) => ({ transform: `translateY(${start}px)` }),
})

function VirtualTranscript({ messages }: { messages: { id: string; content: ReactNode }[] }) {
  const viewportRef = useRef<HTMLDivElement>(null)
  const virtualizer = useVirtualizer({
    count: messages.length,
    getScrollElement: () => viewportRef.current,
    getItemKey: (index) => messages[index]?.id ?? index,
    estimateSize: () => 96,
    gap: 24,
    paddingStart: 16,
    paddingEnd: 16,
    overscan: 8,
  })

  return (
    <MessageScrollerProvider>
      <MessageScroller>
        <MessageScrollerViewport ref={viewportRef}>
          <MessageScrollerContent xstyle={styles.content}>
            <div {...stylex.props(styles.list, styles.listHeight(virtualizer.getTotalSize()))}>
              {virtualizer.getVirtualItems().map((row) => (
                <div
                  key={row.key}
                  ref={virtualizer.measureElement}
                  data-index={row.index}
                  {...stylex.props(styles.row, styles.rowOffset(row.start))}
                >
                  {messages[row.index]?.content}
                </div>
              ))}
            </div>
          </MessageScrollerContent>
        </MessageScrollerViewport>
        <MessageScrollerButton />
      </MessageScroller>
    </MessageScrollerProvider>
  )
}
```

The rows are not `MessageScrollerItem`s, so anchoring, prepend preservation,
visibility tracking and `scrollToMessage` do not reach them, and
`"last-anchor"` opens at the end. Following a stream, the `"start"` and
`"end"` opening positions and the jump button still work, because they read
only the viewport and the content's size. Jump to a row with the virtualizer's `scrollToIndex`.

## Accessibility

`MessageScrollerViewport` is a region named "Messages" that takes focus, so a
keyboard user can move to the transcript and scroll it with the arrow keys,
Page Up, Page Down, Home and End. While it has keyboard focus, the frame draws an inset ring. Pass `aria-label` to name it after the conversation.

`MessageScrollerContent` is a `role="log"` live region with
`aria-relevant="additions"`. New rows are announced; edits to a row as it
streams are not.

`MessageScrollerButton` renders a real button with a hidden label, "Scroll to
latest" or "Scroll to start". When there is nothing to scroll to, it is `inert`
and leaves the tab order, so it never becomes a focus stop that does nothing.

## API reference

Every part wraps the `@shadcn/react/message-scroller` part of the same name and
accepts its props. The parts that render an element also take `xstyle`,
`className` and `style`. `MessageScroller` takes no `ref`; put one on the
viewport to reach the scrolling element.

### MessageScrollerProvider

| Prop                     | Type                                | Default |
| ------------------------ | ----------------------------------- | ------- |
| `autoScroll`             | `boolean`                           | `false` |
| `defaultScrollPosition`  | `"start" \| "end" \| "last-anchor"` | `"end"` |
| `scrollPreviousItemPeek` | `number`                            | `64`    |
| `scrollMargin`           | `number`                            | `0`     |
| `scrollEdgeThreshold`    | `number`                            | `8`     |

`scrollMargin` is the space kept above a row that a command or an anchor
aligns to. `scrollEdgeThreshold` is how near an edge still counts as at it,
which decides when the button shows.

### MessageScrollerViewport

| Prop                      | Type      | Default      |
| ------------------------- | --------- | ------------ |
| `preserveScrollOnPrepend` | `boolean` | `true`       |
| `aria-label`              | `string`  | `"Messages"` |
| `role`                    | `string`  | `"region"`   |
| `tabIndex`                | `number`  | `0`          |

### MessageScrollerContent

| Prop              | Type      | Default       |
| ----------------- | --------- | ------------- |
| `role`            | `string`  | `"log"`       |
| `aria-relevant`   | `string`  | `"additions"` |
| `aria-busy`       | `boolean` | —             |
| `spacerClassName` | `string`  | —             |

The content is a column with `1.5rem` between rows and `1rem` of padding.
Change either through `xstyle`.

### MessageScrollerItem

| Prop           | Type      | Default |
| -------------- | --------- | ------- |
| `messageId`    | `string`  | —       |
| `scrollAnchor` | `boolean` | `false` |

For a long transcript, add `messageScrollerStyles.skipOffscreen` to each
item's `xstyle`. It sets `content-visibility: auto`, so the browser skips
layout and paint for rows far outside the viewport. A skipped row measures as a
`10rem` placeholder until it has rendered once, so only use it where the
scroller mounts on screen: a transcript that opens below the fold or in a
hidden panel lands at the wrong opening position. It also clips anything a row
draws outside its own box.

### MessageScrollerButton

| Prop           | Type                                                                           | Default      |
| -------------- | ------------------------------------------------------------------------------ | ------------ |
| `direction`    | `"start" \| "end"`                                                             | `"end"`      |
| `behavior`     | `ScrollBehavior`                                                               | `"smooth"`   |
| `variant`      | [Button](https://www.arene.style/docs/components/button#api-reference) variant | `"outline"`  |
| `size`         | [Button](https://www.arene.style/docs/components/button#api-reference) size    | `"icon-sm"`  |
| `render`       | `ReactElement \| (props, state) => ReactElement`                               | —            |
| `nativeButton` | `boolean`                                                                      | `true`       |
| `children`     | `ReactNode`                                                                    | arrow, label |

The button renders [Button](https://www.arene.style/docs/components/button), and `render` replaces
that button's element. A function `render` is Button's, so its state is Base
UI Button's `{ disabled }`, not the headless part's `{ active, direction }`.
Read those from the `data-active` and `data-direction` attributes on the
element instead. It is centred over the bottom edge, or the top edge for
`direction="start"`, and slides in and out of that edge as it shows and hides.

### Hooks

| Hook                           | Returns                                           |
| ------------------------------ | ------------------------------------------------- |
| `useMessageScroller`           | `{ scrollToMessage, scrollToStart, scrollToEnd }` |
| `useMessageScrollerScrollable` | `{ start, end }`, the edges it can scroll toward  |
| `useMessageScrollerVisibility` | `{ currentAnchorId, visibleMessageIds }`          |

Each command takes `{ align, behavior, scrollMargin }`. `align` is `"start"`,
`"center"`, `"end"` or `"nearest"`, `"start"` by default; `behavior` is
`"auto"` by default. `scrollToStart` and `scrollToEnd` return `false` only
before the viewport mounts.

### messageScrollerStyles

The style maps behind the component. Spread them onto any element.

| Key                  | What it is                                                     |
| -------------------- | -------------------------------------------------------------- |
| `root`               | The frame: a full-size, clipped, positioned column             |
| `focused`            | The frame's inset ring, while the viewport has keyboard focus  |
| `viewport`           | The scroller and its thin scrollbar                            |
| `content`            | The transcript column, its row gap and padding                 |
| `item`               | A row: no shrinking, no minimum width                          |
| `skipOffscreen`      | `content-visibility: auto` for long transcripts                |
| `button`             | The jump button's position and its slide                       |
| `buttonInactive`     | Hidden: transparent, scaled down, ignoring the pointer         |
| `directions`         | `start` and `end`: which edge the button sits on               |
| `inactiveDirections` | `start` and `end`: the edge the hidden button slides back into |

### Data attributes

| Attribute                               | On              | Effect                                                       |
| --------------------------------------- | --------------- | ------------------------------------------------------------ |
| `data-slot="message-scroller"`          | the frame       | Targets the frame from a parent                              |
| `data-slot="message-scroller-viewport"` | the scroller    | Targets the element that scrolls                             |
| `data-slot="message-scroller-content"`  | the column      | Targets the transcript column                                |
| `data-slot="message-scroller-item"`     | a row           | Targets one row                                              |
| `data-slot="message-scroller-button"`   | the jump button | Targets the button; `data-variant` and `data-size` mirror it |
| `data-scrollable`                       | frame, scroller | `"start"`, `"end"` or `"start end"`; absent when it fits     |
| `data-autoscrolling`                    | frame, scroller | Present during a scroll to the latest message; hides the bar |
| `data-pending-scroll`                   | frame, scroller | Present until the opening position applies; hides the view   |
| `data-message-id`, `data-scroll-anchor` | a row           | Mirror `messageId` and `scrollAnchor`                        |
| `data-direction`, `data-active`         | the jump button | Mirror `direction`, and whether there is anywhere to go      |
