# Message Scroller

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

Source: https://webjs.dev/ui/docs/primitives/message-scroller

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](https://webjs.dev/ui/docs/components/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](https://webjs.dev/ui/docs/components/button) it styles its scroll button with.

```bash
npx @webjsdev/ui add message-scroller
```

### Install the following dependencies:

```bash
npx @webjsdev/ui add button
```

### Copy and paste the following code into your project.

````ts title="components/ui/message-scroller.ts"
/**
 * 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

```ts
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.

```ts
<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.

| Element | Part |
| --- | --- |
| `<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 need | WebJs UI |
| --- | --- |
| Scroll commands | The element's `scrollToMessage()`, `scrollToEnd()` and `scrollToStart()` methods. |
| Which edges can scroll | The element's `scrollable` property and its `ui-scrollable-change` event. |
| Which rows are visible | The element's `visibleMessageIds` property and its `ui-visibility-change` event. |

```ts
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.

```ts title="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 + ' ';
  }
}
```

```ts title="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.

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `auto-scroll` | `boolean` | `false` | Follow 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. |
| `class` | `string` | - | 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 attribute | Value | Description |
| --- | --- | --- |
| `data-slot` | `"message-scroller-viewport"` | Identifies the scrolling element. |
| `data-pending-scroll` | present | Present until the opening position is applied. The viewport is invisible while it is set. |
| `data-autoscrolling` | present | Present 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>`.

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` | `string` | - | Accessible name for the transcript, passed to the log element. |
| `class` | `string` | - | 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.

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `message-id` | `string` | - | Stable row id used by scrollToMessage() and visibility tracking. |
| `scroll-anchor` | `boolean` | `false` | Marks the row as a turn boundary that anchors near the top when it is appended. |
| `class` | `string` | - | 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"`.

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `direction` | `"end" \| "start"` | `"end"` | Transcript edge the button scrolls toward. |
| `variant` | a [Button](https://webjs.dev/ui/docs/components/button) variant | `"secondary"` | The button's variant. |
| `size` | a [Button](https://webjs.dev/ui/docs/components/button) size | `"icon-sm"` | The button's size. |
| `class` | `string` | - | 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 attribute | Value | Description |
| --- | --- | --- |
| `data-direction` | `"start" \| "end"` | Mirrors direction. |
| `data-active` | `"true" \| "false"` | Whether this button can currently scroll. |
| `data-variant` | `string` | Mirrors variant. |
| `data-size` | `string` | Mirrors size. |

### Methods

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

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

Call `scrollToMessage` once the rows are in the DOM.

`scrollToMessage` options:

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `align` | `"start" \| "center" \| "end" \| "nearest"` | `"start"` | How the item aligns in the viewport. |
| `behavior` | `ScrollBehavior` | `"smooth"`, `"auto"` under reduced motion | Native 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.

| Value | Type | Description |
| --- | --- | --- |
| `start` | `boolean` | Whether the viewport can scroll toward the start. `!start` means it is at the top. |
| `end` | `boolean` | Whether 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.

| Value | Type | Description |
| --- | --- | --- |
| `visibleMessageIds` | `string[]` | 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.
