# Combobox

> Pick one or several from a list your server searches: results morph between queries instead of flashing, and picks fly into chips.

The usual combobox empties its list on every keystroke, shows a spinner, then drops in a new list a beat later, and a slow answer for "ma" can land after the answer for "maya". This one asks your search() a moment after you stop typing, aborts the older request, and keeps every answer, so going back a letter is instant. While it waits, the rows you had stay (dimmed after a beat) and a hairline runs along the search field; when the answer lands, rows that stay glide to their new places, new rows rise in and gone rows fade where they stood. The letters you typed are picked out in each name. Picking one folds the panel and morphs the field's label; picking several carries the row's name up into the chip it becomes, and removing a chip slides the rest into its place. When nothing fits, "Create …" runs your onCreate. The panel opens clear of the field on the page's body, so no card clips it, and it follows the field as the page scrolls.

## Install

```bash
npx shadcn@latest add @hairline/combobox
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`, `status-button`
- Docs and live preview: https://hairlineui.com/ui/combobox
- Registry item (source): https://hairlineui.com/r/combobox.json

## Usage

```tsx
import { Combobox } from "@/components/combobox";

<Combobox
  label="Assignee"
  placeholder="Assign"
  search={async (q, { signal }) => {
    const res = await fetch(`/api/people?q=${encodeURIComponent(q)}`, { signal });
    return res.json(); // [{ value, label, description?, image? }]
  }}
  onValueChange={(person) => assign(person?.value ?? null)}
/>
```

## Searching your own database

search() gets the query and an AbortSignal; pass the signal to fetch so typing on cancels the request. The route returns plain options. With several values, onValueChange gets the whole list each time.

```tsx
// app/api/repos/route.ts
import { db } from "@/lib/db";

export async function GET(request: Request) {
  const q = new URL(request.url).searchParams.get("q") ?? "";
  const user = await requireUser();
  const repos = await db.repository.findMany({
    where: { orgId: user.orgId, name: { contains: q, mode: "insensitive" } },
    orderBy: { pushedAt: "desc" },
    take: 20,
  });
  return Response.json(
    repos.map((r) => ({ value: r.id, label: r.name, description: `${r.owner} · ${r.language}` })),
  );
}

// app/settings/repositories.tsx
"use client";
import { useState } from "react";
import { Combobox, type ComboboxOption } from "@/components/combobox";

export function RepositoryPicker({ initial }: { initial: ComboboxOption[] }) {
  const [repos, setRepos] = useState(initial);
  return (
    <form action={connectRepositories}>
      <Combobox
        multiple
        name="repositories"
        label="Repositories"
        placeholder="Search your repositories"
        max={5}
        value={repos}
        onValueChange={setRepos}
        search={async (q, { signal }) => {
          const res = await fetch(`/api/repos?q=${encodeURIComponent(q)}`, { signal });
          if (!res.ok) throw new Error("Couldn't reach GitHub. Try again.");
          return res.json();
        }}
      />
      <button type="submit">Connect</button>
    </form>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` | – | Accessible name, e.g. "Assignee". |
| `options` | `ComboboxOption[]` | – | A list to filter here: { value, label, description?, image?, initials?, icon?, keywords?, group?, disabled? }. Matches rank label starts, then word starts, then anywhere, then description and keywords. |
| `search` | `(query, { signal }) => Promise<ComboboxOption[]>` | – | Ask your server instead. Called with "" when the panel opens; answers are cached per query; throw to show an error with Retry. |
| `multiple` | `boolean` | `false` | Pick several: value is a list, picks become chips and the panel stays open. |
| `value / defaultValue` | `ComboboxOption \| null, or ComboboxOption[]` | – | The picked option objects (not just ids), so a search result needs no lookup to show. |
| `onValueChange` | `(value) => void` | – | The option (or null) for one; the whole list for several. |
| `onCreate` | `(query) => Promise<ComboboxOption \| void>` | – | Offers "Create …" when nothing matches exactly. Return the new option, or nothing to use the text as it is. Throw to refuse. |
| `max` | `number` | – | How many can be picked when multiple; more shakes the row and says so. |
| `variant` | `"field" \| "pill"` | `"field"` | A 38px form field, or a 28px pill for sidebars and toolbars. |
| `debounce` | `number` | `180` | Milliseconds after the last keystroke before search runs. |
| `limit` | `number` | `100` | Rows shown at once; the rest wait for a narrower search. |
| `clearable` | `boolean` | `false` | A × that clears a single choice. |
| `width / align` | `number / "start" \| "end"` | `280 / "start"` | The panel's least width (never narrower than the field) and the edge it lines up with. |
| `name` | `string` | – | Submits each chosen value as a hidden input with a form. |

## States

- **open**: The panel unfolds from the field's edge in 360ms (a clip from the top, or from the bottom when it opens upward), 6px clear of the field, with the search field focused. Things already picked are listed first.
- **searching**: search() runs 180ms after the last keystroke (at once for the first list). The previous rows stay and dim to 55% after 140ms; a 1px bar runs along the search field's edge. An older request is aborted through its AbortSignal.
- **results**: Rows that stay glide to their new places (300ms, additive, so a quick second answer never jumps); new rows rise 4px out of a blur, staggered 14ms; gone rows fade where they stood. The panel's height eases to the new list in 280ms and the highlight glides to the active row.
- **pick one**: A check draws in the row, the panel folds back in 220ms and the field's label morphs to the choice; its avatar or icon scales in through a blur as the old one leaves.
- **pick several**: The row's box fills and its check draws; the name is carried from the row to its new chip in 460ms while the chip pops in, and the field's height eases if the chips wrap. The count in the footer rolls.
- **remove**: A chip's ×, unticking its row, or Backspace in an empty search: the chip fades and shrinks where it stood while the others glide into the gap.
- **create**: When nothing matches exactly, the last row offers "Create …". Its plus becomes a spinner and the label morphs to "Creating"; what onCreate returns is picked. If it throws, the row shakes and the reason shows in the footer.
- **error**: If search() throws, the rows give way to the message and a Retry button (Status button) that says Retrying while it asks again.

## What it handles

shadcn’s Combobox filters a list that’s already in the browser. Once the list lives on your server, every product team ends up writing the same plumbing around it. This is that plumbing, finished.

- **Asks your server as you type**: It waits for a pause in typing, cancels the request it no longer needs and remembers every answer, so going back a letter is instant.
- **Answers land in order**: A slow answer for “ma” can never replace the answer for “maya”.
- **The list never flashes**: Old results stay, dimmed, until new ones arrive; then rows slide to their new places instead of the list going blank.
- **Several picks become chips**: Each picked name flies into a chip; × or Backspace removes one, and an optional limit says how many are allowed.
- **Failures have a way out**: A failed search shows your message and a Retry button, not an empty list that looks like “no results”.
- **Create from what you typed**: “Create label ‘design review’” calls your function and picks whatever it returns.

## Replaces

Popover + Command, a debounce hook, AbortController, a results cache, a multi-select chip input, loading and error rows

## Where it fits

- **Assignee pickers**: Assign an issue or a ticket to anyone in a 300-person workspace.
- **Customer search**: Pick the customer on an invoice from thousands in your database or in Stripe.
- **Repository pickers**: Connect several GitHub repositories to a project in one go.
- **Labels and tags**: Tag a record with existing labels, or create a new one without leaving the field.

## Notes

- The field is a button that opens a dialog holding a real combobox: the search input with aria-activedescendant over a listbox (aria-multiselectable when picking several). Arrows move, Page Up/Down jump, Enter picks, Escape closes and returns focus, Backspace in an empty search removes the last chip. Typing on the closed field opens it with that letter.
- Counts ("8 results"), picks and removals are announced in a status region once typing settles; group names are visible labels, not options.
- Leaving rows and chips are their own detached elements, faded in a layer React never renders into, so they cost no render. Glides are measured from layout offsets right before each change and added to any glide still running.
- The panel is portalled to the body with the field's theme variables copied onto it, so it never gets clipped by an overflow and still matches a themed card. It repositions on scroll and closes when the field leaves the screen.
- Search text is 16px on touch screens so phones don't zoom in. filterOptions() is exported, so a server can rank results the same way.
- Reduced motion: no unfolding, flights or glides; the list and chips change in place.

License: MIT (https://hairlineui.com/license#components)
