# AI composer

> Rich prompt composer with starter chips, slash-command and @-mention pickers, file attachments, model effort controls and stop button.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-composer`
- File: `src/components/haze/blocks/ai-composer.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-composer

## Use when
- Providing a dedicated prompt entry bar with structured commands, file context and model controls
- Embedding an AI ask box at the bottom of a workspace or empty state

## Avoid when
- You need a full multi-turn conversation thread with history; use ai-chat instead

## Alternatives
- [expanding-search](https://hazeui.com/ui/expanding-search.md)
- [mention-input](https://hazeui.com/ui/mention-input.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-composer" | no | Unique prefix for form controls and labels. |
| heading | `string` | "Ask anything about your workspace" | no | Prompt section heading above starter chips. |
| placeholder | `string` | "Type a prompt, / for commands, or @ to mention a file…" | no | Placeholder text inside the textarea. |
| starters | `string[]` | 3 starter prompts | no | Clickable starter prompt suggestions. |
| models | `string[]` | 3 demo models | no | Model options in the composer toolbar. |
| commands | `{ name: string; description: string }[]` | 3 slash commands | no | Slash commands shown in the command picker. |
| mentions | `string[]` | 3 file mentions | no | Workspace files shown in the mention picker. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Command and mention panels expose aria-expanded on their toggle buttons and keep all actions keyboard reachable.
- Attachment changes and submission states are announced via a polite role="status" message.
- Key Tab: Move across starter chips, attachments, textarea, pickers, selectors and send button
- Key Enter / Space: Insert a starter prompt, open commands or mentions, remove an attachment, or send

## Agent prompts

### Install and use

Install the Haze UI block "AI composer" with `npx shadcn@latest add @haze/ai-composer`. 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 AiComposer from "@/components/haze/blocks/ai-composer.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/blocks/ai-composer.md

### Customize with real content

Adapt the Haze ai-composer block for our product. Replace the demo values of these props with our real content: id, heading, placeholder, starters, models, commands, mentions, class. Keep the layout, the heading level rules and these accessibility details: Command and mention panels expose aria-expanded on their toggle buttons and keep all actions keyboard reachable. Attachment changes and submission states are announced via a polite role="status" message. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-composer, check it fits: use it when providing a dedicated prompt entry bar with structured commands, file context and model controls; embedding an ai ask box at the bottom of a workspace or empty state. Avoid it when you need a full multi-turn conversation thread with history; use ai-chat instead. Alternatives: @haze/expanding-search, @haze/mention-input.

## Example requests that should lead here
- Add a dark AI prompt composer with slash commands, @ file mentions, attachments and reasoning effort selector

## Source

```astro
---
import { ArrowUp, AtSign, FileText, Paperclip, Slash, Sparkles, Square, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  placeholder?: string;
  starters?: string[];
  models?: string[];
  commands?: { name: string; description: string }[];
  mentions?: string[];
  class?: string;
}

const {
  id = "haze-ai-composer",
  heading = "Ask anything about your workspace",
  placeholder = "Type a prompt, / for commands, or @ to mention a file…",
  starters = [
    "Summarize yesterday's incident review",
    "Draft a migration plan for Astro 5",
    "Find open accessibility issues",
  ],
  models = ["Sonnet 4.5", "Opus 4.5", "Flash 3.8"],
  commands = [
    { name: "/summarize", description: "Condense a thread or document into key points" },
    { name: "/review", description: "Audit code diff for regressions and edge cases" },
    { name: "/tests", description: "Generate Playwright assertions for a route" },
  ],
  mentions = ["@checkout.ts", "@pricing-copy.md", "@Q4-metrics.csv"],
  class: className,
} = Astro.props;
---

<section aria-labelledby={`${id}-title`} data-haze-ai-composer class={cn("bg-background px-4 py-12 sm:px-6 sm:py-16", className)}>
  <div class="mx-auto max-w-3xl space-y-4">
    <div class="text-center">
      <h2 id={`${id}-title`} class="text-xl/7 font-semibold tracking-tight text-foreground sm:text-2xl/8">{heading}</h2>
      <div class="mt-3 flex flex-wrap justify-center gap-2">
        {
          starters.map((starter) => (
            <button
              type="button"
              data-comp-starter={starter}
              class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field px-3 py-1 text-xs/5 text-muted-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
            >
              <Sparkles class="size-3 text-muted-foreground" aria-hidden="true" />
              {starter}
            </button>
          ))
        }
      </div>
    </div>

    <form data-comp-form class="rounded-2xl border border-border bg-card p-3 has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24">
      <div data-comp-files class="mb-2 flex flex-wrap gap-1.5">
        <span data-comp-chip class="inline-flex items-center gap-1.5 rounded-lg border border-border bg-muted/40 px-2.5 py-1 text-xs/4 text-foreground">
          <FileText class="size-3.5 text-muted-foreground" aria-hidden="true" />
          <span>release-notes.md</span>
          <button type="button" data-comp-remove aria-label="Remove release-notes.md" class="inline-flex size-5 cursor-pointer items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring">
            <X class="size-3" aria-hidden="true" />
          </button>
        </span>
      </div>

      <label for={`${id}-textarea`} class="sr-only">Prompt</label>
      <textarea
        id={`${id}-textarea`}
        data-comp-input
        rows="3"
        placeholder={placeholder}
        class="w-full resize-none bg-transparent px-1.5 py-1 text-sm/6 text-foreground placeholder:text-muted-foreground outline-hidden"
      ></textarea>

      <div data-comp-panel="cmd" hidden class="mb-2 rounded-xl border border-frame bg-popover p-1.5 shadow-key">
        <p class="px-2 py-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase">Slash commands</p>
        <ul role="list" class="grid gap-0.5">
          {
            commands.map((cmd) => (
              <li>
                <button type="button" data-comp-insert={`${cmd.name} `} class="flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-1.5 text-left text-xs/5 hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
                  <span class="font-mono font-medium text-foreground">{cmd.name}</span>
                  <span class="truncate text-muted-foreground">{cmd.description}</span>
                </button>
              </li>
            ))
          }
        </ul>
      </div>

      <div data-comp-panel="mention" hidden class="mb-2 rounded-xl border border-frame bg-popover p-1.5 shadow-key">
        <p class="px-2 py-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase">Mention workspace file</p>
        <div class="flex flex-wrap gap-1.5 p-1">
          {
            mentions.map((m) => (
              <button type="button" data-comp-insert={`${m} `} class="inline-flex h-7 cursor-pointer items-center rounded-md border border-frame bg-field px-2 font-mono text-xs text-foreground hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
                {m}
              </button>
            ))
          }
        </div>
      </div>

      <div class="mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-border pt-2.5">
        <div class="flex flex-wrap items-center gap-1.5">
          <button type="button" data-comp-attach aria-label="Attach sample file" class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg border border-frame bg-field px-2.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:border-frame-strong hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
            <Paperclip class="size-3.5" aria-hidden="true" />
            <span>Attach</span>
          </button>
          <button type="button" data-comp-toggle="cmd" aria-expanded="false" class="inline-flex h-8 cursor-pointer items-center gap-1 rounded-lg border border-frame bg-field px-2.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:border-frame-strong hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
            <Slash class="size-3.5" aria-hidden="true" />
            <span>Commands</span>
          </button>
          <button type="button" data-comp-toggle="mention" aria-expanded="false" class="inline-flex h-8 cursor-pointer items-center gap-1 rounded-lg border border-frame bg-field px-2.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:border-frame-strong hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
            <AtSign class="size-3.5" aria-hidden="true" />
            <span>Mention</span>
          </button>
        </div>

        <div class="flex items-center gap-2">
          <label for={`${id}-model`} class="sr-only">Model</label>
          <select id={`${id}-model`} class="h-8 cursor-pointer rounded-lg border border-frame bg-field px-2 text-xs font-medium text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden">
            {models.map((m) => <option value={m}>{m}</option>)}
          </select>
          <label for={`${id}-effort`} class="sr-only">Reasoning effort</label>
          <select id={`${id}-effort`} class="h-8 cursor-pointer rounded-lg border border-frame bg-field px-2 text-xs font-medium text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden">
            <option value="low">Low effort</option>
            <option value="medium" selected>Medium effort</option>
            <option value="high">High effort</option>
          </select>
          <button type="submit" data-comp-send aria-label="Send prompt" class="inline-flex size-8 cursor-pointer items-center justify-center rounded-lg bg-primary text-primary-foreground transition-[opacity,scale] duration-150 hover:opacity-90 active:scale-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">
            <ArrowUp class="size-4" aria-hidden="true" />
          </button>
          <button type="button" data-comp-stop hidden aria-label="Stop streaming" class="inline-flex size-8 cursor-pointer items-center justify-center rounded-lg border border-frame bg-muted text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
            <Square class="size-3 fill-current" aria-hidden="true" />
          </button>
        </div>
      </div>
    </form>

    <p data-comp-status role="status" class="min-h-5 text-center text-xs/5 text-muted-foreground"></p>
  </div>
</section>

<script>
  function initAiComposers() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-composer]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");
      const input = root.querySelector<HTMLTextAreaElement>("[data-comp-input]");
      const files = root.querySelector<HTMLElement>("[data-comp-files]");
      const status = root.querySelector<HTMLElement>("[data-comp-status]");
      const sendBtn = root.querySelector<HTMLButtonElement>("[data-comp-send]");
      const stopBtn = root.querySelector<HTMLButtonElement>("[data-comp-stop]");
      let timer: number | undefined;
      let fileIndex = 1;

      const closePanels = () => {
        root.querySelectorAll<HTMLElement>("[data-comp-panel]").forEach((p) => (p.hidden = true));
        root.querySelectorAll<HTMLButtonElement>("[data-comp-toggle]").forEach((b) => b.setAttribute("aria-expanded", "false"));
      };

      root.querySelectorAll<HTMLButtonElement>("[data-comp-starter]").forEach((btn) => {
        btn.addEventListener("click", () => {
          if (input) { input.value = btn.dataset.compStarter ?? ""; input.focus(); }
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-comp-toggle]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const name = btn.dataset.compToggle!;
          const panel = root.querySelector<HTMLElement>(`[data-comp-panel="${name}"]`);
          const open = panel ? panel.hidden : false;
          closePanels();
          if (panel && open) {
            panel.hidden = false;
            btn.setAttribute("aria-expanded", "true");
          }
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-comp-insert]").forEach((btn) => {
        btn.addEventListener("click", () => {
          if (input) {
            input.value = `${input.value}${input.value && !input.value.endsWith(" ") ? " " : ""}${btn.dataset.compInsert}`;
            input.focus();
          }
          closePanels();
        });
      });

      root.querySelector<HTMLButtonElement>("[data-comp-attach]")?.addEventListener("click", () => {
        if (!files) return;
        const name = `spec-v${++fileIndex}.pdf`;
        const chip = document.createElement("span");
        chip.className = "inline-flex items-center gap-1.5 rounded-lg border border-border bg-muted/40 px-2.5 py-1 text-xs/4 text-foreground";
        chip.innerHTML = `<span>${name}</span><button type="button" data-comp-remove aria-label="Remove ${name}" class="inline-flex size-5 cursor-pointer items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground">×</button>`;
        files.append(chip);
        if (status) status.textContent = `Attached ${name}.`;
      });

      files?.addEventListener("click", (ev) => {
        const rm = (ev.target as HTMLElement | null)?.closest<HTMLButtonElement>("[data-comp-remove]");
        if (rm) {
          rm.parentElement?.remove();
          if (status) status.textContent = "Attachment removed.";
        }
      });

      stopBtn?.addEventListener("click", () => {
        if (timer) window.clearTimeout(timer);
        if (sendBtn) sendBtn.hidden = false;
        if (stopBtn) stopBtn.hidden = true;
        if (status) status.textContent = "Stopped.";
      });

      root.querySelector<HTMLFormElement>("[data-comp-form]")?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        const value = input?.value.trim();
        if (!value) { if (status) status.textContent = "Enter a prompt first."; return; }
        closePanels();
        if (sendBtn) sendBtn.hidden = true;
        if (stopBtn) stopBtn.hidden = false;
        if (status) status.textContent = `Sending "${value.slice(0, 60)}"…`;
        timer = window.setTimeout(() => {
          if (sendBtn) sendBtn.hidden = false;
          if (stopBtn) stopBtn.hidden = true;
          if (status) status.textContent = "Prompt queued and ready for streaming output.";
        }, 650);
      });
    });
  }
  initAiComposers();
  document.addEventListener("astro:page-load", initAiComposers);
</script>
```
