Skip to content
2k
On This Page

Message Scroller

A chat scroll container that anchors turns, opens saved transcripts, follows streamed responses, loads history without jumping, and jumps to any message.

New Chat
How can I help you today?
Morning, Alex!

What are we working on today? Press send to start a new conversation

Demo is read only. Press send to send messages.
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, For, onCleanup, Show } from "solid-js"

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,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "~/components/ui/dropdown-menu"
import {
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle
} from "~/components/ui/empty"
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton
} from "~/components/ui/input-group"
import { Message, MessageContent } from "~/components/ui/message"
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerViewport
} from "~/components/ui/message-scroller"
import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"

const messages = [
  {
    role: "user",
    text: "I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around."
  },
  {
    role: "assistant",
    text: "That's the classic streaming scroll problem. Wrap your message list in `MessageScroller` and turn on `stickToEnd` — the viewport pins to the bottom as tokens arrive, so users always see the latest text land in place.\n\nThe important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent."
  },
  {
    role: "user",
    text: "Okay, but when someone sends a new message the view still feels jarring — like the whole conversation reloads from the top."
  },
  {
    role: "assistant",
    text: "MessageScrollerItem fixes that with turn anchoring. Scroll to the turn that should settle near the top instead of blindly snapping to the document bottom.\n\nIt also leaves a small peek of the previous exchange visible above the anchor, so context isn't lost. The reply starts in view without that disorienting jump you get from a plain overflow container."
  },
  {
    role: "user",
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down."
  },
  {
    role: "assistant",
    text: "You won't. Auto-scroll only runs when the viewport is already pinned to the bottom, so scrolling up is a deliberate opt-out — their place in the thread stays put even as new tokens keep arriving below.\n\nWhen there is content they haven't seen yet, `MessageScrollerButton` appears at the bottom of the viewport. One tap jumps them back to the newest message and re-engages auto-scroll. Same pattern as Slack or iMessage: quiet when you're caught up, helpful when you're not."
  },
  {
    role: "user",
    text: "Last one — does this work with assistive tech?"
  },
  {
    role: "assistant",
    text: '`MessageScrollerContent` sets `role="log"` and `aria-relevant="additions"` by default, so screen readers announce new messages as they stream in.\n\nThe scroll button is a real `<button>` with an sr-only label, and it\'s removed from the tab order when you\'re already at the bottom — no ghost focus stops.'
  }
]

export default function MessageScrollerDemo() {
  const [count, setCount] = createSignal(0)
  const [response, setResponse] = createSignal("")
  const [busy, setBusy] = createSignal(false)
  const next = () => messages[count()]
  let timer: ReturnType<typeof setInterval> | undefined
  onCleanup(() => clearInterval(timer))

  function send() {
    const index = count()
    const answer = messages[index + 1]
    if (busy() || !answer) return
    setCount(index + 1)
    setBusy(true)
    const words = answer.text.match(/\S+\s*/g) ?? []
    let offset = 0
    timer = setInterval(() => {
      setResponse(words.slice(0, (offset += 2)).join(""))
      if (offset >= words.length) {
        clearInterval(timer)
        setCount(index + 2)
        setBusy(false)
        setResponse("")
      }
    }, 24)
  }

  return (
    <div class="flex w-full flex-col gap-4 text-start">
      <Card class="mx-auto h-140 w-full max-w-sm gap-0">
        <CardHeader class="gap-1 border-b">
          <CardTitle>New Chat</CardTitle>
          <CardDescription>How can I help you today?</CardDescription>
          <CardAction>
            <Tooltip>
              <TooltipTrigger
                render={(part) => (
                  <Button
                    {...part}
                    variant="outline"
                    size="icon"
                    aria-label="Reset conversation"
                    disabled={busy()}
                    onClick={() => setCount(0)}
                  />
                )}
              >
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" />
                  <path d="M21 3v5h-5" />
                </svg>
              </TooltipTrigger>
              <TooltipContent>Reset</TooltipContent>
            </Tooltip>
          </CardAction>
        </CardHeader>
        <CardContent class="min-h-0 flex-1 overflow-hidden p-0">
          <Show
            when={count() > 0}
            fallback={
              <Empty class="h-full">
                <EmptyHeader>
                  <EmptyMedia variant="icon">
                    <svg
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M10.1 2.182a10 10 0 0 1 3.8 0" />
                      <path d="M13.9 21.818a10 10 0 0 1-3.8 0" />
                      <path d="M17.609 3.72a10 10 0 0 1 2.69 2.7" />
                      <path d="M2.182 13.9a10 10 0 0 1 0-3.8" />
                      <path d="M20.28 17.61a10 10 0 0 1-2.7 2.69" />
                      <path d="M21.818 10.1a10 10 0 0 1 0 3.8" />
                      <path d="M3.721 6.391a10 10 0 0 1 2.7-2.69" />
                      <path d="m6.163 21.117-2.906.85a1 1 0 0 1-1.236-1.169l.965-2.98" />
                    </svg>
                  </EmptyMedia>
                  <EmptyTitle>Morning, Alex!</EmptyTitle>
                  <EmptyDescription>
                    What are we working on today? Press send to start a new
                    conversation
                  </EmptyDescription>
                </EmptyHeader>
              </Empty>
            }
          >
            <MessageScroller class="h-full">
              <MessageScrollerViewport role="region" aria-label="Messages">
                <MessageScrollerContent
                  class="gap-4 p-(--card-spacing)"
                  role="log"
                  aria-relevant="additions"
                  aria-busy={busy() ? "true" : "false"}
                >
                  <For each={messages.slice(0, count())}>
                    {(message) => (
                      <MessageScrollerItem>
                        <Message
                          align={message.role === "user" ? "end" : "start"}
                        >
                          <MessageContent>
                            <Bubble
                              variant={
                                message.role === "user" ? "muted" : "ghost"
                              }
                            >
                              <BubbleContent class="whitespace-pre-wrap">
                                {message.text}
                              </BubbleContent>
                            </Bubble>
                          </MessageContent>
                        </Message>
                      </MessageScrollerItem>
                    )}
                  </For>
                  <Show when={busy()}>
                    <Bubble variant="ghost">
                      <BubbleContent class="whitespace-pre-wrap">
                        {response()}
                      </BubbleContent>
                    </Bubble>
                  </Show>
                </MessageScrollerContent>
              </MessageScrollerViewport>
              <MessageScrollerButton />
            </MessageScroller>
          </Show>
        </CardContent>
        <CardFooter class="flex-col gap-2">
          <form
            onSubmit={(event) => {
              event.preventDefault()
              send()
            }}
            class="w-full"
          >
            <InputGroup>
              <div class="h-14 w-full px-3 py-2.5">
                <span class={["line-clamp-2", { "opacity-60": busy() }]}>
                  {next()?.text ??
                    "No messages queued. Reset the conversation."}
                </span>
              </div>
              <InputGroupAddon align="block-end" class="pt-1">
                <DropdownMenu>
                  <DropdownMenuTrigger
                    render={(part) => (
                      <InputGroupButton
                        {...part}
                        aria-label="Add files"
                        type="button"
                        size="icon-sm"
                        variant="outline"
                      />
                    )}
                  >
                    <svg
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M5 12h14" />
                      <path d="M12 5v14" />
                    </svg>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="start" side="top" class="w-44">
                    <DropdownMenuItem>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551" />
                      </svg>{" "}
                      Add Photos &amp; Files
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <rect
                          width="18"
                          height="18"
                          x="3"
                          y="3"
                          rx="2"
                          ry="2"
                        />
                        <circle cx="9" cy="9" r="2" />
                        <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
                      </svg>{" "}
                      Create Image
                    </DropdownMenuItem>
                    <DropdownMenuItem>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <path d="m10.065 12.493-6.18 1.318a.934.934 0 0 1-1.108-.702l-.537-2.15a1.07 1.07 0 0 1 .691-1.265l13.504-4.44" />
                        <path d="m13.56 11.747 4.332-.924" />
                        <path d="m16 21-3.105-6.21" />
                        <path d="M16.485 5.94a2 2 0 0 1 1.455-2.425l1.09-.272a1 1 0 0 1 1.212.727l1.515 6.06a1 1 0 0 1-.727 1.213l-1.09.272a2 2 0 0 1-2.425-1.455z" />
                        <path d="m6.158 8.633 1.114 4.456" />
                        <path d="m8 21 3.105-6.21" />
                        <circle cx="12" cy="13" r="2" />
                      </svg>{" "}
                      Deep Research
                    </DropdownMenuItem>
                    <DropdownMenuItem>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        aria-hidden="true"
                      >
                        <circle cx="12" cy="12" r="10" />
                        <path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" />
                        <path d="M2 12h20" />
                      </svg>{" "}
                      Web Search
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
                <InputGroupButton
                  type="submit"
                  variant="default"
                  size="icon-sm"
                  disabled={!next() || busy()}
                  class="ms-auto"
                >
                  <svg
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m5 12 7-7 7 7" />
                    <path d="M12 19V5" />
                  </svg>
                  <span class="sr-only">Send</span>
                </InputGroupButton>
              </InputGroupAddon>
            </InputGroup>
          </form>
        </CardFooter>
      </Card>
      <div class="px-0.5 text-center text-xs text-muted-foreground">
        Demo is read only. Press send to send messages.
      </div>
    </div>
  )
}

What Makes a Great Streaming Chat Experience

Building a chat interface used to be simple. You create an inverted list with an input. Type a message, it appends at the bottom. When a reply comes in, the list grows and scrolls. Done.

Streaming breaks that model. Messages arrive in chunks while you may still be reading, scrolling, or looking somewhere else entirely.

Now the challenge is preserving the reader’s place while the conversation keeps changing. Get that wrong and the experience feels jumpy: people are pulled to the bottom, lose context, and have to find their way back.

In practice, this comes down to scroll: when to follow, when to hold, and when to let the reader decide. A great streaming chat should:

  1. Move only when the reader asked to move. If someone is reading, don’t pull them somewhere else. Auto-scroll should never be the default.
  2. Follow only while they’re following. If they’re at the live edge, keep the stream in view. If they scroll away, leave them there.
  3. Every interaction is a signal. Scrolling is not the only one. Selecting text, using the keyboard, opening a link, or searching should all stop the interface from moving.
  4. Start a new turn near the top of the viewport. This gives the new turn somewhere it can be read from the beginning.
  5. Then stream in the answer. The answer should grow into the screen, not immediately push everything away.
  6. Keep part of the previous conversation in context. The prompt and reply should stay visually connected, and enough of the previous turn should remain visible so the reader knows where they are.
  7. Let new content arrive offscreen. The conversation can keep streaming without changing what the reader is looking at.
  8. Show what’s happening out of view. Make it clear when a response is still streaming or when new messages have arrived.
  9. Make it easy to return to the latest reply. A “Jump to latest” action should bring the reader back and resume following.
  10. Let people jump anywhere in the conversation. Long threads need message links, search, unread markers, and direct navigation.
  11. Reopen where the reader left off. A saved conversation should open at the last meaningful turn. Often this is the last user message. Not the absolute bottom.
  12. Keep the reader’s place when layout changes. Images load. Markdown expands. Code blocks render. Older messages appear above. None of that should make the reader lose their place.
  13. Handle interruptions without stealing position. Stopping, retrying, regenerating, branching, or errors should not unexpectedly move the conversation.
  14. Stay responsive in long threads. Streaming text, markdown, code, images, and long history should still feel responsive.
  15. Be accessible without the noise. Keep the transcript navigable, preserve keyboard focus, and announce important events at a comfortable pace.

Never move the reader against their intent.

MessageScroller

MessageScroller manages the chat transcript viewport. It follows streamed output with stickToEnd and lets readers return to the latest message with MessageScrollerButton.

The examples build turn anchoring, opening positions, history restoration, and message jumps on top of the viewport. Your application owns the transcript, transport, and persistence.

Installation

pnpm dlx solidui-cli@latest add message-scroller

Install the following dependencies:

pnpm add @ui-sdk/solid @ui-sdk/core

Install the required Solid UI dependencies:

pnpm dlx solidui-cli@latest add button

Copy and paste the following code into your project.

components/ui/message-scroller.tsx
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import type { ComponentProps } from "@solidjs/web"
import {
  ScrollArea as SdkScrollArea,
  ScrollAreaViewport as SdkScrollAreaViewport,
  ScrollAreaContent as SdkScrollAreaContent,
  ScrollAreaScrollToEnd as SdkScrollAreaScrollToEnd
} from "@ui-sdk/solid/scroll-area"
import { omit } from "solid-js"

import { cn } from "~/lib/utils"
import { Button } from "~/components/ui/button"

export { createScrollAreaController as createMessageScrollerController } from "@ui-sdk/solid/scroll-area"
export function MessageScroller(
  props: Omit<ComponentProps<typeof SdkScrollArea>, "class"> & {
    class?: string
  }
) {
  return (
    <SdkScrollArea
      stickToEnd
      {...props}
      class={cn(
        "relative min-h-0 min-w-0 overflow-hidden",
        props.class
      )}
    />
  )
}
export function MessageScrollerViewport(
  props: Omit<ComponentProps<typeof SdkScrollAreaViewport>, "class"> & {
    class?: string
  }
) {
  return (
    <SdkScrollAreaViewport
      {...props}
      class={cn(
        "size-full overflow-auto outline-none focus-visible:ring-2 focus-visible:ring-ring",
        props.class
      )}
    />
  )
}
export function MessageScrollerContent(
  props: Omit<ComponentProps<typeof SdkScrollAreaContent>, "class"> & {
    class?: string
  }
) {
  return (
    <SdkScrollAreaContent
      {...props}
      class={cn(
        "gap-6 flex min-w-0 flex-col",
        props.class
      )}
    />
  )
}
export function MessageScrollerItem(props: ComponentProps<"div">) {
  return (
    <div
      {...props}
      data-slot="message-scroller-item"
      class={cn("min-w-0", props.class)}
    />
  )
}
export function MessageScrollerButton(
  props: Omit<ComponentProps<typeof SdkScrollAreaScrollToEnd>, "class"> & {
    class?: string
  }
) {
  const rest = omit(props, "class", "children")
  return (
    <SdkScrollAreaScrollToEnd
      aria-label="Scroll to end"
      render={(p) => <Button {...p} variant="outline" size="icon-sm" />}
      {...rest}
      class={cn(
        "absolute start-1/2 bottom-4 -translate-x-1/2 not-data-visible:pointer-events-none not-data-visible:opacity-0 rtl:translate-x-1/2",
        props.class
      )}
    >
      {props.children ?? (
        <svg
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M12 5v14" />
          <path d="m19 12-7 7-7-7" />
        </svg>
      )}
    </SdkScrollAreaScrollToEnd>
  )
}

Update the import paths to match your project setup.

Usage

import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerViewport
} from "~/components/ui/message-scroller"
<MessageScroller class="h-64">
  <MessageScrollerViewport role="region" aria-label="Messages">
    <MessageScrollerContent role="log" aria-relevant="additions">
      <MessageScrollerItem>Could you check the preview?</MessageScrollerItem>
      <MessageScrollerItem>It is ready to review.</MessageScrollerItem>
    </MessageScrollerContent>
  </MessageScrollerViewport>
  <MessageScrollerButton />
</MessageScroller>

The root uses SDK Scroll Area with stickToEnd. Scroll up to pause following and return to the bottom or press MessageScrollerButton to resume. Use createMessageScrollerController to drive scrolling from another control.

See the UI SDK scroll-area API for native options and keyboard behavior.

Composition

Use the following composition to build a MessageScroller:

MessageScroller
├── MessageScrollerViewport
│   └── MessageScrollerContent
│       ├── MessageScrollerItem
│       └── MessageScrollerItem
└── MessageScrollerButton

Render messages, separators, and other transcript rows inside MessageScrollerContent. Put the scroll-to-end button next to the viewport so it stays outside the scrolling area.

Core Concepts

Anchoring Turns

A turn often starts with a user message, followed by the assistant’s reply. Use Add turn to append both rows. The demo scrolls to the newly added row for the selected anchor role.

Anchoring Turns
Choose which role settles near the top edge.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "Can you show me how anchoring behaves when a new prompt starts the turn?"
  },
  {
    role: "assistant",
    text: "Append the user prompt first, then append the assistant response. With User selected, the prompt settles near the top and the assistant response fills in below it."
  },
  {
    role: "user",
    text: "What changes when assistant messages are the anchor?"
  },
  {
    role: "assistant",
    text: "Now each assistant response is the item `MessageScroller` keeps in view. This is useful when the reply is the moment you want readers to land on after each turn."
  },
  {
    role: "user",
    text: "Can I switch roles and keep adding turns?"
  },
  {
    role: "assistant",
    text: "Yes. The next appended message with the selected role becomes the anchor, so you can compare user and assistant anchoring without resetting the demo."
  }
] as const

export default function MessageScrollerAnchoring() {
  return (
    <MessageScrollerExample
      title="Anchoring Turns"
      description="Choose which role settles near the top edge."
      scenario="anchoring"
      messages={messages}
    />
  )
}

Group Chat

In a group chat, the turn boundary is more specific than “the user message”. It is often the message that asks the model to respond, or a marker like “Marcus joined the chat”. Typing indicators and history controls usually should not anchor.

Because anchoring is role-independent, you can anchor a marker just as easily as a message.

Group Chat
A group chat with several participants and an assistant. The Marker is marked as a turn.
Grace
@mary, the astrophage line keeps matching Venus energy output. Can you check my math?
Mary (Agent)
Yes. Confirmed. The curve points to a microorganism harvesting stellar energy and breeding near carbon dioxide. If @rocky agrees, this is the clue we need.
Grace
ping @rocky
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "participant",
    text: "@mary, the astrophage line keeps matching Venus energy output. Can you check my math?",
    sender: "Grace"
  },
  {
    role: "assistant",
    text: "Yes. Confirmed. The curve points to a microorganism harvesting stellar energy and breeding near carbon dioxide. If @rocky agrees, this is the clue we need.",
    sender: "Mary (Agent)"
  },
  {
    role: "participant",
    text: "ping @rocky",
    sender: "Grace"
  },
  {
    role: "event",
    text: "Rocky has joined the chat"
  },
  {
    role: "participant",
    text: "Amaze. Astrophage eats light, makes heat, goes to carbon dioxide. Rocky has fuel model. Grace is smart.",
    sender: "Rocky"
  }
] as const

export default function MessageScrollerGroupChat() {
  return (
    <MessageScrollerExample
      title="Group Chat"
      description="A group chat with several participants and an assistant. The Marker is marked as a turn."
      scenario="group-chat"
      messages={messages}
    />
  )
}

Keeping Context Visible

Keep the previous message in view while a new reply begins. Press Send to stream a reply and see how the demo scrolls to the preceding row.

Keeping Context Visible
New turns keep part of the previous reply in view.
I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.
That's the classic streaming scroll problem. Wrap your message list in `MessageScroller` and turn on `autoScroll` — the viewport pins to the bottom as tokens arrive, so users always see the latest text land in place. The important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around."
  },
  {
    role: "assistant",
    text: "That's the classic streaming scroll problem. Wrap your message list in `MessageScroller` and turn on `autoScroll` — the viewport pins to the bottom as tokens arrive, so users always see the latest text land in place.\n\nThe important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent."
  },
  {
    role: "user",
    text: "Okay, but when someone sends a new message the view still feels jarring — like the whole conversation reloads from the top."
  },
  {
    role: "assistant",
    text: "MessageScrollerItem fixes that with turn anchoring. Set `scrollAnchor` on the turn that should settle near the top instead of blindly snapping to the document bottom.\n\nIt also leaves a small peek of the previous exchange visible above the anchor, so context isn't lost. The reply starts in view without that disorienting jump you get from a plain overflow container."
  },
  {
    role: "user",
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down."
  },
  {
    role: "assistant",
    text: "You won't. Auto-scroll only runs when the viewport is already pinned to the bottom, so scrolling up is a deliberate opt-out — their place in the thread stays put even as new tokens keep arriving below.\n\nWhen there is content they haven't seen yet, `MessageScrollerButton` appears at the bottom of the viewport. One tap jumps them back to the newest message and re-engages auto-scroll. Same pattern as Slack or iMessage: quiet when you're caught up, helpful when you're not."
  },
  {
    role: "user",
    text: "Last one — does this work with assistive tech?"
  },
  {
    role: "assistant",
    text: '`MessageScrollerContent` sets `role="log"` and `aria-relevant="additions"` by default, so screen readers announce new messages as they stream in.\n\nThe scroll button is a real `<button>` with an sr-only label, and it\'s removed from the tab order when you\'re already at the bottom — no ghost focus stops.'
  }
] as const

export default function MessageScrollerPreviousContext() {
  return (
    <MessageScrollerExample
      title="Keeping Context Visible"
      description="New turns keep part of the previous reply in view."
      scenario="previous-context"
      messages={messages}
    />
  )
}

Following the Live Edge

With stickToEnd, streamed replies stay in view while the reader is at the bottom. Scroll up to pause following. Return to the bottom or use MessageScrollerButton to resume.

Streaming Messages
Auto-scroll follows the live edge of the conversation.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around."
  },
  {
    role: "assistant",
    text: "That's the classic streaming scroll problem. Wrap your message list in `MessageScroller` and turn on `autoScroll` — the viewport pins to the bottom as tokens arrive, so users always see the latest text land in place.\n\nThe important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent."
  },
  {
    role: "user",
    text: "Okay, but when someone sends a new message the view still feels jarring — like the whole conversation reloads from the top."
  },
  {
    role: "assistant",
    text: "MessageScrollerItem fixes that with turn anchoring. Set `scrollAnchor` on the turn that should settle near the top instead of blindly snapping to the document bottom.\n\nIt also leaves a small peek of the previous exchange visible above the anchor, so context isn't lost. The reply starts in view without that disorienting jump you get from a plain overflow container."
  },
  {
    role: "user",
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down."
  },
  {
    role: "assistant",
    text: "You won't. Auto-scroll only runs when the viewport is already pinned to the bottom, so scrolling up is a deliberate opt-out — their place in the thread stays put even as new tokens keep arriving below.\n\nWhen there is content they haven't seen yet, `MessageScrollerButton` appears at the bottom of the viewport. One tap jumps them back to the newest message and re-engages auto-scroll. Same pattern as Slack or iMessage: quiet when you're caught up, helpful when you're not."
  },
  {
    role: "user",
    text: "Last one — does this work with assistive tech?"
  },
  {
    role: "assistant",
    text: '`MessageScrollerContent` sets `role="log"` and `aria-relevant="additions"` by default, so screen readers announce new messages as they stream in.\n\nThe scroll button is a real `<button>` with an sr-only label, and it\'s removed from the tab order when you\'re already at the bottom — no ghost focus stops.'
  }
] as const

export default function MessageScrollerStreaming() {
  return (
    <MessageScrollerExample
      title="Streaming Messages"
      description="Auto-scroll follows the live edge of the conversation."
      scenario="streaming"
      messages={messages}
    />
  )
}

Opening Saved Threads

Try opening the transcript at the start, end, or last user message. The demo uses the scroll controller for the edges and the viewport for the last message.

Opening Position
Choose where a saved transcript opens.
This is the first message the user sent in the conversation.
Workspace creation rose 8%, but first invite completion only rose 2%.
This is the last message the user sent in the conversation.
Start with the invite step. Teams are creating workspaces but waiting to add collaborators. Recommended follow-up: 1. Compare invite drop-off by account size. 2. Check whether users who skip invites still return within 24 hours. 3. Review the empty-state copy on the first project screen. 4. Segment activation by template, since template users may not need invites right away. If that pattern holds, the next experiment should make collaboration useful earlier instead of prompting for invites harder.

Avoiding a Flash on Reload

Server-rendered transcripts initially start at the top. Use stickToEnd for a chat that should open at the latest message, or apply a saved position after the viewport and its rows are mounted.

Loading Earlier Messages

Press Load earlier messages to prepend history. The demo adjusts the viewport offset by the height of the inserted rows so the message you were reading stays in place.

Load History
Prepended messages keep your place.
Only the export queue worker changed. The deploy moved large CSV jobs onto the shared retry policy, which made each failed attempt hold a worker slot longer than before. The app deploy did not include checkout, pricing, or billing API changes.
Do we need to roll back?
Not yet. Queue depth is recovering after we reduced retry concurrency, and the oldest pending job is now under five minutes old. Keep rollback ready if the queue starts climbing again, but the current trend points toward recovery.
Keep watching for customer-visible issues.
I will watch the queue and support tags for another 15 minutes. I am tracking export failures, delayed download requests, and any support thread that mentions missing reports. If those stay quiet through the next batch window, we can close this as an internal degradation.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "Can you summarize the incident channel?"
  },
  {
    role: "assistant",
    text: "The first alert was a delayed export job. It started backing up around 09:42 UTC and triggered the warning once the retry queue crossed the threshold.\n\nNo customer-facing checkout paths were affected, but exports for larger workspaces were running about 12 minutes behind."
  },
  {
    role: "user",
    text: "Was checkout affected?"
  },
  {
    role: "assistant",
    text: "No checkout errors were reported. Payment authorization, order creation, and confirmation emails stayed inside their normal latency bands.\n\nThe only elevated metric was export queue depth, which maps to analytics downloads instead of checkout."
  },
  {
    role: "user",
    text: "What changed in the last deploy?"
  },
  {
    role: "assistant",
    text: "Only the export queue worker changed. The deploy moved large CSV jobs onto the shared retry policy, which made each failed attempt hold a worker slot longer than before.\n\nThe app deploy did not include checkout, pricing, or billing API changes."
  },
  {
    role: "user",
    text: "Do we need to roll back?"
  },
  {
    role: "assistant",
    text: "Not yet. Queue depth is recovering after we reduced retry concurrency, and the oldest pending job is now under five minutes old.\n\nKeep rollback ready if the queue starts climbing again, but the current trend points toward recovery."
  },
  {
    role: "user",
    text: "Keep watching for customer-visible issues."
  },
  {
    role: "assistant",
    text: "I will watch the queue and support tags for another 15 minutes. I am tracking export failures, delayed download requests, and any support thread that mentions missing reports.\n\nIf those stay quiet through the next batch window, we can close this as an internal degradation."
  }
] as const

export default function MessageScrollerLoadHistory() {
  return (
    <MessageScrollerExample
      title="Load History"
      description="Prepended messages keep your place."
      scenario="load-history"
      messages={messages}
    />
  )
}

Animating New Messages

Apply an entrance animation to MessageScrollerItem. The example fades rows in with motion-safe so readers who prefer reduced motion see them immediately.

Animation
Choose how user messages are animated when they are added to the conversation.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "Can user messages pop in like iMessage without breaking anchoring?"
  },
  {
    role: "assistant",
    text: "Yes. Animate the user row with transform and opacity, and let the assistant response stream normally below it.\n\nThat keeps the row measurement predictable while still giving the newly sent bubble a more tactile entrance."
  },
  {
    role: "user",
    text: "What makes the animation feel more like iMessage?"
  },
  {
    role: "assistant",
    text: "Use a quick spring from the trailing edge: a little scale, a small upward move, and no layout animation.\n\nThe bubble feels tactile, but the measured row stays predictable, so anchoring and auto-scroll do not have to fight a changing layout."
  },
  {
    role: "user",
    text: "Can I switch between presets while testing the same thread?"
  },
  {
    role: "assistant",
    text: "Yes. Keep the conversation in place while you change the preset, then send the next message to compare the new entrance against the same context.\n\nThat makes it easier to judge the difference between a subtle fade, a snappy pop, and a more dramatic 3D tilt without rebuilding the scenario each time."
  }
] as const

export default function MessageScrollerAnimation() {
  return (
    <MessageScrollerExample
      title="Animation"
      description="Choose how user messages are animated when they are added to the conversation."
      scenario="animation"
      messages={messages}
    />
  )
}

Jumping to Messages

Use the message picker to jump to a row in the viewport. The Start and End buttons use createMessageScrollerController to scroll to the transcript edges.

Commands
Drive the transcript from outside.
We're seeing activation dip after workspace creation. Can you help me find the likely step?
The sharpest drop is between creating the workspace and inviting the first teammate. Workspace creation is still healthy, but the invite step is where users pause. That suggests the product is asking for collaboration before the user has enough confidence in the workspace.
What should I compare before we change the onboarding flow?
Compare three cohorts: 1. Users who choose a template before inviting teammates. 2. Users who start from a blank workspace. 3. Users who skip invites and return within 24 hours. If template users invite faster, the fix is probably better first-run guidance rather than a louder invite prompt.
Can you turn that into an experiment?
Yes. Create a variant that shows a short checklist after workspace creation: - Pick a template. - Add one project detail. - Invite a teammate when the workspace has context. Measure first invite completion, 24-hour return rate, and whether teams create a second project.
What's the risk if we delay the invite prompt?
The main risk is reducing team creation for accounts that already know who they want to invite. To protect that path, keep the invite action visible in the header and only change the primary empty-state guidance. That gives confident teams a direct route without forcing uncertain users through the invite step too early.

Tracking the Reader’s Position

Read the visible rows from the viewport as it scrolls. The demo shows the first user message still in view.

Transcript Outline
Track the current anchored turn.
Review the incident handoff and tell me what to read first.
Start with the summary and the impact section. The regression affected the upload queue, but the recovery path completed for every queued job.
What was the customer impact?
Impact was limited to delayed processing. No records were dropped, and the reconciliation worker confirmed each retry batch. Support saw confusion from two customers, but there were no checkout or billing errors.
What actions are open?
Keep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix. The alert should fire on sustained queue growth, not a single short spike.
Give me the follow-up checklist.
After that, compare the queue recovery graph with the deploy timeline so the handoff shows exactly when processing returned to baseline. That makes it easier for support and engineering to answer the same customer questions without re-reading the whole incident thread. I would also add a short owner note beside each follow-up item. The checklist is small, but ownership keeps the retry-window decision, alert tuning, and support macro from drifting into separate follow-up conversations. Keep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix. The alert should fire on sustained queue growth, not a single short spike.

Reading Scroll State

Use controller.isAtStart() and controller.isAtEnd() to distinguish the beginning, end, and middle of the transcript.

Scroll Status
Where the reader can go scroll to based on current scroll position.
Message 1. Scroll through the conversation to see how the status changes.
Message 2. Scroll through the conversation to see how the status changes.
Message 3. Scroll through the conversation to see how the status changes.
Message 4. Scroll through the conversation to see how the status changes.
Message 5. Scroll through the conversation to see how the status changes.
Message 6. Scroll through the conversation to see how the status changes.
Message 7. Scroll through the conversation to see how the status changes.
Message 8. Scroll through the conversation to see how the status changes.
Message 9. Scroll through the conversation to see how the status changes.
Message 10. Scroll through the conversation to see how the status changes.
Message 11. Scroll through the conversation to see how the status changes.
Message 12. Scroll through the conversation to see how the status changes.
import { MessageScrollerExample } from "./message-scroller-example"

const messages = [
  {
    role: "user",
    text: "Message 1. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 2. Scroll through the conversation to see how the status changes."
  },
  {
    role: "user",
    text: "Message 3. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 4. Scroll through the conversation to see how the status changes."
  },
  {
    role: "user",
    text: "Message 5. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 6. Scroll through the conversation to see how the status changes."
  },
  {
    role: "user",
    text: "Message 7. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 8. Scroll through the conversation to see how the status changes."
  },
  {
    role: "user",
    text: "Message 9. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 10. Scroll through the conversation to see how the status changes."
  },
  {
    role: "user",
    text: "Message 11. Scroll through the conversation to see how the status changes."
  },
  {
    role: "assistant",
    text: "Message 12. Scroll through the conversation to see how the status changes."
  }
] as const

export default function MessageScrollerScrollable() {
  return (
    <MessageScrollerExample
      title="Scroll Status"
      description="Where the reader can go scroll to based on current scroll position."
      scenario="scrollable"
      messages={messages}
    />
  )
}

Performance

The SDK tracks follow-output in the scroll-area controller. Message rows stay in the DOM while streamed text updates within the active row.

Virtualization

Virtualization is intentionally left outside the primitive. MessageScroller renders real DOM rows and stays fast well into the thousands of turns (see Performance), so most transcripts never need it.

When a transcript is large enough to need virtualization, use MessageScrollerViewport as the scroll element and let the virtualizer own the rows.

Accessibility

MessageScroller keeps the scroll container keyboard reachable and the transcript announceable without forcing a specific message UI.

Give MessageScrollerViewport a descriptive aria-label and role="region" so readers can find the keyboard-scrollable transcript.

Use role="log" and aria-relevant="additions" on MessageScrollerContent to announce new rows without announcing each streamed token.

Pass aria-busy while a turn streams if announcements should wait for the completed message row.

MessageScrollerButton exposes data-visible when readers can return to the end. It is inert while the reader is already there or scrolling there.

Unstyled

Compose the UI SDK Scroll Area parts with stickToEnd to style an end-following transcript.

API Reference

The root exposes the Scroll Area options. Use createMessageScrollerController() with controller to read scroll state or call scrollToEnd().