# Combobox

> Filters a list as you type and submits a single selected value through a native select.

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

## Use when
- A form asks users to pick one item from a long list.
- People know part of the option name and can type to find it.

## Avoid when
- A few choices fit in a visible radio group.

## Alternatives
- [select](https://hazeui.com/ui/select.md)
- [radio-group](https://hazeui.com/ui/radio-group.md)
- [multi-select](https://hazeui.com/ui/multi-select.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique field ID and prefix for the option list. |
| name | `string` | id | no | Submitted field name. |
| label | `string` | Workspace | no | Visible and accessible field label. |
| options | `Option[]` |  | no | Choices with nonempty values, labels, and optional disabled state. |
| value | `string` |  | no | Initially selected option value. |
| placeholder | `string` |  | no | Prompt shown before a choice is made. |
| required | `boolean` |  | no | Requires a matching choice before submission. |
| disabled | `boolean` |  | no | Disables input and form submission. |
| class | `string` |  | no | Classes for the field wrapper. |

## Accessibility
- The native select remains usable when scripting or popovers are unavailable.
- The active option is announced while focus stays in the search field.
- Key ↑ / ↓: Open the list or move through matching options.
- Key Enter: Choose the active option.
- Key Escape: Close suggestions and keep the selected value.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze combobox ui for our product. Replace the demo values of these props with our real content: id, name, label, options, value, placeholder, required, disabled, class. Keep the layout, the heading level rules and these accessibility details: The native select remains usable when scripting or popovers are unavailable. The active option is announced while focus stays in the search field. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using combobox, check it fits: use it when a form asks users to pick one item from a long list.; people know part of the option name and can type to find it.. Avoid it when a few choices fit in a visible radio group.. Alternatives: @haze/select, @haze/radio-group, @haze/multi-select.

## Example requests that should lead here
- Add a searchable workspace field to the move-project form.
- Choose a single department from a long directory.

## Source

```astro
---
import { Check, Search } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Input from "./input.astro";
import Select from "./select.astro";

interface Option { value: string; label: string; disabled?: boolean }
interface Props {
  id: string;
  name?: string;
  label?: string;
  options?: Option[];
  value?: string;
  placeholder?: string;
  required?: boolean;
  disabled?: boolean;
  class?: string;
  [key: string]: unknown;
}

const {
  id, name = id, label = "Workspace", value, placeholder = "Select a workspace",
  required, disabled, class: className, ...rest
} = Astro.props;
const options = (Astro.props.options ?? [
  { value: "studio", label: "Design studio" },
  { value: "docs", label: "Documentation" },
  { value: "support", label: "Customer support" },
]).filter((option) => option.value !== "");
const available = required ? options : [{ value: "", label: "No selection" }, ...options];
---

<div data-haze-combobox class={cn("grid min-w-0 gap-2", className)}>
  <label id={`${id}-label`} for={id} data-combo-label class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
  <div class="[[data-haze-combobox][data-enhanced]_&]:hidden">
    <Select {...rest} id={id} name={name} options={available} value={value} placeholder={required ? placeholder : undefined}
      required={required} disabled={disabled} data-combo-select />
  </div>
  <div class="relative hidden [[data-haze-combobox][data-enhanced]_&]:block">
    <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 id={`${id}-search`} name="" autocomplete="off" placeholder={placeholder} disabled={disabled}
      role="combobox" aria-expanded="false" aria-autocomplete="list" aria-labelledby={`${id}-label`} aria-controls={`${id}-options`}
      aria-describedby={rest["aria-describedby"]} aria-invalid={rest["aria-invalid"]}
      data-combo-search style={`anchor-name: --${id}`} class="ps-9" />
  </div>
  <div data-combo-popover popover="manual" style={`position-anchor: --${id}`} class={cn(
    "m-auto max-h-[min(15rem,calc(100dvh-1rem))] w-64 max-w-[calc(100vw-1rem)] overflow-y-auto rounded-lg border border-border bg-popover p-1 text-[0.8125rem] text-popover-foreground shadow-float [[data-haze-combobox]:not([data-enhanced])_&]:hidden",
    "origin-top -translate-y-1 scale-[0.97] opacity-0 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",
    "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]",
  )}>
    <ul id={`${id}-options`} role="listbox" aria-labelledby={`${id}-label`}>
      {available.map((option, index) => (
        <li id={`${id}-option-${index}`} role="option" aria-selected={option.value === (value ?? "") ? "true" : "false"} aria-disabled={option.disabled ? "true" : undefined}
          data-combo-value={option.value}
          class="group flex min-h-9 cursor-pointer items-center justify-between gap-2 rounded-sm px-3 py-1.5 transition-colors duration-75 data-[active]:bg-accent aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-hidden:hidden">
          <span class="min-w-0 wrap-anywhere">{option.label}</span>
          <Check aria-hidden="true" class="invisible size-3.5 shrink-0 text-foreground group-aria-selected:visible" />
        </li>
      ))}
    </ul>
    <p data-combo-empty hidden class="px-3 py-1.5 text-[0.8125rem]/5 text-muted-foreground" role="status">No matching options.</p>
  </div>
</div>

<script>
  const fold = (value: string) => value.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLocaleLowerCase().trim();

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const select = root.querySelector<HTMLSelectElement>("[data-combo-select]");
    const search = root.querySelector<HTMLInputElement>("[data-combo-search]");
    const label = root.querySelector<HTMLLabelElement>("[data-combo-label]");
    const popup = root.querySelector<HTMLElement>("[data-combo-popover]");
    const empty = root.querySelector<HTMLElement>("[data-combo-empty]");
    if (!select || !search || !label || !popup || !empty || typeof popup.showPopover !== "function") return;

    const options = Array.from(popup.querySelectorAll<HTMLElement>("[data-combo-value]"));
    const required = select.required;
    const form = select.form;
    let visible = options;
    let active: HTMLElement | undefined;

    const focusOption = (option?: HTMLElement) => {
      active?.removeAttribute("data-active");
      active = option;
      if (!option) {
        search.removeAttribute("aria-activedescendant");
        return;
      }
      option.setAttribute("data-active", "");
      search.setAttribute("aria-activedescendant", option.id);
      if (popup.matches(":popover-open")) option.scrollIntoView({ block: "nearest", inline: "nearest" });
    };
    const selectedLabel = () => select.value ? select.selectedOptions[0]?.label ?? "" : "";
    const updateSelection = () => {
      search.value = selectedLabel();
      search.setCustomValidity(required && !select.value ? "Choose an option." : "");
      options.forEach((option) => option.setAttribute("aria-selected", String(option.dataset.comboValue === select.value)));
    };
    const open = (query = "") => {
      const needle = fold(query);
      const matches = options.filter((option) => {
        const match = fold(option.textContent ?? "").includes(needle);
        option.setAttribute("aria-hidden", String(!match));
        return match;
      });
      empty.hidden = matches.length > 0;
      visible = matches.filter((option) => option.getAttribute("aria-disabled") !== "true");
      if (!popup.matches(":popover-open")) popup.showPopover();
      search.setAttribute("aria-expanded", "true");
      focusOption(visible.find((option) => option.dataset.comboValue === select.value) ?? visible[0]);
    };
    const close = () => {
      if (popup.matches(":popover-open")) popup.hidePopover();
      search.setAttribute("aria-expanded", "false");
      focusOption();
      updateSelection();
    };
    const pick = (option?: HTMLElement) => {
      if (!option || option.getAttribute("aria-disabled") === "true") return;
      const before = select.value;
      select.value = option.dataset.comboValue ?? "";
      close();
      if (select.value === before) return;
      select.dispatchEvent(new Event("input", { bubbles: true }));
      select.dispatchEvent(new Event("change", { bubbles: true }));
    };

    search.addEventListener("focus", () => search.select());
    search.addEventListener("click", () => { if (!popup.matches(":popover-open")) { open(); search.select(); } });
    search.addEventListener("input", (event) => { if (!(event instanceof InputEvent && event.isComposing)) open(search.value); });
    search.addEventListener("compositionend", () => open(search.value));
    search.addEventListener("blur", close);
    search.addEventListener("keydown", (event) => {
      if (event.isComposing) return;
      const isOpen = popup.matches(":popover-open");
      const key = event.key;
      if (key === "ArrowDown" || key === "ArrowUp") {
        event.preventDefault();
        if (!isOpen) { open(); return; }
        const index = active ? visible.indexOf(active) : -1;
        const next = index + (key === "ArrowDown" ? 1 : -1);
        if (visible.length) focusOption(visible[(next + visible.length) % visible.length]);
      } else if (key === "Enter" && isOpen) {
        event.preventDefault();
        pick(active);
      } else if (key === "Escape" && isOpen) {
        event.preventDefault();
        event.stopPropagation();
        close();
      }
    });
    popup.addEventListener("mousedown", (event) => {
      if ((event.target as Element).closest("[data-combo-value]")) event.preventDefault();
    });
    popup.addEventListener("click", (event) => {
      const option = (event.target as Element).closest<HTMLElement>("[data-combo-value]");
      if (!option) return;
      pick(option);
    });
    select.addEventListener("change", updateSelection);
    form?.addEventListener("reset", () => queueMicrotask(close));
    if (form?.id) search.setAttribute("form", form.id);
    select.required = false;
    search.required = required;
    label.htmlFor = search.id;
    updateSelection();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-combobox]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-combobox-listener")) {
    document.documentElement.setAttribute("data-haze-combobox-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
