# Combobox

> The editable dropdown from @salmonui/dropdowns/combobox, with list autocomplete, inline autofill, custom values and IME support.

Canonical: https://salmonui.dev/docs/dropdowns/combobox

`Combobox` is the WAI-ARIA APG editable combobox with list autocomplete:
an `<input role="combobox" aria-autocomplete="list">` keeps DOM
focus while the popup is driven through `aria-activedescendant`. It is the
base of [AutoComplete](https://salmonui.dev/docs/dropdowns/autocomplete), the typing
[MultiSelect](https://salmonui.dev/docs/dropdowns/combobox-multiple) and
[MultiColumn ComboBox](https://salmonui.dev/docs/dropdowns/multicolumn-combobox).

```tsx
import { Combobox } from '@salmonui/dropdowns/combobox';
import '@salmonui/dropdowns/combobox/styles.css';

<Combobox aria-label="Fruit" data={fruits} defaultValue="kiwi" />
```

### Live demo: Combobox basics

Live demo: https://salmonui.dev/demos/dropdowns/combobox-basics

An editable combobox with inline autofill, a creatable combobox, and typing MultiSelect chips that add typed text on blur.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Combobox, type ComboboxValue } from '@salmonui/dropdowns/combobox';

interface Fruit {
  readonly value: string;
  readonly label: string;
}

const FRUITS: Fruit[] = ['Apple', 'Apricot', 'Banana', 'Blueberry', 'Cherry', 'Grape', 'Kiwi', 'Lemon', 'Lime', 'Mango', 'Orange', 'Peach', 'Pear', 'Plum'].map((label) => ({ value: label.toLowerCase(), label }));

// An editable combobox with inline autofill, a creatable one, and typing
// MultiSelect chips with values added on blur.
export default function ComboboxBasicsDemo() {
  const [fruit, setFruit] = useState<ComboboxValue | null>(null);
  const [tags, setTags] = useState<readonly ComboboxValue[]>(['kiwi']);
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 360 }}>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-cbx-label">Fruit (autofill)</span>
        <Combobox aria-labelledby="demo-cbx-label" data={FRUITS} autofill value={fruit} onValueChange={setFruit} placeholder="Type a fruit" />
        <output>Value: {String(fruit)}</output>
      </div>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-create-label">Fruit or your own</span>
        <Combobox aria-labelledby="demo-create-label" data={FRUITS} creatable onCreateItem={(text) => ({ value: text.toLowerCase(), label: text })} />
      </div>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-tags-cbx-label">Tags</span>
        <Combobox aria-labelledby="demo-tags-cbx-label" multiple creatable commitOnBlur data={FRUITS} value={tags} onValueChange={setTags} onCreateItem={(text) => ({ value: text.toLowerCase(), label: text })} />
      </div>
    </div>
  );
}
```

It shares the [Select](https://salmonui.dev/docs/dropdowns/select) props for data, value,
events, search, templates and forms, except `popupMode`: the popup is
always the anchored popover, since the input is already the search field.
Its own props:

| Prop | Meaning |
| --- | --- |
| `inputValue`, `defaultInputValue`, `onInputChange(text, event)` | The input text; `event.reason` is `'input'`, `'select'`, `'clear'`, `'escape'`, `'blur'` or `'reset'` (the owning form was reset) |
| `creatable` | Committed text without a matching item becomes the value; default `false` |
| `onCreateItem(text)` | Builds the item for created text; `null` rejects it; default: the text itself |
| `autofill` | Completes the first match inline with the completed part selected, `aria-autocomplete="both"` |
| `showTrigger` | The dropdown button, default `true`; it is not in the tab order |
| `openOnClick` | A click in the input opens the popup (default `true`) |
| `clearable` | The clear button, default `true` |
| `ref` | The `<input role="combobox">`; DOM props such as `onFocus` and `aria-label` reach it too |

Typing filters the list and opens it; the input text is the search text
(`searchOperator`, `matchCase`, `ignoreAccents`, `minSearchLength`,
`maxResults`). Committing text that equals a label (ignoring case) selects
that item; other text is created with `creatable`, otherwise it reverts to
the selected label when focus leaves.

### Live demo: Combobox input, keys and custom values

Live demo: https://salmonui.dev/demos/dropdowns/combobox-options

A controlled input text with onInputChange, custom values validated by onCreateItem, the optional dropdown button, the editable-combobox keys and IME-safe filtering.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Combobox, type ComboboxValue } from '@salmonui/dropdowns/combobox';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Code {
  readonly value: string;
  readonly label: string;
}

const AIRPORTS: Code[] = [
  ['AMS', 'Amsterdam'], ['CDG', 'Paris Charles de Gaulle'], ['FRA', 'Frankfurt'], ['HND', 'Tokyo Haneda'], ['ICN', 'Seoul Incheon'],
  ['JFK', 'New York JFK'], ['LHR', 'London Heathrow'], ['NRT', 'Tokyo Narita'], ['SIN', 'Singapore Changi'], ['SYD', 'Sydney'],
].map(([value, label]) => ({ value: value as string, label: `${value} · ${label}` }));

const CITIES = ['東京', '大阪', '京都', '札幌', '名古屋', '福岡', 'ソウル', '北京', '上海'];

// Created items must be three letters: anything else is rejected (onCreateItem returns null).
const createAirport = (text: string): Code | null => (/^[a-z]{3}$/i.test(text.trim()) ? { value: text.trim().toUpperCase(), label: `${text.trim().toUpperCase()} · custom code` } : null);

export default function ComboboxOptionsDemo() {
  const [log, push] = useEventLog();
  const [airport, setAirport] = useState<ComboboxValue | null>('LHR');
  const [text, setText] = useState('LHR · London Heathrow');
  const [showTrigger, setShowTrigger] = useState(true);
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 480 }}>
      <Checkbox checked={showTrigger} onCheckedChange={(checked) => setShowTrigger(checked)}>
        Show the dropdown button
      </Checkbox>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="cbx-options-airport">Airport (or any three-letter code)</span>
        <Combobox<Code>
          aria-labelledby="cbx-options-airport"
          data={AIRPORTS}
          searchOperator="contains"
          creatable
          onCreateItem={(created) => {
            const item = createAirport(created);
            push(item ? `onCreateItem "${created}" → ${item.value}` : `onCreateItem "${created}" → rejected`);
            return item;
          }}
          showTrigger={showTrigger}
          value={airport}
          onValueChange={(next, event) => {
            push(`onValueChange ${String(next)} (reason ${event.reason}, source ${event.source})`);
            setAirport(next);
          }}
          inputValue={text}
          onInputChange={(next, event) => {
            push(`onInputChange "${next}" (reason ${event.reason})`);
            setText(next);
          }}
        />
      </div>
      <p>
        Value: <output>{String(airport)}</output> · Input text: <output>{text}</output>
      </p>
      <Button variant="outline" style={{ justifySelf: 'start' }} onClick={() => setText('Tokyo')}>
        Set the input text to “Tokyo”
      </Button>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="cbx-options-ime">都市 (type with a Japanese or Chinese input method)</span>
        <Combobox aria-labelledby="cbx-options-ime" lang="ja" data={CITIES} searchOperator="contains" onInputChange={(next, event) => push(`IME field onInputChange "${next}" (reason ${event.reason})`)} />
      </div>
      <EventLog entries={log} />
    </div>
  );
}
```

## Value and events

Both the value and the text can be controlled or left uncontrolled.
`value` / `defaultValue` / `onValueChange(value, event)` hold one item
value or `null`; `event.reason` is `'select'`, `'create'`, `'clear'` or
`'reset'` and `event.items` holds the new value's items, including created
ones. A controlled `value` vetoes a change by not updating.
`open` / `defaultOpen` / `onOpenChange(open, event)` control the popup.

```tsx
const [city, setCity] = useState<string | null>(null);
const [text, setText] = useState('');

<Combobox
  aria-label="City"
  data={cities}
  creatable
  value={city}
  onValueChange={(next) => setCity(next as string | null)}
  inputValue={text}
  onInputChange={(next) => setText(next)}
/>
```

## Keyboard

| Key | Action |
| --- | --- |
| Arrow Down / Up | Open; move the active option |
| Alt+Down / Alt+Up | Open without moving / close |
| Enter | Commit the active option, or the typed text (`creatable`) |
| Escape | Close; a second Escape clears the input (and the value, with `clearable`) |
| Home / End | Move the caret (the text, not the list) |
| Page Down / Page Up | Move by `maxVisibleItems` while open |
| Tab | Commit or revert the text and move on |

During IME composition there is no filtering, autofill or Enter commit; the
search runs when composition ends.

Opening over 100,000 local items stays within the dropdown open budget
(≤ 50 ms to painted gates the `columns` popup over 100,000 rows):
the popup windows its options and the search index builds after the first
paint.

## Size

`size` (`'sm' | 'md' | 'lg'`, default `'md'`) sets the field to 24, 32 or
40 px with 8, 12 or 16 px of inline padding and 14, 16 or 20 px icons, as
on [Select](https://salmonui.dev/docs/dropdowns/select#size); the AutoComplete and multicolumn
variants take it too. Chips and their remove buttons are 20, 24 or 28 px;
at `sm` the remove button's hit area still covers 24 × 24 px, so touch
targets stay at the WCAG minimum. The popup keeps one size.

## Server rendering

The server renders the input, the selected label and, with `name`, the
hidden form element; the popup and the `columns` grid are lazy chunks
loaded on the client, so a closed Combobox hydrates without a warning.

See the [API reference](https://salmonui.dev/docs/reference/dropdowns/combobox) for every prop and
[Data, search and the popup](https://salmonui.dev/docs/dropdowns/dropdown-popup-data) for the
data model and its limits.
