# Combobox

A text input with a listbox of suggestions (the WAI-ARIA "editable combobox with list autocomplete"). Focus stays in the input; the active option moves with `aria-activedescendant`. The listbox is a `popover="auto"` anchored to the input with CSS, so the platform provides the top layer, light dismiss, Escape and nesting inside dialogs. The library filters nothing: you render the options for a query, synchronously or with `use()` under your own `<Suspense>`.

Typing makes no option active, so by default Enter right after typing picks nothing: the user moves to an option with ArrowDown first (the APG default, "manual selection"). Pass `autoHighlight` to make the first match active when the results settle, so that typing then Enter picks it (APG "automatic selection").

## Anatomy

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

<Combobox.Root name="country" valueChangeAction={saveCountry}>   {/* no DOM; a hidden input with name */}
  <Combobox.Label>Country</Combobox.Label>                          {/* label[for] */}
  <Combobox.Input placeholder="Type to search" required />          {/* input[role=combobox] */}
  <Combobox.Clear aria-label="Clear" />                             {/* button, optional */}
  <Combobox.Trigger aria-label="Show all countries" />              {/* button, optional */}
  <Combobox.Popup className="listbox">                              {/* div[popover=auto] */}
    <Combobox.List>                                                 {/* div[role=listbox] */}
      {({ query }) => (
        <Suspense fallback={<Combobox.Status>Searching…</Combobox.Status>}>
          <CountryOptions query={query} />                          {/* Combobox.Option… */}
        </Suspense>
      )}
    </Combobox.List>
    <Combobox.Empty>No country matches.</Combobox.Empty>            {/* only when settled and empty */}
  </Combobox.Popup>
</Combobox.Root>
```

- **Two states.** `value` (`string | null`) is what is chosen; `inputValue` is what is typed. The library writes the text itself only at defined moments: typing, an accepted option (its `label`, else its text), a revert, Clear, a form reset, and text typed before hydration. It never derives the text from `value`, so a preselected value needs its text too: `<Combobox.Root defaultValue={user.country} defaultInputValue={user.countryName}>` (development warns otherwise).
- **Popup and List are separate** because a listbox may contain only options and groups: `Empty` and a hint `Status` go in the Popup, outside the List. A `Status` inside the List (the Suspense fallback above) marks the results as loading: it renders with `role="none"` (no live region inside the listbox), the List gets `aria-busy="true"`, `Empty` stays hidden and nothing is announced until the results arrive.
- **No portal, no positioner.** The Popup is shown with `showPopover({ source: input })`: the input is its implicit anchor, and a press on the input keeps the listbox open (the Input captures the pointer to the Popup; in Firefox a drag-to-select in the field does not extend while the listbox is open). Known hole: in Chromium, a touch tap on the field inside a same-origin iframe (a Storybook or sandbox preview) still closes it (#124, upstream). Render the Popup next to the Input.
- The listbox is always anchored to the input and opened by the library. The server HTML gives the Trigger no `popovertarget`; after hydration a `<button>` Trigger becomes the listbox's [invoker](../concepts/browser-owned-state.md#popup-triggers) (with every click cancelled), so pressing it while the listbox is open is not a light dismiss, and the browser exposes the listbox's state on it. The Input renders `aria-expanded` itself. Before hydration the input is a plain text field; text typed then is kept and adopted at mount, and nothing opens until the next keystroke.

```tsx title="ComboboxCountry.tsx"
"use client";
import { Suspense, startTransition, use, useState } from "react";
import { Combobox } from "@funstack/ui/combobox";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave, sleep } from "./fake-api.js";

interface Country {
  readonly code: string;
  readonly name: string;
}

const COUNTRIES: readonly Country[] = [
  { code: "ar", name: "Argentina" },
  { code: "au", name: "Australia" },
  { code: "br", name: "Brazil" },
  { code: "ca", name: "Canada" },
  { code: "fr", name: "France" },
  { code: "de", name: "Germany" },
  { code: "in", name: "India" },
  { code: "jm", name: "Jamaica" },
  { code: "jp", name: "Japan" },
  { code: "je", name: "Jersey" },
  { code: "ke", name: "Kenya" },
  { code: "mx", name: "Mexico" },
  { code: "nz", name: "New Zealand" },
  { code: "no", name: "Norway" },
  { code: "es", name: "Spain" },
  { code: "gb", name: "United Kingdom" },
];

// A pretend search API with a cache keyed by query: one promise per query, read with `use()`.
// Results arrive in random order; React only ever renders the latest query's.
const cache = new Map<string, Promise<readonly Country[]>>();
function searchCountries(query: string): Promise<readonly Country[]> {
  const key = query.trim().toLowerCase();
  let promise = cache.get(key);
  if (promise === undefined) {
    promise = sleep(300 + Math.random() * 500).then(() =>
      COUNTRIES.filter((c) => c.name.toLowerCase().includes(key)),
    );
    cache.set(key, promise);
  }
  return promise;
}

function CountryOptions({ query }: { query: string }) {
  const countries = use(searchCountries(query));
  return countries.map((c) => (
    <Combobox.Option key={c.code} value={c.code} label={c.name}>
      {({ pending }) => (
        <>
          {c.name}
          {pending && <span className="demo-spinner" aria-hidden />}
        </>
      )}
    </Combobox.Option>
  ));
}

export function ComboboxCountry() {
  const [country, setCountry] = useState<string | null>(null);
  const [fail, setFail] = useState(false);
  return (
    <div className="demo-stack">
      <DemoErrorBoundary>
        <Combobox.Root
          valueChangeAction={async (next) => {
            await fakeSave(`country ${next}`, { fail });
            startTransition(() => setCountry(next));
          }}
        >
          <Combobox.Label>Country</Combobox.Label>
          <div className="demo-combobox-field demo-combobox-country">
            <Combobox.Input className="demo-combobox-input" placeholder="Type to search" />
            <Combobox.Clear className="demo-combobox-icon demo-combobox-clear" aria-label="Clear">
              ×
            </Combobox.Clear>
            <Combobox.Trigger className="demo-combobox-icon" aria-label="Show countries">
              ▾
            </Combobox.Trigger>
            {/* As wide as the field with its buttons: combobox.css makes the field the Popup's
                anchor (the Root anchors to the Input alone). */}
            <Combobox.Popup
              className="demo-combobox-popup"
              transition={{
                "fsui-combobox-open": "demo-combobox-pop",
                "fsui-combobox-close": "demo-combobox-pop",
                default: "none",
              }}
            >
              <Combobox.List>
                {({ query }) => (
                  <Suspense
                    fallback={
                      <Combobox.Status className="demo-combobox-status">Searching…</Combobox.Status>
                    }
                  >
                    <CountryOptions query={query} />
                  </Suspense>
                )}
              </Combobox.List>
              <Combobox.Empty className="demo-combobox-status">No country matches.</Combobox.Empty>
            </Combobox.Popup>
          </div>
        </Combobox.Root>
      </DemoErrorBoundary>
      <label>
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> Make
        the save fail
      </label>
      <output className="demo-readout">
        saved: <code>{JSON.stringify(country)}</code>
      </output>
    </div>
  );
}
```

```css title="combobox.css"
/* Combobox: the Input is a text field with role="combobox"; the Popup is a <div popover="auto">
   placed below it by the library's inline anchor positioning; the List inside is the listbox.
   The active option (virtual focus) carries `data-active`, the selected one `data-selected`, the
   one being saved `data-pending`; stale results carry `data-stale` on the Popup and the List. */

.demo-combobox-field {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  padding-inline-end: 2px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-bg);
}
.demo-combobox-field:focus-within {
  outline: 2px solid var(--color-primary);
  outline-offset: 1px;
}
.demo-combobox-input {
  min-inline-size: 14rem;
  padding: 0.4em 0.6em;
  border: 0;
  outline: none;
  background: transparent;
  color: var(--color-text);
  font: inherit;
}
.demo-combobox-input[data-pending] {
  cursor: progress;
}
.demo-combobox-icon {
  padding: 0.2em 0.45em;
  border: 0;
  background: none;
  color: var(--color-text-secondary);
  font: inherit;
  cursor: pointer;
}
/* The Country example's field (input, Clear, Trigger) is named as an anchor and made the Popup's
   default anchor (`position-anchor`), so the listbox is placed under the whole field and is as
   wide as it, rather than the input alone: the library's inline `position-area` and
   `min-width: anchor-size(width)` follow the default anchor. Each example on the page uses its
   own anchor name: with a shared name, every Popup would anchor to the last field. */
.demo-combobox-country {
  anchor-name: --demo-country;
}
.demo-combobox-country .demo-combobox-popup {
  position-anchor: --demo-country;
}
/* Nothing to clear: hide Clear (the input shows its placeholder when empty). */
.demo-combobox-field:has(.demo-combobox-input:placeholder-shown) .demo-combobox-clear {
  visibility: hidden;
}

.demo-combobox-popup {
  /* The popover UA stylesheet sets `inset: 0; margin: auto`: reset both for anchored placement. */
  margin: 0;
  margin-block-start: 4px;
  inset: auto;
  padding: 4px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  background: var(--color-bg);
  color: var(--color-text);
  box-shadow: 0 12px 40px rgb(0 0 0 / 0.25);
  /* CSS enter / exit, used by dismissals (Escape, a click outside). */
  opacity: 0;
  transition:
    opacity 120ms,
    display 120ms allow-discrete,
    overlay 120ms allow-discrete;
}
.demo-combobox-popup:popover-open {
  opacity: 1;
}
@starting-style {
  .demo-combobox-popup:popover-open {
    opacity: 0;
  }
}

/* The List scrolls, not the Popup: a scrolling Popup is a scrollable region with no focusable
   content (axe `scrollable-region-focusable`). */
.demo-combobox-popup [role="listbox"] {
  max-block-size: 16rem;
  overflow: auto;
}
/* Old results while the next ones load. */
.demo-combobox-popup [role="listbox"][data-stale] {
  opacity: 0.55;
  transition: opacity 150ms 100ms;
}
.demo-combobox-popup [role="option"] {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: default;
}
/* Virtual focus; hovering makes an option active too, so this is the hover style as well. */
.demo-combobox-popup [role="option"][data-active] {
  background: var(--color-bg-secondary);
}
/* `/ ""`: no "✓" in the option's accessible name; `aria-selected` exposes the state. */
.demo-combobox-popup [role="option"][data-selected]::after {
  content: "✓" / "";
  color: var(--color-primary);
}
.demo-combobox-popup [role="option"][data-pending] {
  cursor: progress;
}
.demo-combobox-status {
  padding: 6px 10px;
  color: var(--color-text-secondary);
}

/* The library's view transition types: animate the library-driven open and close, nothing else
   (a results change would cross-fade otherwise). */
::view-transition-old(.demo-combobox-pop) {
  animation: 120ms ease-in both demo-combobox-out;
}
::view-transition-new(.demo-combobox-pop) {
  animation: 120ms ease-out both demo-combobox-in;
}
@keyframes demo-combobox-out {
  to {
    opacity: 0;
  }
}
@keyframes demo-combobox-in {
  from {
    opacity: 0;
  }
}

@media (prefers-reduced-motion: reduce) {
  .demo-combobox-popup {
    transition: none;
  }
}

/* Combobox `multiple`: the field box holds the chips and the input; Chips is the list of selected
   values, each Chip a focusable list item (the inline-start arrow at the input's start moves into
   them). A chip whose addition is still being saved carries `data-pending`. The box is named as
   an anchor and made the Popup's default anchor, so the listbox is as wide as it. */
.demo-combobox-tags {
  display: flex;
  flex-wrap: wrap;
  max-inline-size: 30rem;
  padding: 2px 4px;
  anchor-name: --demo-tags;
}
.demo-combobox-tags .demo-combobox-popup {
  position-anchor: --demo-tags;
}
.demo-combobox-tags .demo-combobox-input {
  flex: 1;
  min-inline-size: 8rem;
}
.demo-combobox-chips {
  display: flex;
  flex-wrap: wrap;
}
.demo-combobox-chip {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  margin: 2px;
  padding: 0.1em 0.2em 0.1em 0.55em;
  border-radius: 999px;
  background: var(--color-bg-secondary);
  font-size: 0.9em;
}
.demo-combobox-chip:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 1px;
}
.demo-combobox-chip[data-pending] {
  opacity: 0.6;
  cursor: progress;
}
.demo-combobox-chip-remove {
  padding: 0 0.35em;
  border: 0;
  border-radius: 999px;
  background: none;
  color: var(--color-text-secondary);
  font: inherit;
  cursor: pointer;
}
.demo-combobox-chip-remove:hover {
  color: var(--color-text);
}
```

## How it works

### Typing is urgent; everything it causes is not

React requires a controlled text input to update urgently, in the same event as the keystroke: by the time the library hears of it, the text is already in the DOM. So the text is **urgent state**, a [fact](../concepts/action-props.md#fact) rather than a request. It keeps the usual pair, `inputValue` / `defaultInputValue`, but its callback is a handler, not an action: `onInputValueChange` (an [`on*` handler](../concepts/action-props.md#on-handler)) is called synchronously, outside any transition, and never awaited. A controlled parent simply sets its state in the body:

```tsx
const [text, setText] = useState("");
<Combobox.Root inputValue={text} onInputValueChange={(next) => setText(next)}>
```

Everything downstream of the text is a transition again:

- **The results** render from `query`, a deferred copy of the text (`useDeferredValue`). A slow search never blocks a keystroke; the previous results stay on screen (no fallback flash) with `data-stale` and `aria-busy="true"` until the new ones are ready; and only the latest query is ever rendered, so a slow response for "ja" cannot overwrite the results for "jap". While the input shows the selection's own label and the user has not edited it, `query` is `""` ([below](#query)).
- **Opening** is a request (`openChangeAction`): a transition when the Root is controlled or has an `openChangeAction`; otherwise an urgent write, with the listbox shown in a deferred render ([no action prop](../concepts/action-props.md#no-action)). A dismissal (Escape, a click outside, focus leaving) is a fact, reported to `onOpenChange`.
- **Choosing** an option asks the listbox to close in the same event; with no `openChangeAction` it closes at once. The value is a transition (`valueChangeAction`) with an optimistic selection, exactly as every other value in the library, pending on the Input.

> **Do not fetch in onInputValueChange**
>
> `onInputValueChange={async (q) => setResults(await search(q))}` brings back every problem the deferred query solves: responses land in completion order, nothing marks the results stale, and the urgent handler is not awaited anyway. Read a query-keyed cache with `use()` inside the List instead. (Returning a promise is allowed, for work the UI does not wait for such as logging: like every `on*` handler, its rejection goes to `reportError`.)

While any async action is pending in the app (this combobox's own slow save included), React holds every transition. Typing is unaffected (urgent), and so are the results: a deferred render is not held by a pending action (verified in Chromium and Firefox). Opening the listbox is not held either while the Root is uncontrolled with no `openChangeAction`: in a test app with a 1.5 s save pending, the listbox showed within 50 ms of the keystroke. A controlled `open`, or an `openChangeAction`, makes the open a transition that waits for the save: the input shows `data-open` and `data-pending` meanwhile, and its `aria-expanded` turns `"true"` when the listbox is shown. An accepted option shows its text in the input at once and closes the listbox (with no `openChangeAction`; [below](#accepting)); with no `valueChangeAction` on an uncontrolled Root its value is committed at once too, and nothing is pending. With a `valueChangeAction` (or a controlled `value`) the value waits for the save, with `data-pending` on the Input.

### <a id="accepting"></a>Accepting an option

Enter on the active option, or a click: the input text becomes the option's label at once, the listbox is asked to close in the same event, and `valueChangeAction` runs in the Root's transition. With `open` uncontrolled and no `openChangeAction` (the usual Combobox) it closes at once. Until it has settled the Input carries `data-pending`; if the listbox is opened again meanwhile, the picked option shows `data-selected` and `data-pending`. A rejection (a throw, or `details.reject()`) rolls the text and the selection back; the listbox stays closed, and a throw reaches the nearest Error Boundary. Re-choosing the selected option dispatches nothing and closes. Typing after a pick opens the listbox again, also while the save runs; nothing of the value's closes it afterwards.

```tsx
// Autosave on pick: the listbox closes with the click, the input shows "Grace Hopper"
// and data-pending while the save runs, and goes back to the previous author if it fails.
<Combobox.Root
  defaultValue={article.authorId}
  defaultInputValue={article.authorName}
  valueChangeAction={async (id, details) => {
    try { await saveAuthor(article.id, id); }
    catch { toast({ title: "Could not change the author" }); details.reject(); }
  }}
>
```

```css
.author-input[data-pending] { background-image: var(--spinner); }
```

Why the listbox does not wait for the save, as a menu waits for an item's action: the Input is where the value lives, outside the popup, and it already shows the new text and the pending state. A menu item's action has no such place, so a menu stays open.

**With an `openChangeAction`, even a synchronous one** (a load-on-open handler, a controlled `open` with `openChangeAction={setOpen}`), the close is a request: it is a transition, and it waits for the save, as every transition does while an action is pending. The listbox then stays open, with the picked option pending, until the save has settled. That is also the way to keep it open on purpose: control `open` with an `openChangeAction`, which is asked for `false` at the pick, and adopt it when you want. A controlled `open` with `onOpenChange` alone closes at once (the close is a fact, [nothing waits](../concepts/action-props.md#urgent-open)). Load the options in the List under `<Suspense>` ([How it works](#how-it-works)), not in an `openChangeAction`: a load-on-open action brings this wait back to every pick.

A controlled "update on success" parent (`startTransition(() => setValue(next))` after its `await`) works as everywhere. A parent that refuses a value gets the text and the selection reverted, with the listbox closed, as after a rejection.

### <a id="query"></a>The selection's label is not a search

After a pick the input holds "Japan" because Japan is selected, not because the user is looking for it. So while the text is the selection's label and the user has not edited it, `query` is `""`: the Trigger, ArrowDown and `openOnClick` all open the full list, and a filter needs no special case. The label counts when the library put it there (a pick, a rollback, the revert when focus leaves or on Escape, the committed free text of `allowCustomValue`) or you gave it with a value (`defaultInputValue` with `defaultValue`, a form reset, a controlled parent changing `value` and `inputValue` together, that is in one render; a `value` set in a transition and a text set urgently land in two renders, and the text alone ends the rule). Any edit ends it, also retyping the same text; so does a controlled parent changing `inputValue` alone. That includes an `onInputValueChange` that transforms the text it is given (`setText(next.trim())`, a case change): after a pick the text is then not the label the library wrote, and `query` is the text. The raw text is `state.inputValue`. With `multiple` the text is always the search.

```tsx
<Combobox.List>
  {({ query }) => countries
    .filter((c) => c.name.toLowerCase().includes(query.toLowerCase()))
    .map((c) => <Combobox.Option key={c.code} value={c.code}>{c.name}</Combobox.Option>)}
</Combobox.List>
```

### Free text

```tsx title="ComboboxDrink.tsx"
"use client";
import { useState } from "react";
import { Combobox } from "@funstack/ui/combobox";

const SUGGESTIONS = ["Coffee", "Tea", "Matcha", "Hot chocolate", "Lemonade"];

// Free text: `allowCustomValue` makes the typed text the value (Enter with no active
// suggestion, or leaving the field). The text is controlled with a plain setState in the urgent
// `onInputValueChange`. `name` puts the value in a hidden input for the form.
export function ComboboxDrink() {
  const [text, setText] = useState("");
  const [submitted, setSubmitted] = useState<string | null>(null);
  return (
    <form
      className="demo-stack"
      onSubmit={(event) => {
        event.preventDefault();
        setSubmitted(String(new FormData(event.currentTarget).get("drink")));
      }}
    >
      <Combobox.Root
        name="drink"
        allowCustomValue
        inputValue={text}
        onInputValueChange={(next) => setText(next)}
      >
        <Combobox.Label>Favourite drink</Combobox.Label>
        <div className="demo-combobox-field">
          <Combobox.Input className="demo-combobox-input" placeholder="Anything" required />
          <Combobox.Popup className="demo-combobox-popup">
            <Combobox.List>
              {({ query }) =>
                SUGGESTIONS.filter((s) => s.toLowerCase().includes(query.toLowerCase())).map(
                  (s) => (
                    <Combobox.Option key={s} value={s}>
                      {s}
                    </Combobox.Option>
                  ),
                )
              }
            </Combobox.List>
            <Combobox.Empty className="demo-combobox-status">
              Press Enter to use your own.
            </Combobox.Empty>
          </Combobox.Popup>
        </div>
      </Combobox.Root>
      <div className="demo-row">
        <button type="submit" className="demo-button demo-primary">
          Submit
        </button>
        <output className="demo-readout">
          text: <code>{JSON.stringify(text)}</code>, submitted:{" "}
          <code>{JSON.stringify(submitted)}</code>
        </output>
      </div>
    </form>
  );
}
```

`combobox.css`: the same file as above.

With `allowCustomValue` the typed text is a value: Enter with no active option, or focus leaving, dispatches it with `details.custom: true` (an emptied text dispatches `null`). Enter on a closed listbox is not prevented, so a form still submits, and the hidden input already holds the new text. Without `allowCustomValue`, text that is not the selection's label reverts when focus leaves (`reason: "dismiss"`), so the field never shows a value it does not have.

### <a id="multiple"></a>Multiple selection

```tsx title="ComboboxTags.tsx"
"use client";
import { startTransition, useState } from "react";
import { Combobox } from "@funstack/ui/combobox";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

const LANGUAGES = [
  "C",
  "C++",
  "Elixir",
  "Go",
  "Haskell",
  "Java",
  "JavaScript",
  "Kotlin",
  "OCaml",
  "Python",
  "Ruby",
  "Rust",
  "Swift",
  "TypeScript",
];

export function ComboboxTags() {
  const [saved, setSaved] = useState<string[]>(["TypeScript"]);
  const [fail, setFail] = useState(false);
  return (
    <div className="demo-stack">
      <DemoErrorBoundary>
        <Combobox.Root
          multiple
          name="languages"
          defaultValue={["TypeScript"]}
          allowCustomValue
          // With free text, Enter on no active option adds the typed text as a tag: make the first
          // match active, so "ja" then Enter picks Java rather than adding "ja".
          autoHighlight
          valueChangeAction={async (_next, { added, removed }) => {
            // Persist the diff, not `next`: an earlier change may still fail.
            await fakeSave(`+${added.join(",")} -${removed.join(",")}`, { fail });
            startTransition(() =>
              setSaved((prev) => [
                ...prev.filter((v) => !removed.includes(v)),
                ...added.filter((v) => !prev.includes(v)),
              ]),
            );
          }}
        >
          <Combobox.Label>Languages</Combobox.Label>
          <div className="demo-combobox-field demo-combobox-tags">
            <Combobox.Chips className="demo-combobox-chips">
              {({ value }) =>
                value.map((language) => (
                  <Combobox.Chip key={language} value={language} className="demo-combobox-chip">
                    {({ label }) => (
                      <>
                        {label ?? language}
                        <Combobox.ChipRemove
                          className="demo-combobox-chip-remove"
                          aria-label={`Remove ${label ?? language}`}
                        >
                          <span aria-hidden>×</span>
                        </Combobox.ChipRemove>
                      </>
                    )}
                  </Combobox.Chip>
                ))
              }
            </Combobox.Chips>
            <Combobox.Input className="demo-combobox-input" placeholder="Add a language" />
            {/* As wide as the field box: combobox.css makes the box the Popup's anchor (the Root
                anchors to the Input). */}
            <Combobox.Popup className="demo-combobox-popup">
              <Combobox.List>
                {({ query }) =>
                  LANGUAGES.filter((l) => l.toLowerCase().includes(query.toLowerCase())).map(
                    (l) => (
                      <Combobox.Option key={l} value={l}>
                        {({ pending }) => (
                          <>
                            {l}
                            {pending && <span className="demo-spinner" aria-hidden />}
                          </>
                        )}
                      </Combobox.Option>
                    ),
                  )
                }
              </Combobox.List>
              <Combobox.Empty className="demo-combobox-status">
                Press Enter to add it.
              </Combobox.Empty>
            </Combobox.Popup>
          </div>
        </Combobox.Root>
      </DemoErrorBoundary>
      <label>
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> Make
        the save fail
      </label>
      <output className="demo-readout">
        saved: <code>{JSON.stringify(saved)}</code>
      </output>
    </div>
  );
}
```

`combobox.css`: the same file as above.

`multiple` on the Root turns the selection into a list of values (`string[]`, in pick order) shown as chips. The text is then only a search:

- **A pick toggles** the option (a selected option is removed), clears the text and leaves the listbox open for the next pick. The listbox is `aria-multiselectable` and every option keeps its `aria-selected`. A rejection rolls back that one change (the chip and `data-selected`), never the text.
- **The value follows the set rules** of CheckboxGroup: each dispatch is one change, with `details.added` and `details.removed`; picks made while an earlier save runs stack, and only the changes whose action resolved are kept. Persist the diff, not `next`, which may contain a change that fails later.
- **`Combobox.Chips`** is a list of the optimistic values (a removed chip disappears at once and comes back if its save fails); you map them to `Combobox.Chip`s. A chip's `label` state is the text of the option the library last saw for its value, so an async search needs no map of its own. It is the list of chips only, not the field box: put the Input next to it in your own element.
- **Keys:** Backspace in the empty input removes the last chip; the inline-start arrow (Left, Right in RTL) at the caret's start moves focus into the chips, where the arrows, Home and End move, Backspace or Delete remove, Escape goes back and a letter types into the input. The combobox keeps one Tab stop. Chips removed outside the listbox are announced (`"Japan removed"`, `announceRemoved` to localise).
- **Forms:** one hidden input per value (`formData.getAll(name)`), nothing for an empty selection. `required` on the Input means "at least one": native `required` is rendered only while nothing is selected, and `aria-required` always. Unmatched text is cleared when focus leaves and by Enter in a closed listbox, so it never satisfies `required`. With `allowCustomValue`, Enter (prevented, the form does not submit) and focus leaving add the text as a value instead.
- **A tag picker with `allowCustomValue` needs `autoHighlight`.** Typing makes no option active, and Enter with no active option adds the typed text. So without `autoHighlight`, typing "ja" then Enter adds a "ja" tag instead of picking Java, and users create typo tags. The example above passes it: Enter picks the first match, and text that matches nothing is still added. To add text that does match an option as it is, press End (or Escape, which closes the listbox) before Enter: End clears the active option and nothing highlights it again until the next edit.

```tsx
<Combobox.Root multiple name="countries" defaultValue={["jp"]} valueChangeAction={saveCountries}>
  <Combobox.Label>Countries</Combobox.Label>
  <div className="field">                                {/* your box around chips and input */}
    <Combobox.Chips>                                     {/* div[role=list] */}
      {({ value }) => value.map((code) => (
        <Combobox.Chip key={code} value={code}>          {/* div[role=listitem][tabindex=-1] */}
          {({ label }) => (
            <>
              {label ?? code}
              <Combobox.ChipRemove aria-label={`Remove ${label ?? code}`} />  {/* button */}
            </>
          )}
        </Combobox.Chip>
      ))}
    </Combobox.Chips>
    <Combobox.Input placeholder="Add a country" required />
  </div>
  <Combobox.Popup>…</Combobox.Popup>
</Combobox.Root>
```

### <a id="locale-switch"></a>Switching the language

The library never derives the text from `value`: it keeps the last text shown for each value (an option's label, a pick, or the text you passed), and without `allowCustomValue` focus leaving reverts edited text to it. With a controlled `inputValue`, rewriting the text on the switch is enough. A text that changes when the library did not just write it (no keystroke, pick, revert, Clear or form reset since the previous render) is read as the selection's new name, so the next blur keeps it:

```tsx
const [text, setText] = useState(cityName(city, locale));
const [shownLocale, setShownLocale] = useState(locale);
if (shownLocale !== locale) {
  setShownLocale(locale);
  setText(city === null ? "" : cityName(city, locale));
}

<Combobox.Root
  value={city}
  valueChangeAction={saveCity}
  inputValue={text}
  onInputValueChange={setText}
>
```

For the same reason, transform typed text in `onInputValueChange` (`(t) => setText(t.toUpperCase())`), not in an effect: a change made in a later render is taken as the selection's name. An empty text is never taken as a name. Set `value` and `inputValue` in the same update (both urgent, or both in one transition): a text that commits before its value, as with `startTransition(() => setValue("cai")); setText("Cairo")`, renames the old selection. The same holds for any text you write from outside: filling the input with "par" while Dubai is selected makes "par" Dubai's name, and the next blur keeps it. Set `value` to `null` with it when the text is a search.

Remount the Root with a `key` on the locale where the old name is not yours to rewrite: `defaultInputValue` (read once, at mount), the default content of the chips with `multiple` (their `label` is the last text an option showed, the old language until the listbox shows that option again), and the default content of `MultiSelect.Value` for the same reason. Chips and `MultiSelect.Value` that render your own names need no `key`.

```tsx
<Combobox.Root
  key={locale}
  defaultValue={trip.city}
  defaultInputValue={cityName(trip.city, locale)}
  valueChangeAction={saveCity}
>
```

A remount also resets the uncontrolled value to `defaultValue`, so pass the saved selection there. Options that show the new names refresh the stored text as they mount (or when an option's `label` changes): the old text left in the input is then not taken as typed, and focus leaving replaces it with the new label, also with `allowCustomValue`.

## Props

### `Combobox.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `multiple` | `boolean` | `false` | `true`: the selection is a list of values shown as chips ([Multiple selection](#multiple)); `value`, `defaultValue`, `valueChangeAction`, `announce` and `children` take the multiple types below. Fixed at mount (development warns on a change). |
| `value` | `V \| null; readonly V[] with multiple` | – | Controlled selection. `null`: nothing selected. `undefined` means uncontrolled. With `multiple`: `V[]`, `[]` for nothing; the order is the chip order, duplicates are ignored. `V` is the item value type: a declared union you pass is kept, a literal is `string` ([Typed values](../concepts/action-props.md#typed-values)). With `allowCustomValue`, `V` must be `string`. |
| `defaultValue` | `V \| null; readonly V[] with multiple` | `null` | Initial selection when uncontrolled; what a form reset returns to. With `multiple`: `V[]`, default `[]`. |
| `valueChangeAction` | `ChangeAction<V \| null, ComboboxValueChangeDetails>; with multiple ChangeAction<V[], ComboboxMultipleValueChangeDetails<V>>` | – | Runs in the Root's transition when the user accepts an option, commits free text, presses Clear, or the form resets. Awaited, with `data-pending` on the Input; the listbox is asked to close in the pick's own event, and with no `openChangeAction` it closes at once; with one (even a synchronous one) the close is a transition and waits for this action ([Accepting an option](#accepting)). A rejection, or a controlled parent that does not adopt the value, rolls the text and the selection back. Without it (uncontrolled), the value is written at once and nothing is pending. May be a Server Function. A `setState` after your own `await` needs `startTransition`. With `multiple`: `ChangeAction<V[], ComboboxMultipleValueChangeDetails<V>>`, called for every change (a pick, a removed chip, Clear, free text, a reset); the listbox does not close; a rejection undoes that change only. |
| `inputValue` | `string` | – | Controlled text. `undefined` means uncontrolled. Single selection: a change you make on your own (not in answer to `onInputValueChange`, and not to `""`) renames the selection, so focus leaving keeps it. Set `value` in the same update as the text: a text committed before its value renames the old selection ([Switching the language](#locale-switch)). |
| `defaultInputValue` | `string` | `""` | Initial text when uncontrolled, and the visible input's form-reset target. Single selection: pass the selected option's label together with `defaultValue`. With `multiple` the text is only a search (usually left empty). |
| `onInputValueChange` | `UrgentChangeHandler<string, ComboboxInputValueChangeDetails>` | – | A [handler](../concepts/action-props.md#on-handler), not an action: called synchronously, outside any transition, on every change of the text (typing, and the library's own writes). Not awaited, never pending. Set your state in the body. May return a promise; a rejection or a throw goes to `reportError` ([the rule of every on\* handler](../concepts/action-props.md#handlers)). |
| `open` | `boolean` | – | Controlled open state. `undefined` means uncontrolled. Pass `onOpenChange` too (development warns). |
| `defaultOpen` | `boolean` | `false` | Initial open state; opens after hydration. |
| `openChangeAction` | `ChangeAction<boolean, ComboboxOpenChangeDetails>` | – | Requests only: awaited for opens and for the closes a part asks for (an accepted option, the Trigger, Alt+ArrowUp; with `multiple`, a chip taking focus while an open is still on its way cancels it). Never called for a dismissal (`onOpenChange`). Runs in the Root's transition; may be a Server Function. `details.reason`: `"activate"` (typing, ArrowDown / ArrowUp / Alt+ArrowDown, the Trigger, a click on the input with `openOnClick`, an accepted option, Alt+ArrowUp, the cancel by a focused chip, a foreign `showPopover()`) or `"platform"` (found open on mount, which only script can cause; `event` is `undefined`). |
| `onOpenChange` | `UrgentChangeHandler<boolean, ComboboxOpenChangeDetails>` | – | Facts only: the listbox was closed without the library closing it on request. Always `false`. `details.reason`: `"dismiss"` (Escape, focus leaving the input, a click outside, a Clear click while open, another popover opening, script) or `"activate"` (a [foreign invoker](../concepts/browser-owned-state.md#foreign-invoker), whose press does not move focus out of the input, so the text is left as typed; a Trigger rendered as another element, pressed while open). Called synchronously in the browser's `toggle` event, outside any transition, and not awaited: nothing is pending and no view transition runs. In controlled mode set state directly here (`onOpenChange={setOpen}`), never in `startTransition` or after an `await`; a parent that keeps `open` gets the listbox shown again at once, with focus left where the dismissal put it. May return a promise (a Server Function); a rejection or a throw goes to `reportError`. On a controlled Root with no `openChangeAction`, also a part's close (a pick, the Trigger while open): the library performs it at once and calls this with `"activate"` ([nothing waits](../concepts/action-props.md#urgent-open)). |
| `allowCustomValue` | `boolean` | `false` | Free text is a value (Enter with no active option, focus leaving), dispatched with `details.custom: true`. Otherwise unmatched text reverts when focus leaves. With `multiple`: Enter (prevented, open or closed) and focus leaving add the text as a value (`added: [text]`) and clear it; without it unmatched text is cleared. |
| `autoHighlight` | `boolean` | `false` | Make the first enabled option active when the results for an open or an edit settle (APG automatic selection): typing then Enter picks the first match. Stale results are never highlighted, so an Enter before they settle commits the typed text (`allowCustomValue`) or does nothing. |
| `openOnClick` | `boolean` | `false` | Open on a click in the input (never on focus alone). |
| `loop` | `boolean` | `false` | ArrowDown / ArrowUp wrap from the last option to the first and back. |
| `announce` | `(count: number, state: ComboboxRootState) => string \| null; ComboboxMultipleRootState with multiple` | `"No results" / "1 result" / "N results"` | The message `ariaNotify()` announces on the List when the results settle. Override for localisation; return `null` to announce nothing. Ignored where `ariaNotify` is missing. |
| `announceRemoved` | `(labels: readonly string[], state: ComboboxMultipleRootState) => string \| null` | `"Japan removed" (the labels joined with ", ")` | `multiple` only. The message `ariaNotify()` announces on the Input when chips are removed outside the listbox (Backspace, Delete, `ChipRemove`, Clear). A label is the Chip's `label`, else the option text the library saw, else the chip's text. Return `null` to announce nothing. |
| `name` | `string` | – | Renders `<input type="hidden" name>` holding the optimistic value (`""` for `null`), the Root's only element. With `multiple`: one hidden input per value, in value order; none named while the selection is empty. |
| `form` | `string` | – | The hidden input's `form` attribute. |
| `disabled` | `boolean` | `false` | Disables the Input, Trigger and Clear (and every `ChipRemove`); nothing dispatches for user interaction. A disabled Combobox (this prop or the Field's) is not submitted: the hidden input(s) are `disabled` too. A form reset still reaches it. A click on a disabled control runs no `onClick`, a `render` element's included ([unavailable parts](../concepts/render.md#unavailable)). |
| `readOnly` | `boolean` | `false` | The selection is shown, focusable and submitted, and cannot be changed, or the enclosing `Field.Root`'s: the Input renders native `readonly` (its text stays selectable; no `aria-readonly` next to it), the popup never opens (the arrows, Alt+ArrowDown, a click on the Input and the Trigger request nothing; `aria-expanded` stays `"false"`), the Trigger, Clear and every `ChipRemove` are disabled, and nothing dispatches (`allowCustomValue` commits nothing). With `multiple` the chip keys still move focus and Backspace / Delete remove nothing. The hidden inputs are not disabled. When it turns on, an open listbox gets a close request (a controlled `open` parent decides) and edited text goes back to the text of the committed value (with `multiple` the search is cleared), reported to `onInputValueChange` with `"dismiss"`. Escape and Alt+ArrowUp still close a listbox a parent keeps open. |
| `children` | `ReactNode \| ((state: ComboboxRootState) => ReactNode); ComboboxMultipleRootState with multiple` | – | The parts, or a function of the Root's state (`ComboboxMultipleRootState` with `multiple`). |

- **State**: `ComboboxRootState` is `{ value, inputValue, query, stale, activeValue, open, pending, disabled, readOnly }`; `value` and `open` are optimistic; `inputValue` is the raw text; `query` is the deferred search, `""` while the text is the selection's unedited label ([below](#query)); `stale`: the results shown are for an older search; `pending` covers the value and the open transitions. `ComboboxMultipleRootState` is the same with `value: readonly string[]` (pick order).
- **Owned**: none: the Root renders no element (no `ref`, `className` or `style`), only the hidden input(s) when `name` is given.

The props type is `ComboboxRootProps = ComboboxRootSingleProps | ComboboxRootMultipleProps`, discriminated on `multiple`; the props both share are `ComboboxRootBaseProps`. `Partial<ComboboxRootProps>` is not assignable to either member, so a wrapper that spreads one into `Combobox.Root` types it as `Partial<ComboboxRootSingleProps>` (or the multiple one) instead.

`ComboboxValueChangeDetails`: `{ reason, custom, valid, event }`. `valid` (see [details.valid](field.md#details-valid)): the Input's `required` for the next selection (a committed value always has text, a cleared one has none) and the Field's `validate`; other constraints on the Input (`pattern`, `minLength`) describe the typed text and are not part of it, and neither is an Option whose label is empty text. `reason` is `"activate"` (an accepted option: the `keydown` or `click`; free text: the `keydown` or `focusout`; Clear: the `click`) or `"platform"` (a form reset: the `reset` event). `ComboboxInputValueChangeDetails`: `{ reason, event }`, with `"activate"` for typing (the `input` event), an accepted label and Clear, `"dismiss"` for a revert (focus leaving with unmatched text, a rolled-back selection, Escape on edited text with the listbox closed: the `keydown`), `"platform"` for a reset or text found at mount (no event). `ComboboxOpenChangeDetails`: `{ reason, event }`; the reasons are listed with `openChangeAction` and `onOpenChange` above.

`ComboboxMultipleValueChangeDetails` (with `multiple`): `{ reason, added, removed, custom, valid, event }` (`valid`: `required` means at least one value). `added` lists the values this dispatch added, in the order they join; `removed` the values it removed, in value order; `custom` is `true` for free text. `reason` is `"activate"` (a toggled option: the `keydown` or `click`; a removed chip: the `keydown` of Backspace or Delete, the `click` of `ChipRemove`; Clear; free text: the `keydown` or `focusout`) or `"platform"` (a form reset, dispatched whole with the diff). With `multiple` the library writes the text on typing, a pick (`""`, `"activate"`), Clear, focus leaving and Escape with the listbox closed (`""`, `"dismiss"`), a reset and at mount.

### `Combobox.Label`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: ComboboxLabelState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxLabelState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxLabelState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: ComboboxLabelState) => ReactNode)` | – | Replace the default \<label> (element form) or take over rendering (function form). |

- **State**: `ComboboxLabelState` is `{ disabled, readOnly, pending }`, the Root's; the Label renders them as `data-disabled`, `data-readonly` and `data-pending`.
- **Owned**: `id`, `htmlFor`.

A `<label for>` of the Input; its id also names the List (`aria-labelledby`), only while a Label is mounted. Inside a `Field.Root`, `Field.Label` takes that role instead.

### `Combobox.Input`

One per Root: the Input is the listbox's anchor, so a second `Combobox.Input` in the same Root is not supported (development warns). Use a Root per input.

| Prop | Type | Default | Description |
| - | - | - | - |
| `required` | `boolean` | – | Native: an empty text is `valueMissing`, with the browser's message. With `multiple` it means at least one value: native `required` only while nothing is selected (optimistic), `aria-required` always. |
| `className` | `string \| ((state: ComboboxInputState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxInputState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: ComboboxInputState) => ReactNode)` | – | Replace the default \<input> (element form) or take over rendering (function form). |

- **State**: `ComboboxInputState` is `{ value, values, inputValue, open, pending, stale, empty, disabled, readOnly, invalid, required }`. `values` is the optimistic selection as a list (`[value]` or `[]` in single mode); with `multiple`, `value` is always `null`. `empty`: nothing is selected (`data-empty`). `invalid` is `true` while the enclosing `Field.Root` shows an error (`data-invalid`), `false` outside a Field; `required` is the Input's own or the Field's.
- **Owned**: `id`, `type` (`"text"`, or `"search"` when a `render` element says so), `role`, `value`, `autoComplete` (`"off"`), `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged; the List id only while the List is rendered), `aria-activedescendant`, `disabled`, `readOnly` (from the Root), `onChange`, `onKeyDown`, `onFocus`, `onBlur`, `onClick`, `onPointerDown`, `data-open`, `data-pending`, `data-empty`, `data-stale`, `data-disabled`, `data-readonly`. Inside a `Field.Root` also `required`, `aria-invalid`, `aria-describedby` (token-merged) and `data-invalid`. With `multiple` also `required` and `aria-required`.

`placeholder`, `name` (a second field with the raw text), `aria-describedby`, `onFocusCapture` (to react to focus) and other input props pass through. During a primary mouse or pen press while the listbox is open, the Input's `onPointerUp`, `onMouseUp` and `onDoubleClick` go to the Popup instead (the press is captured to it), and the Input gets pointer and mouse leave (then enter) events. A `render` element must stay an `<input>` of type text or search. `readOnly` is not accepted (a type error): it is the Root's, which also keeps the popup shut and disables the Trigger, Clear and `ChipRemove`.

### `Combobox.Trigger`, `Combobox.Clear`

| Prop | Type | Default | Description |
| - | - | - | - |
| `disabled` | `boolean` | `false` | Native `disabled`; the Root's `disabled` applies too. With a link or component `render`, `aria-disabled="true"` instead. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: ComboboxTriggerState \| ComboboxClearState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxTriggerState \| ComboboxClearState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxTriggerState \| ComboboxClearState) => ReactNode)` | – | Content, usually an icon; give the button an `aria-label` (development warns without a name). |
| `render` | `ReactElement \| ((props, state: ComboboxTriggerState \| ComboboxClearState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `ComboboxTriggerState` is `{ open, pending, disabled, readOnly }`; `ComboboxClearState` is `{ value, values, inputValue, disabled, readOnly }` (`values` as on the Input). `disabled` includes the Root's `readOnly`: neither button has a job while the value cannot change.
- **Owned**: `type` (on a `<button>`), `tabIndex` (`-1`: the input is the one Tab stop), `disabled`, `aria-disabled` (link or component `render`), `onClick`, `onPointerDown`, `onMouseDown`, `data-disabled`, `data-readonly`; the Trigger also `aria-expanded` (only when it is no invoker: a non-button `render`, or while `aria-disabled`), `aria-controls` (token-merged; the List id only while the List is rendered), `popovertarget` (written as an attribute after hydration, only on a `<button>`, while enabled or natively disabled; not while `aria-disabled`), `data-open`, `data-pending`. Owned and never written: `popoverTarget`, `popoverTargetAction`, `commandfor`, `command` (on the Trigger).

Both keep focus in the input when pressed and focus it when clicked. The Trigger toggles the listbox; on a `<button>` Trigger a click while it is open keeps it shown until `openChangeAction(false)` settles (a controlled parent that keeps `open` sees no flicker). A Trigger rendered as another element is light-dismissed before its click and warns in development ([Triggers of a popup](../concepts/browser-owned-state.md#popup-triggers)). Clear empties the text and dispatches `null` unless nothing is selected (with `multiple`: one change removing every value, announced); it is always rendered, so hide it with CSS (`:has(input:placeholder-shown)`) or its state. A click on Clear while the listbox is open closes it (light dismiss: the button is outside the popup).

### `Combobox.Popup`

| Prop | Type | Default | Description |
| - | - | - | - |
| `keepMounted` | `boolean` | `false` | `false`: the children render only while open. `true`: they stay mounted in a hidden `<Activity>`; an action inside that rejects while it is hidden goes to `reportError`, not to an Error Boundary. |
| `transition` | `ViewTransitionClass` | – | The class of the `<ViewTransition>` around the popup element; without it no boundary is rendered. A string animates this combobox's own opens and closes that the library dispatched and its own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)), in all engines; nothing else (not another combobox, not an unrelated transition, not content that changes inside). Results that change inside the open popup, value dispatches and keystrokes start no view transition with a string. A map with a class on `default` would cross-fade every results render, and typed characters can be lost then; never key a map on `fsui-combobox`, which every value dispatch carries. A controlled `open` you change in your own transition needs a map keyed on `fsui-combobox-open` / `fsui-combobox-close` plus `addTransitionType` ([recipe](../concepts/transitions.md#controlled)). A type map is React's: it names every combobox that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). Dismissals animate with CSS only. Keep it static. A closed Popup renders its element one commit after its mount, before paint, so placing it starts no view transition and its `ref` is still empty in the mount effects of the component that renders it ([two-step mount](../concepts/transitions.md#closed-popups)). |
| `className` | `string \| ((state: ComboboxPopupState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxPopupState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxPopupState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: ComboboxPopupState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ComboboxPopupState` is `{ open, stale, query }`; `open` is committed.
- **Owned**: `id`, `popover` (`"auto"`), `onPointerDown` and `onMouseDown` (a press anywhere in it keeps focus in the input), `data-stale`; no role.

Inline style `position-area: self-block-end span-self-inline-end; position-try-fallbacks: flip-block; min-width: anchor-size(width)` places it below the input (above when it does not fit), at least as wide; your `style` wins per property. A `render` element must stay a `<div>`.

### `Combobox.List`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: ComboboxListState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxListState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxListState) => ReactNode)` | – | Usually a function of `{ query }` returning the Options for it, under your own `<Suspense>` for an async search. |
| `render` | `ReactElement \| ((props, state: ComboboxListState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ComboboxListState` is `{ query, stale, empty }`.
- **Owned**: `id`, `role` (`"listbox"`), `aria-labelledby` (token-merged with yours; only while a `Combobox.Label` is rendered, else the enclosing `Field.Label` while one is mounted), `aria-busy`, `data-stale`, `data-empty`; with `multiple`, `aria-multiselectable` (`"true"`).

Without a Label give the List an `aria-label` (development warns otherwise). `aria-busy="true"` is set while the results are stale or loading (a `Status` fallback inside it); `data-empty` when settled with no options.

### `Combobox.Option`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required and unique within the Combobox; the option's id is derived from it, so it keeps its id across result sets. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `label` | `string` | – | The text written into the input when the option is accepted. Default: the option's trimmed text at that moment. Also the selection's stored name: a mounted option given a new `label` refreshes it (pass `label` when the text can change under a mounted option). Not used for matching. |
| `disabled` | `boolean` | `false` | `aria-disabled`: shown, skipped by the arrow keys, never accepted. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: ComboboxOptionState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxOptionState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxOptionState) => ReactNode)` | – | Content, or a function of the option's state; must not suspend. |
| `render` | `ReactElement \| ((props, state: ComboboxOptionState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ComboboxOptionState` is `{ value, selected, active, pending, disabled }`; `selected` is optimistic, `active` is virtual focus, `pending` is true on the option being saved (with `multiple`: being added or removed).
- **Owned**: `id` (derived from `value`), `role`, `aria-selected`, `aria-disabled`, `onClick`, `onPointerDown`, `onMouseDown`, `onPointerMove`, `data-selected`, `data-active`, `data-pending`, `data-disabled`.

Never focused, no `tabindex`; hovering makes it active.

### `Combobox.Group`, `Combobox.GroupLabel`, `Combobox.Empty`, `Combobox.Status`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: {} (Empty: ComboboxListState)) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: {} (Empty: ComboboxListState)) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: {} (Empty: ComboboxListState)) => ReactNode)` | – | Content. Empty renders only when the List has no options, the results are not stale and none are loading. |
| `render` | `ReactElement \| ((props, state) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: none (Empty: `ComboboxListState`).
- **Owned**: Group: `role` (`"group"`), `aria-labelledby` (while a GroupLabel is mounted); GroupLabel: `id`; Status: `role` (`"none"` inside the List, `"status"` in the Popup).

`Group` is named by the `GroupLabel` inside it. `Status` inside the List (as a Suspense fallback) marks the results as loading (the List is `aria-busy`); in the Popup it is a plain hint. `Empty` is a plain `<div>` that renders nothing unless the results are settled and empty, so "No results" never flashes during a search.

### `Combobox.Chips` (with `multiple`)

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: ComboboxChipsState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxChipsState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxChipsState) => ReactNode)` | – | Usually a function of `{ value }` rendering one `Combobox.Chip` per value, keyed by the value; must not suspend. |
| `render` | `ReactElement \| ((props, state: ComboboxChipsState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ComboboxChipsState` is `{ value, pending, empty, disabled, readOnly }`; `value` is the optimistic selection in pick order, `pending` the value action in flight, `empty` no chips (`data-empty`).
- **Owned**: `role` (`"list"`, absent while empty), `aria-labelledby` (the Label, token-merged; absent while empty), `onKeyDown` (the chip keys), `onPointerDown`, `onMouseDown`, `onClick` (a press keeps focus where it is; a click focuses the Input), `onFocus`, `onBlur` (a chip is inside the combobox: focus on it closes the listbox and keeps the text), `data-empty`, `data-pending`, `data-disabled`, `data-readonly`.

The list of chips, not the field box: render the Input next to it, in your own element. Under a Root without `multiple` it warns in development and renders empty.

### `Combobox.Chip`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required: a value of the selection (development warns otherwise). `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `label` | `string` | – | The chip's text for the removal announcement. Default: the state's `label`, else the chip's trimmed text. |
| `className` | `string \| ((state: ComboboxChipState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxChipState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxChipState) => ReactNode)` | – | Content, or a function of the chip's state; default `label ?? value`. Must not suspend. |
| `render` | `ReactElement \| ((props, state: ComboboxChipState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ComboboxChipState` is `{ value, label, pending, disabled, readOnly }`. `label` is the text of the option with this value as the library last saw it (written at the pick), `undefined` if no option for it was ever rendered (a preselected value before the listbox first opens). `pending`: its addition is not committed yet.
- **Owned**: `role` (`"listitem"`), `tabIndex` (`-1`), `data-pending`, `data-disabled`, `data-readonly`.

Focused by keys only, never a Tab stop. On a focused chip: the previous / next arrow (in the inline direction) moves, the next arrow past the last chip returns to the Input, Home / End go to the first / last chip, Backspace and Delete remove it (focus moves first to the next chip, else the previous, else the Input), Escape returns to the Input, a printable key types into the Input; Enter and Space do nothing. `aria-description` passes through for a hint such as "Press Backspace to remove".

### `Combobox.ChipRemove`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: ComboboxChipRemoveState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ComboboxChipRemoveState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ComboboxChipRemoveState) => ReactNode)` | – | Content, usually an icon in an `aria-hidden` element (never read as part of the chip's text in the removal announcement, nor is any `aria-hidden` content); give the button an `aria-label` (development warns without a name). |
| `render` | `ReactElement \| ((props, state: ComboboxChipRemoveState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `ComboboxChipRemoveState` is `{ value, pending, disabled, readOnly }` (the Chip's value and pending; `disabled` includes the Root's `readOnly`).
- **Owned**: `type` (on a `<button>`), `tabIndex` (`-1`), `disabled` (the Root's `disabled` or `readOnly`), `aria-disabled` (link or component `render`), `onClick`, `onPointerDown`, `onMouseDown`, `data-pending`, `data-disabled`, `data-readonly`.

Inside a `Combobox.Chip` (outside one it throws). A press keeps focus in the Input; the click removes the chip's value, announces it and focuses the Input. A press while the listbox is open closes it (light dismiss), as Clear's does.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-open` | Input, Trigger | Optimistic open state. The Input's `aria-expanded` follows the shown listbox instead; a `<button>` Trigger has no `aria-expanded` (the browser exposes its state). |
| `data-pending` | Input | A selection or an open is in flight (the Root's `pending`). |
| `data-pending` | Trigger | The open (or close) is in flight. |
| `data-pending` | Option | The option the in-flight selection is choosing (with `multiple`: being added or removed). |
| `data-pending` | Chip, ChipRemove | With `multiple`: the chip's addition is not committed yet (a removed chip is gone at once). |
| `data-pending` | Chips | With `multiple`: a value action is in flight. |
| `data-empty` | Input | Nothing is selected (optimistic `null`; with `multiple`, no values). A value is selected: `:not([data-empty])`. |
| `data-selected` | Option | This option is the optimistic selection. |
| `data-active` | Option | `aria-activedescendant` points here (keyboard or hover). |
| `data-stale` | Input, Popup, List | The results shown are for an older text; the List also has `aria-busy`. |
| `data-empty` | List | Settled with no options. |
| `data-empty` | Chips | With `multiple`: nothing is selected. |
| `data-pending` | Label | The Root's `pending`. |
| `data-disabled` | Label, Input, Trigger, Clear, Option, Chips, Chip, ChipRemove | Disabled (the Trigger, Clear and ChipRemove also while read-only). |
| `data-readonly` | Label, Input, Trigger, Clear, Chips, Chip, ChipRemove | The Root's `readOnly` (or the Field's). On the Input `:read-only` matches too. |
| `:popover-open` | Popup | The listbox is shown (browser-owned, no attribute). |

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| A printable character / Backspace / Paste | anywhere | Changes the text (urgent), clears the active option and opens the listbox. |
| ArrowDown / ArrowUp | listbox closed | Opens with the first / last enabled option active. |
| ArrowDown / ArrowUp | listbox open | Next / previous enabled option; stops at the ends (wraps with `loop`). |
| Alt+ArrowDown | listbox closed | Opens with no option active. |
| Alt+ArrowUp | listbox open | Accepts the active option, or closes. |
| Enter | listbox open | Accepts the active option; with none, commits free text (`allowCustomValue`) or does nothing. |
| Enter | listbox closed | Not handled (a form submits); commits changed free text first with `allowCustomValue`. |
| Escape | listbox open | The platform closes the listbox; focus and text stay. |
| Escape | listbox opening (requested, not shown yet) | As if it were shown: the coming open is cancelled (`openChangeAction(false)`, `"activate"`), the text stays, and the key is consumed, so an enclosing Dialog or Popover stays open. |
| Escape | listbox closed, text edited | Reverts the text to the committed value's text (the selection's label, the committed custom value with `allowCustomValue`, `""` with no selection; with `multiple` the search text is cleared and the chips stay), through `onInputValueChange` with `reason: "dismiss"`; no value is dispatched. The key is consumed: an enclosing Dialog or Popover stays open. |
| Escape | listbox closed, text unchanged | Not handled: reaches an enclosing Dialog or Popover. |
| Tab / Shift+Tab | anywhere | Focus moves on and the listbox closes; the text reverts or, with `allowCustomValue`, commits. Tab never accepts the active option. |
| Home / End / ArrowLeft / ArrowRight | anywhere | The input's caret; the active option is cleared (focus is back on the text). |
| Read-only | anywhere | Only Tab, the caret keys, (with `multiple`) the move into the chips, Escape and Alt+ArrowUp (which close a listbox a parent keeps open) work: nothing opens, commits or removes. Every other key is left to the browser (Enter submits a form). |

Disabled options are skipped. Keys during an IME composition belong to the composition. Ctrl and Meta combinations are left alone.

With `multiple`, in the Input (the chip keys are with [Combobox.Chip](#props)):

| Key | Where | Behaviour |
| - | - | - |
| Enter | listbox open, an option active | Toggles it; the listbox stays open. |
| Enter | listbox open, no option active | Adds the text as a value with `allowCustomValue`; otherwise nothing. |
| Enter | listbox opening (requested, not shown yet), text typed | Nothing: prevented, the text is kept (you are about to pick). Right after Escape the closed rule below applies. |
| Enter | listbox closed, text typed | `allowCustomValue`: adds the text (prevented, the form does not submit). Otherwise clears the text, then a form submits. |
| Alt+ArrowUp | listbox open | Closes; the active option is not toggled. |
| Backspace | empty text | Removes the last chip and announces it (not on key repeat). |
| ArrowLeft (ArrowRight under `direction: rtl`) | caret at the start | Moves focus to the last chip; the listbox closes, the text stays. |

Screen readers hear a toggled option through its `aria-selected` under `aria-activedescendant`; a chip removed outside the listbox is announced with `ariaNotify()` on the Input (`"Japan removed"`). The label is the Chip's `label`, else the option text the library saw, else the chip's text without its `ChipRemove` and without `aria-hidden` content. The announcement is optimistic: if the removal's save fails the chip comes back without a second announcement. Localise it with:

```tsx
<Combobox.Root multiple announceRemoved={(labels) => `${labels.join("、")}を削除しました`}>
```

### Accessibility and announcements

- The Input is `role="combobox"` with `aria-autocomplete="list"`, `aria-expanded`, `aria-controls` (the List, while it is rendered: a closed Combobox renders no List, so the Input and the Trigger carry no `aria-controls` then) and `aria-activedescendant` (the active option, never a stale id; removed while you edit the text). Name it with `Combobox.Label`, which names the listbox too.
- When results settle, the library announces their count with `ariaNotify()` on the List: by default the English `"No results"`, `"1 result"`, `"N results"`. Nothing is announced while results are stale or loading (a `Status` fallback showing in the List), or for an unchanged result set. Localise with one function:

```tsx
<Combobox.Root announce={(n) => (n === 0 ? "該当なし" : `${n}件`)}>
```

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

Every value dispatch: `fsui-combobox` and `fsui-combobox-select` (with `multiple`: `-select` when something is added, `fsui-combobox-deselect` when something is removed). Opens and closes: `fsui-combobox` plus `fsui-combobox-open` or `fsui-combobox-close`. A deferred results render carries no type: a string `transition` ignores it, and a map must end with `default: "none"`. These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

The selected value and the open state are optimistic (`data-empty` on the Input, `data-selected` on the Option). `data-pending` is on the Input while a selection or an open is in flight, on the Trigger while an open or close is, and on the Option being chosen. With `multiple` the chips render from the optimistic value: a removed chip disappears at once and returns if its save fails, an added chip has `data-pending` until it is committed. The typed text is urgent, not optimistic (a [fact](../concepts/action-props.md#fact), reported to `onInputValueChange`).

### A slow `openChangeAction`

Here every `openChangeAction` call takes 2 seconds, like a server call, and `onOpenChange` logs the dismissals. The Input's `aria-expanded`, and the state the browser exposes on the Trigger, follow the shown listbox:

```tsx title="ComboboxSlowOpen.tsx"
"use client";
import { startTransition, useState } from "react";
import { Combobox } from "@funstack/ui/combobox";
import type { ComboboxOpenChangeDetails } from "@funstack/ui/combobox";
import { sleep } from "./fake-api.js";

const FRUITS = ["Apple", "Banana", "Cherry", "Grape", "Lemon", "Mango", "Orange", "Pear"];

// A slow `openChangeAction`: a pretend server call of 2 seconds for every request. Opening
// (typing, ArrowDown or the Trigger): the Input and the Trigger get data-open and data-pending at
// once, the listbox is shown when the action settles. Accepting an option or pressing the Trigger
// again closes it when the close's action settles. Escape, a click outside and focus leaving are
// the browser's, a fact: the listbox hides at once, nothing is pending and the action is not
// called; `onOpenChange` reports it. The Input's `aria-expanded` and the state the browser
// exposes on the Trigger follow the shown listbox. The readout is plain text, not a live region.
export function ComboboxSlowOpen() {
  const [log, setLog] = useState("(none yet)");
  const slow = async (open: boolean, { reason }: ComboboxOpenChangeDetails) => {
    const call = `openChangeAction(${open}, "${reason}")`;
    setLog(`${call}: running…`);
    await sleep(2000);
    // After an await: wrap the update in startTransition (React limitation).
    startTransition(() => setLog(`${call}: settled`));
  };
  // A fact: called in the browser's event, not awaited. A plain setState here is urgent.
  const dismissed = (open: boolean, { reason }: ComboboxOpenChangeDetails) => {
    setLog(`onOpenChange(${open}, "${reason}")`);
  };
  return (
    <div className="demo-stack">
      <Combobox.Root openChangeAction={slow} onOpenChange={dismissed}>
        <Combobox.Label>Fruit</Combobox.Label>
        <div className="demo-combobox-field">
          <Combobox.Input className="demo-combobox-input" placeholder="Type or press ArrowDown" />
          <Combobox.Trigger className="demo-combobox-icon" aria-label="Show fruits">
            {({ pending }) => (pending ? <span className="demo-spinner" aria-hidden /> : "▾")}
          </Combobox.Trigger>
          <Combobox.Popup className="demo-combobox-popup">
            <Combobox.List>
              {({ query }) =>
                FRUITS.filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => (
                  <Combobox.Option key={f} value={f}>
                    {f}
                  </Combobox.Option>
                ))
              }
            </Combobox.List>
            <Combobox.Empty className="demo-combobox-status">No fruit matches.</Combobox.Empty>
          </Combobox.Popup>
        </div>
      </Combobox.Root>
      <p className="demo-readout">
        Last: <code>{log}</code>
      </p>
    </div>
  );
}
```

`combobox.css`: the same file as above.

- Open (type, ArrowDown or the Trigger): the Input and the Trigger get `data-open` and `data-pending` at once and stay collapsed; the listbox is shown and both are expanded when the action settles.
- Accept an option, or press the Trigger again: the listbox stays shown and both stay expanded until the close's action settles.
- Escape or a click outside: a fact. The listbox hides and both are collapsed at once; nothing is pending and the slow action is not called; `onOpenChange` is.

The readout under the example is plain text, not a live region, so it does not interrupt a screen reader.

## Suspense

Concept: [Suspense](../concepts/suspense.md)

Results render from a deferred copy of the text (`useDeferredValue`), so an async search is `use(search(query))` inside a boundary in the List. The first load shows your fallback; after that every keystroke keeps the previous results on screen, marked `data-stale` and `aria-busy`, until the new ones are ready. Only the latest query is ever rendered. Option content must not suspend.

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

The listbox is a popover: a dismissal (Escape, a click outside, another popover opening) is the browser's. Focus leaving the input is closed by the library at once, which it cannot hold either. Either way it is a fact: `onOpenChange(false)` with `reason: "dismiss"`, nothing pending.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

A plain text field: typing works and the form posts the default selection (and the raw text, if the Input has a `name`). The listbox never opens before hydration. Text typed then is kept and reported once, with `reason: "platform"`.

## Forms

- `name` on the Root posts the value through a hidden input (`""` for `null`); a `name` on the Input posts the raw text as well. `required` on the Input is native.
- With `multiple`: one hidden input per value, so the form posts what same-named checkboxes would (`formData.getAll(name)`, nothing for an empty selection). `required` means at least one value (see [Multiple selection](#multiple)). A form reset replaces the whole selection with the reset target, even while saves are still running. Inside a `Field.Root`, `validate` gets the first value; read the others from `formData.getAll(name)`.
- A form reset (the Reset button, `form.reset()`, or React's automatic reset after a form action) dispatches `valueChangeAction` with `reason: "platform"` and writes the text: uncontrolled, back to the latest `defaultValue` / `defaultInputValue`; controlled, to the mount-time values.
- Text typed before hydration (and Firefox's form restoration) is kept and reported once through `onInputValueChange` with `reason: "platform"`.

## Styling

```css
.listbox { margin: 0; inset: auto; }                            /* the Popup */
.listbox [role="listbox"] { max-block-size: 20rem; overflow: auto; }  /* the List scrolls */
.listbox [role="listbox"][data-stale] { opacity: .6; }          /* old results while searching */
.listbox [role="option"][data-active] { background: var(--accent-weak); }
.listbox [role="option"][data-selected]::after { content: "✓" / ""; }
.listbox [role="option"][data-pending] { cursor: progress; }
.combobox-input:user-invalid { border-color: var(--danger); }

/* Enter / exit for dismissals too (Escape, a click outside). */
.listbox { opacity: 0; transition: opacity 120ms, display 120ms allow-discrete, overlay 120ms allow-discrete; }
.listbox:popover-open { opacity: 1; }
@starting-style { .listbox:popover-open { opacity: 0; } }
```

Put the scroll on the List (`[role="listbox"]`), not on the Popup. Nothing in a scrolling Popup takes focus (the options are `aria-activedescendant` targets), so axe reports the Popup as `scrollable-region-focusable`; with the scroll on the List it reports nothing (checked in Chromium and Firefox). The active option is scrolled into view either way.

`transition` on the Popup animates the library's own opens and closes with a view transition in every engine (including the close of an accepted option, in the pick's own event). A string animates nothing else: a results change (a deferred render), a value dispatch and a keystroke start no view transition, so no typed character is lost to one ([Input during a view transition](../concepts/transitions.md#input)).

```tsx
<Combobox.Popup transition="pop">
```

A hand-written map must end with `default: "none"`, or every results render cross-fades, and must not be keyed on `fsui-combobox`, which every value dispatch carries.

Types: every value dispatch adds `fsui-combobox` and `fsui-combobox-select`; opens and closes add `fsui-combobox-open` / `fsui-combobox-close`. With `multiple`, a value dispatch adds `fsui-combobox-select` when it adds a value and `fsui-combobox-deselect` when it removes one. Chips have no `transition` prop: to animate them, wrap each in your own `<ViewTransition>` and key on these types.

Keep the CSS exit above next to `transition`: it animates the dismissals (focus leaving, Escape, a click outside). The library turns the popup's CSS transitions off for the moment of its own show and hide while a view transition runs, so you need no extra rule ([A popup with a CSS exit and a view transition](../concepts/transitions.md#css-exit)).

## Recipes

### <a id="command-palette"></a>A command palette

A command palette is a Combobox inside a modal [Dialog](dialog.md). Open the Dialog from your shortcut with a plain `setOpen(true)` ([Open your own controlled overlay urgently](../concepts/action-props.md#urgent-open)), and run the command from `valueChangeAction`.

Leave the Combobox's own `open` uncontrolled, with no `openChangeAction`: the listbox then opens with the first keystroke even while a save elsewhere in the app is pending ([Pending actions hold other transitions](../concepts/action-props.md#pending-actions-hold-transitions)). A controlled `open`, or one with an `openChangeAction`, waits for that save.

Picking a command closes the listbox at once, but what you do in `valueChangeAction` waits: a `setOpen(false)` in its synchronous part is a transition update, so the palette stays open until every action pending in the app has settled. In a test app with a 1.5 s save pending, Enter took about 1.3 s to close the palette.

To close the palette at once, queue the close and the command with `queueMicrotask`. The microtask runs after the action's synchronous part has returned, outside its transition, so `setOpen(false)` there is an [urgent update](../concepts/action-props.md#urgent-update). In the same test app the palette closed within 20 ms (Chromium and Firefox). `toast()` leaves an action's transition the same way ([Toast](toast.md#how-it-works)). A `setTimeout` works too; the microtask runs before the next paint. What still waits:

- The Combobox's own commit, since it has a `valueChangeAction`: its value and `data-pending`. Nobody sees it, because the closed Dialog unmounts its content (unless its Popup has `keepMounted`).
- Every transition the command starts. A navigation is one in most routers: React Router 8 hands the new route to React in `startTransition` unless the router has `useTransitions={false}`, wherever `navigate()` is called ([React Router](../concepts/react-router.md#use-transitions)). The palette closes at once, but the new route renders only when the save has settled. Passing `useTransitions={false}` is the only way around it. It applies to every navigation in the app, and route content that suspends then shows its Suspense fallback.

Nothing awaits the command, so it shows no pending state, and a rejection reaches no Error Boundary: catch it yourself. When the palette must show the result before it closes (an error message inside it), await the command in the action and close after it with `startTransition(() => setOpen(false))`. The palette then also waits for every other pending action.

A click handler on an Option's `render` element is no substitute: Enter accepts the active option from the input's keydown, with no click on the option. A handler on the input would have to repeat the Combobox's rules for when Enter accepts. `valueChangeAction` is called for every accepted option, however it was picked.

By default, leaving the palette with the keyboard takes up to three Escapes, because [one Escape closes one layer](../concepts/browser-owned-state.md#one-escape) and the Combobox has two:

1. With the listbox open, the browser closes the listbox. The text stays.
2. With the listbox closed and the text edited, the Combobox puts the committed text back (the APG combobox pattern allows clearing it) and takes the key, so the Dialog stays open.
3. With the text unchanged, the Escape reaches the Dialog, which closes.

There is no prop to skip these steps. A palette that closes on the first Escape handles the key itself. `onKeyDown` is not in `Combobox.Input`'s props type (the part installs its own), so put yours on the `render` element, where it runs before the library's. Call `preventDefault()`: the listbox, the text revert and the Dialog then all leave the key alone. Then close the controlled Dialog with an [urgent](../concepts/action-props.md#urgent-update) `setOpen(false)`.

This is a deliberate exception to one Escape per layer. It uses the documented `preventDefault()` contract ([One Escape closes one layer](../concepts/browser-owned-state.md#one-escape)), and it fits a Dialog whose only content is the palette. The Combobox's own steps stay as the APG pattern describes them.

```tsx
const [open, setOpen] = useState(false);

<Dialog.Root open={open} openChangeAction={setOpen} onOpenChange={setOpen}>
  <Dialog.Popup className="palette" aria-label="Command palette">
    <Combobox.Root
      autoHighlight
      valueChangeAction={(command) => {
        if (command === null) return;
        // Out of the action's transition: urgent, not held by a save pending elsewhere.
        queueMicrotask(() => {
          setOpen(false);
          // A synchronous command's throw becomes a rejection too.
          Promise.resolve().then(() => runCommand(command)).catch(showError);
        });
      }}
    >
      <Combobox.Label>Command</Combobox.Label>
      <Combobox.Input
        render={
          <input
            onKeyDown={(event) => {
              // One Escape closes the palette, also while the listbox is open or the text edited.
              // Not an Escape that cancels an IME composition (WebKit reports it as keyCode 229).
              const key = event.nativeEvent;
              if (key.key === "Escape" && !key.isComposing && key.keyCode !== 229) {
                event.preventDefault();
                setOpen(false);
              }
            }}
          />
        }
      />
      <Combobox.Popup className="listbox">
        <Combobox.List>{({ query }) => <Commands query={query} />}</Combobox.List>
      </Combobox.Popup>
    </Combobox.Root>
  </Dialog.Popup>
</Dialog.Root>
```

The `isComposing` and `keyCode` checks leave an Escape that cancels an IME composition to the input method: in WebKit that Escape has `isComposing` false and `keyCode` 229. Without the handler the palette keeps the three steps above.

## Browser notes

- **Right-to-left:** the listbox lines up with the input's inline-start edge (the right edge in RTL) under a `dir="rtl"` page or container. The `self-*` `position-area` keywords follow the popup's own inherited direction, with no JavaScript; plain logical keywords would follow the root's only, because the listbox is in the top layer. Firefox misplaces a popover inside a direction island ([#89](https://github.com/uhyo/funstack-ui/issues/89); see [Tooltip](tooltip.md#browser-notes)). The Popup emits no `data-side`.
- Inside a Dialog or a Popover the listbox nests in the top layer: the first Escape closes the listbox, the next reverts edited text, the next the outer overlay; an outside click closes the stack. Inside a `Menu.Popup` a combobox is not supported (the menu's typeahead and focus handling compete with the input).
- Safari: a WebKit bug (302008) can hang a page that opens a popover with position fallbacks inside another popover. If a Combobox inside a Popover or Dialog misbehaves in Safari, turn the flip off: `style={{ positionTryFallbacks: "none" }}` on `Combobox.Popup`.
- Want the listbox as wide as an input-plus-buttons group? Give the group an `anchor-name` and make it the Popup's default anchor in your stylesheet (`.group .popup { position-anchor: --group; }`), as the first example does. The inline `position-area` and `min-width: anchor-size(width)` follow the default anchor, so the listbox is placed under the group and is at least as wide. Give each group on a page its own name: with a shared one, every listbox anchors to the last group.
