Message Scroller
import { ArrowUpIcon, GlobeIcon, ImageIcon, MessageCircleDashedIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon,} from "lucide-solid";import { For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";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 { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";import { createScriptedChat, MessageAnimated, scrollBehaviorScript,} from "./message-scroller-utils";
export default function MessageScrollerDemo() { const chat = createScriptedChat({ delayMs: 20, script: scrollBehaviorScript });
return ( <MessageScroller.Provider> <div class="relative flex flex-col gap-4"> <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 as="span" class="inline-block w-fit"> <Button variant="outline" size="icon" aria-label="Reset conversation" disabled={chat.messages.length === 0 || chat.isBusy()} onClick={chat.reset} > <RotateCwIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Reset</p> </TooltipContent> </Tooltip> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <Show when={chat.messages.length > 0} fallback={ <Empty class="h-full"> <EmptyHeader> <EmptyMedia variant="icon"> <MessageCircleDashedIcon /> </EmptyMedia> <EmptyTitle>Morning, zaidan!</EmptyTitle> <EmptyDescription> What are we working on today? Press send to start a new conversation </EmptyDescription> </EmptyHeader> </Empty> } > <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content aria-busy={chat.isBusy()} class="p-(--card-spacing)"> <For each={chat.messages}> {(message) => <MessageAnimated message={message} />} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </Show> </CardContent> <CardFooter class="flex-col gap-2"> <form class="w-full" onSubmit={(event) => { event.preventDefault(); chat.send(); }} > <InputGroup> <div class="h-14 w-full px-3 py-2.5"> <span class="line-clamp-2 opacity-60 data-[status=ready]:opacity-100" data-status={chat.status()} > <Show when={chat.nextMessage()} keyed fallback={ <span class="text-muted-foreground"> No messages queued. Reset the conversation. </span> } > {(message) => message.text} </Show> </span> </div> <InputGroupAddon align="block-end" class="pt-1"> <DropdownMenu placement="top-start"> <DropdownMenuTrigger as={InputGroupButton} aria-label="Add files" type="button" size="icon-sm" variant="outline" > <PlusIcon /> </DropdownMenuTrigger> <DropdownMenuContent class="w-44"> <DropdownMenuItem> <PaperclipIcon /> Add Photos & Files </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem> <ImageIcon /> Create Image </DropdownMenuItem> <DropdownMenuItem> <TelescopeIcon /> Deep Research </DropdownMenuItem> <DropdownMenuItem> <GlobeIcon /> Web Search </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> <InputGroupButton type="submit" variant="default" size="icon-sm" disabled={!chat.nextMessage() || chat.isBusy()} class="ml-auto" > <ArrowUpIcon /> <span class="sr-only">Send</span> </InputGroupButton> </InputGroupAddon> </InputGroup> </form> </CardFooter> </Card> <div class="px-0.5 text-center text-muted-foreground text-xs"> Demo is read only. Press send to send messages. </div> </div> </MessageScroller.Provider> );}MessageScroller is a Solid chat transcript scroller for saved conversations and live responses. It keeps the reader in control: streaming output follows only at the live edge, appending a turn can preserve nearby context, and prepended history does not displace the visible row.
What Makes a Great Streaming Chat Experience
Streaming changes a simple message list into a scroll-state problem. New content should arrive without taking readers away from a selection, an older reply, a keyboard interaction, or a link they are following.
- Move only when the reader has chosen to follow.
- Keep following while the reader stays at the live edge.
- Treat scrolling, keyboard navigation, and direct jumps as reader intent.
- Start a new turn near the top of the viewport, with a little previous context still visible.
- Let off-screen content arrive quietly, and make it easy to jump back to it.
- Reopen a saved transcript at a meaningful turn rather than always at its final pixel.
- Keep the visible row stable while history, images, or rich content change layout.
- Keep the transcript navigable without noisy announcements.
Never move the reader against their intent.
MessageScroller
MessageScroller is a chat transcript scroller built for these behaviors. MessageScroller.Provider owns the scroll state and transcript-row behavior: opening position, streamed output, new-turn anchoring, prepended history, visibility, and scroll controls. MessageScroller.Root is the styled frame that renders inside it.
MessageScroller is scoped to the scroll viewport. It does not own messages, AI state, transport, persistence, branching, or model state. Your product code stays focused on composing messages, markers, tools, attachments, and prompt inputs.
It gives you the scroll behavior that chat needs, without taking over the rest of the chat UI. And it stays fast, even in long conversations with rich markdown.
Installation
Usage
import { For } from "solid-js";import { MessageScroller } from "~/components/blocks/message-scroller";<MessageScroller.Provider autoScroll> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content> <For each={messages}> {(message) => ( <MessageScroller.Item messageId={message.id} scrollAnchor={message.role === "user"} > <Bubble>Message content</Bubble> </MessageScroller.Item> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root></MessageScroller.Provider>MessageScroller.Root fills its parent, so place it in a height-constrained layout.
<div class="flex h-screen flex-col"> <MessageScroller.Provider> <MessageScroller.Root class="flex-1">{/* transcript */}</MessageScroller.Root> </MessageScroller.Provider></div>Composition
MessageScroller.Provider└── MessageScroller.Root ├── MessageScroller.Viewport │ └── MessageScroller.Content │ └── MessageScroller.Item └── MessageScroller.ButtonMessageScroller.Provideris the headless root. It owns opening position, follow-output, anchoring, scroll commands, and visibility state.MessageScroller.Rootis the styled frame.MessageScroller.Viewportreceives native scroll input and preserves the visible row when history is prepended.MessageScroller.Contentis the transcript container and defaults to a live log.MessageScroller.Itemwraps each direct row so it can be measured, anchored, preserved, tracked, and addressed bymessageId.MessageScroller.Buttonis an inert scroll control until content exists in its direction.
Core Concepts
Anchoring Turns
Mark the row that starts a meaningful exchange with scrollAnchor. It can be a user prompt, a system marker, or a group-chat event; it is not tied to a role. A newly appended anchor settles near the top of the viewport and leaves room for its response below.
import { ArrowUpIcon, MessageCircleDashedIcon, RotateCwIcon } from "lucide-solid";import { createSignal, For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";import { Button } from "~/components/ui/button";import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle,} from "~/components/ui/card";import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,} from "~/components/ui/empty";import { ToggleGroup, ToggleGroupItem } from "~/components/ui/toggle-group";import { createScript, type DemoMessage, MessageAnimated } from "./message-scroller-utils";
type AnchorRole = DemoMessage["role"];
const anchorScript = createScript("anchor", [ { question: "Can you show me how anchoring behaves when a new prompt starts the turn?", answer: "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.", }, { question: "What changes when assistant messages are the anchor?", answer: "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.", }, { question: "Can I switch roles and keep adding turns?", answer: "Yes. The next appended message with the selected role becomes the anchor, so you can compare user and assistant anchoring without resetting the demo.", },]);
export default function MessageScrollerAnchoring() { const [anchorRole, setAnchorRole] = createSignal<AnchorRole>("user"); const [messages, setMessages] = createSignal<DemoMessage[]>([]); const [messageIndex, setMessageIndex] = createSignal(0); const nextMessage = () => anchorScript.messages[messageIndex()];
const reset = () => { setMessages([]); setMessageIndex(0); };
return ( <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="border-b"> <CardTitle>Anchoring Turns</CardTitle> <CardDescription>Choose which role settles near the top edge.</CardDescription> <CardAction> <Button variant="outline" size="icon" aria-label="Reset anchored turns" disabled={messages().length === 0} onClick={reset} > <RotateCwIcon /> </Button> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <Show when={messages().length > 0} fallback={ <Empty class="h-full"> <EmptyHeader> <EmptyMedia variant="icon"> <MessageCircleDashedIcon /> </EmptyMedia> <EmptyTitle>No anchored messages yet</EmptyTitle> <EmptyDescription> Send the first message to see the selected role anchor. </EmptyDescription> </EmptyHeader> </Empty> } > <MessageScroller.Provider> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={messages()}> {(message) => ( <MessageAnimated message={message} scrollAnchor={message.role === anchorRole()} userVariant="muted" assistantVariant="ghost" /> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </MessageScroller.Provider> </Show> </CardContent> <CardFooter> <ToggleGroup aria-label="Select scroll anchor role" value={anchorRole()} onChange={(value) => { if (value === "user" || value === "assistant") { setAnchorRole(value); reset(); } }} > <ToggleGroupItem value="user" aria-label="Anchor user messages"> User </ToggleGroupItem> <ToggleGroupItem value="assistant" aria-label="Anchor assistant messages"> Assistant </ToggleGroupItem> </ToggleGroup> <Button size="icon" class="ml-auto" disabled={!nextMessage()} onClick={() => { const message = nextMessage(); if (!message) return;
setMessages((current) => [...current, message]); setMessageIndex((index) => index + 1); }} > <ArrowUpIcon /> <span class="sr-only">Send Message</span> </Button> </CardFooter> </Card> <div class="mx-auto max-w-xs px-0.5 text-center text-muted-foreground text-xs"> Toggle the anchor role, then send messages to compare where turns settle. </div> </div> );}Group Chat
Group-chat turn boundaries are often markers rather than a participant message. Put the marker inside its own item and set scrollAnchor on that item.
<MessageScroller.Item messageId="marcus-joined" scrollAnchor> <p>Marcus joined the chat</p></MessageScroller.Item>import { RotateCwIcon } from "lucide-solid";import { createSignal, For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";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, MessageHeader } from "~/components/ui/message";import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";import type { BubbleVariant } from "./message-scroller-utils";
type GroupChatItem = | { id: string; type: "event"; text: string; scrollAnchor?: boolean; } | { id: string; type: "message"; sender: string; role: "assistant" | "participant"; text: string; scrollAnchor?: boolean; };
const currentUser = "Grace";
const initialItems = [ { id: "group-1", type: "message", sender: "Grace", role: "participant", text: "@mary, the astrophage line keeps matching Venus energy output. Can you check my math?", }, { id: "group-2", type: "message", sender: "Mary (Agent)", 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.", }, { id: "group-3", type: "message", sender: "Grace", role: "participant", text: "ping @rocky", scrollAnchor: true, },] satisfies GroupChatItem[];
const rockyMarker = { id: "group-4", type: "event", text: "Rocky has joined the chat", scrollAnchor: true,} satisfies GroupChatItem;
const rockyMessage = { id: "group-5", type: "message", sender: "Rocky", role: "participant", text: "Amaze. Astrophage eats light, makes heat, goes to carbon dioxide. Rocky has fuel model. Grace is smart.",} satisfies GroupChatItem;
type RockyTurn = "idle" | "marker" | "message";
export default function MessageScrollerGroupChat() { // Solid has no `key` prop; bumping this value re-creates the keyed `Show` // subtree below, which is how the upstream demo resets scroller state. const [demoKey, setDemoKey] = createSignal(1); const [rockyTurn, setRockyTurn] = createSignal<RockyTurn>("idle"); const items = (): GroupChatItem[] => { if (rockyTurn() === "message") return [...initialItems, rockyMarker, rockyMessage]; if (rockyTurn() === "marker") return [...initialItems, rockyMarker]; return initialItems; }; const buttonLabel = () => (rockyTurn() === "idle" ? "Add Rocky" : "Send Message as Rocky"); const isComplete = () => rockyTurn() === "message";
return ( <MessageScroller.Provider> <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Group Chat</CardTitle> <CardDescription> A group chat with several participants and an assistant. The Marker is marked as a turn. </CardDescription> <CardAction> <Tooltip> <TooltipTrigger as="span" class="inline-block w-fit"> <Button type="button" variant="outline" size="icon" aria-label="Reset conversation" disabled={rockyTurn() === "idle"} onClick={() => { setRockyTurn("idle"); setDemoKey((key) => key + 1); }} > <RotateCwIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Reset</p> </TooltipContent> </Tooltip> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <Show when={demoKey()} keyed> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={items()}> {(item) => item.type === "message" ? ( <GroupChatMessage item={item} /> ) : ( <GroupChatMarker item={item} scrollAnchor={item.scrollAnchor} /> ) } </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </Show> </CardContent> <CardFooter class="flex flex-col items-center gap-2 border-t"> <Button type="button" disabled={isComplete()} onClick={() => setRockyTurn((turn) => (turn === "idle" ? "marker" : "message"))} class="w-full" variant="secondary" > {buttonLabel()} </Button> <p class="text-muted-foreground text-xs"> {rockyTurn() === "idle" ? "This will create a marker and make it the anchor" : "Now send Rocky's reply into the conversation"} </p> </CardFooter> </Card> <div class="mx-auto max-w-sm px-0.5 text-balance text-center text-muted-foreground text-xs"> When a user joins, a marker is created. scrollAnchor on the marker marks it as the next turn </div> </div> </MessageScroller.Provider> );}
function GroupChatMessage(props: { item: Extract<GroupChatItem, { type: "message" }> }) { const isCurrentUser = () => props.item.sender === currentUser; const variant = (): BubbleVariant => { if (isCurrentUser()) return "muted"; return props.item.role === "assistant" ? "ghost" : "tinted"; };
return ( <MessageScroller.Item messageId={props.item.id} scrollAnchor={props.item.scrollAnchor}> <Message align={isCurrentUser() ? "end" : "start"}> <MessageContent> <Show when={!isCurrentUser()}> <MessageHeader>{props.item.sender}</MessageHeader> </Show> <Bubble variant={variant()}> <BubbleContent>{props.item.text}</BubbleContent> </Bubble> </MessageContent> </Message> </MessageScroller.Item> );}
function GroupChatMarker(props: { item: Extract<GroupChatItem, { type: "event" }>; scrollAnchor?: boolean;}) { return ( <MessageScroller.Item scrollAnchor={props.scrollAnchor ?? false}> <Marker variant="separator"> <MarkerContent>{props.item.text}</MarkerContent> </Marker> </MessageScroller.Item> );}Keeping Context Visible
scrollPreviousItemPeek keeps a slice of the prior item above a newly anchored row. This makes a new turn feel connected to the conversation that led into it.
import { ArrowUpIcon, GlobeIcon, ImageIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon,} from "lucide-solid";import { createSignal, For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";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 { InputGroup, InputGroupAddon, InputGroupButton } from "~/components/ui/input-group";import { Slider } from "~/components/ui/slider";import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";import { createScriptedChat, MessageAnimated, scrollBehaviorScript,} from "./message-scroller-utils";
const DEFAULT_PEEK = 64;
export default function MessageScrollerPreviousContext() { const [peek, setPeek] = createSignal(DEFAULT_PEEK); // One turn is already on screen so the peek band has something to preserve. const chat = createScriptedChat({ delayMs: 35, initialCount: 2, script: scrollBehaviorScript, });
return ( <MessageScroller.Provider scrollMargin={24} scrollPreviousItemPeek={peek()}> <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Keeping Context Visible</CardTitle> <CardDescription>New turns keep part of the previous reply in view.</CardDescription> <CardAction> <Tooltip> <TooltipTrigger as="span" class="inline-block w-fit"> <Button variant="outline" size="icon" aria-label="Reset context example" disabled={chat.isBusy()} onClick={() => { chat.reset(); setPeek(DEFAULT_PEEK); }} > <RotateCwIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Reset</p> </TooltipContent> </Tooltip> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content aria-busy={chat.isBusy()} class="p-(--card-spacing)"> <For each={chat.messages}> {(message) => ( <MessageAnimated message={message} scrollAnchor={message.role === "user"} /> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </CardContent> <CardFooter class="flex-col gap-2"> <form class="w-full" onSubmit={(event) => { event.preventDefault(); chat.send(); }} > <InputGroup> <div class="h-14 w-full px-3 py-2.5"> <span class="line-clamp-2 opacity-60 data-[status=ready]:opacity-100" data-status={chat.status()} > <Show when={chat.nextMessage()} keyed fallback={ <span class="text-muted-foreground"> No messages queued. Reset the context. </span> } > {(message) => message.text} </Show> </span> </div> <InputGroupAddon align="block-end" class="pt-1"> <DropdownMenu placement="top-start"> <DropdownMenuTrigger as={InputGroupButton} aria-label="Add files" type="button" size="icon-sm" variant="outline" > <PlusIcon /> </DropdownMenuTrigger> <DropdownMenuContent class="w-44"> <DropdownMenuItem> <PaperclipIcon /> Add Photos & Files </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem> <ImageIcon /> Create Image </DropdownMenuItem> <DropdownMenuItem> <TelescopeIcon /> Deep Research </DropdownMenuItem> <DropdownMenuItem> <GlobeIcon /> Web Search </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> <div class="flex w-28 items-center gap-2"> <span class="text-muted-foreground text-xs tabular-nums">{peek()}px</span> <Slider aria-label="Previous context peek" value={[peek()]} minValue={64} maxValue={128} step={1} disabled={chat.isBusy()} onChange={(value) => setPeek(value[0] ?? DEFAULT_PEEK)} /> </div> <InputGroupButton type="submit" variant="default" size="icon-sm" disabled={!chat.nextMessage() || chat.isBusy()} class="ml-auto" > <ArrowUpIcon /> <span class="sr-only">Send</span> </InputGroupButton> </InputGroupAddon> </InputGroup> </form> </CardFooter> </Card> <div class="px-0.5 text-center text-muted-foreground text-xs"> Adjust the slider and send. Observe the previous message peak </div> </div> </MessageScroller.Provider> );}Following the Live Edge
With autoScroll, streamed output remains visible only while the reader is already at the live edge. Scrolling with a wheel, touch, keyboard, scrollbar, or a direct message jump releases the view. MessageScroller.Button returns to the latest reply and re-engages follow-output.
import { ArrowUpIcon, GlobeIcon, ImageIcon, MessageCircleDashedIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon,} from "lucide-solid";import { For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";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 { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";import { createScriptedChat, MessageAnimated, scrollBehaviorScript,} from "./message-scroller-utils";
export default function MessageScrollerStreaming() { const chat = createScriptedChat({ delayMs: 20, initialCount: 0, script: scrollBehaviorScript, });
return ( <MessageScroller.Provider autoScroll> <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Streaming Messages</CardTitle> <CardDescription> Auto-scroll follows the live edge of the conversation. </CardDescription> <CardAction> <Tooltip> <TooltipTrigger as="span" class="inline-block w-fit"> <Button variant="outline" size="icon" aria-label="Reset stream" disabled={chat.messages.length === 0 || chat.isBusy()} onClick={chat.reset} > <RotateCwIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Reset</p> </TooltipContent> </Tooltip> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <Show when={chat.messages.length > 0} fallback={ <Empty class="h-full"> <EmptyHeader> <EmptyMedia variant="icon"> <MessageCircleDashedIcon /> </EmptyMedia> <EmptyTitle>Ready to Stream</EmptyTitle> <EmptyDescription> Press send to stream a scripted launch summary. </EmptyDescription> </EmptyHeader> </Empty> } > <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content aria-busy={chat.isBusy()} class="p-(--card-spacing)"> <For each={chat.messages}> {(message) => ( <MessageAnimated message={message} scrollAnchor={message.role === "user"} /> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </Show> </CardContent> <CardFooter class="flex-col gap-2"> <form class="w-full" onSubmit={(event) => { event.preventDefault(); chat.send(); }} > <InputGroup> <div class="h-14 w-full px-3 py-2.5"> <span class="line-clamp-2 opacity-60 data-[status=ready]:opacity-100" data-status={chat.status()} > <Show when={chat.nextMessage()} keyed fallback={ <span class="text-muted-foreground"> No messages queued. Reset the stream. </span> } > {(message) => message.text} </Show> </span> </div> <InputGroupAddon align="block-end" class="pt-1"> <DropdownMenu placement="top-start"> <DropdownMenuTrigger as={InputGroupButton} aria-label="Add files" type="button" size="icon-sm" variant="outline" > <PlusIcon /> </DropdownMenuTrigger> <DropdownMenuContent class="w-44"> <DropdownMenuItem> <PaperclipIcon /> Add Photos & Files </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem> <ImageIcon /> Create Image </DropdownMenuItem> <DropdownMenuItem> <TelescopeIcon /> Deep Research </DropdownMenuItem> <DropdownMenuItem> <GlobeIcon /> Web Search </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> <InputGroupButton type="submit" variant="default" size="icon-sm" disabled={!chat.nextMessage() || chat.isBusy()} class="ml-auto" > <ArrowUpIcon /> <span class="sr-only">Send</span> </InputGroupButton> </InputGroupAddon> </InputGroup> </form> </CardFooter> </Card> <div class="px-0.5 text-center text-muted-foreground text-xs"> Streaming is simulated. `autoScroll` is enabled. </div> </div> </MessageScroller.Provider> );}Calling scrollToEnd, or pressing MessageScroller.Button, re-engages follow-output when autoScroll is enabled. The root and viewport expose data-autoscrolling while that programmatic scroll to the latest message runs, so you can apply styles during the transition.
Opening Saved Threads
Use defaultScrollPosition="last-anchor" to reopen at the last meaningful turn. It falls back to the end when no anchor exists or the final anchored turn already fits in view. Use "start" or "end" when those positions better match the product.
import { createEffect, createSignal, For, onCleanup, Show } from "solid-js";import { MessageScroller, useMessageScroller } from "@/registry/kobalte/blocks/message-scroller";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 { Tabs, TabsList, TabsTrigger } from "~/components/ui/tabs";import { type DemoMessage, splitParagraphs } from "./message-scroller-utils";
type Position = "end" | "last-anchor" | "start";
const messages: DemoMessage[] = [ { id: "open-1", role: "user", text: "This is the first message the user sent in the conversation.", }, { id: "open-2", role: "assistant", text: "Workspace creation rose 8%, but first invite completion only rose 2%.", }, { id: "open-3", role: "user", text: "This is the last message the user sent in the conversation.", }, { id: "open-4", role: "assistant", text: "Start with the invite step. Teams are creating workspaces but waiting to add collaborators.\n\nRecommended follow-up:\n\n1. Compare invite drop-off by account size.\n2. Check whether users who skip invites still return within 24 hours.\n3. Review the empty-state copy on the first project screen.\n4. Segment activation by template, since template users may not need invites right away.\n\nIf that pattern holds, the next experiment should make collaboration useful earlier instead of prompting for invites harder.", },];
const positions: { label: string; value: Position }[] = [ { label: "start", value: "start" }, { label: "end", value: "end" }, { label: "last-anchor", value: "last-anchor" },];
export default function MessageScrollerOpeningPosition() { const [position, setPosition] = createSignal<Position>("last-anchor");
return ( <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Opening Position</CardTitle> <CardDescription>Choose where a saved transcript opens.</CardDescription> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <MessageScroller.Provider> {/* Keyed so switching tabs recreates the scroller and genuinely re-opens the thread at the new position. */} <Show when={position()} keyed> {(current) => <OpeningPositionScroller position={current} />} </Show> </MessageScroller.Provider> </CardContent> <CardFooter class="flex items-center justify-center border-t"> <Tabs value={position()} onChange={(value) => setPosition(value as Position)} class="w-full" > <TabsList class="w-full"> <For each={positions}> {(option) => <TabsTrigger value={option.value}>{option.label}</TabsTrigger>} </For> </TabsList> </Tabs> </CardFooter> </Card> <div class="mx-auto max-w-sm px-0.5 text-center text-muted-foreground text-xs"> Toggle the defaultScrollPosition to see where the transcript starts when you open the thread </div> </div> );}
function OpeningPositionScroller(props: { position: Position }) { const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScroller();
createEffect(() => { const position = props.position; const frame = window.requestAnimationFrame(() => { if (position === "start") { scrollToStart({ behavior: "auto" }); return; }
if (position === "end") { scrollToEnd({ behavior: "auto" }); return; }
scrollToMessage("open-3", { align: "start", behavior: "auto", scrollMargin: 64 }); });
onCleanup(() => window.cancelAnimationFrame(frame)); });
return ( <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={messages}> {(message) => { const isUser = message.role === "user";
return ( <MessageScroller.Item messageId={message.id} scrollAnchor={isUser}> <Message align={isUser ? "end" : "start"}> <MessageContent> <Bubble variant={isUser ? "muted" : "ghost"}> <BubbleContent class="space-y-2"> <For each={splitParagraphs(message.text)}> {(paragraph) => <p class="whitespace-pre-wrap">{paragraph}</p>} </For> </BubbleContent> </Bubble> </MessageContent> </Message> </MessageScroller.Item> ); }} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> );}Loading Earlier Messages
preserveScrollOnPrepend is enabled by default on the viewport. Give rows stable messageId values so the component can preserve a specific visible row when older messages are loaded above it.
import { RotateCwIcon } from "lucide-solid";import { createSignal, For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";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 { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip";import { createScript, splitParagraphs } from "./message-scroller-utils";
const script = createScript("history", [ { question: "Can you summarize the incident channel?", answer: "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.", }, { question: "Was checkout affected?", answer: "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.", }, { question: "What changed in the last deploy?", answer: "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.", }, { question: "Do we need to roll back?", answer: "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.", }, { question: "Keep watching for customer-visible issues.", answer: "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.", },]);
const history = script.messages;const INITIAL_VISIBLE_COUNT = 5;
export default function MessageScrollerLoadHistory() { // Starts at 1 so the keyed Show below is always truthy and renders. const [demoKey, setDemoKey] = createSignal(1); const [visibleCount, setVisibleCount] = createSignal(INITIAL_VISIBLE_COUNT); const visibleMessages = () => history.slice(-visibleCount()); const canLoadHistory = () => visibleCount() < history.length;
return ( <MessageScroller.Provider> <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Load History</CardTitle> <CardDescription>Prepended messages keep your place.</CardDescription> <CardAction> <Tooltip> <TooltipTrigger as="span" class="inline-block w-fit"> <Button type="button" variant="outline" size="icon" aria-label="Reset loaded messages" disabled={visibleCount() === INITIAL_VISIBLE_COUNT} onClick={() => { setVisibleCount(INITIAL_VISIBLE_COUNT); setDemoKey((key) => key + 1); }} > <RotateCwIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Reset</p> </TooltipContent> </Tooltip> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> {/* Keyed so resetting recreates the scroller and re-seeds its opening position, matching the upstream remount. */} <Show when={demoKey()} keyed> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={visibleMessages()}> {(message) => { const isUser = message.role === "user";
return ( <MessageScroller.Item messageId={message.id}> <Message align={isUser ? "end" : "start"}> <MessageContent> <Bubble variant={isUser ? "muted" : "ghost"}> <BubbleContent class="space-y-2"> <For each={splitParagraphs(message.text)}> {(paragraph) => ( <p class="whitespace-pre-wrap">{paragraph}</p> )} </For> </BubbleContent> </Bubble> </MessageContent> </Message> </MessageScroller.Item> ); }} </For> <MessageScroller.Item scrollAnchor={false}> <Marker variant="separator"> <MarkerContent>End of Conversation</MarkerContent> </Marker> </MessageScroller.Item> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </Show> </CardContent> <CardFooter class="flex flex-col items-center gap-2 border-t"> <Button type="button" class="w-full" variant="secondary" disabled={!canLoadHistory()} onClick={() => setVisibleCount(history.length)} > {canLoadHistory() ? "Load History" : "History Loaded"} </Button> <p class="text-muted-foreground text-xs"> Restore earlier messages while keeping your place. </p> </CardFooter> </Card> <div class="mx-auto max-w-sm px-0.5 text-center text-muted-foreground text-xs text-balance"> Click Load History to load the entire conversation </div> </div> </MessageScroller.Provider> );}Animating New Messages
Animate a MessageScroller.Item with transform and opacity. Avoid height, margin, and padding animation because layout changes can fight the scroller's position work. Respect reduced-motion preferences while preserving the same scroll behavior.
import { ArrowUpIcon, MessageCircleDashedIcon, RotateCwIcon } from "lucide-solid";import { createSignal, For, Show } from "solid-js";import { MessageScroller } from "@/registry/kobalte/blocks/message-scroller";import { Button } from "~/components/ui/button";import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle,} from "~/components/ui/card";import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,} from "~/components/ui/empty";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "~/components/ui/select";import { createScript, createScriptedChat, MESSAGE_ANIMATIONS, MessageAnimated, type MessageAnimationId, type MessageAnimationPreset,} from "./message-scroller-utils";
const animationScript = createScript("animation", [ { question: "Can user messages pop in like iMessage without breaking anchoring?", answer: "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.", }, { question: "What makes the animation feel more like iMessage?", answer: "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.", }, { question: "Can I switch between presets while testing the same thread?", answer: "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.", },]);
const animationPresets = Object.values(MESSAGE_ANIMATIONS);
export default function MessageScrollerAnimation() { const chat = createScriptedChat({ delayMs: 15, initialCount: 0, script: animationScript }); const [presetId, setPresetId] = createSignal<MessageAnimationId>("fade"); const preset = () => MESSAGE_ANIMATIONS[presetId()];
return ( <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="border-b"> <CardTitle>Animation</CardTitle> <CardDescription> Choose how user messages are animated when they are added to the conversation. </CardDescription> <CardAction class="flex items-center gap-2"> <Button variant="outline" size="icon" aria-label="Reset animated messages" disabled={chat.messages.length === 0 || chat.isBusy()} onClick={chat.reset} > <RotateCwIcon /> </Button> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <Show when={chat.messages.length > 0} fallback={ <Empty class="h-full"> <EmptyHeader> <EmptyMedia variant="icon"> <MessageCircleDashedIcon /> </EmptyMedia> <EmptyTitle>No Messages Yet</EmptyTitle> <EmptyDescription> Click the button below to send the first message. </EmptyDescription> </EmptyHeader> </Empty> } > <MessageScroller.Provider> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content aria-busy={chat.isBusy()} class="p-(--card-spacing)"> <For each={chat.messages}> {(message) => ( <MessageAnimated message={message} animationPreset={preset()} userVariant="muted" assistantVariant="ghost" /> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </MessageScroller.Provider> </Show> </CardContent> <CardFooter class="border-t"> <Select<MessageAnimationPreset> options={animationPresets} optionValue="id" optionTextValue="name" placement="top-start" value={preset()} onChange={(value) => setPresetId(value?.id ?? "fade")} itemComponent={(props) => ( <SelectItem item={props.item}>{props.item.rawValue.name}</SelectItem> )} > <SelectTrigger aria-label="Animation preset"> <SelectValue<MessageAnimationPreset>> {(state) => state.selectedOption().name} </SelectValue> </SelectTrigger> <SelectContent /> </Select> <Button size="icon" class="ml-auto" disabled={!chat.nextMessage() || chat.isBusy()} onClick={chat.send} > <ArrowUpIcon /> <span class="sr-only">Send Message</span> </Button> </CardFooter> </Card> <div class="mx-auto max-w-sm text-balance px-0.5 text-center text-muted-foreground text-xs"> Select an animation then click send to see it in action. </div> </div> );}Jumping to Messages
useMessageScroller exposes commands from anywhere inside the provider, including controls outside the styled frame.
const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScroller();
scrollToMessage("message-id", { align: "start", behavior: "smooth" });scrollToMessage uses the row messageId. It returns false when a target is not mounted and cannot be queued; a true result means the scroll ran or was queued.
import { For } from "solid-js";import { MessageScroller, useMessageScroller } from "@/registry/kobalte/blocks/message-scroller";import { Bubble, BubbleContent } from "~/components/ui/bubble";import { Button } from "~/components/ui/button";import { Card, CardAction, CardContent, CardDescription, 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 { createScript, type DemoMessage, splitParagraphs } from "./message-scroller-utils";
const script = createScript("command", [ { questionId: "command-activation", question: "We're seeing activation dip after workspace creation. Can you help me find the likely step?", answer: "The sharpest drop is between creating the workspace and inviting the first teammate.\n\nWorkspace 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.", }, { questionId: "command-compare", question: "What should I compare before we change the onboarding flow?", answer: "Compare three cohorts:\n\n1. Users who choose a template before inviting teammates.\n2. Users who start from a blank workspace.\n3. Users who skip invites and return within 24 hours.\n\nIf template users invite faster, the fix is probably better first-run guidance rather than a louder invite prompt.", }, { questionId: "command-experiment", question: "Can you turn that into an experiment?", answer: "Yes. Create a variant that shows a short checklist after workspace creation:\n\n- Pick a template.\n- Add one project detail.\n- Invite a teammate when the workspace has context.\n\nMeasure first invite completion, 24-hour return rate, and whether teams create a second project.", }, { questionId: "command-risk", question: "What's the risk if we delay the invite prompt?", answer: "The main risk is reducing team creation for accounts that already know who they want to invite.\n\nTo 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.", },]);
export default function MessageScrollerCommands() { return ( <MessageScroller.Provider defaultScrollPosition="end"> <div class="relative flex flex-col gap-4"> <Card class="mx-auto h-140 w-full max-w-sm gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Commands</CardTitle> <CardDescription>Drive the transcript from outside.</CardDescription> <CardAction> <CommandMenu /> </CardAction> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={script.messages}> {(message) => { const isUser = message.role === "user";
return ( <MessageScroller.Item messageId={message.id} scrollAnchor={isUser}> <Message align={isUser ? "end" : "start"}> <MessageContent> <Bubble variant={isUser ? "muted" : "ghost"}> <BubbleContent class="space-y-2"> <For each={splitParagraphs(message.text)}> {(paragraph) => <p class="whitespace-pre-wrap">{paragraph}</p>} </For> </BubbleContent> </Bubble> </MessageContent> </Message> </MessageScroller.Item> ); }} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </CardContent> </Card> <div class="mx-auto max-w-sm px-0.5 text-center text-muted-foreground text-xs text-balance"> Use the controls to jump to any message in the conversation. </div> </div> </MessageScroller.Provider> );}
function CommandMenu() { const { scrollToMessage } = useMessageScroller();
return ( <DropdownMenu placement="bottom-end"> <DropdownMenuTrigger as={Button} type="button" variant="secondary"> Jump to... </DropdownMenuTrigger> <DropdownMenuContent class="w-64"> <DropdownMenuGroup> <DropdownMenuLabel>Conversations</DropdownMenuLabel> <For each={script.userMessages}> {(message) => ( <DropdownMenuItem onSelect={() => scrollToMessage(message.id, { align: "start", behavior: "smooth" })} > <span class="line-clamp-1 min-w-0">{getTrimmedMessageText(message)}</span> </DropdownMenuItem> )} </For> </DropdownMenuGroup> </DropdownMenuContent> </DropdownMenu> );}
function getTrimmedMessageText(message: DemoMessage) { return message.text.length > 42 ? `${message.text.slice(0, 39)}...` : message.text;}Tracking the Reader's Position
useMessageScrollerVisibility reports the current anchored turn and the message ids currently visible in document order. Tracking is pay-for-what-you-use: it only runs while a consumer subscribes, and rows need messageId values to participate.
import { For } from "solid-js";import { MessageScroller, useMessageScroller, useMessageScrollerVisibility,} from "@/registry/kobalte/blocks/message-scroller";import { Bubble, BubbleContent } from "~/components/ui/bubble";import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from "~/components/ui/card";import { HoverCard, HoverCardContent, HoverCardTrigger } from "~/components/ui/hover-card";import { Message, MessageContent } from "~/components/ui/message";import { createScript, type DemoMessage, splitParagraphs } from "./message-scroller-utils";
const script = createScript("vis", [ { questionId: "vis-brief", question: "Review the incident handoff and tell me what to read first.", answer: "Start with the summary and the impact section. The regression affected the upload queue, but the recovery path completed for every queued job.", }, { questionId: "vis-impact", question: "What was the customer impact?", answer: "Impact was limited to delayed processing.\n\nNo 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.", }, { questionId: "vis-actions", question: "What actions are open?", answer: "Keep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix.\n\nThe alert should fire on sustained queue growth, not a single short spike.", }, { questionId: "vis-checklist", question: "Give me the follow-up checklist.", answer: "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.\n\nI 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.\n\nKeep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix.\n\nThe alert should fire on sustained queue growth, not a single short spike.", },]);
export default function MessageScrollerVisibility() { return ( <MessageScroller.Provider scrollMargin={12}> <div class="relative flex flex-col gap-4"> <div class="relative mx-auto w-full max-w-sm"> <Card class="h-140 w-full gap-0"> <CardHeader class="gap-1 border-b"> <CardTitle>Transcript Outline</CardTitle> <CardDescription>Track the current anchored turn.</CardDescription> </CardHeader> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="p-(--card-spacing)"> <For each={script.messages}> {(message) => { const isUser = message.role === "user";
return ( <MessageScroller.Item messageId={message.id} scrollAnchor={isUser}> <Message align={isUser ? "end" : "start"}> <MessageContent> <Bubble variant={isUser ? "muted" : "ghost"}> <BubbleContent class="space-y-2"> <For each={splitParagraphs(message.text)}> {(paragraph) => ( <p class="whitespace-pre-wrap">{paragraph}</p> )} </For> </BubbleContent> </Bubble> </MessageContent> </Message> </MessageScroller.Item> ); }} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </CardContent> </Card> <div class="-right-12 -translate-y-1/2 absolute top-1/2"> <TranscriptOutline /> </div> </div> <div class="mx-auto max-w-sm px-0.5 text-center text-muted-foreground text-xs"> Open the outline to jump between anchored turns as you read. </div> </div> </MessageScroller.Provider> );}
function TranscriptOutline() { const { scrollToMessage } = useMessageScroller(); // `currentAnchorId` is a getter; read it through the object at each use site // so the outline stays reactive. Destructuring would freeze it. const visibility = useMessageScrollerVisibility();
return ( <HoverCard placement="left"> <HoverCardTrigger as="button" type="button" aria-label="Open transcript outline" class="flex h-9 w-9 flex-col items-center justify-center gap-1 rounded-md outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/50" > <For each={script.userMessages}> {(message) => ( <span data-current={message.id === visibility.currentAnchorId} class="h-0.5 w-4 rounded-full bg-muted-foreground/40 data-[current=true]:bg-foreground" /> )} </For> </HoverCardTrigger> <HoverCardContent class="flex w-64 flex-col gap-1 rounded-2xl p-1"> <For each={script.userMessages}> {(message) => ( <button type="button" aria-current={visibility.currentAnchorId === message.id ? "location" : undefined} class="flex min-h-7 items-center rounded-xl px-2 py-1.5 text-left text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground aria-current:bg-accent aria-current:text-accent-foreground" onClick={() => scrollToMessage(message.id, { align: "start", behavior: "smooth" })} > <span class="line-clamp-1 min-w-0">{getTrimmedMessageText(message)}</span> </button> )} </For> </HoverCardContent> </HoverCard> );}
function getTrimmedMessageText(message: DemoMessage) { return message.text.length > 42 ? `${message.text.slice(0, 39)}...` : message.text;}Reading Scroll State
useMessageScrollerScrollable reports whether the viewport can still scroll toward the start or end. The opposite tells you that the corresponding edge has been reached. For styles, prefer the root data-scrollable state.
import { For } from "solid-js";import { MessageScroller, useMessageScrollerScrollable,} from "@/registry/kobalte/blocks/message-scroller";import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle,} from "~/components/ui/card";import { type DemoMessage, MessageAnimated } from "./message-scroller-utils";
const messages: DemoMessage[] = Array.from({ length: 12 }, (_, index) => ({ id: `scrollable-${index + 1}`, role: index % 2 === 0 ? "user" : "assistant", text: index % 2 === 0 ? `Review scroll checkpoint ${index + 1}.` : `Checkpoint ${index + 1} is synced. The scrollable hook updates as the viewport moves.\n\nWhen the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.\n\nAt the latest message, the footer should switch again and only point them back up.`,}));
export default function MessageScrollerScrollable() { return ( <div class="mx-auto flex w-full max-w-sm flex-col gap-4"> <Card class="h-140 w-full gap-0 overflow-hidden"> <CardHeader class="gap-1 border-b"> <CardTitle>Scroll Status</CardTitle> <CardDescription> Where the reader can go scroll to based on current scroll position. </CardDescription> </CardHeader> <MessageScroller.Provider defaultScrollPosition="start"> <CardContent class="min-h-0 flex-1 overflow-hidden p-0"> <MessageScroller.Root> <MessageScroller.Viewport> <MessageScroller.Content class="gap-4 p-(--card-spacing)"> <For each={messages}> {(message) => ( <MessageAnimated message={message} scrollAnchor={message.role === "user"} userVariant="muted" assistantVariant="ghost" /> )} </For> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </CardContent> <ScrollStateFooter /> </MessageScroller.Provider> </Card> <div class="px-0.5 text-center text-muted-foreground text-xs"> Scroll the transcript to see the footer update. </div> </div> );}
function ScrollStateFooter() { // The hook returns getters; reading them inside the thunk keeps the footer // reactive. Destructuring here would freeze the status at its first value. const scrollable = useMessageScrollerScrollable(); const status = () => getScrollStatus(scrollable.start, scrollable.end);
return ( <CardFooter class="justify-center border-t text-center text-muted-foreground text-sm"> {status()} </CardFooter> );}
function getScrollStatus(start: boolean, end: boolean) { if (start && end) { return "You can scroll both ways."; }
if (end) { return "You are at the top. You can only scroll down."; }
if (start) { return "You are at the bottom. You can only scroll up."; }
return "All messages fit in the viewport.";}Performance
The scroll hot path is imperative: transcript rows do not rerender for each scroll event. The root and viewport mirror relevant state through data attributes, and each item uses content-visibility: auto with an intrinsic size so far-off rows can avoid paint work while remaining present for selection, find-in-page, server rendering, and assistive technology.
For the expected range of hundreds to low thousands of rich transcript rows, real DOM items preserve the best selection and accessibility behavior. When a much larger transcript needs virtualization, use MessageScroller.Viewport as the virtualizer's scroll element and let the virtualizer own the rows.
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 MessageScroller.Viewport as the scroll element and let the virtualizer own the rows.
import { createVirtualizer } from "@tanstack/solid-virtual";import type { JSX } from "solid-js";import { For, Show } from "solid-js";import { MessageScroller } from "~/components/blocks/message-scroller";
function VirtualizedTranscript(props: { messages: { id: string; content: JSX.Element }[] }) { let viewportRef: HTMLDivElement | undefined;
const virtualizer = createVirtualizer({ get count() { return props.messages.length; }, getScrollElement: () => viewportRef ?? null, estimateSize: () => 86, getItemKey: (index) => props.messages[index]?.id ?? index, overscan: 8, });
return ( <MessageScroller.Provider> <MessageScroller.Root> <MessageScroller.Viewport ref={(element) => (viewportRef = element)}> <MessageScroller.Content class="block min-h-full"> <div class="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}> <For each={virtualizer.getVirtualItems()}> {(virtualItem) => { const message = () => props.messages[virtualItem.index];
return ( <Show when={message()}> {(item) => ( <div data-index={virtualItem.index} ref={virtualizer.measureElement} class="absolute start-0 top-0 w-full" style={{ transform: `translateY(${virtualItem.start}px)` }} > <Bubble>{item().content}</Bubble> </div> )} </Show> ); }} </For> </div> </MessageScroller.Content> </MessageScroller.Viewport> <MessageScroller.Button /> </MessageScroller.Root> </MessageScroller.Provider> );}Accessibility
MessageScroller.Content defaults to role="log" and aria-relevant="additions". Set aria-busy while a response is streaming so assistive technology receives a coherent update. The viewport is a labelled, keyboard-focusable region; scroll keys signal reader intent, and the inactive scroll button is removed from tab order.
<MessageScroller.Content aria-busy={status() === "streaming"}> {/* messages */}</MessageScroller.Content>API Reference
This is native Solid composition rather than a wrapped primitive. The full implementation lives in the Message Scroller source.
MessageScroller.Provider
The headless root. It owns scroll state and the behavior props, provides them to the parts and hooks, and renders no DOM of its own.
MessageScroller.Root
The styled frame and layout container. It fills its parent, so use it inside a height-constrained layout, within a MessageScroller.Provider. Remaining props spread onto the frame div.
The root mirrors the scroll-state attributes below (the viewport carries them too), so you can style the container by scroll state, such as edge fades on the frame.
MessageScroller.Viewport
The scrollable viewport. Remaining props spread onto the viewport div, and it carries the same data attributes as the root.
MessageScroller.Content
The transcript content element. Every direct child should be a MessageScroller.Item. Remaining props spread onto the content div.
MessageScroller.Item
One transcript row: a message, marker, typing row, separator, or load-more row. Remaining props spread onto the item div.
MessageScroller.Button
A button that scrolls to the start or end of the transcript. It is inert and removed from the tab order when there is nothing to scroll toward. Remaining props are forwarded to the underlying Button, including variant (default "secondary") and size (default "icon-sm").
useMessageScroller
Imperative transcript commands, available anywhere inside the provider.
All commands return false when the command could not be applied. scrollToStart and scrollToEnd return false only when the viewport is not mounted yet. scrollToMessage returns false when the target is not mounted and cannot be queued.
Command options:
useMessageScrollerScrollable
Which edges the viewport can scroll toward, for sibling UI that needs the values in JavaScript. Prefer the data-scrollable attribute for styling the scroller itself.
useMessageScrollerVisibility
Visibility state for outline, search, and active-turn UI. It subscribes separately from useMessageScrollerScrollable, so visibility work is only paid for when a consumer needs it.
Filter visibleMessageIds in your app when you need a narrower outline, such as user messages, anchored turns, or search hits.