# AutoComplete

> AutoComplete as a Combobox recipe - free text with suggestions from the first character, contains matching, capped and highlighted results.

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

AutoComplete is a [`Combobox`](https://salmonui.dev/docs/dropdowns/combobox) whose value is the
text. The recipe sets the AutoComplete defaults:
suggestions from the first character, at most 20 of them, contains
matching, highlighted matches, a clear button and no dropdown button.

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

<Combobox
  aria-label="City"
  data={cities}
  creatable
  clearable
  showTrigger={false}
  minSearchLength={1}
  maxResults={20}
  searchOperator="contains"
  highlightMatches
/>
```

### Live demo: AutoComplete

Live demo: https://salmonui.dev/demos/dropdowns/autocomplete

A free-text Combobox with suggestions from the first character, contains matching, five results and highlighted matches.

`Demo.tsx`:

```tsx
'use client';

import { Combobox } from '@salmonui/dropdowns/combobox';

const CITIES = ['Amsterdam', 'Barcelona', 'Bern', 'Kraków', 'Lisbon', 'Lyon', 'Málaga', 'Montréal', 'Reykjavík', 'São Paulo', 'Turin', 'Zürich'];

// Autocomplete on Combobox: free text with suggestions that open from the
// first character, contain the text, are capped and marked.
export default function AutocompleteDemo() {
  return (
    <div style={{ display: 'grid', gap: 4, maxWidth: 320 }}>
      <span id="demo-city-label">City</span>
      <Combobox aria-labelledby="demo-city-label" data={CITIES} creatable showTrigger={false} minSearchLength={1} maxResults={5} searchOperator="contains" ignoreAccents highlightMatches placeholder="Start typing" />
    </div>
  );
}
```

With string `data` the committed text is the value: `onValueChange(text,
event)` fires when a suggestion is picked or typed text is committed
(Enter, Tab, blur), with `event.reason` `'select'` or `'create'`.
`onInputChange(text, event)` reports every keystroke, and
`inputValue` / `defaultInputValue` control the text, as on
[Combobox](https://salmonui.dev/docs/dropdowns/combobox), which also covers forms and server
rendering.

| Task | How |
| --- | --- |
| Characters before suggestions show | `minSearchLength` (default 0; the recipe sets 1) |
| Cap the number of suggestions | `maxResults`; for a remote source, the read range |
| Highlight the matched text | `highlightMatches`: `<mark class="salmon-dropdown__match">`; `renderItem` gets `matches` |
| Show a dropdown button | `showTrigger` |

Keys: typing filters and opens the suggestions once the text is
long enough; Arrow Down / Up open them when hidden; Backspace re-filters;
Escape closes and clears the active suggestion.

ARIA: `aria-autocomplete="list"` (`"both"` with `autofill`),
`aria-busy` on the list while remote suggestions load. Templates and
remote loading need no extra ARIA wiring from the application: render props
render inside the option element, which keeps its role and state, and the
result count after a search is announced by the component.

### Live demo: AutoComplete with remote suggestions

Live demo: https://salmonui.dev/demos/dropdowns/autocomplete-remote

A free-text Combobox over a remote source, with the optional popup button, the suggestion keys, aria-busy while loading, a custom option template and announced result counts.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Combobox, type ComboboxValue } from '@salmonui/dropdowns/combobox';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createDemoListSource } from '../../lib/demo-list-source';

interface Airport {
  readonly value: string;
  readonly label: string;
  readonly country: string;
}

const AIRPORTS: Airport[] = [
  ['AKL', 'Auckland', 'New Zealand'], ['ATH', 'Athens', 'Greece'], ['BCN', 'Barcelona', 'Spain'], ['BKK', 'Bangkok', 'Thailand'], ['BOG', 'Bogotá', 'Colombia'],
  ['CPT', 'Cape Town', 'South Africa'], ['DEL', 'Delhi', 'India'], ['DXB', 'Dubai', 'United Arab Emirates'], ['GRU', 'São Paulo', 'Brazil'], ['IST', 'Istanbul', 'Türkiye'],
  ['KEF', 'Reykjavík', 'Iceland'], ['LIM', 'Lima', 'Peru'], ['LIS', 'Lisbon', 'Portugal'], ['MAD', 'Madrid', 'Spain'], ['MEX', 'Mexico City', 'Mexico'],
  ['NBO', 'Nairobi', 'Kenya'], ['OSL', 'Oslo', 'Norway'], ['PRG', 'Prague', 'Czechia'], ['SCL', 'Santiago', 'Chile'], ['YUL', 'Montréal', 'Canada'],
].map(([value, label, country]) => ({ value: value as string, label: label as string, country: country as string }));

// AutoComplete over a remote source: suggestions load after typing, the
// list is busy while a read is pending and options render a custom template.
export default function AutocompleteRemoteDemo() {
  const [log, push] = useEventLog();
  const [source] = useState(() => createDemoListSource<Airport>({ rows: AIRPORTS, latency: 700, log: push }));
  const [showTrigger, setShowTrigger] = useState(false);
  const [value, setValue] = useState<ComboboxValue | null>(null);
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
      <Checkbox checked={showTrigger} onCheckedChange={(checked) => setShowTrigger(checked)}>
        Show the popup button (<code>showTrigger</code>)
      </Checkbox>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="autocomplete-remote-label">Destination</span>
        <Combobox<Airport>
          aria-labelledby="autocomplete-remote-label"
          data={source}
          creatable
          showTrigger={showTrigger}
          minSearchLength={1}
          maxResults={8}
          searchOperator="contains"
          searchFields={['label', 'country']}
          ignoreAccents
          debounce={250}
          placeholder="City or country"
          renderItem={({ item, label }) => (
            <span>
              {label} <small>({item.value}, {item.country})</small>
            </span>
          )}
          value={value}
          onValueChange={(next) => setValue(next)}
        />
      </div>
      <p>
        Value: <output>{String(value)}</output>
      </p>
      <EventLog entries={log} label="Requests" />
    </div>
  );
}
```

See the [API reference](https://salmonui.dev/docs/reference/dropdowns/combobox) for every prop.
