# Combobox

A field you type into to find and choose an option, or several, also called an autocomplete. Built on ui-sdk's Combobox: typing filters the list, arrows move, Enter chooses, Escape closes. Options take a second line, an icon and a group; long labels clip with their full text on hover. With serverFilter, onQueryChange fetches results and loading shows a spinner.

- Beta: ready to use; its API can still change in a minor release.
- Category: Form fields

```tsx
import { Combobox } from "@leap-crm/design-system";
```

## Best practices

- Do: Use it when people find the option by typing, like a contact, a referrer or a lender among hundreds. Use `Select` for a short fixed list, like a matter status.
- Do: Set `serverFilter` with `onQueryChange` and `loading` when results come from the server, so the list keeps what the server returned and shows a spinner while it loads.
- Do: Use an option's `description` for the detail that tells two options apart, like the email under a contact's name.
- Do: Put it in a `Field` for its label and error. Alone, name it with `aria-label`.
- Do: Set `multiple` when the field holds several records, like the practice areas a contact works in. The field stays one line, saying how many are chosen; the list stays open while you pick and ticks each choice.
- Don't: Set `allowCustomValue` on a field that must hold a record, like the client on an opportunity. Text that matches no option becomes the value.
- Don't: Use `multiple` for tags on a record. Use `TagInput`, which shows the chosen tags inline and can create a new one.

## Keyboard

| Keys | What they do |
| --- | --- |
| Typing | Opens the list with the items that match. |
| Arrow keys | Move the highlight while focus stays in the input, skipping disabled items. |
| Enter | Chooses the highlighted item, puts its label in the input and closes. |
| Escape | Closes the list and keeps focus in the input. |
| Tab | Closes the list and moves on. |

## Related

- [Select](./select.md)
- [Tag Input](./tag-input.md)
- [Time Picker](./time-picker.md)
- [Dropdown Menu](./dropdown-menu.md)

## Examples

What the examples import:

```tsx
import { useRef, useState } from "react";
import { Combobox, Field, type ComboboxOption } from "@leap-crm/design-system";
```

Scaffolding the examples call. It lives in the docs page, not in the library:

```tsx
const contacts: ComboboxOption[] = [
  {
    value: "ada",
    label: "Ada Hartley",
    description: "ada@hartley.com.au",
    group: "Contacts",
  },
  {
    value: "ben",
    label: "Ben Okafor",
    description: "ben.okafor@outlook.com",
    group: "Contacts",
  },
  {
    value: "chloe",
    label: "Chloe Ng",
    description: "chloe@ngfamily.net",
    group: "Contacts",
  },
  {
    value: "hart-trust",
    label: "Hartley Okafor Moreau Family Trust (Superannuation Fund No. 2)",
    description: "Trust",
    group: "Organisations",
  },
  {
    value: "paddington",
    label: "Paddington Realty",
    description: "Real estate agent",
    group: "Organisations",
  },
  {
    value: "westpac",
    label: "Westpac",
    description: "Lender",
    group: "Organisations",
    disabled: true,
  },
];

const areas: ComboboxOption[] = [
  { value: "conveyancing", label: "Conveyancing" },
  { value: "family", label: "Family law" },
  { value: "wills", label: "Wills and estates" },
  { value: "commercial", label: "Commercial" },
  { value: "litigation", label: "Litigation" },
];

const suburbs = [
  "Paddington",
  "Parramatta",
  "Penrith",
  "Petersham",
  "Pymble",
  "Potts Point",
  "Punchbowl",
];

function ServerSearch() {
  const [results, setResults] = useState<ComboboxOption[]>([]);
  const [loading, setLoading] = useState(false);
  // Only the latest query's answer lands, so a slow earlier one can't overwrite it.
  const latest = useRef("");
  return (
    <Field label="Suburb" className="w-80">
      <Combobox
        options={results}
        serverFilter
        loading={loading}
        placeholder="Start typing a suburb"
        emptyText="No suburbs found"
        onQueryChange={query => {
          latest.current = query;
          setLoading(true);
          setTimeout(() => {
            if (query !== latest.current) return;
            setResults(
              suburbs
                .filter(suburb =>
                  suburb.toLowerCase().startsWith(query.toLowerCase()),
                )
                .map(suburb => ({ value: suburb, label: suburb })),
            );
            setLoading(false);
          }, 500);
        }}
      />
    </Field>
  );
}
```

### In a field

Grouped options with a second line. Westpac is disabled; the trust's long name clips and shows in full on hover.

```tsx
<Field label="Client" className="w-80">
  <Combobox
    options={contacts}
    placeholder="Search contacts"
    defaultValue="ada"
  />
</Field>
```

### Multiple

multiple keeps the list open while you choose and ticks each chosen row on its right. The field stays one line: the label when one is chosen, "2 selected" for more, with × to clear them all.

```tsx
<Field label="Practice areas" className="w-96">
  <Combobox
    multiple
    options={areas}
    placeholder="Add an area"
    defaultValue={["conveyancing", "family"]}
  />
</Field>
```

### From a server

serverFilter keeps the results as given while onQueryChange fetches them; loading shows the spinner and Loading in the list.

```tsx
<ServerSearch />
```

### States

Invalid, read-only and disabled, at the four field sizes.

```tsx
<div className="flex w-80 flex-col gap-4">
  <Field label="Client" error="Please choose a client">
    <Combobox
      options={contacts}
      invalid
      placeholder="Search contacts"
    />
  </Field>
  <Field label="Read-only">
    <Combobox options={contacts} readOnly defaultValue="ben" />
  </Field>
  <Field label="Disabled" disabled>
    <Combobox options={contacts} disabled defaultValue="chloe" />
  </Field>
  {(["xs", "sm", "md", "lg"] as const).map(size => (
    <Combobox
      key={size}
      size={size}
      aria-label={`Contact, ${size}`}
      options={contacts}
      placeholder={`Size ${size}`}
    />
  ))}
</div>
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `options` (required) | `ComboboxOption[]` |  | Every option, or the current results when `serverFilter` is on. |
| `placeholder` | `string` |  | Grey hint text while it's empty. Never a replacement for a label. |
| `size` | `TextSize` |  | xs 28 · sm 32 · md 36 (forms) · lg 40. |
| `id` | `string` |  | The control's id, for a label's htmlFor or aria-describedby. |
| `aria-label` | `string` |  | Names the field when no Field label does. |
| `name` | `string` |  | The field's name when a form submits. |
| `disabled` | `boolean` |  | Shows it as unavailable and stops it responding. |
| `readOnly` | `boolean` |  | Shows the value without letting it change. Still focusable. |
| `required` | `boolean` |  | Marks it required: the label gets its asterisk and the form checks it. |
| `invalid` | `boolean` |  | Shows the field as invalid, as a Field error does. |
| `onQueryChange` | `(query: string) => void` |  | Runs as the text changes, to fetch results. |
| `serverFilter` | `boolean` |  | Keeps every option as given, for results a server already filtered. |
| `loading` | `boolean` |  | Results are loading: a spinner in the field and Loading in the list. |
| `emptyText` | `string` |  | What the list says when nothing matches. |
| `allowCustomValue` | `boolean` |  | Text that matches no option becomes the value on Enter. |
| `className` | `string` |  | Classes added to the root element, merged with its own. Tokens only. |
| `multiple` | `boolean` |  | Chooses several. The field stays one line: the label when one is chosen, "3 selected" for more. |
| `value` | `string \| null \| string[]` |  | The chosen option's value, when you control it: null for none. An array with multiple. |
| `defaultValue` | `string \| null \| string[]` |  | The option chosen at the start, when it controls itself. An array with multiple. |
| `onValueChange` | `((value: string \| null) => void) \| ((value: string[]) => void)` |  | Runs with the chosen value, or null once cleared. With multiple, every chosen value. |
