Skip to content
WebJs
Menu

Message Scroller

Use the Message Scroller elements directly, with your own markup and classes on top of the kit's.

Message Scroller is a set of custom elements, <ui-message-scroller> and its parts. The elements own all of the scroll behavior: anchoring turns, following streamed output, keeping the reader's place as history loads, and tracking visibility.

Each element applies the kit's classes to the box it renders, and a class you write on an element is merged with them, so you style the scroller by adding classes, or by editing the copy of the component that the CLI puts in your project.

For the behavior guide and live examples, see the Message Scroller component.

Installation

The elements ship in the Message Scroller component file. Adding it copies components/ui/message-scroller.ts into your project, together with the Button it styles its scroll button with.

pnpm dlx @webjsdev/ui add message-scroller

Usage

import '#components/ui/message-scroller.ts';

Importing the file registers the elements. Each part is its own element, and the behavior is the same one the component page shows.

<ui-message-scroller>
  <ui-message-scroller-viewport>
    <ui-message-scroller-content aria-label="Conversation">
      ${repeat(messages, (message) => message.id, (message) => html`
        <ui-message-scroller-item
          message-id=${message.id}
          ?scroll-anchor=${message.role === 'user'}
        >
          <!-- your message UI -->
        </ui-message-scroller-item>
      `)}
    </ui-message-scroller-content>
  </ui-message-scroller-viewport>
  <ui-message-scroller-button></ui-message-scroller-button>
</ui-message-scroller>

Parts

Each part is one element. The root holds the scroll state and renders the frame, so state and frame are one element.

ElementPart
<ui-message-scroller>The root: the scroll state, the behavior and the frame.
<ui-message-scroller-viewport>The scrolling element.
<ui-message-scroller-content>The transcript list.
<ui-message-scroller-item>One transcript row.
<ui-message-scroller-button>The scroll-to-start or scroll-to-end button.

The state and the commands are members of the <ui-message-scroller> element, which any code that can reach the element can use:

What you needWebJs UI
Scroll commandsThe element's scrollToMessage(), scrollToEnd() and scrollToStart() methods.
Which edges can scrollThe element's scrollable property and its ui-scrollable-change event.
Which rows are visibleThe element's visibleMessageIds property and its ui-visibility-change event.
const scroller = document.querySelector('ui-message-scroller');

scroller.scrollToEnd();
scroller.addEventListener('ui-scrollable-change', (e) => {
  const { start, end } = e.detail;
});
scroller.addEventListener('ui-visibility-change', (e) => {
  const { visibleMessageIds } = e.detail;
});

Example

Here is a complete example that adds its own classes and streams the reply from a 'use server' action. An action that returns an async generator streams each chunk over one response, and the component reads the chunks with for await, appending each to the reply as it arrives.

modules/chat/actions/reply.server.ts
'use server';

export async function* reply(question: string): AsyncGenerator<string> {
  // Yield each chunk as your model or upstream produces it.
  for (const word of `You asked: ${question}`.split(' ')) {
    yield word + ' ';
  }
}
modules/chat/components/chat-thread.ts
import { WebComponent, html, signal } from '@webjsdev/core';
import { repeat } from '@webjsdev/core/directives';
import '#components/ui/message-scroller.ts';
import { reply } from '../actions/reply.server.ts';

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

export class ChatThread extends WebComponent {
  private messages = signal<ChatMessage[]>([]);
  private busy = signal(false);

  private async send(e: SubmitEvent) {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const question = String(new FormData(form).get('question') ?? '').trim();
    if (!question) return;
    form.reset();

    const id = crypto.randomUUID();
    const answerId = `${id}-answer`;
    this.messages.set([
      ...this.messages.get(),
      { id, role: 'user', text: question },
      { id: answerId, role: 'assistant', text: '' },
    ]);
    this.busy.set(true);
    try {
      for await (const chunk of await reply(question)) {
        this.messages.set(this.messages.get().map((m) =>
          m.id === answerId ? { ...m, text: m.text + chunk } : m));
      }
    } finally {
      this.busy.set(false);
    }
  }

  render() {
    return html`
      <div class="flex h-svh w-full flex-col">
        <ui-message-scroller auto-scroll class="flex-1">
          <ui-message-scroller-viewport>
            <ui-message-scroller-content aria-label="Conversation" class="gap-4 p-6 text-base">
              ${repeat(this.messages.get(), (m) => m.id, (m) => html`
                <ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${m.role === 'user'}>
                  <div class="rounded-lg bg-muted p-4">${m.text}</div>
                </ui-message-scroller-item>
              `)}
            </ui-message-scroller-content>
          </ui-message-scroller-viewport>
          <ui-message-scroller-button></ui-message-scroller-button>
        </ui-message-scroller>
        <form class="flex gap-2 p-4" @submit=${(e: SubmitEvent) => this.send(e)}>
          <input name="question" aria-label="Message" class="flex-1 rounded-md border px-3 py-2">
          <button ?disabled=${this.busy.get()}>Send</button>
        </form>
      </div>
    `;
  }
}
ChatThread.register('chat-thread');

<ui-message-scroller-button> renders its own arrow icon and its "Scroll to end" or "Scroll to start" label and takes no content, so it can be restyled with class, variant and size but not relabelled.

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 would show the oldest messages first, and you would see a jump once JavaScript moves the view to default-scroll-position.

The kit handles this for you. The frame and the viewport are served with data-pending-scroll, for every opening position, and the viewport's own classes include data-[pending-scroll]:invisible, so the transcript stays hidden until the element has applied the position and removed the attribute. Because the attribute is only removed by the element, a transcript also stays hidden while JavaScript is off.

No inline script can scroll the server-rendered viewport before the element upgrades. The scrolling element is rendered by <ui-message-scroller-viewport>, so an id written on that element stays on the host rather than reaching the scrolling box, and the element serves its viewport hidden until it upgrades in any case.

API Reference

ui-message-scroller

The root. It owns the scroll state and the behavior, and renders the frame. The frame fills its parent, so use it inside a height-constrained layout.

AttributeTypeDefaultDescription
auto-scrollbooleanfalseFollow new content only while the reader is at the live edge. A scroll away from the end releases it, and a scroll back to the end, or scrollToEnd(), resumes it.
default-scroll-position"end" | "start" | "last-anchor""end"Opening position, applied once after the messages lay out. "last-anchor" opens at the last scroll-anchor item and falls back to "end" when there is none.
classstring-Merged with the frame's classes on the frame element.

The distance that still counts as being at an edge is 24px, and a newly anchored turn keeps 64px of the previous item in view.

The frame carries data-slot="message-scroller" and data-pending-scroll until the opening position applies. It does not carry data-scrollable or data-autoscrolling: read the scroll state from the scrollable property, and data-autoscrolling is on the viewport.

ui-message-scroller-viewport

The scrolling element. A class on it is merged with its classes.

Data attributeValueDescription
data-slot"message-scroller-viewport"Identifies the scrolling element.
data-pending-scrollpresentPresent until the opening position is applied. The viewport is invisible while it is set.
data-autoscrollingpresentPresent for a frame while auto-scroll moves the viewport to the newest content.

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. Keeping the reader's place when rows are prepended is the browser's own scroll anchoring.

ui-message-scroller-content

The transcript. Every direct child should be a <ui-message-scroller-item>.

AttributeTypeDefaultDescription
aria-labelstring-Accessible name for the transcript, passed to the log element.
classstring-Merged with the list's classes on the list element.

The list it renders has role="log" and aria-relevant="additions", which are fixed. It also renders the spacer that makes room under a newly anchored turn, as its last child with data-message-scroller-spacer. The spacer is internal.

ui-message-scroller-item

One transcript row: a message, marker, typing row, separator, or load-more row.

AttributeTypeDefaultDescription
message-idstring-Stable row id used by scrollToMessage() and visibility tracking.
scroll-anchorbooleanfalseMarks the row as a turn boundary that anchors near the top when it is appended.
classstring-Merged with the item's classes on the item itself.

The item is the row box, so it carries its classes and data-slot="message-scroller-item" on itself. It keeps your message-id and scroll-anchor attributes as written, so select on those ([scroll-anchor]). It does not mirror them into data-* attributes.

ui-message-scroller-button

A button that scrolls to the start or end of the transcript. When there is nothing to scroll toward it is hidden, removed from the tab order with tabindex="-1", and hidden from assistive technology with aria-hidden="true".

AttributeTypeDefaultDescription
direction"end" | "start""end"Transcript edge the button scrolls toward.
varianta Button variant"secondary"The button's variant.
sizea Button size"icon-sm"The button's size.
classstring-Merged with the button's classes on the button element.

The button scrolls smoothly, or instantly when the reader prefers reduced motion. It renders its own icon and label.

Data attributeValueDescription
data-direction"start" | "end"Mirrors direction.
data-active"true" | "false"Whether this button can currently scroll.
data-variantstringMirrors variant.
data-sizestringMirrors size.

Methods

Imperative transcript controls, called on the <ui-message-scroller> element.

MethodTypeDescription
scrollToMessage(id: string, options?) => voidScroll to the mounted item with that message-id. Does nothing when no mounted item has it.
scrollToEnd() => voidScroll to the newest message, and follow new ones again when auto-scroll is set.
scrollToStart() => voidScroll to the oldest message.
viewport() => HTMLElement | nullThe scrolling element, for a virtualizer or your own listeners.

Call scrollToMessage once the rows are in the DOM.

scrollToMessage options:

OptionTypeDefaultDescription
align"start" | "center" | "end" | "nearest""start"How the item aligns in the viewport.
behaviorScrollBehavior"smooth", "auto" under reduced motionNative scroll behavior for the command.

scrollable

Which edges the viewport can scroll toward, for UI that needs the values in JavaScript. It is read from the element's scrollable property and reported by the ui-scrollable-change event (which bubbles) each time it changes.

ValueTypeDescription
startbooleanWhether the viewport can scroll toward the start. !start means it is at the top.
endbooleanWhether the viewport can scroll toward the end. !end means it is at the bottom.

visibleMessageIds

Visibility state for outline, search, and active-turn UI. It is read from the element's visibleMessageIds property and reported by the ui-visibility-change event (which bubbles) with { visibleMessageIds } as its detail.

ValueTypeDescription
visibleMessageIdsstring[]The message-ids of the items intersecting the viewport, in document order.

To find the current turn, take the last scroll-anchor item at or above the first visible id. Only items with a message-id are tracked.