# Autocomplete

Free text with suggestions loaded as people type, grouped and with detail lines.

- Family: selection
- Import: `import { Autocomplete } from "@senvenli/react/selection";`
- Page: https://design.senvenli.com/docs/components/autocomplete
- JSON: https://design.senvenli.com/docs/components/autocomplete.json

## Example: Free text with suggestions

Any text is a valid value; a suggestion only fills it in.

```tsx
import { Autocomplete, type AutocompleteSuggestion } from "@senvenli/react/selection";
import { useState } from "react";

const COMPANIES: AutocompleteSuggestion[] = [
  { id: "analytical", label: "Analytical Engines Ltd", description: "London · 12 open invoices" },
  { id: "northwind", label: "Northwind Traders", description: "Seattle · 3 open invoices" },
  { id: "norfolk", label: "Norfolk Paper Co.", description: "Norwich · no open invoices" },
  { id: "acme", label: "Acme Supplies", description: "Chicago · 1 open invoice" },
];

// Stands in for a request to your API; pass `signal` to fetch so superseded requests abort.
async function getSuggestions(text: string) {
  const query = text.toLowerCase();
  return COMPANIES.filter((company) => company.label.toLowerCase().includes(query));
}

export default function Example() {
  const [company, setCompany] = useState("");
  return (
    <div className="max-w-80">
      <Autocomplete
        label="Company"
        icon="building-2"
        placeholder="Start typing a name"
        description="Pick a customer or type a new company."
        value={company}
        onChange={setCompany}
        getSuggestions={getSuggestions}
      />
    </div>
  );
}
```

## Examples

### Grouped, with icons

Suggestions under headers, in the order the groups prop gives.

```tsx
import { Autocomplete, type AutocompleteSuggestion } from "@senvenli/react/selection";
import { useState } from "react";

const PLACES: AutocompleteSuggestion[] = [
  { id: "hq", label: "Head office", description: "1 Market Street, San Francisco", icon: "building-2", group: "Saved addresses" },
  { id: "warehouse", label: "Main warehouse", description: "480 Harbor Road, Oakland", icon: "warehouse", group: "Saved addresses" },
  { id: "sfo", label: "San Francisco International Airport", description: "Cargo terminal", icon: "plane", group: "Places" },
  { id: "sjc", label: "San Jose", description: "California", icon: "map-pin", group: "Places" },
  { id: "sac", label: "Sacramento", description: "California", icon: "map-pin", group: "Places" },
];

async function getSuggestions(text: string) {
  const query = text.toLowerCase();
  return PLACES.filter((place) => `${place.label} ${place.description}`.toLowerCase().includes(query));
}

export default function Example() {
  const [address, setAddress] = useState("");
  const [picked, setPicked] = useState<AutocompleteSuggestion | null>(null);
  return (
    <div className="max-w-80">
      <Autocomplete
        label="Ship to"
        icon="map-pin"
        placeholder="Address or place"
        description={picked ? `Picked: ${picked.label}` : "Try “sa” or “market”."}
        groups={["Saved addresses", "Places"]}
        value={address}
        onChange={(text) => {
          setAddress(text);
          setPicked(null);
        }}
        onSelectSuggestion={setPicked}
        getSuggestions={getSuggestions}
      />
    </div>
  );
}
```

### Required

Left empty, the field reports itself on blur.

```tsx
import { Autocomplete } from "@senvenli/react/selection";
import { useState } from "react";

const CITIES = ["Amsterdam", "Berlin", "Lisbon", "London", "Madrid", "Paris", "Vienna"];

async function getSuggestions(text: string) {
  return CITIES.filter((city) => city.toLowerCase().startsWith(text.toLowerCase())).map((city) => ({ id: city, label: city }));
}

export default function Example() {
  const [city, setCity] = useState("");
  return (
    <div className="max-w-80">
      <Autocomplete label="City" isRequired minLength={1} value={city} onChange={setCity} getSuggestions={getSuggestions} />
    </div>
  );
}
```

## Guidelines

### When to use it

- Free text where suggestions help: addresses, places.

### Use something else when

- [combobox](https://design.senvenli.com/docs/components/combobox.md): The value must be one of a known list.

## Accessibility

Built in:

- Announces loading and the suggestion count.
- Required fields show "Fill in this field." after a blur or a submit; your own `errorMessage` replaces it.

You provide:

- A visible label.

## API reference

### Autocomplete

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| label | `React.ReactNode` |  | yes |  |
| value | `string` |  | yes | The free text; it is a valid value on its own. |
| onChange | `(value: string) => void` |  | yes |  |
| getSuggestions | `(text: string, signal: AbortSignal) => Promise<AutocompleteSuggestion[]>` |  | yes | Suggestions for the typed text (called after `minLength` characters, debounced). |
| onSelectSuggestion | `(suggestion: AutocompleteSuggestion) => void` |  | no | Called when a suggestion fills the text, with the suggestion itself (coordinates, ids). |
| groups | `readonly string[]` |  | no | Group order ("Suggested places" first, then "Addresses"). |
| icon | `IconName` |  | no | The field's context icon (default `search`). |
| description | `React.ReactNode` |  | no |  |
| errorMessage | `React.ReactNode` |  | no |  |
| placeholder | `string` |  | no |  |
| isRequired | `boolean` |  | no |  |
| requiredValidation | `RequiredValidation` |  | no | Who says an empty required Autocomplete is missing: `field` (default) shows "Fill in this field." on blur and on a DS Form submit, which it then blocks; `app` only marks the field. See {@link RequiredValidation}. The app's `isInvalid` (`true` with its `errorMessage`, or `false`) overrides the check, as on TextField. Disabled, empty and required, it still blocks a DS Form's submit and cannot take focus (as TextField). |
| isDisabled | `boolean` |  | no |  |
| isInvalid | `boolean` |  | no |  |
| name | `string` |  | no |  |
| minLength | `number` |  | no | Characters before suggesting (default 2). |
| debounce | `number` |  | no | Debounce in ms (default 250). |
| size | `FieldSize` |  | no |  |
| radius | `ComponentRadius` |  | no | Corner radius: `none`, `small`, `medium` (the design), `large` or `full`. The provider's default otherwise. |

### Tokens it reads

`--ds-background-brand-bold`, `--ds-background-disabled`, `--ds-background-input`, `--ds-background-input-hovered`, `--ds-background-neutral`, `--ds-background-neutral-pressed`, `--ds-background-neutral-subtle-hovered`, `--ds-background-selected`, `--ds-background-selected-hovered`, `--ds-border`, `--ds-border-bold`, `--ds-border-danger`, `--ds-border-focused`, `--ds-border-selected`, `--ds-easing-standard`, `--ds-icon-subtle`, `--ds-link`, `--ds-radius-control-medium`, `--ds-radius-control-small`, `--ds-radius-full`, `--ds-radius-large`, `--ds-radius-medium`, `--ds-radius-small`, `--ds-radius-xsmall`, `--ds-shadow-overlay`, `--ds-shadow-raised`, `--ds-size-control`, `--ds-size-control-compact`, `--ds-size-icon`, `--ds-space-050`, `--ds-space-075`, `--ds-space-100`, `--ds-space-150`, `--ds-space-200`, `--ds-surface-overlay`, `--ds-surface-raised`, `--ds-text`, `--ds-text-disabled`, `--ds-text-on-brand`, `--ds-text-subtle`, `--ds-text-subtlest`

## Related

- [combobox](https://design.senvenli.com/docs/components/combobox.md)
