# Autocomplete

> Free-text input with grouped typeahead suggestions, clear and browse controls, and a native datalist fallback.

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

## Use when
- Typing tags, commands, or custom strings while offering quick filtered suggestions
- Allowing users to keep custom typed values alongside saved recommendations
- Replacing basic browser datalist inputs with keyboard-navigable grouped menus

## Avoid when
- Users must pick strictly from a fixed list of options; use combobox or select
- Selecting multiple discrete tags into chips; use tags-input

## Alternatives
- [combobox](https://hazeui.com/ui/combobox.md)
- [search-field](https://hazeui.com/ui/search-field.md)
- [tags-input](https://hazeui.com/ui/tags-input.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique id for the input and derived listbox and datalist ids. |
| name | `string` |  | no | Submitted form field name; defaults to id. |
| label | `string` | "Model or tag" | no | Visible label associated with the input. |
| value | `string` | "" | no | Initial text value. |
| placeholder | `string` | "Search models..." | no | Placeholder hint shown when empty. |
| suggestions | `{ value: string; label?: string; hint?: string; group?: string }[]` |  | no | Grouped or flat suggestion entries. |
| size | `"sm" \| "md" \| "lg"` | "md" | no | Field height matching Haze input sizing. |
| leadingIcon | `boolean` | true | no | Displays a search icon at the start of the field. |
| showClear | `boolean` | true | no | Displays a clear button whenever the field contains text. |
| showTrigger | `boolean` | true | no | Displays a chevron button to browse all suggestions. |
| required | `boolean` | false | no | Marks the underlying input as required. |
| disabled | `boolean` | false | no | Disables typing, clearing, and opening suggestions. |
| class | `string` |  | no | Extra classes on the outer container. |

## Accessibility
- Progressive enhancement strips native datalist and promotes the input to role="combobox" with aria-autocomplete="list" and aria-activedescendant.
- Users can freely type and submit custom text or confirm a highlighted suggestion with Enter.
- Clicking the clear button clears the field and returns keyboard focus directly to the input.
- Key Down / Up: Open suggestions and cycle through visible matches
- Key Enter: Accept the highlighted suggestion (or submit form when closed)
- Key Escape: Close the suggestion popover while keeping typed text

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze autocomplete ui for our product. Replace the demo values of these props with our real content: id, name, label, value, placeholder, suggestions, size, leadingIcon, showClear, showTrigger, required, disabled, class. Keep the layout, the heading level rules and these accessibility details: Progressive enhancement strips native datalist and promotes the input to role="combobox" with aria-autocomplete="list" and aria-activedescendant. Users can freely type and submit custom text or confirm a highlighted suggestion with Enter. Clicking the clear button clears the field and returns keyboard focus directly to the input. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using autocomplete, check it fits: use it when typing tags, commands, or custom strings while offering quick filtered suggestions; allowing users to keep custom typed values alongside saved recommendations; replacing basic browser datalist inputs with keyboard-navigable grouped menus. Avoid it when users must pick strictly from a fixed list of options; use combobox or select; selecting multiple discrete tags into chips; use tags-input. Alternatives: @haze/combobox, @haze/search-field, @haze/tags-input.

## Example requests that should lead here
- Add an Autocomplete field for deployment region with regional latency hints
- Create a model picker input that allows custom model strings alongside suggested defaults

## Source

```astro
---
import { ChevronsUpDown, Search, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Suggestion {
  value: string;
  label?: string;
  hint?: string;
  group?: string;
}

interface Props {
  id: string;
  name?: string;
  label?: string;
  value?: string;
  placeholder?: string;
  suggestions?: Suggestion[];
  size?: "sm" | "md" | "lg";
  /** Shows a leading search icon inside the text field. */
  leadingIcon?: boolean;
  /** Shows a clear button while the field holds text. */
  showClear?: boolean;
  /** Shows a toggle button to browse all suggestions without typing first. */
  showTrigger?: boolean;
  required?: boolean;
  disabled?: boolean;
  class?: string;
  [key: string]: unknown;
}

const {
  id,
  name = id,
  label = "Model or tag",
  value = "",
  placeholder = "Search models...",
  suggestions = [
    { value: "gpt-4.1", label: "GPT-4.1", hint: "General", group: "Recommended" },
    { value: "claude-sonnet-4", label: "Claude Sonnet 4", hint: "Code", group: "Recommended" },
    { value: "gemini-2.5-pro", label: "Gemini 2.5 Pro", hint: "Reasoning", group: "Recommended" },
    { value: "llama-3.3-70b", label: "Llama 3.3 70B", hint: "Open weights", group: "Self-hosted" },
    { value: "qwen-2.5-coder", label: "Qwen 2.5 Coder", hint: "Open weights", group: "Self-hosted" },
  ],
  size = "md",
  leadingIcon = true,
  showClear = true,
  showTrigger = true,
  required = false,
  disabled = false,
  class: className,
  ...rest
} = Astro.props;

const heights = {
  sm: "h-8 text-xs/5",
  md: "h-10 text-sm/5",
  lg: "h-11 text-sm/5",
};
const rightPad = showClear && showTrigger ? "pe-16" : showClear || showTrigger ? "pe-9" : "pe-3";

// Group suggestions preserving first-seen group order.
const grouped: { name: string; items: (Suggestion & { index: number })[] }[] = [];
const byGroup = new Map<string, (Suggestion & { index: number })[]>();
suggestions.forEach((s, index) => {
  const g = s.group ?? "";
  let list = byGroup.get(g);
  if (!list) {
    list = [];
    byGroup.set(g, list);
    grouped.push({ name: g, items: list });
  }
  list.push({ ...s, index });
});
---

<div data-haze-autocomplete class={cn("grid min-w-0 gap-2", className)}>
  <label id={`${id}-label`} for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
  <div class="relative min-w-0" style={`anchor-name: --${id}`}>
    {
      leadingIcon && (
        <Search aria-hidden="true" class="pointer-events-none absolute start-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
      )
    }
    <input
      {...rest}
      id={id}
      name={name}
      type="text"
      value={value}
      list={`${id}-datalist`}
      autocomplete="off"
      placeholder={placeholder}
      required={required}
      disabled={disabled}
      data-ac-input
      class={cn(
        "w-full min-w-0 rounded-lg border border-frame-input bg-field tracking-[-0.01em] text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy 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 disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50 aria-invalid:border-destructive aria-invalid:focus-visible:ring-destructive/24",
        heights[size],
        leadingIcon ? "ps-9" : "ps-3",
        rightPad,
      )}
    />
    <datalist id={`${id}-datalist`} data-ac-datalist>
      {suggestions.map((s) => <option value={s.value} label={s.label ?? s.value}></option>)}
    </datalist>

    {
      showClear && (
        <button
          type="button"
          data-ac-clear
          hidden
          disabled={disabled}
          aria-label="Clear input"
          class={cn(
            "absolute top-1/2 inline-flex size-7 -translate-y-1/2 cursor-pointer items-center justify-center rounded-sm text-muted-foreground transition-[color,background-color,scale] duration-150 ease-snappy active:scale-90 active:duration-100 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring",
            showTrigger ? "end-8" : "end-1.5",
          )}
        >
          <X class="size-3.5" aria-hidden="true" />
        </button>
      )
    }
    {
      showTrigger && (
        <button
          type="button"
          data-ac-trigger
          hidden
          disabled={disabled}
          aria-label={`Browse ${label.toLowerCase()} suggestions`}
          aria-expanded="false"
          aria-controls={`${id}-listbox`}
          class="absolute end-1.5 top-1/2 inline-flex size-7 -translate-y-1/2 cursor-pointer items-center justify-center rounded-sm text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-45"
        >
          <ChevronsUpDown class="size-3.5" aria-hidden="true" />
        </button>
      )
    }
  </div>

  <div
    data-ac-popover
    popover="manual"
    style={`position-anchor: --${id}`}
    class="m-auto max-h-[min(16rem,calc(100dvh-1rem))] w-68 max-w-[calc(100vw-1rem)] origin-top -translate-y-1 scale-[0.97] overflow-y-auto rounded-lg border border-border bg-popover p-1 text-[0.8125rem] text-popover-foreground opacity-0 shadow-float transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 [[data-haze-autocomplete]:not([data-enhanced])_&]:hidden supports-[position-area:block-end]:m-0 supports-[position-area:block-end]:mt-1 supports-[position-area:block-end]:w-[anchor-size(width)] supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block]"
  >
    <div id={`${id}-listbox`} role="listbox" aria-labelledby={`${id}-label`} class="grid gap-1">
      {
        grouped.map((group) => (
          <div data-ac-group class="grid">
            {group.name && (
              <p class="px-2.5 py-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase">
                {group.name}
              </p>
            )}
            {group.items.map((item) => (
              <button
                type="button"
                id={`${id}-opt-${item.index}`}
                role="option"
                aria-selected="false"
                data-ac-option
                data-ac-value={item.value}
                data-ac-search={`${item.value} ${item.label ?? ""} ${item.hint ?? ""}`}
                class="flex min-h-8 w-full cursor-pointer items-center justify-between gap-2 rounded-sm px-2.5 py-1 text-left text-foreground transition-colors duration-75 hover:bg-accent data-[active]:bg-accent data-[active]:text-accent-foreground aria-hidden:hidden"
              >
                <span class="min-w-0 truncate">{item.label ?? item.value}</span>
                {item.hint && <span class="shrink-0 font-mono text-[0.6875rem] text-muted-foreground">{item.hint}</span>}
              </button>
            ))}
          </div>
        ))
      }
    </div>
    <p data-ac-empty hidden role="status" class="px-2.5 py-2 text-xs/5 text-muted-foreground">
      No saved matches — press Enter to keep your custom entry.
    </p>
  </div>
</div>

<script>
  const fold = (s: string) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLocaleLowerCase().trim();

  function enhanceAutocomplete() {
    document.querySelectorAll<HTMLElement>("[data-haze-autocomplete]:not([data-enhanced])").forEach((root) => {
      const input = root.querySelector<HTMLInputElement>("[data-ac-input]");
      const datalist = root.querySelector<HTMLDataListElement>("[data-ac-datalist]");
      const clearBtn = root.querySelector<HTMLButtonElement>("[data-ac-clear]");
      const triggerBtn = root.querySelector<HTMLButtonElement>("[data-ac-trigger]");
      const popup = root.querySelector<HTMLElement>("[data-ac-popover]");
      const empty = root.querySelector<HTMLElement>("[data-ac-empty]");
      if (!input || !popup || !empty || typeof popup.showPopover !== "function") return;

      const options = Array.from(popup.querySelectorAll<HTMLButtonElement>("[data-ac-option]"));
      const groups = Array.from(popup.querySelectorAll<HTMLElement>("[data-ac-group]"));
      let visible: HTMLButtonElement[] = options;
      let active: HTMLButtonElement | null = null;

      input.removeAttribute("list");
      datalist?.remove();
      input.setAttribute("role", "combobox");
      input.setAttribute("aria-autocomplete", "list");
      input.setAttribute("aria-expanded", "false");
      input.setAttribute("aria-controls", `${input.id}-listbox`);

      const syncClear = () => {
        if (!clearBtn) return;
        clearBtn.hidden = input.disabled || input.value.length === 0;
      };

      const setActive = (opt: HTMLButtonElement | null) => {
        active?.removeAttribute("data-active");
        active = opt;
        if (!opt) {
          input.removeAttribute("aria-activedescendant");
          return;
        }
        opt.setAttribute("data-active", "");
        input.setAttribute("aria-activedescendant", opt.id);
        if (popup.matches(":popover-open")) opt.scrollIntoView({ block: "nearest" });
      };

      const filter = (query: string) => {
        const needle = fold(query);
        visible = [];
        options.forEach((opt) => {
          const match = !needle || fold(opt.dataset.acSearch ?? "").includes(needle);
          opt.setAttribute("aria-hidden", String(!match));
          opt.setAttribute("aria-selected", String(opt.dataset.acValue === input.value));
          if (match) visible.push(opt);
        });
        groups.forEach((g) => {
          const hasVisible = g.querySelector('[data-ac-option]:not([aria-hidden="true"])') !== null;
          g.hidden = !hasVisible;
        });
        empty.hidden = visible.length > 0;
        setActive(visible[0] ?? null);
      };

      const open = (query = input.value) => {
        if (input.disabled) return;
        filter(query);
        if (!popup.matches(":popover-open")) popup.showPopover();
        input.setAttribute("aria-expanded", "true");
        triggerBtn?.setAttribute("aria-expanded", "true");
      };

      const close = () => {
        if (popup.matches(":popover-open")) popup.hidePopover();
        input.setAttribute("aria-expanded", "false");
        triggerBtn?.setAttribute("aria-expanded", "false");
        setActive(null);
      };

      const commit = (val: string) => {
        input.value = val;
        syncClear();
        close();
        input.dispatchEvent(new Event("input", { bubbles: true }));
        input.dispatchEvent(new Event("change", { bubbles: true }));
        input.focus();
      };

      input.addEventListener("input", () => {
        syncClear();
        open(input.value);
      });
      input.addEventListener("focus", () => {
        if (!popup.matches(":popover-open")) open("");
      });
      input.addEventListener("keydown", (event) => {
        if (event.key === "ArrowDown") {
          event.preventDefault();
          if (!popup.matches(":popover-open")) return open("");
          if (!visible.length) return;
          const idx = active ? visible.indexOf(active) : -1;
          setActive(visible[(idx + 1) % visible.length] ?? null);
        } else if (event.key === "ArrowUp") {
          event.preventDefault();
          if (!popup.matches(":popover-open")) return open("");
          if (!visible.length) return;
          const idx = active ? visible.indexOf(active) : 0;
          setActive(visible[(idx - 1 + visible.length) % visible.length] ?? null);
        } else if (event.key === "Enter" && popup.matches(":popover-open") && active) {
          event.preventDefault();
          commit(active.dataset.acValue ?? "");
        } else if (event.key === "Escape" && popup.matches(":popover-open")) {
          event.preventDefault();
          close();
        }
      });

      options.forEach((opt) => {
        opt.addEventListener("pointerenter", () => setActive(opt));
        opt.addEventListener("click", () => commit(opt.dataset.acValue ?? ""));
      });

      clearBtn?.addEventListener("click", () => {
        input.value = "";
        syncClear();
        input.dispatchEvent(new Event("input", { bubbles: true }));
        input.dispatchEvent(new Event("change", { bubbles: true }));
        open("");
        input.focus();
      });

      triggerBtn?.addEventListener("click", () => {
        if (popup.matches(":popover-open")) close();
        else {
          open("");
          input.focus();
        }
      });

      root.addEventListener("haze:ac-outside", close);
      input.form?.addEventListener("reset", () => queueMicrotask(() => { syncClear(); close(); }));

      if (triggerBtn) triggerBtn.hidden = false;
      syncClear();
      root.setAttribute("data-enhanced", "");
    });
  }

  enhanceAutocomplete();
  if (!document.documentElement.hasAttribute("data-haze-autocomplete-listener")) {
    document.documentElement.setAttribute("data-haze-autocomplete-listener", "");
    document.addEventListener("astro:page-load", enhanceAutocomplete);
    document.addEventListener("pointerdown", (event) => {
      const target = event.target as Node | null;
      document.querySelectorAll<HTMLElement>("[data-haze-autocomplete][data-enhanced]").forEach((root) => {
        if (target && root.contains(target)) return;
        root.dispatchEvent(new Event("haze:ac-outside"));
      });
    });
  }
</script>
```
