# Tags input

> A comma-separated text field enhanced with removable tags and an explicit add button.

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

## Use when
- People attach several short free-form labels to an item
- The set can include values outside a predefined list

## Avoid when
- The value must come from a predefined list. Use select or checkbox.
- Values may contain commas or need more structure than a label.

## Alternatives
- [input](https://hazeui.com/ui/input.md)
- [tag](https://hazeui.com/ui/tag.md)
- [checkbox](https://hazeui.com/ui/checkbox.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique control ID. Use it to associate a label with the input. |
| name | `string` | id | no | Form field name. |
| label | `string` | "Tags" | no | Visible field label. |
| value | `string[]` | [] | no | Initial tags without commas. |
| hint | `string` | "Separate tags with commas." | no | Instructions placed below the field. |
| addLabel | `string` | "Add tag" | no | Accessible name of the add button. |
| removeLabel | `string` | "Remove" | no | Accessible prefix for a tag removal button. |
| required | `boolean` |  | no | Requires at least one tag. |
| form | `string` |  | no | ID of the form that owns the field if it is outside the form. |
| ...attributes | `HTML input attributes` |  | no | Additional attributes for the native input. |
| class | `string` |  | no | Additional classes on the wrapper. |

## Accessibility
- The submitted value is one comma-separated string. The plain field accepts the same format without JavaScript.
- After a removal, focus returns to the editor and the change is announced.
- Key Enter or comma: Add the draft as a tag.
- Key Tab then Enter or Space: Focus and activate an add or remove button.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze tags-input ui for our product. Replace the demo values of these props with our real content: id, name, label, value, hint, addLabel, removeLabel, required, form, ...attributes, class. Keep the layout, the heading level rules and these accessibility details: The submitted value is one comma-separated string. The plain field accepts the same format without JavaScript. After a removal, focus returns to the editor and the change is announced. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using tags-input, check it fits: use it when people attach several short free-form labels to an item; the set can include values outside a predefined list. Avoid it when the value must come from a predefined list. use select or checkbox.; values may contain commas or need more structure than a label.. Alternatives: @haze/input, @haze/tag, @haze/checkbox.

## Example requests that should lead here
- Add a Project tags field with two initial tags, editable labels, and accessible removal.

## Source

```astro
---
import { Plus, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Input from "./input.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  value?: string[];
  hint?: string;
  addLabel?: string;
  removeLabel?: string;
  required?: boolean;
  form?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  id, name = id, label = "Tags", value = [], hint = "Separate tags with commas.",
  addLabel = "Add tag", removeLabel = "Remove", required, form, class: className,
  "aria-describedby": additionalDescription, ...rest
} = Astro.props;
const describedBy = [hint ? `${id}-hint` : undefined, additionalDescription].filter(Boolean).join(" ") || undefined;
const initial = value.join(", ");
---

<div data-haze-tags-input data-remove-label={removeLabel} class={cn("grid w-full min-w-0 gap-2", className)}>
  <label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
  <ul data-tags-list aria-label={label} class="hidden flex-wrap gap-1.5 [[data-haze-tags-input][data-enhanced]_&:not(:empty)]:flex"></ul>
  <div class="flex min-w-0 items-center gap-1.5">
    <Input {...rest} id={id} name={name} type="text" value={initial} required={required} form={form}
      autocomplete="off" aria-describedby={describedBy} data-tags-editor />
    <Button data-tags-add aria-label={addLabel} size="icon" variant="outline" class="hidden [[data-haze-tags-input][data-enhanced]_&]:inline-flex active:scale-90">
      <Plus aria-hidden="true" />
    </Button>
  </div>
  {hint && <p id={`${id}-hint`} class="text-[0.8125rem]/5 text-muted-foreground">{hint}</p>}
  <input type="hidden" name={name} value={initial} form={form} disabled data-tags-payload />
  <p data-tags-status aria-live="polite" class="sr-only"></p>
  <template data-tags-template>
    <li class="inline-flex max-w-full min-w-0 items-center gap-1 rounded-full border border-frame bg-muted ps-2.5 pe-0.5 py-0.5 text-xs/5 font-medium text-foreground">
      <span data-tag class="min-w-0 wrap-anywhere"></span>
      <button type="button" data-remove class="grid size-5 shrink-0 cursor-pointer place-items-center rounded-full text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground active:scale-90 active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50">
        <X aria-hidden="true" class="size-3.5" />
      </button>
    </li>
  </template>
</div>

<script>
  const parseTags = (text: string) =>
    [...new Set(text.split(",").map((tag) => tag.trim()).filter(Boolean))];

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const editor = root.querySelector<HTMLInputElement>("[data-tags-editor]");
    const payload = root.querySelector<HTMLInputElement>("[data-tags-payload]");
    const list = root.querySelector<HTMLUListElement>("[data-tags-list]");
    const template = root.querySelector<HTMLTemplateElement>("[data-tags-template]");
    const add = root.querySelector<HTMLButtonElement>("[data-tags-add]");
    const status = root.querySelector<HTMLElement>("[data-tags-status]");
    if (!editor || !payload || !list || !template || !add || !status) return;

    let tags = parseTags(editor.value);
    const required = editor.required;
    editor.removeAttribute("name");
    editor.value = "";

    const sync = () => {
      payload.value = parseTags([...tags, editor.value].join(",")).join(", ");
      payload.disabled = editor.disabled;
      editor.required = required && tags.length === 0;
      editor.setCustomValidity(editor.required && editor.value && !payload.value ? "Enter a tag." : "");
      add.disabled = editor.disabled || editor.readOnly;
    };

    let shown: Set<string> | null = null;
    const render = () => {
      list.replaceChildren();
      for (const tag of tags) {
        const row = template.content.cloneNode(true) as DocumentFragment;
        if (shown && !shown.has(tag)) row.firstElementChild?.classList.add("motion-safe:animate-rise");
        row.querySelector("[data-tag]")!.textContent = tag;
        const remove = row.querySelector<HTMLButtonElement>("[data-remove]")!;
        remove.setAttribute("aria-label", `${root.dataset.removeLabel || "Remove"} ${tag}`);
        remove.disabled = editor.disabled || editor.readOnly;
        remove.addEventListener("click", () => {
          tags = tags.filter((item) => item !== tag);
          editor.focus();
          render();
          sync();
          status.textContent = `Removed ${tag}.`;
        });
        list.append(row);
      }
      shown = new Set(tags);
    };

    const commit = () => {
      const candidates = parseTags(editor.value);
      if (!candidates.length || editor.readOnly || editor.matches(":disabled")) return;
      const added = candidates.filter((tag) => !tags.includes(tag));
      tags.push(...added);
      editor.value = "";
      render();
      sync();
      status.textContent = added.length ? `Added ${added.join(", ")}.` : "Those tags are already added.";
    };

    editor.addEventListener("input", (event) => {
      sync();
      if (!(event instanceof InputEvent && event.isComposing) && editor.value.includes(",")) commit();
    });
    editor.addEventListener("keydown", (event) => {
      if (event.key !== "Enter" || event.isComposing || !parseTags(editor.value).length) return;
      event.preventDefault();
      commit();
    });
    add.addEventListener("click", () => {
      commit();
      editor.focus();
    });
    editor.form?.addEventListener("reset", (event) => queueMicrotask(() => {
      if (event.defaultPrevented) return;
      tags = parseTags(editor.defaultValue);
      editor.value = "";
      status.textContent = "";
      render();
      sync();
    }));
    new MutationObserver(() => { render(); sync(); }).observe(editor, { attributeFilter: ["disabled", "readonly"] });
    render();
    sync();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-tags-input]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-tags-input-listener")) {
    document.documentElement.setAttribute("data-haze-tags-input-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
