A chat scroll container that anchors turns, opens saved transcripts, follows streamed responses, loads history without jumping, and jumps to any message.
Reset
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:
- 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.
- 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.
- 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.
- Start a new turn near the top of the viewport. This gives the new turn somewhere it can be read from the beginning.
- Then stream in the answer. The answer should grow into the screen, not immediately push everything away.
- 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.
- Let new content arrive offscreen. The conversation can keep streaming without changing what the reader is looking at.
- Show what's happening out of view. Make it clear when a response is still streaming or when new messages have arrived.
- Make it easy to return to the latest reply. A "Jump to latest" action should bring the reader back and resume following.
- Let people jump anywhere in the conversation. Long threads need message links, search, unread markers, and direct navigation.
- 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.
- 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.
- Handle interruptions without stealing position. Stopping, retrying, regenerating, branching, or errors should not unexpectedly move the conversation.
- Stay responsive in long threads. Streaming text, markdown, code, images, and long history should still feel responsive.
- 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
Copy and paste the following code into your project.
/**
* Message scroller: the scroll container for a chat transcript. Tier-2. A
* port of shadcn's MessageScroller (the headless primitive in
* `@shadcn/react`, styled): it opens at the newest message, follows new ones
* while the reader is at the end, leaves them where they are once they have
* scrolled up, and offers a button back to the end.
*
* shadcn parity:
* MessageScroller.Provider + MessageScroller
* → <ui-message-scroller auto-scroll default-scroll-position
* scroll-edge-threshold scroll-previous-item-peek>
* MessageScrollerViewport → <ui-message-scroller-viewport>
* MessageScrollerContent → <ui-message-scroller-content> (a role="log")
* MessageScrollerItem (messageId, scrollAnchor)
* → <ui-message-scroller-item message-id scroll-anchor>
* MessageScrollerButton direction, children
* → <ui-message-scroller-button direction="end" | "start" label>,
* its children in place of the arrow
* useMessageScroller() → the element: scrollToEnd(), scrollToStart(), scrollToMessage(id)
* useMessageScrollerScrollable()
* → `scrollable` ({ start, end }) and `ui-scrollable-change`
* useMessageScrollerVisibility()
* → `visibleMessageIds` and `ui-visibility-change`
*
* `default-scroll-position` is where it opens: "end" (the default), "start",
* or "last-anchor", the last item marked `scroll-anchor` at the top (a new
* question with the answer streaming in under it). The transcript is always
* served visible, so it reads with JavaScript off (the opening position is
* then the start, the browser's own). A scroller the browser builds on the
* client, which has never painted, is held invisible until that position
* applies, so the reader never sees a jump; one the server rendered moves
* to it once its script runs.
* After that, an item that ARRIVES marked `scroll-anchor` (the question a
* reader just sent) settles near the top with `scroll-previous-item-peek`
* pixels (64 by default, shadcn's) of the previous turn still in view, and stays there while the reply streams in below it: a
* tail spacer at the end of the list makes the room, and shrinks as the
* reply grows. Once the reply fills the viewport, `auto-scroll` follows it.
* Messages added at the top keep the reader's place through the browser's
* own scroll anchoring. `scroll-edge-threshold` (8 pixels by default,
* shadcn's) is how near an edge counts as being at it: what keeps the
* scroller following, and what shows the button.
*
* A11y (handled by the element, plus your part): the content is a
* `role="log"` that announces additions, and the button is named "Scroll to
* end" / "Scroll to start" (or its `label`) and is inert while there is
* nowhere to go. Your
* part: label the transcript (`aria-label` on `<ui-message-scroller-content>`).
*
* @example
* ```html
* <ui-message-scroller auto-scroll class="h-96">
* <ui-message-scroller-viewport>
* <ui-message-scroller-content aria-label="Conversation">
* <ui-message-scroller-item message-id="m1">Hello</ui-message-scroller-item>
* <ui-message-scroller-item message-id="m2" scroll-anchor>What is WebJs?</ui-message-scroller-item>
* </ui-message-scroller-content>
* </ui-message-scroller-viewport>
* <ui-message-scroller-button></ui-message-scroller-button>
* </ui-message-scroller>
* ```
*/
import { WebComponent, html, prop, signal, nothing } from '@webjsdev/core';
import { cn, takeAuthoredClass } from '../lib/utils.ts';
import { buttonClass, type ButtonVariant, type ButtonSize } from './button.ts';
/** The frame's classes (the element applies them). */
export const messageScrollerClass = (): string =>
'group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden';
/** The scrolling viewport (the element applies them). */
export const messageScrollerViewportClass = (): string =>
'size-full min-h-0 min-w-0 scroll-fade-b scrollbar-thin scrollbar-gutter-stable overflow-y-auto overscroll-contain contain-content data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent data-[pending-scroll]:invisible';
/** The message list (the element applies them). */
export const messageScrollerContentClass = (): string =>
'gap-6 flex h-max min-h-full flex-col';
/** One message (the element puts them on the item itself). */
export const messageScrollerItemClass = (): string =>
'min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]';
/** The scroll button (the element applies them). */
export const messageScrollerButtonClass = (): string =>
'absolute inset-s-1/2 -translate-x-1/2 border-border bg-background text-foreground transition-[translate,scale,opacity] duration-200 hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180';
const ROOT = 'ui-message-scroller';
// How near an edge counts as being at it, in pixels, and how much of the
// previous turn stays in view above a newly anchored one: shadcn's defaults
// (DEFAULT_SCROLL_EDGE_THRESHOLD and DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK).
const EDGE = 8;
const PEEK = 64;
// shadcn's className lands on the element each part renders (the frame, the
// viewport, the list, the button), so each host hands its authored class to
// that element and becomes display: contents. A block host would otherwise
// sit between the frame's flex column and the viewport, the viewport would
// grow to its content, and nothing would scroll.
function takeAuthored(part: HTMLElement): string | null {
return takeAuthoredClass(part, 'contents');
}
function rootOf(el: Element): UiMessageScroller | null {
return (typeof el.closest === 'function' ? el.closest(ROOT) : null) as UiMessageScroller | null;
}
// --------------------------------------------------------------------------
// <ui-message-scroller>
// --------------------------------------------------------------------------
export class UiMessageScroller extends WebComponent({
autoScroll: prop(Boolean, { attribute: 'auto-scroll' }),
defaultScrollPosition: prop<'end' | 'start' | 'last-anchor'>(String, { attribute: 'default-scroll-position' }),
scrollEdgeThreshold: prop(Number, { attribute: 'scroll-edge-threshold' }),
scrollPreviousItemPeek: prop(Number, { attribute: 'scroll-previous-item-peek' }),
}) {
// Served visible: a transcript must read with JavaScript off.
readonly pending = signal(false);
/** The edges the viewport can still scroll toward. */
scrollable = { start: false, end: false };
/** The messages on screen, by `message-id`. */
visibleMessageIds: string[] = [];
_following = true;
_opened = false;
_resize: ResizeObserver | null = null;
_visible: IntersectionObserver | null = null;
_shown = new Set<string>();
// Turn anchoring: the anchored items already placed, the one being held,
// the scroll position that holds it, and the tail spacer's height.
_anchored = new WeakSet<Element>();
_held: Element | null = null;
_heldTop = 0;
_spacerHeight = 0;
_growFrame = 0;
constructor() {
super();
this.autoScroll = false;
this.defaultScrollPosition = 'end';
this.scrollEdgeThreshold = EDGE;
this.scrollPreviousItemPeek = PEEK;
}
connectedCallback(): void {
// A scroller built in the browser has not painted yet, so it is held
// invisible until its opening position applies. One the server rendered
// has painted already (its frame is in the markup), and hiding it now
// would blank text the reader can see, so it moves in place instead.
if (!this._opened && typeof this.querySelector === 'function' && !this.querySelector('[data-slot="message-scroller"]')) this.pending.set(true);
super.connectedCallback?.();
queueMicrotask(() => this._setup());
}
_edge(): number {
const n = Number(this.scrollEdgeThreshold);
return Number.isFinite(n) && n >= 0 ? n : EDGE;
}
_peek(): number {
const n = Number(this.scrollPreviousItemPeek);
return Number.isFinite(n) && n >= 0 ? n : PEEK;
}
disconnectedCallback(): void {
cancelAnimationFrame(this._growFrame);
this._resize?.disconnect();
this._visible?.disconnect();
this._resize = null;
this._visible = null;
super.disconnectedCallback?.();
}
render() {
return html`<div data-slot="message-scroller" ?data-pending-scroll=${this.pending.get()} class=${cn(messageScrollerClass(), takeAuthored(this))}><slot></slot></div>`;
}
viewport(): HTMLElement | null {
return this.querySelector<HTMLElement>('[data-slot="message-scroller-viewport"]');
}
_content(): HTMLElement | null {
return this.querySelector<HTMLElement>('[data-slot="message-scroller-content"]');
}
_items(): UiMessageScrollerItem[] {
if (typeof this.querySelectorAll !== 'function') return [];
return Array.from(this.querySelectorAll<UiMessageScrollerItem>('ui-message-scroller-item')).filter((i) => rootOf(i) === this);
}
_setup(): void {
const viewport = this.viewport();
const content = this._content();
if (!viewport || !content) {
requestAnimationFrame(() => this._setup());
return;
}
viewport.addEventListener('scroll', this._onScroll, { passive: true });
// New or growing messages: follow them if the reader is at the end.
if (typeof ResizeObserver === 'function') {
// Following the end is decided at once, before the next frame's scroll
// event can read the grown list as "scrolled away". The spacer is fitted
// a frame later, since resizing it inside the observed content would
// otherwise loop the observer; its own resize then comes back here.
this._resize = new ResizeObserver(() => {
this._onGrow();
cancelAnimationFrame(this._growFrame);
this._growFrame = requestAnimationFrame(() => this._fitSpacer());
});
this._resize.observe(content);
}
if (typeof IntersectionObserver === 'function') {
this._visible = new IntersectionObserver(this._onIntersect, { root: viewport });
for (const item of this._items()) this._visible.observe(item);
}
requestAnimationFrame(() => this._open());
}
// The opening position, applied once the messages have laid out.
_open(): void {
const viewport = this.viewport();
if (!viewport) return;
const pos = this.defaultScrollPosition;
if (pos === 'start') viewport.scrollTop = 0;
else if (pos === 'last-anchor') {
const anchors = this._items().filter((i) => i.hasAttribute('scroll-anchor'));
const last = anchors[anchors.length - 1];
if (last) this._scrollToItem(last, 'start', 'auto');
else viewport.scrollTop = viewport.scrollHeight;
} else viewport.scrollTop = viewport.scrollHeight;
this._opened = true;
// The turns present at open are placed by the opening position.
for (const item of this._items()) if (item.hasAttribute('scroll-anchor')) this._anchored.add(item);
this._following = this._atEnd();
this.pending.set(false);
// The viewport draws its own pending flag, so it redraws with it.
this.querySelector<UiMessageScrollerViewport>('ui-message-scroller-viewport')?.requestUpdate?.();
this._measure();
}
_atEnd(): boolean {
const v = this.viewport();
return !!v && v.scrollHeight - v.scrollTop - v.clientHeight <= this._edge();
}
_onScroll = (): void => {
// A scroll the reader makes away from the end stops the following; one
// back to the end resumes it.
if (this._opened) this._following = this._atEnd();
this._measure();
};
_onGrow = (): void => {
if (!this._opened) return;
if (this.autoScroll && this._following) {
const v = this.viewport();
if (v) {
v.setAttribute('data-autoscrolling', '');
v.scrollTop = v.scrollHeight;
requestAnimationFrame(() => v.removeAttribute('data-autoscrolling'));
}
}
this._measure();
};
_measure(): void {
const v = this.viewport();
if (!v) return;
const edge = this._edge();
const next = { start: v.scrollTop > edge, end: v.scrollHeight - v.scrollTop - v.clientHeight > edge };
if (next.start !== this.scrollable.start || next.end !== this.scrollable.end) {
this.scrollable = next;
this.dispatchEvent(new CustomEvent('ui-scrollable-change', { bubbles: true, detail: { ...next } }));
}
for (const b of Array.from(this.querySelectorAll<UiMessageScrollerButton>('ui-message-scroller-button'))) b.requestUpdate?.();
}
_onIntersect = (entries: IntersectionObserverEntry[]): void => {
for (const e of entries) {
const id = (e.target as Element).getAttribute('message-id');
if (!id) continue;
if (e.isIntersecting) this._shown.add(id);
else this._shown.delete(id);
}
const ids = this._items().map((i) => i.getAttribute('message-id')).filter((id): id is string => !!id && this._shown.has(id));
this.visibleMessageIds = ids;
this.dispatchEvent(new CustomEvent('ui-visibility-change', { bubbles: true, detail: { visibleMessageIds: ids } }));
};
// An item that arrives after setup is tracked too.
_itemConnected(item: UiMessageScrollerItem): void {
this._visible?.observe(item);
// A new turn marked scroll-anchor settles near the top, a peek of the
// previous turn above it, as shadcn's does. Placed once per item, since
// an item can connect again when the list re-renders around it.
if (this._opened && item.hasAttribute('scroll-anchor') && !this._anchored.has(item)) {
this._anchored.add(item);
requestAnimationFrame(() => this._anchorTurn(item));
}
}
_spacer(): HTMLElement | null {
return this.querySelector<HTMLElement>('[data-message-scroller-spacer]');
}
// Scroll a new anchored turn to the top, keeping the peek of the turn
// before it, with room made below by the tail spacer when the conversation
// is still too short to scroll that far.
_anchorTurn(item: Element): void {
const v = this.viewport();
const content = this._content();
if (!v || !content || !item.isConnected) return;
const pad = parseFloat(getComputedStyle(content).paddingTop) || 0;
// Where the turn sits in the layout, read through offsetTop so a
// transform on it (an entrance sliding it up) does not move the target.
const listTop = v.scrollTop + content.getBoundingClientRect().top - v.getBoundingClientRect().top;
const top = listTop + (item as HTMLElement).offsetTop - content.offsetTop;
this._held = item;
this._heldTop = Math.max(0, top - pad - this._peek());
this._fitSpacer();
v.scrollTo({ top: this._heldTop, behavior: this._behavior() });
}
// The spacer fills exactly the room the held turn needs below it, so it
// shrinks as the reply streams in and the turn stays where it is. Once the
// reply fills the viewport the spacer is gone, and a following viewport
// (auto-scroll) takes over from the end.
_fitSpacer(): void {
const v = this.viewport();
const spacer = this._spacer();
if (!v || !spacer) return;
if (this._held && !this._held.isConnected) this._held = null;
const natural = v.scrollHeight - this._spacerHeight;
const next = this._held ? Math.max(0, Math.ceil(this._heldTop + v.clientHeight - natural)) : 0;
if (next === this._spacerHeight) return;
this._spacerHeight = next;
if (next === 0) this._held = null;
const content = this._content();
const gap = content ? parseFloat(getComputedStyle(content).rowGap) || 0 : 0;
spacer.hidden = next === 0;
spacer.style.height = `${next}px`;
// The list's flex gap would add itself above the spacer, so it is taken
// back. The spacer is never the browser's scroll anchor (overflow-anchor:
// none): it is the last thing in view, so the browser would keep IT in
// place as the reply grows above it, pushing the held turn up a line at
// a time.
spacer.style.marginTop = next > 0 ? `${-gap}px` : '';
}
_scrollToItem(item: Element, align: 'start' | 'center' | 'end' | 'nearest', behavior: ScrollBehavior): void {
const v = this.viewport();
if (!v) return;
const vr = v.getBoundingClientRect();
const ir = item.getBoundingClientRect();
let top = v.scrollTop + (ir.top - vr.top);
if (align === 'end') top -= vr.height - ir.height;
else if (align === 'center') top -= (vr.height - ir.height) / 2;
else if (align === 'nearest') {
if (ir.top >= vr.top && ir.bottom <= vr.bottom) return;
if (ir.bottom > vr.bottom) top -= vr.height - ir.height;
}
v.scrollTo({ top, behavior });
}
_behavior(): ScrollBehavior {
return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth';
}
/** Scroll to the newest message, and follow new ones again. */
scrollToEnd(): void {
const v = this.viewport();
if (!v) return;
this._following = true;
v.scrollTo({ top: v.scrollHeight, behavior: this._behavior() });
}
/** Scroll to the oldest message. */
scrollToStart(): void {
this.viewport()?.scrollTo({ top: 0, behavior: this._behavior() });
}
/** Scroll the message with `id` into view. */
scrollToMessage(id: string, opts: { align?: 'start' | 'center' | 'end' | 'nearest'; behavior?: ScrollBehavior } = {}): void {
const item = this._items().find((i) => i.getAttribute('message-id') === id);
if (item) this._scrollToItem(item, opts.align ?? 'start', opts.behavior ?? this._behavior());
}
}
UiMessageScroller.register('ui-message-scroller');
// --------------------------------------------------------------------------
// <ui-message-scroller-viewport> and <ui-message-scroller-content>
// --------------------------------------------------------------------------
export class UiMessageScrollerViewport extends WebComponent {
render() {
const pending = rootOf(this)?.pending?.get() ?? false;
return html`<div data-slot="message-scroller-viewport" ?data-pending-scroll=${!!pending} class=${cn(messageScrollerViewportClass(), takeAuthored(this))}><slot></slot></div>`;
}
}
UiMessageScrollerViewport.register('ui-message-scroller-viewport');
export class UiMessageScrollerContent extends WebComponent {
render() {
return html`<div
data-slot="message-scroller-content"
role="log"
aria-relevant="additions"
aria-label=${this.getAttribute?.('aria-label') || nothing}
class=${cn(messageScrollerContentClass(), takeAuthored(this))}
><slot></slot><div data-message-scroller-spacer aria-hidden="true" hidden style="overflow-anchor: none"></div></div>`;
}
}
UiMessageScrollerContent.register('ui-message-scroller-content');
// --------------------------------------------------------------------------
// <ui-message-scroller-item>
// --------------------------------------------------------------------------
export class UiMessageScrollerItem extends WebComponent {
_authored: string | null = null;
connectedCallback(): void {
super.connectedCallback?.();
rootOf(this)?._itemConnected(this);
}
// An item is a flex child of the column, so it carries its own classes.
render() {
this._authored = takeAuthoredClass(this);
if (typeof this.setAttribute === 'function') {
this.setAttribute('class', cn(messageScrollerItemClass(), this._authored));
this.setAttribute('data-slot', 'message-scroller-item');
}
return html`<slot></slot>`;
}
}
UiMessageScrollerItem.register('ui-message-scroller-item');
// --------------------------------------------------------------------------
// <ui-message-scroller-button>
// --------------------------------------------------------------------------
export class UiMessageScrollerButton extends WebComponent({
direction: prop<'end' | 'start'>(String),
// The button's accessible name, for a transcript in another language.
label: String,
variant: String,
size: String,
}) {
constructor() {
super();
this.direction = 'end';
this.variant = 'secondary';
this.size = 'icon-sm';
}
render() {
const root = rootOf(this);
const toStart = this.direction === 'start';
const active = !!root && (toStart ? root.scrollable.start : root.scrollable.end);
return html`<button
type="button"
data-slot="message-scroller-button"
data-direction=${toStart ? 'start' : 'end'}
data-variant=${this.variant}
data-size=${this.size}
data-active=${active ? 'true' : 'false'}
tabindex=${active ? nothing : '-1'}
aria-hidden=${active ? nothing : 'true'}
class=${cn(buttonClass({ variant: this.variant as ButtonVariant, size: this.size as ButtonSize }), messageScrollerButtonClass(), takeAuthored(this))}
@click=${() => (toStart ? root?.scrollToStart() : root?.scrollToEnd())}
aria-label=${this.label || nothing}
><slot><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"></path><path d="m19 12-7 7-7-7"></path></svg>${this.label ? '' : html`<span class="sr-only">${toStart ? 'Scroll to start' : 'Scroll to end'}</span>`}</slot></button>`;
}
}
UiMessageScrollerButton.register('ui-message-scroller-button');
Update the import paths to match your project setup.
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.
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>
Reset
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.
Reset
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 & 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>
Reset
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 & 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>
"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.
Reset
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.
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();
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;
});
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;
});
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.
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.