# Autocomplete

A text input that suggests values while people type.

[View source and API](https://github.com/tempoxyz/ds/blob/main/src/web/components/Autocomplete.tsx)

## Overview

A text input with a suggestion list. Any typed string is a valid value, so suggestions only speed up entry.

## Examples

### Basic

```tsx
import { Autocomplete } from '@tempoxyz/ds'

const actions = ['Send payment', 'Send request', 'Swap tokens', 'View activity']

export function Demo() {
  return (
    <Autocomplete.Root items={actions}>
      <Autocomplete.InputGroup>
        <Autocomplete.Input aria-label="Search" placeholder="Search actions" />
        <Autocomplete.Clear />
      </Autocomplete.InputGroup>
      <Autocomplete.Popup>
        <Autocomplete.Empty>No matches</Autocomplete.Empty>
        <Autocomplete.List>
          {(action: string) => (
            <Autocomplete.Item key={action} value={action}>
              {action}
            </Autocomplete.Item>
          )}
        </Autocomplete.List>
      </Autocomplete.Popup>
    </Autocomplete.Root>
  )
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Autocomplete/Basic.tsx)

## Anatomy

Import the component and assemble its parts.

```tsx
import { Autocomplete } from '@tempoxyz/ds'

<Autocomplete.Root>
  <Autocomplete.InputGroup>
    <Autocomplete.Input />
    <Autocomplete.Clear />
  </Autocomplete.InputGroup>
  <Autocomplete.Popup>
    <Autocomplete.Empty />
    <Autocomplete.List>
      <Autocomplete.Group>
        <Autocomplete.GroupLabel />
        <Autocomplete.Collection>
          <Autocomplete.Item />
        </Autocomplete.Collection>
      </Autocomplete.Group>
      <Autocomplete.Separator />
    </Autocomplete.List>
  </Autocomplete.Popup>
</Autocomplete.Root>
```

## Guidelines

### When to Use

* Enter free text with suggested values, such as a recipient address with recent recipients below it.
* Search actions or pages from one field, such as Send payment or View activity.

### When Not to Use

* If the value must be one of the items, such as the asset to send, use [Combobox](/docs/components/combobox).
* Use [Select](/docs/components/select) for a short list of fixed options.
* If there is nothing useful to suggest, use [TextInput](/docs/components/text-input).

### Accept Any Typed Value

Validate the text as you would a plain [TextInput](/docs/components/text-input), such as a 0x prefix on an address, and explain problems in a `Field.Error`.

**Do:** Accept a new 0x address that isn't among the suggestions.

```tsx
/**
 * Do example for "Accept Any Typed Value" on the Autocomplete page.
 * Accept a new 0x address that isn't among the suggestions.
 * @module
 */
import { Autocomplete, Field, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Recipient</Field.Label>
      <Autocomplete.Root defaultValue="0x8f3a…c21d" items={recipients}>
        <Autocomplete.InputGroup>
          <Autocomplete.Input placeholder="Name or 0x address" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <Field.Description>A new address. Check it before you send.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '16rem !custom', width: '100% !custom' })
}
```

**Don't:** Clear or reject text because it doesn't match a suggestion.

```tsx
/**
 * Don't example for "Accept Any Typed Value" on the Autocomplete page.
 * Don't clear or reject text because it doesn't match a suggestion.
 * @module
 */
import { Autocomplete, Field, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root invalid {...styles.field()}>
      <Field.Label>Recipient</Field.Label>
      <Autocomplete.Root defaultValue="0x8f3a…c21d" items={recipients}>
        <Autocomplete.InputGroup invalid>
          <Autocomplete.Input aria-invalid placeholder="Name or 0x address" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <Field.Error match>Select a saved recipient</Field.Error>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '16rem !custom', width: '100% !custom' })
}
```

### Suggest Likely Values

* **`items`:** Filters automatically.
* **`filteredItems`:** Accepts items you filter yourself, such as results from a server.

**Do:** List recent, frequent, or saved values first, such as the last few recipients.

```tsx
/**
 * Do example for "Suggest Likely Values" on the Autocomplete page.
 * List recent, frequent, or saved values first, such as the last few recipients.
 * @module
 */
import { style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo', 'treasury.tempo']

// A static copy of the open popup, since the real one portals and opens on input.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.popup()}>
      <div {...styles.label()}>Recent recipients</div>
      {recipients.map((recipient) => (
        <div key={recipient} {...styles.item()}>
          {recipient}
        </div>
      ))}
    </div>
  )
}

namespace styles {
  export const item = style({
    alignItems: 'center',
    display: 'flex',
    minHeight: '40',
    paddingInline: '16',
    typography: 'body.b2Strong',
  })

  export const label = style({
    color: 'content.secondary',
    paddingBlock: '8',
    paddingInline: '16',
    typography: 'body.b3',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    padding: '6px !custom',
    width: '16rem !custom',
  })
}
```

**Don't:** Suggest a list too long to scan without scrolling.

```tsx
/**
 * Don't example for "Suggest Likely Values" on the Autocomplete page.
 * Don't suggest a list too long to scan without scrolling.
 * @module
 */
import { style } from '@tempoxyz/ds'

const recipients = [
  'acme.tempo',
  'alice.tempo',
  'bob.tempo',
  'carol.tempo',
  'dave.tempo',
  'erin.tempo',
  'frank.tempo',
]

// A static copy of the open popup, since the real one portals and opens on input.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    // oxlint-disable-next-line tds/require-scroll-region -- An inert picture of a popup, which never takes focus.
    <div {...styles.popup()}>
      {recipients.map((recipient) => (
        <div key={recipient} {...styles.item()}>
          {recipient}
        </div>
      ))}
    </div>
  )
}

namespace styles {
  export const item = style({
    alignItems: 'center',
    display: 'flex',
    flexShrink: '0 !custom',
    minHeight: '40',
    paddingInline: '16',
    typography: 'body.b2Strong',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    display: 'flex',
    flexDirection: 'column',
    maxHeight: '10rem !custom',
    overflowY: 'auto',
    padding: '6px !custom',
    width: '16rem !custom',
  })
}
```

### Show the Text a Suggestion Inserts

Pressing an `Autocomplete.Item` fills the input with the string form of its `value`.

**Do:** Show the same text in the item that it inserts.

```tsx
/**
 * Do example for "Show the Text a Suggestion Inserts" on the Autocomplete page.
 * Show the same text in the item that it inserts.
 * @module
 */
import { Autocomplete, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

// The popup portals and opens on input, so a static copy shows the picked suggestion.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Autocomplete.Root defaultValue="alice.tempo" items={recipients}>
        <Autocomplete.InputGroup>
          <Autocomplete.Input aria-label="Recipient" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <div {...styles.popup()}>
        <div {...styles.item()}>alice.tempo</div>
      </div>
    </div>
  )
}

namespace styles {
  export const column = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    maxWidth: '16rem !custom',
    width: '100% !custom',
  })

  export const item = style({
    alignItems: 'center',
    display: 'flex',
    minHeight: '40',
    paddingInline: '16',
    typography: 'body.b2Strong',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    padding: '6px !custom',
  })
}
```

**Don't:** Show a name that inserts an address.

```tsx
/**
 * Don't example for "Show the Text a Suggestion Inserts" on the Autocomplete page.
 * Don't show a name that inserts an address.
 * @module
 */
import { Autocomplete, style } from '@tempoxyz/ds'

const recipients = ['0x8f3a…c21d', '0x51b0…9e04']

// The popup portals and opens on input, so a static copy shows the picked suggestion.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Autocomplete.Root defaultValue="0x8f3a…c21d" items={recipients}>
        <Autocomplete.InputGroup>
          <Autocomplete.Input aria-label="Recipient" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <div {...styles.popup()}>
        <div {...styles.item()}>Alice</div>
      </div>
    </div>
  )
}

namespace styles {
  export const column = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    maxWidth: '16rem !custom',
    width: '100% !custom',
  })

  export const item = style({
    alignItems: 'center',
    display: 'flex',
    minHeight: '40',
    paddingInline: '16',
    typography: 'body.b2Strong',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    padding: '6px !custom',
  })
}
```

### Keep Autocomplete.Empty Mounted

`Autocomplete.Empty` shows its children only when nothing matches, and announces them politely. It requires `items` on `Autocomplete.Root`.

**Do:** Keep it mounted, and say that people can continue.

```tsx
/**
 * Do example for "Keep Autocomplete.Empty Mounted" on the Autocomplete page.
 * Keep it mounted, and say that people can continue.
 * @module
 */
import { Autocomplete, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

// The popup portals and opens on input, so a static copy shows it open.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Autocomplete.Root defaultValue="0x8f3a…c21d" items={recipients}>
        <Autocomplete.InputGroup>
          <Autocomplete.Input aria-label="Recipient" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <div {...styles.popup()}>
        <div {...styles.empty()}>No saved recipients. You can still send to this address.</div>
      </div>
    </div>
  )
}

namespace styles {
  export const column = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    maxWidth: '16rem !custom',
    width: '100% !custom',
  })

  export const empty = style({
    color: 'content.secondary',
    paddingBlock: '12',
    paddingInline: '16',
    typography: 'body.b2',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    padding: '6px !custom',
  })
}
```

**Don't:** Hide it. Hiding it stops the announcement.

```tsx
/**
 * Don't example for "Keep Autocomplete.Empty Mounted" on the Autocomplete page.
 * Don't hide it. Hiding it stops the announcement.
 * @module
 */
import { Autocomplete, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

// The popup portals and opens on input, so a static copy shows it open.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Autocomplete.Root defaultValue="0x8f3a…c21d" items={recipients}>
        <Autocomplete.InputGroup>
          <Autocomplete.Input aria-label="Recipient" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
      <div {...styles.popup()} />
    </div>
  )
}

namespace styles {
  export const column = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    maxWidth: '16rem !custom',
    width: '100% !custom',
  })

  export const popup = style({
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    padding: '6px !custom',
  })
}
```

### Add Clear for Long Values

`Autocomplete.Clear` mounts only while there is text.

**Do:** Add `Autocomplete.Clear` to fields with long values, such as addresses.

```tsx
/**
 * Do example for "Add Clear for Long Values" on the Autocomplete page.
 * Add `Autocomplete.Clear` to fields with long values, such as addresses.
 * @module
 */
import { Autocomplete, Field, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Recipient</Field.Label>
      <Autocomplete.Root
        defaultValue="0x8f3a2b7c9d1e4f60a5b3c2d1e0f9a8b7c6d5c21d"
        items={recipients}
      >
        <Autocomplete.InputGroup>
          <Autocomplete.Input placeholder="Name or 0x address" />
          <Autocomplete.Clear />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '16rem !custom', width: '100% !custom' })
}
```

**Don't:** Make people delete a long address one character at a time.

```tsx
/**
 * Don't example for "Add Clear for Long Values" on the Autocomplete page.
 * Don't make people delete a long address one character at a time.
 * @module
 */
import { Autocomplete, Field, style } from '@tempoxyz/ds'

const recipients = ['alice.tempo', 'payroll.tempo']

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Recipient</Field.Label>
      <Autocomplete.Root
        defaultValue="0x8f3a2b7c9d1e4f60a5b3c2d1e0f9a8b7c6d5c21d"
        items={recipients}
      >
        <Autocomplete.InputGroup>
          <Autocomplete.Input placeholder="Name or 0x address" />
        </Autocomplete.InputGroup>
      </Autocomplete.Root>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '16rem !custom', width: '100% !custom' })
}
```

## Content

* **Label:** Use a noun, such as Recipient, or Search for a search field.
* **Placeholder:** Name what people can enter, such as Search actions.
* **Suggestions:** Use the typed format, so a pasted value and a picked one look alike.

## Accessibility

Follows the [WAI-ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) with list autocomplete.

### Semantics

* **Autocomplete.Input (combobox):** A text input that announces a suggestion list and whether it is open.
* **Highlighted Suggestion (aria-activedescendant):** Points to the highlighted suggestion while focus stays in the input.
* **Autocomplete.List and Autocomplete.Item (listbox and option):** Each suggestion is announced as an option inside a listbox.
* **Autocomplete.Group (group):** Named by the `Autocomplete.GroupLabel` inside it, and announced as a group.
* **Autocomplete.Clear (button):** Named "Clear" by default. Renders only while the input has text.

### Keyboard

* **Move to the TextInput (Tab):** Moves focus to the input.
* **Filter the Suggestions (Typing):** Filters the suggestions and opens the list.
* **Highlight the Next Suggestion (Down Arrow):** Opens the list, then highlights the next suggestion.
* **Highlight the Previous Suggestion (Up Arrow):** Highlights the previous one, then the typed text.
* **Choose the Suggestion (Enter):** Enters the highlighted suggestion and closes the list.
* **Close or Clear (Escape):** Closes the list. A second press clears the input.

### Focus

DOM focus stays on the input while the arrow keys highlight suggestions, so typing continues at any point.

### Announcements

* **Highlighted Suggestion (aria-activedescendant):** Each suggestion is announced on highlight.
* **No Matches (Autocomplete.Empty):** Announces "No matches" politely.

### Your Responsibilities

* **Label the TextInput (aria-label):** Name the input with `Field.Label`, or `aria-label` if no label fits. The placeholder disappears.
* **Set aria-invalid on the TextInput (aria-invalid):** The group's `invalid` prop only fills it red. Set the attribute on the input, and explain the error.

## Related

[Combobox](/docs/components/combobox)

Use for choosing from fixed options.

[TextInput](/docs/components/text-input)

Use for text without suggestions.

[Field](/docs/components/field)

Use for the label and error.

[Select](/docs/components/select)

Use for short lists.

[Blockchain Values](/docs/patterns/blockchain-values)

Covers entering and showing addresses.
