# Conversation

A scrolling thread of messages that follows a reply as it streams in.

Source: [conversation.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/conversation.tsx)

```tsx
"use client";

import * as React from "react";

import {
  Conversation,
  ConversationContent,
  ConversationItem,
  ConversationScrollButton,
} from "@/components/ui/conversation";
import { Markdown } from "@/components/ui/markdown";
import { Message, MessageBubble, MessageContent } from "@/components/ui/message";
import {
  PromptInput,
  PromptInputActions,
  PromptInputSubmit,
  PromptInputTextarea,
  type PromptInputStatus,
} from "@/components/ui/prompt-input";
import { TraceLine, TraceTitle } from "@/components/ui/trace";

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

const history: ChatMessage[] = [
  { id: 1, role: "user", text: "How do I point www.example.com at my site?" },
  {
    id: 2,
    role: "assistant",
    text: "Add the domain under Settings → Domains, then create a CNAME record at your DNS provider that points www.example.com to cname.example.net.",
  },
  { id: 3, role: "user", text: "How long does it take to verify?" },
  {
    id: 4,
    role: "assistant",
    text: "Usually a few minutes. Some DNS providers cache records for up to an hour, so if it hasn’t verified by then, check that the record was saved.",
  },
];

const reply = `Once it verifies, a certificate is issued automatically, and **www.example.com** serves your site over HTTPS. It renews about a month before it expires, so there’s nothing to do.

If you also want \`example.com\` without the www to work:

1. Add it as a second domain.
2. Choose to redirect it to www.example.com.`;

export default function ConversationChat() {
  const [messages, setMessages] = React.useState(history);
  const [status, setStatus] = React.useState<PromptInputStatus>("ready");
  const timer = React.useRef<ReturnType<typeof setInterval>>(undefined);
  const nextId = React.useRef(history.length + 1);
  const [replyId, setReplyId] = React.useState<number>();
  const [announcement, setAnnouncement] = React.useState("");
  const replyRef = React.useRef<HTMLDivElement>(null);
  const busy = status === "submitted" || status === "streaming";

  React.useEffect(() => () => clearInterval(timer.current), []);

  React.useEffect(() => {
    if (!busy) setAnnouncement(replyRef.current?.innerText ?? "");
  }, [busy]);

  function send({ text }: { text: string }) {
    const id = nextId.current;
    nextId.current += 2;
    setReplyId(id + 1);
    setAnnouncement("");
    setMessages((current) => [
      ...current,
      { id, role: "user", text },
      { id: id + 1, role: "assistant", text: "" },
    ]);
    setStatus("submitted");
    const words = reply.split(" ");
    let count = 0;
    timer.current = setInterval(() => {
      count += 1;
      setStatus("streaming");
      setMessages((current) =>
        current.map((message) =>
          message.id === id + 1 ? { ...message, text: words.slice(0, count).join(" ") } : message,
        ),
      );
      if (count >= words.length) stop();
    }, 60);
  }

  function stop() {
    clearInterval(timer.current);
    setStatus("ready");
  }

  return (
    <div className="flex h-112 w-full max-w-lg flex-col overflow-hidden rounded-lg bg-layer-0 inset-ring-[0.5px] inset-ring-border-muted">
      <Conversation>
        <ConversationContent aria-busy={busy}>
          {messages.map((message) => (
            <ConversationItem
              key={message.id}
              ref={message.id === replyId ? replyRef : undefined}
              anchor={message.role === "user"}
            >
              <Message align={message.role === "user" ? "end" : "start"}>
                <MessageContent>
                  {message.role === "user" ? (
                    <MessageBubble>{message.text}</MessageBubble>
                  ) : message.text ? (
                    <Markdown streaming={busy && message.id === replyId}>{message.text}</Markdown>
                  ) : (
                    <TraceLine status="running">
                      <TraceTitle>Thinking</TraceTitle>
                    </TraceLine>
                  )}
                </MessageContent>
              </Message>
            </ConversationItem>
          ))}
        </ConversationContent>
        <ConversationScrollButton />
      </Conversation>
      <div role="status" className="sr-only">
        {announcement}
      </div>
      <div className="px-4 pt-1 pb-4">
        <PromptInput status={status} onSubmit={send} onStop={stop}>
          <PromptInputTextarea placeholder="Ask a follow-up…" />
          <PromptInputActions align="end">
            <PromptInputSubmit />
          </PromptInputActions>
        </PromptInput>
      </div>
    </div>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/conversation
```

## Usage

```tsx
import {
  Conversation,
  ConversationContent,
  ConversationItem,
  ConversationScrollButton,
} from "@/components/ui/conversation";
import { Message, MessageBubble, MessageContent } from "@/components/ui/message";

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

export function Thread({ messages, busy }: { messages: ChatMessage[]; busy: boolean }) {
  return (
    <Conversation className="h-96">
      <ConversationContent aria-busy={busy}>
        {messages.map((message) => (
          <ConversationItem key={message.id} anchor={message.role === "user"}>
            <Message align={message.role === "user" ? "end" : "start"}>
              <MessageContent>
                <MessageBubble variant={message.role === "user" ? "default" : "ghost"}>
                  {message.text}
                </MessageBubble>
              </MessageContent>
            </Message>
          </ConversationItem>
        ))}
      </ConversationContent>
      <ConversationScrollButton />
    </Conversation>
  );
}
```

A conversation opens at its latest message. While someone is scrolled to the bottom, it follows a
reply as it streams in. If they scroll up, it keeps their place until they scroll back down or press
`ConversationScrollButton`. The button shows whenever there's more below and the conversation isn't
following. The messages fade out under the button, and content focused with the keyboard scrolls
clear of the fade. Pressing the button from the keyboard moves focus to the messages, since the
button hides once they're at the bottom.

Opening or closing something in a message, such as a [Trace](https://ui.jarv.is/components/trace.md) or a
[Tool](https://ui.jarv.is/components/tool.md), keeps the pressed control in place rather than scrolling to follow the
revealed content to the bottom, even in the latest message.

Mark the start of each turn, usually the person's message, with `anchor`. When an anchored item is
added, it settles `anchorOffset` pixels below the top, and the reply fills the space below it rather
than pushing it out of view. Once the reply fills that space, the conversation follows it again.

Give `Conversation` a height, or put it in a flex column where it can grow. It never grows wider
than its container, so a long line wraps or scrolls inside its message rather than widening the
page. The scrolling area is a region labeled "Messages" that can be scrolled with the keyboard.
Change its label through `viewportProps`. The conversation inherits its parent's corner radius, so
its focus ring follows the corners of a rounded card.

`ConversationContent` has the `log` role, so screen readers announce new messages. Set `aria-busy`
on it while a reply is submitted or streaming, as in the example above. Otherwise screen readers
read each paragraph as it begins rather than the whole reply. Clear `aria-busy` once the reply ends,
including when it fails, or the log stays silent. Not every screen reader announces what changed
while the log was busy once it clears, so also announce the finished reply in a polite status
region. The example at the top of the page does this with a visually hidden `role="status"`
element.

## Composition

- `Conversation`
  - `ConversationContent`
    - `ConversationItem`
  - `ConversationScrollButton`

## Examples

### Loading earlier messages

When messages are added above the ones in view, such as older messages loaded on request, the
conversation keeps the message someone was looking at in place rather than letting the new ones
push it down. Messages marked `anchor` that are added above don't move it either.

Set `aria-busy` on `ConversationContent` while the messages load and until one frame after they
render, so screen readers don't announce the history as new messages. If the button that loaded
them disappears, move focus to the first loaded message, using `tabIndex={-1}` and
`preventScroll`. Keyboard navigation then continues from the start of the history without
scrolling the view.

```tsx
"use client";

import * as React from "react";

import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
  ConversationScrollButton,
} from "@/components/ui/conversation";
import { Message, MessageBubble, MessageContent } from "@/components/ui/message";

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

const older: ChatMessage[] = [
  { id: 1, role: "user", text: "Can I deploy from a branch other than main?" },
  {
    id: 2,
    role: "assistant",
    text: "Yes. Every branch you push gets a preview deployment, and you can choose which branch production follows under Settings → Git.",
  },
  { id: 3, role: "user", text: "Do previews get their own URL?" },
  {
    id: 4,
    role: "assistant",
    text: "Each one does, and the newest preview of a branch also answers at a URL named after the branch.",
  },
];

const recent: ChatMessage[] = [
  { id: 5, role: "user", text: "How do I point www.example.com at my site?" },
  {
    id: 6,
    role: "assistant",
    text: "Add the domain under Settings → Domains, then create a CNAME record at your DNS provider that points www.example.com to cname.example.net.",
  },
  { id: 7, role: "user", text: "How long does it take to verify?" },
  {
    id: 8,
    role: "assistant",
    text: "Usually a few minutes. Some DNS providers cache records for up to an hour.",
  },
  { id: 9, role: "user", text: "Do I need a certificate?" },
  {
    id: 10,
    role: "assistant",
    text: "No. One is issued as soon as the domain verifies, and it renews on its own.",
  },
];

async function fetchEarlierMessages() {
  await new Promise((resolve) => setTimeout(resolve, 500));
  return older;
}

export default function ConversationLoadEarlier() {
  const [messages, setMessages] = React.useState(recent);
  const [loading, setLoading] = React.useState(false);
  const firstLoaded = React.useRef<HTMLDivElement>(null);
  const loaded = messages.length > recent.length;

  React.useEffect(() => {
    if (!loading || !loaded) return;
    if (document.activeElement === document.body) {
      firstLoaded.current?.focus({ preventScroll: true });
    }
    const frame = requestAnimationFrame(() => setLoading(false));
    return () => cancelAnimationFrame(frame);
  }, [loading, loaded]);

  async function loadEarlier() {
    setLoading(true);
    const earlier = await fetchEarlierMessages();
    setMessages((current) => [...earlier, ...current]);
  }

  return (
    <div className="flex h-72 w-full max-w-lg flex-col overflow-hidden rounded-lg bg-layer-0 inset-ring-[0.5px] inset-ring-border-muted">
      <Conversation>
        <ConversationContent aria-busy={loading}>
          {!loaded && (
            <ConversationItem className="flex justify-center">
              <Button variant="ghost" size="sm" onClick={loadEarlier}>
                Load earlier messages
              </Button>
            </ConversationItem>
          )}
          {messages.map((message, index) => {
            const first = loaded && index === 0;
            return (
              <ConversationItem
                key={message.id}
                ref={first ? firstLoaded : undefined}
                tabIndex={first ? -1 : undefined}
                anchor={message.role === "user"}
                className={first ? "outline-none" : undefined}
              >
                <Message align={message.role === "user" ? "end" : "start"}>
                  <MessageContent>
                    <MessageBubble variant={message.role === "user" ? "default" : "ghost"}>
                      {message.text}
                    </MessageBubble>
                  </MessageContent>
                </Message>
              </ConversationItem>
            );
          })}
        </ConversationContent>
        <ConversationScrollButton />
      </Conversation>
    </div>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `Conversation` | [`ScrollArea`](https://ui.jarv.is/components/scroll-area.md) |
| `ConversationContent` | `<div>` |
| `ConversationItem` | `<div>` |
| `ConversationScrollButton` | [`ScrollAreaScrollToBottom`](https://ui.jarv.is/components/scroll-area.md) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### Conversation

| Prop                     | Type                                                                                        | Default | Description                                                                                                                                                                                                                |
| ------------------------ | ------------------------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `overflowEdgeThreshold?` | `number \| Partial<{ xStart: number; xEnd: number; yStart: number; yEnd: number; }>`        | `0`     | The threshold in pixels that must be passed before the overflow edge attributes are applied. Accepts a single number for all edges or an object to configure them individually.                                            |
| `scrollbarGutter?`       | `boolean`                                                                                   | `false` | Adds room beside the content for each scrollbar while its axis overflows, so the scrollbar doesn't cover the content. The room matches `--scrollbar-size`, which also sets the scrollbars' thickness (0.75rem by default). |
| `hideScrollbars?`        | `boolean`                                                                                   | `false` | Leaves out the scrollbars. The content still scrolls by wheel, touch and keyboard, and still fades at its edges.                                                                                                           |
| `viewportProps?`         | `Omit<ScrollAreaViewportProps, "children">`                                                 | `{}`    | Props for the viewport, the element that scrolls. Pass `tabIndex: -1` to keep it out of the tab order when the content handles the keyboard itself, as a grid or a list of tabs does.                                      |
| `anchorOffset?`          | `number`                                                                                    | `48`    | How far below the top a new turn settles when it's added, in pixels. The space keeps the end of the previous turn in view.                                                                                                 |
| `className?`             | `string \| ((state: ScrollAreaRootState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                                                       |
| `style?`                 | `React.CSSProperties \| ((state: ScrollAreaRootState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                                                    |
| `render?`                | `ComponentRenderFn<HTMLProps, ScrollAreaRootState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.                                  |

### ConversationContent

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ConversationItem

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `anchor?`    | `boolean`                                                | `false` | Marks the item that starts a turn, usually the person's message. When an anchored item is added, it settles near the top and the reply fills in below it.                                 |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ConversationScrollButton

| Prop                     | Type                                                                                 | Default     | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`     | Whether the button should be focusable when disabled.                                                                                                                                     |
| `nativeButton?`          | `boolean`                                                                            | `true`      | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `variant?`               | `"destructive" \| "ghost" \| "link" \| "outline" \| "primary" \| "secondary"`        | `"outline"` |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"icon-sm"` |                                                                                                                                                                                           |
| `className?`             | `string \| ((state: ButtonState) => string \| undefined)`                            | —           | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                 | `React.CSSProperties \| ((state: ButtonState) => React.CSSProperties \| undefined)`  | —           | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`                | `ComponentRenderFn<HTMLProps, ButtonState> \| React.ReactElement`                    | —           | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### useConversation

`useConversation()` reads the `Conversation` that your part renders in, and returns:

| Value            | Type                                                 | Description                                                                                                                                                 |
| ---------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scrollToBottom` | `(options?: { behavior?: ScrollBehavior; }) => void` | Scrolls to the latest message and follows the conversation from there. It scrolls smoothly unless `behavior` says otherwise or reduced motion is preferred. |
