# Message Scroller

A user-respecting transcript scroller for live replies, saved conversations, and long message history.

Message Scroller manages the scrolling behavior around a conversation without owning the message UI. It follows new content only while the reader is at the live edge, preserves their position when older history is prepended, and exposes commands for navigation.

```tsx
import { ArrowClockwiseIcon, ArrowUpIcon, ChatCircleDotsIcon, PlusIcon } from "@phosphor-icons/react";
import { useChat } from "@ai-sdk/react";
import type { ChatTransport, TextUIPart, UIMessage, UIMessageChunk } from "ai";
import { Bubble, Center, IconButton, Message, MessageScroller, Stack, Text, Textarea, VisuallyHidden } from "@zentara-co/zenos-ui";
import { useState } from "react";

const messageScrollerInitialPrompt =
  "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.";

const messageScrollerMockReply =
  "That is the classic streaming scroll problem. MessageScroller follows new content only while the reader is already at the live edge. If they scroll up, their position stays put while the response continues below. The jump button brings them back whenever they are ready.";

const messageScrollerChunkDelay = 24;

function waitForMessageScrollerChunk(signal?: AbortSignal) {
  return new Promise<boolean>((resolve) => {
    if (signal?.aborted) {
      resolve(false);
      return;
    }

    const timer = window.setTimeout(() => {
      signal?.removeEventListener("abort", handleAbort);
      resolve(true);
    }, messageScrollerChunkDelay);
    const handleAbort = () => {
      window.clearTimeout(timer);
      resolve(false);
    };
    signal?.addEventListener("abort", handleAbort, { once: true });
  });
}

const messageScrollerMockTransport = {
  async sendMessages({ abortSignal, messages }) {
    const messageNumber = messages.length;
    const messageId = `assistant-${messageNumber}`;
    const textId = `assistant-text-${messageNumber}`;

    return new ReadableStream<UIMessageChunk>({
      async start(controller) {
        controller.enqueue({ type: "start", messageId });
        controller.enqueue({ type: "text-start", id: textId });

        for (const delta of messageScrollerMockReply.split(/(?<=\s)/)) {
          if (!(await waitForMessageScrollerChunk(abortSignal))) {
            controller.enqueue({ type: "abort" });
            controller.close();
            return;
          }
          controller.enqueue({ type: "text-delta", id: textId, delta });
        }

        controller.enqueue({ type: "text-end", id: textId });
        controller.enqueue({ type: "finish", finishReason: "stop" });
        controller.close();
      },
    });
  },
  async reconnectToStream() {
    return null;
  },
} satisfies ChatTransport<UIMessage>;

function getMessageScrollerText(message: UIMessage) {
  return message.parts
    .filter((part): part is TextUIPart => part.type === "text")
    .map((part) => part.text)
    .join("");
}

function MessageScrollerExample() {
  const [draft, setDraft] = useState(messageScrollerInitialPrompt);
  const { messages, sendMessage, setMessages, status } = useChat({
    transport: messageScrollerMockTransport,
  });
  const isBusy = status === "submitted" || status === "streaming";

  const handleSubmit = async (event: { preventDefault: () => void }) => {
    event.preventDefault();
    const text = draft.trim();
    if (!text || isBusy) return;

    setDraft("");
    await sendMessage({ text });
  };

  return (
    <div className="flex h-[35rem] w-full !max-w-[24rem] flex-col overflow-hidden rounded-3xl border border-border-default bg-background-neutral-card shadow-md">
      <div className="flex items-start justify-between border-b border-border-default px-5 py-4">
        <div className="flex flex-col gap-1">
          <Text size="l" weight="bold">
            New Chat
          </Text>
          <Text color="subtle">How can I help you today?</Text>
        </div>
        <IconButton
          aria-label="Reset conversation"
          size="sm"
          variant="outline"
          disabled={isBusy || messages.length === 0}
          onClick={() => {
            setMessages([]);
            setDraft(messageScrollerInitialPrompt);
          }}
        >
          <ArrowClockwiseIcon />
        </IconButton>
      </div>
      <div className="min-h-0 flex-1">
        {messages.length === 0 ? (
          <Center className="h-full px-8 text-center">
            <Stack align="center" gap="3" className="max-w-xs">
              <div className="grid size-12 place-items-center rounded-xl bg-background-muted text-icon-default">
                <ChatCircleDotsIcon className="size-6" />
              </div>
              <Text type="heading" size="h6">
                Morning, Zenos!
              </Text>
              <Text color="subtle">
                What are we working on today? Press send to start a new conversation.
              </Text>
            </Stack>
          </Center>
        ) : (
          <MessageScroller.Provider>
            <MessageScroller>
              <MessageScroller.Viewport>
                <MessageScroller.Content aria-busy={isBusy}>
                  {messages.map((message) => {
                    const align = message.role === "user" ? "end" : "start";
                    return (
                      <MessageScroller.Item
                        key={message.id}
                        messageId={message.id}
                        scrollAnchor={message.role === "user"}
                      >
                        <Message align={align}>
                          <Message.Content>
                            <Bubble
                              align={align}
                              variant={message.role === "user" ? "default" : "secondary"}
                            >
                              <Bubble.Content>{getMessageScrollerText(message)}</Bubble.Content>
                            </Bubble>
                          </Message.Content>
                        </Message>
                      </MessageScroller.Item>
                    );
                  })}
                </MessageScroller.Content>
              </MessageScroller.Viewport>
              <MessageScroller.Button />
            </MessageScroller>
          </MessageScroller.Provider>
        )}
      </div>
      <form
        className="m-4 flex flex-col gap-2 rounded-2xl bg-background-muted p-3"
        onSubmit={handleSubmit}
      >
        <Textarea
          aria-label="Message"
          className="min-h-16 resize-none px-1 py-0"
          disabled={isBusy}
          placeholder="Ask Zenos anything..."
          size="sm"
          value={draft}
          variant="none"
          onChange={(event) => setDraft(event.target.value)}
        />
        <div className="flex items-center justify-between">
          <IconButton aria-label="Add attachment" size="sm" variant="outline" disabled={isBusy}>
            <PlusIcon />
          </IconButton>
          <IconButton
            aria-label="Send message"
            type="submit"
            size="sm"
            variant="primary"
            disabled={!draft.trim() || isBusy}
            isLoading={isBusy}
          >
            <ArrowUpIcon />
          </IconButton>
        </div>
      </form>
      <VisuallyHidden aria-live="polite">{isBusy ? "Zenos is responding" : "Ready"}</VisuallyHidden>
    </div>
  );
}
```

The preview uses `useChat` from `@ai-sdk/react` with a local scripted `ChatTransport`. It exercises
the same message, status, and streamed-part shapes as an AI-backed application without sending a
network request or requiring an API key. Replace the mock transport with your application transport
when connecting a real model.

## Import

```tsx
import { Message, MessageScroller } from "@zentara-co/zenos-ui";
import { useChat } from "@ai-sdk/react";
```

## Composition

Give the root a height-constrained parent, then compose the viewport, live-region content, and stable message items. `MessageScroller.Button` appears after the reader moves away from the latest message.

```tsx
<div className="h-96">
  <MessageScroller.Provider>
    <MessageScroller>
      <MessageScroller.Viewport>
        <MessageScroller.Content>
          {messages.map((message) => (
            <MessageScroller.Item
              key={message.id}
              messageId={message.id}
              scrollAnchor={message.startsTurn}
            >
              <Message>{message.content}</Message>
            </MessageScroller.Item>
          ))}
        </MessageScroller.Content>
      </MessageScroller.Viewport>
      <MessageScroller.Button />
    </MessageScroller>
  </MessageScroller.Provider>
</div>
```

## Following live replies

`autoScroll` defaults to `true`. Appended content follows the live edge only while the reader is already there. Scrolling upward releases that behavior, so a streamed response cannot pull the reader away from older content. Set `autoScroll={false}` when the application should never follow appended content automatically.

```tsx
<MessageScroller.Provider autoScroll={false}>{/* transcript */}</MessageScroller.Provider>
```

## Opening saved conversations

Choose the initial position with `defaultScrollPosition`:

- `"end"` opens at the newest message.
- `"start"` opens at the beginning.
- `"last-anchor"` opens at the latest item marked with `scrollAnchor`.

Use `scrollPreviousItemPeek` to control the space shown above an anchored turn.

```tsx
<MessageScroller.Provider defaultScrollPosition="last-anchor" scrollPreviousItemPeek={64}>
  {/* transcript */}
</MessageScroller.Provider>
```

## Loading older history

`preserveScrollOnPrepend` defaults to `true`. When older items are inserted before the current list, the viewport compensates for the added height so the visible message stays in place. Keep every `messageId` stable across pagination.

## Scroll commands

Use `useMessageScroller` inside the provider for transcript navigation. `scrollToMessage` returns `false` when the requested ID is not mounted.

```tsx
function TranscriptControls() {
  const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScroller();

  return (
    <>
      <button onClick={() => scrollToStart({ behavior: "smooth" })}>First</button>
      <button onClick={() => scrollToMessage("message-42", { block: "center" })}>
        Jump to result
      </button>
      <button onClick={() => scrollToEnd({ behavior: "smooth" })}>Latest</button>
    </>
  );
}
```

## Visibility

`useMessageScrollerVisibility` returns `visibleMessageIds` and the nearest visible `currentAnchorId`. Use that state for a transcript outline, unread markers, or a synchronized search result list.

## RTL

The jump button uses logical positioning and mirrors automatically in a `dir="rtl"` region or `DirectionProvider`. Message alignment remains the responsibility of the composed `Message` and `Bubble` parts.

## Anatomy

```text
MessageScroller.Provider
MessageScroller.Root
MessageScroller.Viewport
MessageScroller.Content
MessageScroller.Item
MessageScroller.Button
```

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| autoScroll | boolean | true | Follows appended content while the reader remains at the live edge. |
| defaultScrollPosition | start \| end \| last-anchor | end | Initial position when the transcript is mounted. |
| preserveScrollOnPrepend | boolean | true | Preserves the visible position when older history is prepended. |
| scrollPreviousItemPeek | number | 48 | Space above an item when a turn anchor is positioned. |
| messageId | string | — | Stable Item identifier used by commands and visibility tracking. |
| scrollAnchor | boolean | false | Marks an Item as a conversation-turn boundary. |
| target | start \| end | end | Transcript boundary targeted by MessageScroller.Button. |
| native props | React.HTMLAttributes<HTMLDivElement> | — | Forwards native attributes, events, aria-*, data-*, className, style, and ref. |

Unless narrowed above, each DOM-rendering part also accepts its underlying native or Base UI props, including className, style, aria-*, and data-*.

## Accessibility

The viewport is keyboard-focusable and labeled “Conversation” by default. Content uses `role="log"` with a polite live region for additions. Keep sender names and message status in readable text, provide stable IDs, and avoid announcing large batches when loading historical messages.

The behavior is informed by the [shadcn Message Scroller](https://ui.shadcn.com/docs/components/base/message-scroller) while using Zenos tokens, compound APIs, and direction conventions.

Source: https://zenos-ui.pages.dev/components/message-scroller/