# Composer

> Message box for a chat or comment thread: a growing textarea, optional file chips, a send button, a key hint and a counter.

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

## Use when
- The reply box under a chat, comment or ticket thread
- A short message that sends on Enter and may carry file attachments
- An app where Enter should add a line and Cmd/Ctrl+Enter sends

## Avoid when
- A longer form field with a fixed height. Use textarea.
- The user must mention people with @ while typing. Use mention-input.
- You need the whole conversation panel with bubbles. Use chat-thread.

## Alternatives
- [textarea](https://hazeui.com/ui/textarea.md)
- [mention-input](https://hazeui.com/ui/mention-input.md)
- [chat-thread](https://hazeui.com/ui/chat-thread.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Textarea id. The hint and attach input ids derive from it. |
| name | `string` |  | no | Field name posted with the form. Defaults to id. |
| action | `string` |  | no | Where the form posts. Omitted by default: the form then has no action or method attribute, so apps intercept the haze:composer-send event and call preventDefault on submit, or pass an action. |
| method | `"get" \| "post"` | "post" | no | Form method. |
| placeholder | `string` | "Write a message…" | no | Placeholder of the empty box. |
| label | `string` | "Message" | no | Screen-reader label of the textarea. |
| value | `string` |  | no | Initial text. |
| maxRows | `number` | 6 | no | The box grows to this many lines, then scrolls. |
| submitOn | `"enter" \| "mod-enter"` | "enter" | no | Which keys send. Cmd/Ctrl+Enter always sends; Shift+Enter always adds a line in enter mode. |
| hint | `string` |  | no | Line under the box explaining the keys. |
| maxLength | `number` |  | no | Limits the text and shows a counter. |
| attach | `boolean` | false | no | Shows the attach button and lists chosen files as chips with remove buttons. |
| accept | `string` |  | no | Accepted file types for the attach input. |
| fileName | `string` |  | no | Name of the file input. Defaults to <id>-files. |
| sendLabel | `string` | "Send" | no | Accessible name of the send button. |
| attachLabel | `string` | "Attach files" | no | Accessible name of the attach button. |
| removeLabel | `string` | "Remove" | no | Start of each chip remove button's name; the file name follows. |
| attachedLabel | `string` | "Attached files" | no | Name of the file list and start of the spoken count. |
| counterLabel | `string` | "Character limit" | no | Screen-reader text before the limit. |
| class | `string` |  | no | Extra classes on the form. |
| actions | `slot` |  | no | Extra buttons after the attach button, such as an emoji picker. |

## Accessibility
- The textarea has a visually hidden label. The hint is linked with aria-describedby.
- Enter never sends while an IME composition is open, so people typing in Japanese, Chinese or Korean keep their text.
- The send button is disabled while the box is empty or only whitespace; without scripts it stays enabled and the browser requires text.
- Attached files form a list. Removing a chip moves focus to the next chip, and a status line announces the count.
- The counter turns red and bold at the limit, and its number is always shown, so it never relies on color.
- Key Enter: Send (submitOn "enter") or add a line (submitOn "mod-enter").
- Key Shift+Enter: Add a line.
- Key Cmd+Enter / Ctrl+Enter: Send in both modes.
- Key Tab: Move between the box, attach button, chips' remove buttons and Send.

## Agent prompts

### Install and use

Install the Haze UI component "Composer" with `npx shadcn@latest add @haze/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 Composer from "@/components/haze/ui/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/ui/composer.md

### Customize with real content

Adapt the Haze composer ui for our product. Replace the demo values of these props with our real content: id, name, action, method, placeholder, label, value, maxRows, submitOn, hint, maxLength, attach, accept, fileName, sendLabel, attachLabel, removeLabel, attachedLabel, counterLabel, class, actions. Keep the layout, the heading level rules and these accessibility details: The textarea has a visually hidden label. The hint is linked with aria-describedby. Enter never sends while an IME composition is open, so people typing in Japanese, Chinese or Korean keep their text. The send button is disabled while the box is empty or only whitespace; without scripts it stays enabled and the browser requires text. Attached files form a list. Removing a chip moves focus to the next chip, and a status line announces the count. The counter turns red and bold at the limit, and its number is always shown, so it never relies on color. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using composer, check it fits: use it when the reply box under a chat, comment or ticket thread; a short message that sends on enter and may carry file attachments; an app where enter should add a line and cmd/ctrl+enter sends. Avoid it when a longer form field with a fixed height. use textarea.; the user must mention people with @ while typing. use mention-input.; you need the whole conversation panel with bubbles. use chat-thread.. Alternatives: @haze/textarea, @haze/mention-input, @haze/chat-thread.

## Example requests that should lead here
- Add a reply box under the support thread that sends on Enter and lets people attach files.
- Make a comment composer where Enter adds a line and Cmd+Enter posts, with a 500 character counter.

## Source

```astro
---
import { ArrowUp, Paperclip, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  /** Required. The textarea id; the hint, counter and file input ids derive from it. */
  id: string;
  /** Field name posted with the form. Defaults to `id`. */
  name?: string;
  /** Where the form posts. Optional: without it the form has no action attribute, so apps intercept the `haze:composer-send` event (and call preventDefault on submit) or pass an action. */
  action?: string;
  method?: "get" | "post";
  /** Placeholder shown in the empty box. */
  placeholder?: string;
  /** Screen-reader label of the message box. */
  label?: string;
  /** Initial text. */
  value?: string;
  /** The box grows with its text up to this many lines, then scrolls. */
  maxRows?: number;
  /** "enter": Enter sends, Shift+Enter adds a line. "mod-enter": Enter adds a line, Cmd/Ctrl+Enter sends. */
  submitOn?: "enter" | "mod-enter";
  /** Line under the box that explains the keys, such as "Enter to send, Shift+Enter for a new line". */
  hint?: string;
  /** Shows a character counter and limits the text. */
  maxLength?: number;
  /** Shows an attach button wired to a file input; chosen files are listed as chips. */
  attach?: boolean;
  accept?: string;
  /** Name of the file input. */
  fileName?: string;
  sendLabel?: string;
  attachLabel?: string;
  /** Start of each remove button's name; the file name follows it. */
  removeLabel?: string;
  /** Name of the file list and start of the screen-reader count, such as "Attached files: 2". */
  attachedLabel?: string;
  /** Screen-reader text for the counter; the limit follows it. */
  counterLabel?: string;
  class?: string;
  /** Any other textarea attribute, for example disabled, autocomplete or aria-describedby. */
  [key: string]: unknown;
}

const {
  id,
  name = id,
  action,
  method = "post",
  placeholder = "Write a message…",
  label = "Message",
  value = "",
  maxRows = 6,
  submitOn = "enter",
  hint,
  maxLength,
  attach = false,
  accept,
  fileName = `${id}-files`,
  sendLabel = "Send",
  attachLabel = "Attach files",
  removeLabel = "Remove",
  attachedLabel = "Attached files",
  counterLabel = "Character limit",
  class: className,
  ...rest
} = Astro.props;

const hintId = `${id}-hint`;
const describedBy = [hint ? hintId : "", rest["aria-describedby"] as string | undefined].filter(Boolean).join(" ") || undefined;
const { "aria-describedby": _ignored, ...textareaRest } = rest;
const hasActions = Astro.slots.has("actions");
---

<form
  action={action}
  method={action ? method : undefined}
  enctype={attach ? "multipart/form-data" : undefined}
  data-haze-composer
  data-submit-on={submitOn}
  data-remove-label={removeLabel}
  data-attached-label={attachedLabel}
  class={cn("grid min-w-0 gap-1.5", className)}
>
  <div
    class="flex min-w-0 flex-col rounded-xl border border-frame-input bg-field transition-[border-color,box-shadow] duration-150 ease-snappy 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 hover:border-frame-foreground"
  >
    <ul data-composer-files hidden aria-label={attachedLabel} class="flex min-w-0 flex-wrap gap-1.5 px-2.5 pt-2.5"></ul>
    <label for={id} class="sr-only">{label}</label>
    <textarea
      id={id}
      name={name}
      rows="1"
      required
      maxlength={maxLength}
      placeholder={placeholder}
      aria-describedby={describedBy}
      data-max-rows={maxRows}
      style={`max-height: calc(${maxRows} * 1.5rem + 1.25rem)`}
      class="block w-full min-w-0 resize-none overflow-y-auto bg-transparent px-3 py-2.5 text-sm/6 tracking-[-0.01em] text-foreground [field-sizing:content] placeholder:text-muted-foreground focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50"
      {...textareaRest}>{value}</textarea
    >
    <div class="flex items-center gap-1 px-2 pb-2">
      {
        attach && (
          <label class="relative inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-ring active:scale-[0.97] active:duration-75 motion-reduce:active:scale-100">
            <input type="file" id={`${id}-attach`} name={fileName} multiple accept={accept} data-composer-input class="peer absolute inset-0 size-full cursor-pointer opacity-0" />
            <Paperclip class="size-4" aria-hidden="true" />
            <span class="sr-only">{attachLabel}</span>
          </label>
        )
      }
      {hasActions && <div class="flex items-center gap-1"><slot name="actions" /></div>}
      <span class="flex-1"></span>
      {
        maxLength && (
          <span data-composer-counter data-limit={value.length >= maxLength ? "" : undefined} class="px-1 text-xs/5 text-muted-foreground tabular-nums data-limit:font-medium data-limit:text-destructive">
            <span class="sr-only">{counterLabel} {maxLength}: </span>
            <span data-composer-count>{value.length}</span> / {maxLength}
          </span>
        )
      }
      <button
        type="submit"
        data-composer-send
        aria-label={sendLabel}
        class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-primary 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-75 disabled:pointer-events-none disabled:opacity-52 motion-reduce:active:scale-100"
      >
        <ArrowUp class="size-4" aria-hidden="true" />
      </button>
    </div>
  </div>
  {hint && <p id={hintId} class="px-1 text-xs/5 text-muted-foreground">{hint}</p>}
  {
    attach && (
      <>
        <p data-composer-status role="status" class="sr-only"></p>
        <template data-composer-chip>
          <li class="inline-flex max-w-full min-w-0 items-center gap-1 rounded-full border border-border bg-muted py-0.5 pr-0.5 pl-2.5 text-xs/5 font-medium text-foreground">
            <span data-chip-name class="truncate" />
            <button type="button" data-chip-remove class="inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-[background-color,color] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">
              <X class="size-3.5" aria-hidden="true" />
            </button>
          </li>
        </template>
      </>
    )
  }
</form>

<script>
  function enhance(form: HTMLFormElement) {
    if (form.hasAttribute("data-enhanced")) return;
    form.setAttribute("data-enhanced", "");
    const area = form.querySelector<HTMLTextAreaElement>("textarea");
    const send = form.querySelector<HTMLButtonElement>("[data-composer-send]");
    if (!area || !send) return;
    const counter = form.querySelector<HTMLElement>("[data-composer-counter]");
    const count = form.querySelector<HTMLElement>("[data-composer-count]");
    const fileInput = form.querySelector<HTMLInputElement>("[data-composer-input]");
    const list = form.querySelector<HTMLElement>("[data-composer-files]");
    const status = form.querySelector<HTMLElement>("[data-composer-status]");
    const chip = form.querySelector<HTMLTemplateElement>("template[data-composer-chip]");
    const modOnly = form.getAttribute("data-submit-on") === "mod-enter";
    const removeLabel = form.getAttribute("data-remove-label") ?? "Remove";
    const attachedLabel = form.getAttribute("data-attached-label") ?? "Attached files";
    const nativeGrow = CSS.supports("field-sizing", "content");

    const grow = () => {
      if (nativeGrow) return;
      // Hidden (dialog, closed tab): measuring now would give height 0. The resize observer re-syncs once visible.
      if (!area.offsetParent || area.scrollHeight === 0) return;
      area.style.height = "auto";
      const max = parseFloat(getComputedStyle(area).maxHeight);
      area.style.height = Math.min(area.scrollHeight, Number.isFinite(max) ? max : Infinity) + "px";
    };
    const sync = () => {
      send.disabled = area.disabled || area.value.trim().length === 0;
      if (counter && count) {
        const text = String(area.value.length);
        if (count.textContent !== text) count.textContent = text;
        counter.toggleAttribute("data-limit", area.maxLength > 0 && area.value.length >= area.maxLength);
      }
      grow();
    };

    let known: File[] = [];
    const files = (): File[] => (fileInput?.files ? Array.from(fileInput.files) : []);
    const setFiles = (next: File[]) => {
      if (!fileInput) return;
      const transfer = new DataTransfer();
      next.forEach((file) => transfer.items.add(file));
      fileInput.files = transfer.files;
      known = next;
      render();
    };
    let shown = new Set<string>();
    const render = () => {
      if (!list || !chip) return;
      const current = files();
      list.replaceChildren();
      const next = new Set<string>();
      current.forEach((file, index) => {
        const item = chip.content.firstElementChild!.cloneNode(true) as HTMLElement;
        item.querySelector("[data-chip-name]")!.textContent = file.name;
        const key = `${file.name}|${file.size}|${file.lastModified}`;
        next.add(key);
        if (!shown.has(key)) item.classList.add("motion-safe:animate-rise");
        const remove = item.querySelector<HTMLButtonElement>("[data-chip-remove]")!;
        remove.setAttribute("aria-label", `${removeLabel} ${file.name}`);
        remove.addEventListener("click", () => {
          setFiles(files().filter((_, i) => i !== index));
          const buttons = list.querySelectorAll<HTMLButtonElement>("[data-chip-remove]");
          (buttons[Math.min(index, buttons.length - 1)] ?? fileInput)?.focus();
        });
        list.append(item);
      });
      shown = next;
      list.hidden = current.length === 0;
      if (status) {
        const text = current.length ? `${attachedLabel}: ${current.length}` : "";
        if (status.textContent !== text) status.textContent = text;
      }
    };
    fileInput?.addEventListener("change", () => {
      // The browser replaces the list on every pick; keep the earlier files and skip duplicates.
      const same = (a: File, b: File) => a.name === b.name && a.size === b.size && a.lastModified === b.lastModified;
      setFiles([...known, ...files().filter((file) => !known.some((k) => same(k, file)))]);
    });

    area.addEventListener("input", sync);
    area.addEventListener("keydown", (event) => {
      if (event.key !== "Enter" || event.isComposing || event.keyCode === 229) return;
      const mod = event.metaKey || event.ctrlKey;
      const submit = modOnly ? mod : mod || !event.shiftKey;
      if (!submit) return;
      event.preventDefault();
      if (area.value.trim()) form.requestSubmit();
    });
    form.addEventListener("submit", (event) => {
      if (!area.value.trim()) {
        event.preventDefault();
        area.focus();
        return;
      }
      form.dispatchEvent(new CustomEvent("haze:composer-send", { bubbles: true, detail: { text: area.value, files: files() } }));
    });
    form.addEventListener("reset", () => {
      known = [];
      // The reset event fires before values change; sync afterwards.
      setTimeout(() => {
        render();
        sync();
      });
    });
    sync();
    if (!nativeGrow && "ResizeObserver" in window) {
      let width = -1;
      new ResizeObserver(() => {
        const next = area.clientWidth;
        if (next === width) return;
        width = next;
        grow();
      }).observe(area);
    }
  }
  const init = () => document.querySelectorAll<HTMLFormElement>("form[data-haze-composer]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-composer-listener")) {
    document.documentElement.setAttribute("data-haze-composer-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
