# Chat thread

> An assistant or person conversation: timed bubbles that rise in, a typing indicator and a message box with a send button.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/chat-thread`
- File: `src/components/haze/ui/chat-thread.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/avatar, @haze/utils
- Docs page: https://hazeui.com/ui/chat-thread

## Use when
- A product has an AI assistant or agent the user talks to
- A support or sales screen shows a short conversation with a reply box

## Avoid when
- The screen lists many conversations to choose from. Use inbox-list.
- Messages are announcements, not a dialogue. Use notification-stack.

## Alternatives
- [inbox-list](https://hazeui.com/ui/inbox-list.md)
- [notification-stack](https://hazeui.com/ui/notification-stack.md)
- [timeline](https://hazeui.com/ui/timeline.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Base for the message box id. |
| title | `string` | "Mira, sales assistant" | no | Visible name of the conversation. |
| subtitle | `string` |  | no | Line under the title: role or state. |
| messages | `{ from: "user" \| "assistant"; name: string; text: string; time?: string }[]` |  | no | Messages, oldest first. |
| typing | `boolean` | true | no | Shows three dots while the assistant writes. |
| action | `string` | "#send" | no | Where the message form posts; empty hides the composer. |
| placeholder | `string` | "Write a message…" | no | Placeholder and label of the message box. |
| sendLabel | `string` | "Send" | no | Accessible name of the send button. |
| typingLabel | `string` | "Mira is writing" | no | Screen-reader text for the typing dots. |
| class | `string` |  | no | Additional classes on the panel. |

## Accessibility
- Messages sit in a list with the log role, and each starts with its sender's name for screen readers.
- The typing dots are hidden from assistive technology and replaced by a status text.
- Key Tab: Move to the message box, then to Send.
- Key Enter: Send the message when scripts run. Shift+Enter adds a new line.

## Agent prompts

### Install and use

Install the Haze UI component "Chat thread" with `npx shadcn@latest add @haze/chat-thread`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ChatThread from "@/components/haze/ui/chat-thread.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/chat-thread.md

### Customize with real content

Adapt the Haze chat-thread ui for our product. Replace the demo values of these props with our real content: id, title, subtitle, messages, typing, action, placeholder, sendLabel, typingLabel, class. Keep the layout, the heading level rules and these accessibility details: Messages sit in a list with the log role, and each starts with its sender's name for screen readers. The typing dots are hidden from assistive technology and replaced by a status text. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using chat-thread, check it fits: use it when a product has an ai assistant or agent the user talks to; a support or sales screen shows a short conversation with a reply box. Avoid it when the screen lists many conversations to choose from. use inbox-list.; messages are announcements, not a dialogue. use notification-stack.. Alternatives: @haze/inbox-list, @haze/notification-stack, @haze/timeline.

## Example requests that should lead here
- Add an assistant chat panel with a few messages, a typing indicator and a message box.

## Source

```astro
---
import { ArrowUp } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Avatar from "./avatar.astro";

interface Message {
  from: "user" | "assistant";
  /** Sender name; read before the message and used for the assistant's avatar. */
  name: string;
  text: string;
  /** Time as it should read, such as "09:41". */
  time?: string;
}

interface Props {
  /** Required. The composer's ids are derived from it. */
  id: string;
  /** Visible title of the conversation, such as the agent's name. */
  title?: string;
  /** Line under the title: the agent's role or state. */
  subtitle?: string;
  messages?: Message[];
  /** Shows three dots under the last message while the assistant writes. */
  typing?: boolean;
  /** Where the composer form posts. Leave empty to hide the composer. */
  action?: string;
  placeholder?: string;
  sendLabel?: string;
  /** Screen-reader text for the typing dots. */
  typingLabel?: string;
  class?: string;
}

const {
  id,
  title = "Mira, sales assistant",
  subtitle = "Answers from your price list and FAQ",
  messages = [
    { from: "user", name: "You", text: "Can a customer book two services in one visit?", time: "09:40" },
    {
      from: "assistant",
      name: "Mira",
      text: "Yes. They pick both services on the booking page and get one time slot long enough for both, 75 minutes for a cut and color.",
      time: "09:40",
    },
    { from: "user", name: "You", text: "And if the stylist is busy for that long?", time: "09:41" },
  ],
  typing = true,
  action = "#send",
  placeholder = "Write a message…",
  sendLabel = "Send",
  typingLabel = "Mira is writing",
  class: className,
} = Astro.props;
// Without a caller-supplied action the composer is a local demo: a script appends the message instead of posting.
const local = Astro.props.action === undefined;
const assistant = messages.find((m) => m.from === "assistant")?.name ?? title;
---

<section data-haze-chat-thread data-local={local ? "" : undefined} aria-label={title} class={cn("flex flex-col overflow-hidden rounded-xl border border-border bg-card", className)}>
  <div class="flex items-center gap-3 border-b border-border px-4 py-3">
    <Avatar name={assistant} size="sm" status="online" statusLabel="Online" />
    <div class="min-w-0">
      <p class="truncate text-[0.8125rem]/5 font-medium text-foreground">{title}</p>
      {subtitle && <p class="truncate text-[0.8125rem]/5 text-muted-foreground">{subtitle}</p>}
    </div>
  </div>
  <div role="log" aria-label={`Messages with ${assistant}`} class="px-4 py-4">
  <ol data-chat-list class="flex flex-col gap-4">
    {
      messages.map((m) => (
        <li class={cn("flex max-w-[85%] flex-col gap-1", m.from === "user" ? "items-end self-end" : "items-start self-start")}>
          <span class="sr-only">{m.name}:</span>
          <p
            class={cn(
              "rounded-2xl px-3.5 py-2 text-[0.8125rem]/5",
              m.from === "user" ? "rounded-br-md bg-primary text-primary-foreground" : "rounded-bl-md bg-popover text-foreground",
            )}
          >
            {m.text}
          </p>
          {m.time && <span class="px-1 text-xs/4 text-muted-foreground tabular-nums">{m.time}</span>}
        </li>
      ))
    }
    {
      typing && (
        <li data-chat-typing class="self-start">
          <span class="flex h-9 items-center gap-1 rounded-2xl rounded-bl-md bg-popover px-3.5">
            <span class="sr-only">{typingLabel}</span>
            <span aria-hidden="true" class="size-1.5 animate-blink rounded-full bg-muted-foreground motion-reduce:animate-none"></span>
            <span aria-hidden="true" class="size-1.5 animate-blink rounded-full bg-muted-foreground [animation-delay:160ms] motion-reduce:animate-none"></span>
            <span aria-hidden="true" class="size-1.5 animate-blink rounded-full bg-muted-foreground [animation-delay:320ms] motion-reduce:animate-none"></span>
          </span>
        </li>
      )
    }
  </ol>
  </div>
  {
    action && (
      <form data-chat-form action={action} method="post" class="flex items-end gap-2 border-t border-border p-3">
        <label for={`${id}-message`} class="sr-only">
          {placeholder}
        </label>
        <textarea
          id={`${id}-message`}
          name="message"
          rows="1"
          required
          placeholder={placeholder}
          class="max-h-40 min-h-10 flex-1 resize-none rounded-lg border border-frame-input bg-field px-3 py-2 text-sm/5 tracking-[-0.01em] text-foreground transition-[border-color,box-shadow] duration-150 ease-snappy [field-sizing:content] placeholder:text-muted-foreground hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
        ></textarea>
        <button
          type="submit"
          aria-label={sendLabel}
          class="inline-flex size-10 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-primary text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-91 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-100 motion-reduce:active:scale-100"
        >
          <ArrowUp aria-hidden="true" class="size-4" />
        </button>
      </form>
    )
  }
</section>
<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const form = root.querySelector<HTMLFormElement>("[data-chat-form]");
    const list = root.querySelector<HTMLElement>("[data-chat-list]");
    const input = form?.querySelector<HTMLTextAreaElement>("textarea");
    if (!list) return;
    // Messages added after load, sent or received, rise in. The typing row has its own dots.
    new MutationObserver((records) => {
      for (const record of records) {
        for (const node of record.addedNodes) {
          if (node instanceof HTMLElement && node.tagName === "LI" && !node.hasAttribute("data-chat-typing")) node.classList.add("motion-safe:animate-rise");
        }
      }
    }).observe(list, { childList: true });
    root.setAttribute("data-enhanced", "");
    if (!root.hasAttribute("data-local") || !form || !input) return;
    const last = list.querySelector<HTMLElement>("li:has(> p.bg-primary)");
    const name = last?.querySelector<HTMLElement>(".sr-only")?.textContent?.replace(/:\s*$/, "") || "You";
    const send = () => {
      const text = input.value.trim();
      if (!text) { input.focus(); return; }
      const model = last ?? list.querySelector<HTMLElement>("li:not([data-chat-typing])");
      const item = document.createElement("li");
      item.className = "flex max-w-[85%] flex-col gap-1 items-end self-end";
      const who = document.createElement("span");
      who.className = "sr-only";
      who.textContent = name + ":";
      const bubble = document.createElement("p");
      bubble.className = "rounded-2xl px-3.5 py-2 text-[0.8125rem]/5 rounded-br-md bg-primary text-primary-foreground whitespace-pre-wrap wrap-anywhere";
      bubble.textContent = text;
      const time = document.createElement("span");
      time.className = "px-1 text-xs/4 text-muted-foreground tabular-nums";
      const now = new Date();
      time.textContent = String(now.getHours()).padStart(2, "0") + ":" + String(now.getMinutes()).padStart(2, "0");
      item.append(who, bubble);
      if (model?.querySelector(".tabular-nums")) item.append(time);
      list.insertBefore(item, list.querySelector("[data-chat-typing]"));
      form.reset();
      input.focus();
      item.scrollIntoView({ block: "nearest", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
      root.dispatchEvent(new CustomEvent("haze:chat-send", { bubbles: true, detail: { text } }));
    };
    form.addEventListener("submit", (event) => { event.preventDefault(); send(); });
    input.addEventListener("keydown", (event) => {
      if (event.key !== "Enter" || event.shiftKey || event.isComposing) return;
      event.preventDefault();
      send();
    });
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-chat-thread]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-chat-thread-listener")) {
    document.documentElement.setAttribute("data-haze-chat-thread-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
