Skip to content
WebJs
Menu

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, webjs!
What are we working on today? Press send to start a new conversation
Demo is read only. Press send to send messages.
import { html } from '@webjsdev/core';

/**
 * shadcn's message-scroller-demo, the chat card the /ui home page shows too:
 * <message-scroller-demo> (components/message-scroller-demo.ts) is the port.
 */
export default function MessageScrollerDemo() {
  return html`<message-scroller-demo></message-scroller-demo>`;
}
View Code

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 is a chat transcript scroller built for these behaviors. <ui-message-scroller> owns the scroll state and transcript-row behavior: opening position, streamed output, new-turn anchoring, prepended history, visibility, and scroll controls. It is also the styled frame the transcript renders inside, so one element holds both the state and the frame.

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

pnpm dlx @webjsdev/ui add message-scroller

Usage

import '#components/ui/message-scroller.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
<ui-message-scroller>
  <ui-message-scroller-viewport>
    <ui-message-scroller-content aria-label="Conversation">
      ${repeat(messages, (m) => m.id, (m) => html`
        <ui-message-scroller-item
          message-id=${m.id}
          ?scroll-anchor=${m.role === 'user'}
        >
          <div data-slot="message" class=${messageClass()}>...</div>
        </ui-message-scroller-item>
      `)}
    </ui-message-scroller-content>
  </ui-message-scroller-viewport>
  <ui-message-scroller-button></ui-message-scroller-button>
</ui-message-scroller>

<ui-message-scroller> fills its parent, so place it inside a height-constrained container.

<div class="flex h-screen flex-col">
  <ui-message-scroller class="flex-1">...</ui-message-scroller>
</div>

Composition

<ui-message-scroller>
  <ui-message-scroller-viewport>
    <ui-message-scroller-content>
      <ui-message-scroller-item>
        <!-- a message, marker, or row -->
      </ui-message-scroller-item>
      <ui-message-scroller-item></ui-message-scroller-item>
      <ui-message-scroller-item></ui-message-scroller-item>
    </ui-message-scroller-content>
  </ui-message-scroller-viewport>
  <ui-message-scroller-button></ui-message-scroller-button>
</ui-message-scroller>
  • <ui-message-scroller>: the root and the styled frame. Owns the scroll state and the attributes for opening position and auto-scroll, carries the scroll methods, and tracks visibility. It lays out the viewport, content, and controls inside it.
  • <ui-message-scroller-viewport>: the scrollable element. Receives native scroll events, and stays hidden until the opening position applies.
  • <ui-message-scroller-content>: the transcript container. Holds the rows and is the live region that announces new messages.
  • <ui-message-scroller-item>: the transcript row boundary. Wrap every direct child of the content so the scroller can measure, anchor, track visibility, and jump to it. An item can be a message, marker, typing indicator, separator, join/leave event, or "load earlier" row.
  • <ui-message-scroller-button>: the scroll control. Scrolls to the start or end of the transcript and is hidden and out of the tab order until there is content in its direction.

Core Concepts

Anchoring Turns

A turn is the part of the conversation that starts a new exchange. In a simple AI chat, that is usually the user's message and the assistant reply that follows.

An anchor is the row the viewport should treat as the start of that turn. Mark that row with the scroll-anchor attribute. When a new anchor is appended, the viewport moves it near the top and keeps a peek of the previous item above it, so the new turn does not feel detached from its context.

<!-- This tells the scroller to anchor the user's message for the next turn. -->
<ui-message-scroller-item
  message-id=${message.id}
  ?scroll-anchor=${message.role === 'user'}
></ui-message-scroller-item>

Scroll anchors are not tied to message role. You can turn any row into an anchor: a user message, a system marker, a handoff event, or anything else that starts a meaningful turn. The scroller only needs to know which row should anchor the viewport.

In the following example, the user's message is anchored. When you send a new message, the viewport anchors it near the top and appends the assistant reply below it. Toggle the anchor to the assistant's message to see the difference.

Anchoring Turns
Choose which role settles near the top edge.

Can you show me how anchoring behaves when a new prompt starts the turn?

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.

What changes when assistant messages are the anchor?

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.

Can I switch roles and keep adding turns?

Yes. The next appended message with the selected role becomes the anchor, so you can compare user and assistant anchoring without resetting the demo.

Toggle the anchor role, then send messages to compare where turns settle.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { ArrowUpIcon, RotateCwIcon } from '#lib/ui/lucide.ts';

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

const messages: ChatMessage[] = [
  {
    id: 'anchor-1-user',
    role: 'user',
    text: 'Can you show me how anchoring behaves when a new prompt starts the turn?',
  },
  {
    id: 'anchor-1-assistant',
    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.',
  },
  {
    id: 'anchor-2-user',
    role: 'user',
    text: 'What changes when assistant messages are the anchor?',
  },
  {
    id: 'anchor-2-assistant',
    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.',
  },
  {
    id: 'anchor-3-user',
    role: 'user',
    text: 'Can I switch roles and keep adding turns?',
  },
  {
    id: 'anchor-3-assistant',
    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.',
  },
];

// The role whose messages carry scroll-anchor.
const anchorRole = 'user';

const row = (m: ChatMessage) => {
  const user = m.role === 'user';
  return html`
    <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${m.role === anchorRole}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              <p class="whitespace-pre-wrap">${m.text}</p>
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerAnchoring() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Anchoring Turns</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Choose which role settles near the top edge.
          </div>
          <div data-slot="card-action" class=${cardActionClass()}>
            <button type="button" data-slot="button" data-variant="outline" data-size="icon" aria-label="Reset anchored turns" disabled class=${buttonClass({ variant: 'outline', size: 'icon' })}>
              ${RotateCwIcon()}
            </button>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'min-h-0 flex-1 overflow-hidden p-0')}>
          <ui-message-scroller>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Conversation" class="p-(--card-spacing)">
                ${messages.map(row)}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cardFooterClass()}>
          <ui-toggle-group type="single" value=${anchorRole} aria-label="Select scroll anchor role">
            <ui-toggle-group-item value="user" aria-label="Anchor user messages">User</ui-toggle-group-item>
            <ui-toggle-group-item value="assistant" aria-label="Anchor assistant messages">Assistant</ui-toggle-group-item>
          </ui-toggle-group>
          <button type="button" data-slot="button" data-variant="default" data-size="icon" disabled class=${cn(buttonClass({ size: 'icon' }), 'ml-auto')}>
            ${ArrowUpIcon()}
            <span class="sr-only">Send Message</span>
          </button>
        </div>
      </div>
      <div class="mx-auto max-w-xs px-0.5 text-center text-xs text-muted-foreground">
        Toggle the anchor role, then send messages to compare where turns
        settle.
      </div>
    </div>
  `;
}
View Code

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.

<ui-message-scroller-item message-id="marcus-joined" scroll-anchor>
  <div data-slot="marker" data-variant="separator" class=${markerClass({ variant: 'separator' })}>
    <span data-slot="marker-content" class=${markerContentClass()}>Marcus joined the chat</span>
  </div>
</ui-message-scroller-item>
Group Chat
A group chat with several participants and an assistant. The Marker is marked as a turn.
@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.
ping @rocky
Rocky has joined the chat
Rocky
Amaze. Astrophage eats light, makes heat, goes to carbon dioxide. Rocky has fuel model. Grace is smart.
When a user joins, a marker is created. scrollAnchor on the marker marks it as the next turn
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { markerClass, markerContentClass } from '#components/ui/marker.ts';
import { messageClass, messageContentClass, messageHeaderClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { RotateCwIcon } from '#lib/ui/lucide.ts';

const currentUser = 'Grace';

type GroupChatItem =
  | { id: string; type: 'event'; text: string; scrollAnchor?: boolean }
  | {
      id: string;
      type: 'message';
      sender: string;
      role: 'assistant' | 'participant';
      text: string;
      scrollAnchor?: boolean;
    };

// The conversation once Rocky has joined and replied.
const items: GroupChatItem[] = [
  {
    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,
  },
  {
    id: 'group-4',
    type: 'event',
    text: 'Rocky has joined the chat',
    scrollAnchor: true,
  },
  {
    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.',
  },
];

const message = (item: Extract<GroupChatItem, { type: 'message' }>) => {
  const isCurrentUser = item.sender === currentUser;
  const variant = isCurrentUser ? 'muted' : item.role === 'assistant' ? 'ghost' : 'tinted';
  return html`
    <ui-message-scroller-item message-id=${item.id} ?scroll-anchor=${!!item.scrollAnchor}>
      <div data-slot="message" data-align=${isCurrentUser ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          ${isCurrentUser ? '' : html`<div data-slot="message-header" class=${messageHeaderClass()}>${item.sender}</div>`}
          <div data-slot="bubble" data-variant=${variant} class=${bubbleClass({ variant })}>
            <div data-slot="bubble-content" class=${bubbleContentClass()}>${item.text}</div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

const marker = (item: Extract<GroupChatItem, { type: 'event' }>) => html`
  <ui-message-scroller-item message-id=${item.id} ?scroll-anchor=${!!item.scrollAnchor}>
    <div data-slot="marker" data-variant="separator" class=${markerClass({ variant: 'separator' })}>
      <span data-slot="marker-content" class=${markerContentClass()}>${item.text}</span>
    </div>
  </ui-message-scroller-item>
`;

export default function MessageScrollerGroupChat() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Group Chat</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            A group chat with several participants and an assistant. The
            Marker is marked as a turn.
          </div>
          <div data-slot="card-action" class=${cardActionClass()}>
            <ui-tooltip>
              <ui-tooltip-trigger>
                <button type="button" data-slot="tooltip-trigger" data-variant="outline" data-size="icon" aria-label="Reset conversation" class=${buttonClass({ variant: 'outline', size: 'icon' })}>
                  ${RotateCwIcon()}
                </button>
              </ui-tooltip-trigger>
              <ui-tooltip-content><p>Reset</p></ui-tooltip-content>
            </ui-tooltip>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'min-h-0 flex-1 p-0')}>
          <ui-message-scroller>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Group chat" class="p-(--card-spacing)">
                ${items.map((item) => (item.type === 'message' ? message(item) : marker(item)))}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex flex-col items-center gap-2 border-t')}>
          <button type="button" data-slot="button" data-variant="secondary" data-size="default" disabled class=${cn(buttonClass({ variant: 'secondary' }), 'w-full')}>
            Send Message as Rocky
          </button>
          <p class="text-xs text-muted-foreground">
            Now send Rocky's reply into the conversation
          </p>
        </div>
      </div>
      <div class="mx-auto max-w-sm px-0.5 text-center text-xs text-balance text-muted-foreground">
        When a user joins, a marker is created. scrollAnchor on the marker
        marks it as the next turn
      </div>
    </div>
  `;
}
View Code

Keeping Context Visible

When a new turn starts, it should still feel like part of the same continuous thread. The scroller keeps a slice of the previous item visible above the anchor, so the reader keeps their context instead of feeling like the conversation restarted on a blank page.

The kit keeps 64px of the previous turn in view.

<!-- 64px of the previous turn stays visible above a newly anchored row. -->
<ui-message-scroller>...</ui-message-scroller>

The example below shows the peek in a live transcript. Its slider leaves the peek at 64px, since the amount is fixed.

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.

Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.

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.

It 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.

And if they've scrolled up to re-read an older answer? I don't want to yank them back down.

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.

When 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.

Last one: does this work with assistive tech?

`MessageScrollerContent` sets `role="log"` and `aria-relevant="additions"` by default, so screen readers announce new messages as they stream in.

The 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.

Adjust the slider and send. Observe the previous message peak
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { inputGroupClass, inputGroupAddonClass, inputGroupButtonClass } from '#components/ui/input-group.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { sliderClass } from '#components/ui/slider.ts';
import {
  ArrowUpIcon, GlobeIcon, ImageIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon,
} from '#lib/ui/lucide.ts';

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

// The whole script, every turn sent. The kit keeps 64px of the previous
// turn above a new anchored one.
const messages: ChatMessage[] = [
  {
    id: 'context-1',
    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.",
  },
  {
    id: 'context-2',
    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.",
  },
  {
    id: 'context-3',
    role: 'user',
    text: 'Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.',
  },
  {
    id: 'context-4',
    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.",
  },
  {
    id: 'context-5',
    role: 'user',
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down.",
  },
  {
    id: 'context-6',
    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.",
  },
  {
    id: 'context-7',
    role: 'user',
    text: 'Last one: does this work with assistive tech?',
  },
  {
    id: 'context-8',
    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.',
  },
];

const row = (m: ChatMessage) => {
  const user = m.role === 'user';
  const paragraphs = m.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
  return html`
    <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${user}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              ${paragraphs.map((p) => html`<p class="whitespace-pre-wrap">${p}</p>`)}
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerPreviousContext() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Keeping Context Visible</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            New turns keep part of the previous reply in view.
          </div>
          <div data-slot="card-action" class=${cardActionClass()}>
            <ui-tooltip>
              <ui-tooltip-trigger>
                <button type="button" data-slot="tooltip-trigger" data-variant="outline" data-size="icon" aria-label="Reset context example" class=${buttonClass({ variant: 'outline', size: 'icon' })}>
                  ${RotateCwIcon()}
                </button>
              </ui-tooltip-trigger>
              <ui-tooltip-content><p>Reset</p></ui-tooltip-content>
            </ui-tooltip>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'flex-1 overflow-hidden p-0')}>
          <ui-message-scroller>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Conversation" class="p-(--card-spacing)">
                ${messages.map(row)}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex-col gap-2')}>
          <form class="w-full">
            <div data-slot="input-group" role="group" class=${inputGroupClass()}>
              <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="ready">
                  <span class="text-muted-foreground">No messages queued. Reset the context.</span>
                </span>
              </div>
              <div role="group" data-slot="input-group-addon" data-align="block-end" class=${cn(inputGroupAddonClass({ align: 'block-end' }), 'pt-1')}>
                <ui-dropdown-menu>
                  <ui-dropdown-menu-trigger>
                    <button type="button" data-slot="input-group-button" data-variant="outline" data-size="icon-sm" aria-label="Add files" class=${inputGroupButtonClass({ size: 'icon-sm', variant: 'outline' })}>${PlusIcon()}</button>
                  </ui-dropdown-menu-trigger>
                  <ui-dropdown-menu-content align="start" side="top" class="w-44">
                    <ui-dropdown-menu-item>${PaperclipIcon()}Add Photos &amp; Files</ui-dropdown-menu-item>
                    <ui-dropdown-menu-separator></ui-dropdown-menu-separator>
                    <ui-dropdown-menu-item>${ImageIcon()}Create Image</ui-dropdown-menu-item>
                    <ui-dropdown-menu-item>${TelescopeIcon()}Deep Research</ui-dropdown-menu-item>
                    <ui-dropdown-menu-item>${GlobeIcon()}Web Search</ui-dropdown-menu-item>
                  </ui-dropdown-menu-content>
                </ui-dropdown-menu>
                <div class="flex w-28 items-center gap-2">
                  <span class="text-xs text-muted-foreground tabular-nums">64px</span>
                  <ui-slider class="w-full">
                    <input type="range" min="64" max="128" step="1" value="64" disabled aria-label="Previous context peek" class=${sliderClass()}>
                  </ui-slider>
                </div>
                <button type="submit" data-slot="input-group-button" data-variant="default" data-size="icon-sm" disabled class=${cn(inputGroupButtonClass({ size: 'icon-sm', variant: 'default' }), 'ml-auto')}>
                  ${ArrowUpIcon()}<span class="sr-only">Send</span>
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
      <div class="px-0.5 text-center text-xs text-muted-foreground">
        Adjust the slider and send. Observe the previous message peak
      </div>
    </div>
  `;
}
View Code

Following the Live Edge

When the reader is at the live edge, either because they stayed there or returned there, auto-scroll keeps streamed replies in view as they grow. Scrolling away from the live edge releases the view, whether by wheel, touch, keyboard scroll keys, or dragging the scrollbar. New chunks can then arrive without moving the reader.

auto-scroll composes with turn anchoring. When a new turn anchors near the top, the view stays put while the reply streams into the room below it. Once the reply fills the viewport, the reader is back at the live edge and follow-output takes over from the anchor.

<ui-message-scroller auto-scroll>...</ui-message-scroller>
Streaming Messages
Auto-scroll follows the live edge of the conversation.

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.

Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.

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.

It 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.

And if they've scrolled up to re-read an older answer? I don't want to yank them back down.

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.

When 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.

Last one: does this work with assistive tech?

`MessageScrollerContent` sets `role="log"` and `aria-relevant="additions"` by default, so screen readers announce new messages as they stream in.

The 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.

Streaming is simulated. `auto-scroll` is enabled.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { inputGroupClass, inputGroupAddonClass, inputGroupButtonClass } from '#components/ui/input-group.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import {
  ArrowUpIcon, GlobeIcon, ImageIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon,
} from '#lib/ui/lucide.ts';

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

// The whole script, every turn streamed in.
const messages: ChatMessage[] = [
  {
    id: 'stream-1',
    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.",
  },
  {
    id: 'stream-2',
    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.",
  },
  {
    id: 'stream-3',
    role: 'user',
    text: 'Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.',
  },
  {
    id: 'stream-4',
    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.",
  },
  {
    id: 'stream-5',
    role: 'user',
    text: "And if they've scrolled up to re-read an older answer? I don't want to yank them back down.",
  },
  {
    id: 'stream-6',
    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.",
  },
  {
    id: 'stream-7',
    role: 'user',
    text: 'Last one: does this work with assistive tech?',
  },
  {
    id: 'stream-8',
    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.',
  },
];

const note = 'Streaming is simulated. `auto-scroll` is enabled.';

const row = (m: ChatMessage) => {
  const user = m.role === 'user';
  const paragraphs = m.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
  return html`
    <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${user}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              ${paragraphs.map((p) => html`<p class="whitespace-pre-wrap">${p}</p>`)}
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerStreaming() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Streaming Messages</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Auto-scroll follows the live edge of the conversation.
          </div>
          <div data-slot="card-action" class=${cardActionClass()}>
            <ui-tooltip>
              <ui-tooltip-trigger>
                <button type="button" data-slot="tooltip-trigger" data-variant="outline" data-size="icon" aria-label="Reset stream" class=${buttonClass({ variant: 'outline', size: 'icon' })}>
                  ${RotateCwIcon()}
                </button>
              </ui-tooltip-trigger>
              <ui-tooltip-content><p>Reset</p></ui-tooltip-content>
            </ui-tooltip>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'flex-1 overflow-hidden p-0')}>
          <ui-message-scroller auto-scroll>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Conversation" class="p-(--card-spacing)">
                ${messages.map(row)}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex-col gap-2')}>
          <form class="w-full">
            <div data-slot="input-group" role="group" class=${inputGroupClass()}>
              <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="ready">
                  <span class="text-muted-foreground">No messages queued. Reset the stream.</span>
                </span>
              </div>
              <div role="group" data-slot="input-group-addon" data-align="block-end" class=${cn(inputGroupAddonClass({ align: 'block-end' }), 'pt-1')}>
                <ui-dropdown-menu>
                  <ui-dropdown-menu-trigger>
                    <button type="button" data-slot="input-group-button" data-variant="outline" data-size="icon-sm" aria-label="Add files" class=${inputGroupButtonClass({ size: 'icon-sm', variant: 'outline' })}>${PlusIcon()}</button>
                  </ui-dropdown-menu-trigger>
                  <ui-dropdown-menu-content align="start" side="top" class="w-44">
                    <ui-dropdown-menu-item>${PaperclipIcon()}Add Photos &amp; Files</ui-dropdown-menu-item>
                    <ui-dropdown-menu-separator></ui-dropdown-menu-separator>
                    <ui-dropdown-menu-item>${ImageIcon()}Create Image</ui-dropdown-menu-item>
                    <ui-dropdown-menu-item>${TelescopeIcon()}Deep Research</ui-dropdown-menu-item>
                    <ui-dropdown-menu-item>${GlobeIcon()}Web Search</ui-dropdown-menu-item>
                  </ui-dropdown-menu-content>
                </ui-dropdown-menu>
                <button type="submit" data-slot="input-group-button" data-variant="default" data-size="icon-sm" disabled class=${cn(inputGroupButtonClass({ size: 'icon-sm', variant: 'default' }), 'ml-auto')}>
                  ${ArrowUpIcon()}<span class="sr-only">Send</span>
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
      <div class="px-0.5 text-center text-xs text-muted-foreground">
        ${note}
      </div>
    </div>
  `;
}
View Code

Calling scrollToEnd() on the element, or pressing <ui-message-scroller-button>, re-engages follow-output when auto-scroll is set, so a reader who scrolled away can return to the live edge and keep following. The viewport exposes data-autoscrolling while it follows new output, so you can conditionally apply styles during the transition.

Opening Saved Threads

It can seem reasonable to reopen a saved thread at the absolute end of the transcript, but that often drops the reader into the conversation without enough context. A better default is "last-anchor": show the last meaningful turn, like the user's latest message, with the reply below it.

That gives the reader an immediate place in the thread. They can see what they asked, where the answer starts, and continue from there without reconstructing the conversation from the bottom edge.

<ui-message-scroller default-scroll-position="last-anchor">...</ui-message-scroller>
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.

Toggle the defaultScrollPosition to see where the transcript starts when you open the thread

"last-anchor" is keyed on scroll-anchor, not message role. If no anchor exists, it falls back to "end".

Use "start" when you want to resume at the beginning of a conversation, or "end" (the default) when the absolute latest message is the right place to land.

Avoiding a Flash on Reload

A scroll container always opens at the top. HTML has no way to set scrollTop, so a server-rendered transcript shows the oldest messages first. After JavaScript runs, default-scroll-position moves the view, and you would see a jump.

The kit's viewport carries data-pending-scroll from the server render until the element applies the opening position, for every position including "start". The styled viewport stays hidden while the attribute is present, so you see the frame instead of the jump.

The element renders its own viewport and applies the position once it upgrades, so the hidden frame is what shows until then.

Loading Earlier Messages

Loading earlier messages should not move the conversation the reader is already looking at. When older rows are prepended above the current transcript, the browser's own scroll anchoring keeps the visible row in place, so the reader stays where they are while history loads above them.

This needs no setting: the behavior is the browser's own scroll anchoring (overflow-anchor), and it is on by default.

Load History
Prepended messages keep your place.

Can you summarize the incident channel?

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.

No customer-facing checkout paths were affected, but exports for larger workspaces were running about 12 minutes behind.

Was checkout affected?

No checkout errors were reported. Payment authorization, order creation, and confirmation emails stayed inside their normal latency bands.

The only elevated metric was export queue depth, which maps to analytics downloads instead of checkout.

What changed in the last deploy?

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.

End of Conversation
Click Load History to load the entire conversation
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { markerClass, markerContentClass } from '#components/ui/marker.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { RotateCwIcon } from '#lib/ui/lucide.ts';

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

// The whole history, loaded.
const history: ChatMessage[] = [
  { id: 'history-1', role: 'user', text: 'Can you summarize the incident channel?' },
  {
    id: 'history-2',
    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.',
  },
  { id: 'history-3', role: 'user', text: 'Was checkout affected?' },
  {
    id: 'history-4',
    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.',
  },
  { id: 'history-5', role: 'user', text: 'What changed in the last deploy?' },
  {
    id: 'history-6',
    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.',
  },
  { id: 'history-7', role: 'user', text: 'Do we need to roll back?' },
  {
    id: 'history-8',
    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.',
  },
  { id: 'history-9', role: 'user', text: 'Keep watching for customer-visible issues.' },
  {
    id: 'history-10',
    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.',
  },
];

const row = (m: ChatMessage) => {
  const user = m.role === 'user';
  const paragraphs = m.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
  return html`
    <ui-message-scroller-item message-id=${m.id}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              ${paragraphs.map((p) => html`<p class="whitespace-pre-wrap">${p}</p>`)}
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerLoadHistory() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Load History</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Prepended messages keep your place.
          </div>
          <div data-slot="card-action" class=${cardActionClass()}>
            <ui-tooltip>
              <ui-tooltip-trigger>
                <button type="button" data-slot="tooltip-trigger" data-variant="outline" data-size="icon" aria-label="Reset loaded messages" class=${buttonClass({ variant: 'outline', size: 'icon' })}>
                  ${RotateCwIcon()}
                </button>
              </ui-tooltip-trigger>
              <ui-tooltip-content><p>Reset</p></ui-tooltip-content>
            </ui-tooltip>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'flex-1 overflow-hidden p-0')}>
          <ui-message-scroller>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Incident channel" class="p-(--card-spacing)">
                ${history.map(row)}
                <ui-message-scroller-item>
                  <div data-slot="marker" data-variant="separator" class=${markerClass({ variant: 'separator' })}>
                    <span data-slot="marker-content" class=${markerContentClass()}>End of Conversation</span>
                  </div>
                </ui-message-scroller-item>
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex flex-col items-center gap-2 border-t')}>
          <button type="button" data-slot="button" data-variant="secondary" data-size="default" disabled class=${cn(buttonClass({ variant: 'secondary' }), 'w-full')}>
            History Loaded
          </button>
          <p class="text-xs text-muted-foreground">
            Restore earlier messages while keeping your place.
          </p>
        </div>
      </div>
      <div class="mx-auto max-w-sm px-0.5 text-center text-xs text-balance text-muted-foreground">
        Click Load History to load the entire conversation
      </div>
    </div>
  `;
}
View Code

Use stable message-id values for message rows, and render the list with repeat() keyed on them, so a prepend inserts new rows rather than rewriting the ones the reader is looking at.

Animating New Messages

<ui-message-scroller-item> can be animated directly. Keep message-id and scroll-anchor on it, and use transform and opacity for the entrance.

A common chat pattern is to animate the user's message when it is sent, then let the assistant reply stream into a regular row below it. Start the user row below its final position so it feels like it rises from the live edge of the viewport.

item.animate(
  [{ opacity: 0, transform: 'translateY(10px)' }, { opacity: 1, transform: 'none' }],
  { duration: 260, easing: 'cubic-bezier(0.16, 1, 0.3, 1)' },
);

Run it once, when the row is first added, with element.animate() rather than a CSS animation: the content's slot can re-insert an item, which would restart a CSS animation.

Animation
Choose how user messages are animated when they are added to the conversation.

Can user messages pop in like iMessage without breaking anchoring?

Yes. Animate the user row with transform and opacity, and let the assistant response stream normally below it.

That keeps the row measurement predictable while still giving the newly sent bubble a more tactile entrance.

What makes the animation feel more like iMessage?

Use a quick spring from the trailing edge: a little scale, a small upward move, and no layout animation.

The bubble feels tactile, but the measured row stays predictable, so anchoring and auto-scroll do not have to fight a changing layout.

Can I switch between presets while testing the same thread?

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.

That 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.

Select an animation then click send to see it in action.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { selectTriggerClass } from '#components/ui/select.ts';
import { ArrowUpIcon, RotateCwIcon } from '#lib/ui/lucide.ts';

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

const messages: ChatMessage[] = [
  {
    id: 'animation-1',
    role: 'user',
    text: 'Can user messages pop in like iMessage without breaking anchoring?',
  },
  {
    id: 'animation-2',
    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.',
  },
  {
    id: 'animation-3',
    role: 'user',
    text: 'What makes the animation feel more like iMessage?',
  },
  {
    id: 'animation-4',
    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.',
  },
  {
    id: 'animation-5',
    role: 'user',
    text: 'Can I switch between presets while testing the same thread?',
  },
  {
    id: 'animation-6',
    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.',
  },
];

// shadcn's entrance presets, by name.
const presets = [
  { id: 'fade', name: 'Fade' },
  { id: 'slide-up', name: 'Slide Up' },
  { id: 'slide-side', name: 'Slide Side' },
  { id: 'pop', name: 'Pop' },
  { id: 'spring-bounce', name: 'Spring Bounce' },
  { id: 'blur-fade', name: 'Blur Fade' },
  { id: 'scale-fade', name: 'Scale Fade' },
];

const row = (m: ChatMessage) => {
  const user = m.role === 'user';
  const paragraphs = m.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
  return html`
    <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${user}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              ${paragraphs.map((p) => html`<p class="whitespace-pre-wrap">${p}</p>`)}
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerAnimation() {
  return html`
    <div class="relative flex flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Animation</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Choose how user messages are animated when they are added to the
            conversation.
          </div>
          <div data-slot="card-action" class=${cn(cardActionClass(), 'flex items-center gap-2')}>
            <button type="button" data-slot="button" data-variant="outline" data-size="icon" aria-label="Reset animated messages" class=${buttonClass({ variant: 'outline', size: 'icon' })}>
              ${RotateCwIcon()}
            </button>
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'min-h-0 flex-1 overflow-hidden p-0')}>
          <ui-message-scroller>
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Conversation" class="p-(--card-spacing)">
                ${messages.map(row)}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'border-t')}>
          <ui-select position="popper">
            <select aria-label="Animation preset" class=${selectTriggerClass()}>
              ${presets.map((p) => html`<option value=${p.id} ?selected=${p.id === 'fade'}>${p.name}</option>`)}
            </select>
          </ui-select>
          <button type="button" data-slot="button" data-variant="default" data-size="icon" disabled class=${cn(buttonClass({ size: 'icon' }), 'ml-auto')}>
            ${ArrowUpIcon()}
            <span class="sr-only">Send Message</span>
          </button>
        </div>
      </div>
      <div class="mx-auto max-w-sm px-0.5 text-center text-xs text-balance text-muted-foreground">
        Select an animation then click send to see it in action.
      </div>
    </div>
  `;
}
View Code

Avoid animating height, margin, or padding for row entrances; those changes can fight the scroller's positioning work. If the reader prefers reduced motion, skip the entrance animation and keep the scroll behavior the same.

Jumping to Messages

Search results, permalinks, outline items, and toolbar buttons often need to drive the transcript from outside the message list. Call the methods on the <ui-message-scroller> element for those controls. Any code that can reach the element can call them, including controls rendered outside the frame.

const scroller = document.querySelector('ui-message-scroller');
scroller.scrollToMessage(id, { align: 'start' });
scroller.scrollToEnd();
scroller.scrollToStart();
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.

Use the controls to jump to any message in the conversation.

scrollToMessage targets the message-id on <ui-message-scroller-item>, so rows that need to be addressable should have stable ids. It returns nothing, and does nothing when no mounted row has that id.

scrollToMessage does not queue a target before the rows exist, so for a permalink resolved while the transcript mounts, call it once the rows are in the DOM.

Tracking the Reader's Position

Use the element's visibleMessageIds and its ui-visibility-change event to track the reader's position in the conversation. A common example is a table-of-contents or a jump menu that highlights the current anchored turn.

scroller.addEventListener('ui-visibility-change', (e) => {
  const { visibleMessageIds } = e.detail;
});
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.

Open the outline to jump between anchored turns as you read.

visibleMessageIds answers "what is on screen", in document order. To answer "where am I", take the last anchored row at or above the first visible id.

Visibility tracking runs for every item that has a message-id, and rows need one to participate.

Reading Scroll State

Use the element's scrollable property and its ui-scrollable-change event when you need scroll state in JavaScript, such as a status indicator or a custom "jump to latest" control. It reports which edges the viewport can still scroll toward; "at the start/end" is the negation (!start / !end), and "scrollable at all" is start || end. The button styles itself from its data-active attribute.

scroller.addEventListener('ui-scrollable-change', (e) => {
  const { start, end } = e.detail;
});
Scroll Status
Where the reader can go scroll to based on current scroll position.

Review scroll checkpoint 1.

Checkpoint 2 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 3.

Checkpoint 4 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 5.

Checkpoint 6 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 7.

Checkpoint 8 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 9.

Checkpoint 10 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 11.

Checkpoint 12 is synced. The scrollable hook updates as the viewport moves.

When 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.

At the latest message, the footer should switch again and only point them back up.

Scroll the transcript to see the footer update.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';

const messages = 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.`,
}));

// The footer's sentence for the edges the viewport can still scroll toward,
// as the scroller reports them in `scrollable` and ui-scrollable-change.
function scrollStatus({ start, end }: { 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.';
}

const row = (m: (typeof messages)[number]) => {
  const user = m.role === 'user';
  const paragraphs = m.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
  return html`
    <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${user}>
      <div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant=${user ? 'muted' : 'ghost'} class=${bubbleClass({ variant: user ? 'muted' : 'ghost' })}>
            <div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
              ${paragraphs.map((p) => html`<p class="whitespace-pre-wrap">${p}</p>`)}
            </div>
          </div>
        </div>
      </div>
    </ui-message-scroller-item>
  `;
};

export default function MessageScrollerScrollable() {
  return html`
    <div class="mx-auto flex w-full max-w-sm flex-col gap-4">
      <div data-slot="card" data-size="default" class=${cn(cardClass(), 'h-140 w-full gap-0 overflow-hidden')}>
        <div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
          <div data-slot="card-title" class=${cardTitleClass()}>Scroll Status</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Where the reader can go scroll to based on current scroll position.
          </div>
        </div>
        <div data-slot="card-content" class=${cn(cardContentClass(), 'flex-1 overflow-hidden p-0')}>
          <ui-message-scroller default-scroll-position="start">
            <ui-message-scroller-viewport>
              <ui-message-scroller-content aria-label="Conversation" class="gap-4 p-(--card-spacing)">
                ${messages.map(row)}
              </ui-message-scroller-content>
            </ui-message-scroller-viewport>
            <ui-message-scroller-button></ui-message-scroller-button>
          </ui-message-scroller>
        </div>
        <div data-slot="card-footer" class=${cn(cardFooterClass(), 'justify-center border-t text-center text-sm text-muted-foreground')}>
          ${scrollStatus({ start: false, end: true })}
        </div>
      </div>
      <div class="px-0.5 text-center text-xs text-muted-foreground">
        Scroll the transcript to see the footer update.
      </div>
    </div>
  `;
}
View Code

Performance

Our performance goal for the scroller is to keep the scroll hot path off the render path: no re-render of transcript rows when the reader scrolls, and as little off-screen paint work as the browser can avoid.

Scroll position, anchoring, and follow-output are tracked imperatively, by a scroll listener, a ResizeObserver and an IntersectionObserver, and mirrored onto the viewport and button through data-* attributes, so scrolling and streaming do not re-render transcript rows.

The styled <ui-message-scroller-item> also ships with content-visibility: auto and contain-intrinsic-size. Rows stay in the DOM for selection, copy, find-in-page, SSR, and assistive tech, but the browser can skip rendering work for rows far outside the viewport.

This is comfortable for the expected range of a chat transcript: hundreds to low thousands of turns, including messages with markdown and composed components.

Virtualization

Virtualization is intentionally left outside the element. The scroller renders real DOM rows, so most transcripts never need it (see Performance).

When a transcript is large enough to need virtualization, hand the scroller's scrolling element to your virtualizer and let the virtualizer own the rows. The element returns it from viewport().

const scroller = document.querySelector('ui-message-scroller');
const viewport = scroller.viewport(); // the scrolling element

Accessibility

The scroller keeps the transcript announceable without forcing a specific message UI.

<ui-message-scroller-content> marks the transcript as a live region with role="log" and aria-relevant="additions". New rows can be announced, but streamed text mutations do not have to be announced token by token. Label the transcript with aria-label on the element, which passes it to the log.

<ui-message-scroller-content aria-label="Conversation">
  ...
</ui-message-scroller-content>

The viewport is a plain scroll container. To let keyboard users focus the transcript directly, set role="region", an aria-label and tabindex="0" on the scrolling element, which the root's viewport() method returns.

<ui-message-scroller-button> renders a real button named "Scroll to end" or "Scroll to start". When there is nothing to scroll toward, it uses tabindex="-1" and aria-hidden="true", and exposes data-active="false", so inactive scroll controls do not create extra focus stops.

Unstyled

The behavior lives in the elements, and the classes they apply are exported as helpers (messageScrollerClass(), messageScrollerViewportClass(), messageScrollerContentClass(), messageScrollerItemClass(), messageScrollerButtonClass()), so you can read or restyle them. A class on any part is merged with that part's classes.

API Reference

ui-message-scroller

The root and the styled frame.

AttributeTypeDefault
auto-scrollbooleanfalse
default-scroll-position"end" | "start" | "last-anchor""end"
Method or propertyDescription
scrollToEnd()Scrolls to the newest message and follows new ones again.
scrollToStart()Scrolls to the oldest message.
scrollToMessage(id, { align?, behavior? })Scrolls the item with that message-id into view. align is "start" | "center" | "end" | "nearest", "start" by default.
viewport()Returns the scrolling element.
scrollable{ start: boolean, end: boolean }, the edges the viewport can still scroll toward.
visibleMessageIdsThe message-ids on screen, in document order.
EventDetail
ui-scrollable-change{ start: boolean, end: boolean }
ui-visibility-change{ visibleMessageIds: string[] }

ui-message-scroller-viewport

The scrolling element. It carries data-pending-scroll until the opening position applies and data-autoscrolling while it follows new output.

ui-message-scroller-content

The transcript, a role="log" with aria-relevant="additions". Its aria-label is passed to the log.

ui-message-scroller-item

AttributeTypeDefault
message-idstringnone
scroll-anchorbooleanfalse

ui-message-scroller-button

AttributeTypeDefault
direction"end" | "start""end"
varianta Button variant"secondary"
sizea Button size"icon-sm"