# Autocomplete

A text input with suggestions: the WAI-ARIA combobox pattern, with list autocomplete and manual selection. A Combobox picks a value from a list; an Autocomplete is free text with suggestions, such as a search or a city. Its value is the text: typing opens the list and you filter it, by rendering the suggestions that match, with includesText, a separate import that ignores case and accents, or your own search, on the server too. Focus stays in the input, which names the active suggestion in aria-activedescendant: Down and Up move through the suggestions, Enter puts the active one in the input, Escape closes the list and, once it is closed, empties the input. Text that matches no suggestion is kept when focus leaves. The input is the form control itself: it submits the text under name, blocks a submission while required and empty, and follows a form reset. It builds on Combobox: Trigger, Clear, Popup, List, Group, GroupLabel and Status are Combobox's parts, so an app that uses both pays for them once. The Popup is a popover="manual" element, so the browser puts it in the top layer, above every z-index; there is no portal. Menhir places it with Floating UI, below the Input and aligned to its start, and writes --anchor-width and --available-height on it. Name the Autocomplete with a <label> for the Input, and the List with aria-labelledby.

- Entry point: `menhir/autocomplete`
- Size: 10.8 kB, minified and gzipped, Solid left out

> To add Autocomplete to a project, install the packages below with the project's package manager, then copy the example that matches how the project is styled, Tailwind CSS or plain CSS, and adapt its markup and class names to the project.

## Install

```sh
pnpm add menhir solid-js @solidjs/web
```

## Anatomy

```tsx
<label for="city" id="city-label" />
<Autocomplete.Root>
  <Autocomplete.Input id="city" />
  <Autocomplete.Trigger />
  <Autocomplete.Clear />
  <Autocomplete.Popup>
    <Autocomplete.List aria-labelledby="city-label">
      <Autocomplete.Item />
      <Autocomplete.Group>
        <Autocomplete.GroupLabel />
        <Autocomplete.Item />
      </Autocomplete.Group>
    </Autocomplete.List>
    <Autocomplete.Status />
  </Autocomplete.Popup>
</Autocomplete.Root>
```

## Example

### Tailwind CSS

`AutocompleteExample.tsx`:

```tsx
import { Autocomplete, includesText } from "menhir/autocomplete";
import { createMemo, createSignal, For } from "solid-js";

const cities = [
  "Amsterdam",
  "Athens",
  "Berlin",
  "Lisbon",
  "London",
  "Madrid",
  "Oslo",
  "Paris",
  "Rome",
  "Vienna",
];

export default function AutocompleteExample() {
  // The text the user typed, which the suggestions are filtered by. A
  // suggestion the user accepted filters nothing.
  const [query, setQuery] = createSignal("");
  const shown = createMemo(() =>
    cities.filter((city) => includesText(city, query())),
  );
  let field!: HTMLDivElement;
  return (
    <div class="flex flex-col gap-1.5 text-sm">
      <label
        for="autocomplete-city-tailwind"
        id="autocomplete-city-tailwind-label"
      >
        City
      </label>
      <Autocomplete.Root
        name="city"
        onValueChange={(text, { reason }) =>
          setQuery(reason === "input-change" ? text : "")
        }
      >
        <div
          ref={field}
          class="flex w-48 items-center rounded-md border border-stone-300 focus-within:outline-2 focus-within:outline-offset-2 focus-within:outline-stone-500 dark:border-stone-600"
        >
          <Autocomplete.Input
            id="autocomplete-city-tailwind"
            placeholder="Any city"
            class="min-w-0 flex-1 border-0 bg-transparent px-3 py-1.5 text-inherit outline-none"
          />
          <Autocomplete.Clear
            class="cursor-pointer border-0 bg-transparent px-2 text-inherit"
            aria-label="Clear"
          >
            ×
          </Autocomplete.Clear>
        </div>
        <Autocomplete.Popup
          anchor={() => field}
          sideOffset={4}
          class="m-0 box-border max-h-(--available-height) min-w-(--anchor-width) overflow-y-auto rounded-lg border border-stone-200 bg-white p-1 text-sm text-inherit shadow-lg transition-opacity duration-100 data-closed:opacity-0 dark:border-stone-700 dark:bg-stone-900 starting:data-open:opacity-0"
        >
          <Autocomplete.List aria-labelledby="autocomplete-city-tailwind-label">
            <For each={shown()}>
              {(city) => (
                <Autocomplete.Item
                  value={city}
                  class="cursor-default rounded px-2 py-1.5 select-none data-active:bg-stone-100 dark:data-active:bg-stone-800"
                >
                  {city}
                </Autocomplete.Item>
              )}
            </For>
          </Autocomplete.List>
          <Autocomplete.Status class="px-2 py-1.5 opacity-70 empty:hidden">
            {(count) => count === 0 && "No suggestions"}
          </Autocomplete.Status>
        </Autocomplete.Popup>
      </Autocomplete.Root>
    </div>
  );
}
```

### CSS

`AutocompleteExample.tsx`:

```tsx
import { Autocomplete, includesText } from "menhir/autocomplete";
import { createMemo, createSignal, For } from "solid-js";

import "./autocomplete.css";

const cities = [
  "Amsterdam",
  "Athens",
  "Berlin",
  "Lisbon",
  "London",
  "Madrid",
  "Oslo",
  "Paris",
  "Rome",
  "Vienna",
];

export default function AutocompleteExample() {
  // The text the user typed, which the suggestions are filtered by. A
  // suggestion the user accepted filters nothing.
  const [query, setQuery] = createSignal("");
  const shown = createMemo(() =>
    cities.filter((city) => includesText(city, query())),
  );
  let field!: HTMLDivElement;
  return (
    <div class="autocomplete-field">
      <label
        class="autocomplete-label"
        for="autocomplete-city"
        id="autocomplete-city-label"
      >
        City
      </label>
      <Autocomplete.Root
        name="city"
        onValueChange={(text, { reason }) =>
          setQuery(reason === "input-change" ? text : "")
        }
      >
        <div class="autocomplete-box" ref={field}>
          <Autocomplete.Input
            class="autocomplete-input"
            id="autocomplete-city"
            placeholder="Any city"
          />
          <Autocomplete.Clear class="autocomplete-button" aria-label="Clear">
            ×
          </Autocomplete.Clear>
        </div>
        <Autocomplete.Popup
          class="autocomplete-popup"
          anchor={() => field}
          sideOffset={4}
        >
          <Autocomplete.List aria-labelledby="autocomplete-city-label">
            <For each={shown()}>
              {(city) => (
                <Autocomplete.Item class="autocomplete-item" value={city}>
                  {city}
                </Autocomplete.Item>
              )}
            </For>
          </Autocomplete.List>
          <Autocomplete.Status class="autocomplete-status">
            {(count) => count === 0 && "No suggestions"}
          </Autocomplete.Status>
        </Autocomplete.Popup>
      </Autocomplete.Root>
    </div>
  );
}
```

`autocomplete.css`:

```css
/* The least CSS that makes the Autocomplete look like one: a box with the
   input and its clear button, and a card below it, as wide as the box at
   least (--anchor-width, the Popup's anchor is the box) and no taller than
   the space left (--available-height). Menhir places the popup; the
   suggestion the keys or the pointer reached has data-active. The Status is
   empty unless no suggestion matches. The popup fades in on data-open and
   out on data-closed. Colours are Tailwind's stone palette; light-dark()
   picks the second one in dark mode (color-scheme: dark). */
.autocomplete-field {
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
  font:
    0.875rem system-ui,
    sans-serif;
}

.autocomplete-box {
  display: flex;
  align-items: center;
  width: 12rem;
  border: 1px solid
    light-dark(
      oklch(86.9% 0.005 56.366) /* stone-300 */,
      oklch(44.4% 0.011 73.639) /* stone-600 */
    );
  border-radius: 0.375rem;
}

.autocomplete-box:focus-within {
  outline: 2px solid oklch(55.3% 0.013 58.071) /* stone-500 */;
  outline-offset: 2px;
}

.autocomplete-input {
  flex: 1;
  min-width: 0;
  padding: 0.375rem 0.75rem;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  outline: none;
}

.autocomplete-button {
  padding: 0 0.5rem;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  cursor: pointer;
}

.autocomplete-popup {
  box-sizing: border-box;
  min-width: var(--anchor-width);
  max-height: var(--available-height);
  margin: 0;
  padding: 0.25rem;
  overflow-y: auto;
  border: 1px solid
    light-dark(
      oklch(92.3% 0.003 48.717) /* stone-200 */,
      oklch(37.4% 0.01 67.558) /* stone-700 */
    );
  border-radius: 0.5rem;
  background: light-dark(white, oklch(21.6% 0.006 56.043) /* stone-900 */);
  color: inherit;
  font:
    0.875rem system-ui,
    sans-serif;
  box-shadow: 0 4px 12px oklch(0% 0 0 / 10%);
}

.autocomplete-popup[data-open] {
  animation: autocomplete-in 120ms ease-out;
}

.autocomplete-popup[data-closed] {
  animation: autocomplete-in 120ms ease-in reverse;
}

@keyframes autocomplete-in {
  from {
    opacity: 0;
  }
}

.autocomplete-item {
  padding: 0.375rem 0.5rem;
  border-radius: 0.25rem;
  cursor: default;
  user-select: none;
}

.autocomplete-item[data-active] {
  background: light-dark(
    oklch(97% 0.001 106.424) /* stone-100 */,
    oklch(26.8% 0.007 34.298) /* stone-800 */
  );
}

.autocomplete-status:not(:empty) {
  padding: 0.375rem 0.5rem;
  opacity: 0.7;
}
```

## API reference

### Root

Holds the text, which is the value, and the open state, and renders no element. The Input, the Trigger and the Popup have data-open or data-closed, data-disabled and data-required.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | — | The text in the input, when controlled. Pair it with onValueChange. |
| `defaultValue` | `string` | `""` | The text at first, when uncontrolled. The server HTML shows it, and a form reset goes back to it. |
| `onValueChange` | `(text: string, details: { reason, event }) => void` | — | Called with the new text, and why: "input-change" (the user typed), "item-press" (a suggestion was accepted, and the text is its value), "escape-key" or "clear-press" (emptied) or "reset". Filter by the text for "input-change" only, and show every suggestion otherwise, so the list shows them all after one is accepted. A controlled Autocomplete changes only if value does. |
| `open` | `boolean` | — | Whether the list is open, when controlled. Pair it with onOpenChange. |
| `defaultOpen` | `boolean` | `false` | Whether the list is open at first, when uncontrolled. |
| `onOpenChange` | `(open: boolean, details: { reason, event }) => void` | — | Called with the new value when the user opens or closes the list, and why: "input-change" (typing opened it), "arrow-key" (Down, Up, Alt + Down or Alt + Up), "trigger-press", "item-press" (a suggestion was accepted), "enter-key" (Enter with no suggestion active), "escape-key" or "focus-out" (focus left the input, as a press outside does). A controlled Autocomplete changes only if open does. |
| `name` | `string` | — | The name the text is submitted under, with the form. |
| `form` | `string` | — | The id of the form the Autocomplete belongs to, when it is not inside it. |
| `required` | `boolean` | — | Whether the form can be submitted only with some text, which the browser checks on the Input. |
| `disabled` | `boolean` | — | Whether the Autocomplete ignores the user: the Input and the buttons are disabled, and the text is not submitted. |

### Input

<input type="text" role="combobox" aria-autocomplete="list" autocomplete="off"> with aria-expanded, with aria-controls naming the List, and with aria-activedescendant naming the active suggestion. It keeps focus while the list is open. It is the form control: it takes name, form, required and disabled from the Root. Takes your id, for a <label for>.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `autocomplete` | `string` | `"off"` | What the browser may suggest. Off by default, so its own list does not cover the Autocomplete's. |
| `render` | `(props) => JSX.Element` | — | Renders the input with your own component. Read once. |

### Trigger

Combobox's Trigger: a <button type="button" tabindex="-1"> that opens and closes the list and focuses the input, with aria-expanded and aria-controls naming the List. Name it with aria-label. Its render function must render a <button>.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the trigger with your own button component. Read once. |

### Clear

Combobox's Clear: a <button type="button" tabindex="-1"> that empties the text and focuses the input, as Escape on a closed list does. Name it with aria-label. Its render function must render a <button>.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the button with your own button component. Read once. |

### Popup

Combobox's Popup: a <div popover="manual">, placed against the Input, around the List and the Status, with side, align, sideOffset, alignOffset, collisionPadding and anchor as on Combobox's page. It takes no focus, and a press in it moves none. It has the CSS variables --anchor-width and --available-height.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the popup with your own component. Read once. |

### List

Combobox's List: a <div role="listbox"> around the suggestions, with a generated id for the Input to name. Name it with aria-labelledby, such as the id of the input's <label>, or aria-label.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the list with your own component. Read once. |

### Item

<div role="option">, a suggestion, with aria-selected="true" and data-active while it is the active one, and no aria-selected otherwise: there is no selected item, only the text. A click puts its value in the input and closes the list. Takes your id, else a generated one. Render the suggestions that match the text.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | — | The text it puts in the input when accepted. Its content may differ, such as an icon or a highlighted match. |
| `disabled` | `boolean` | — | Whether it is disabled: the keys and the pointer still reach it, but it is not accepted. |
| `render` | `(props) => JSX.Element` | — | Renders the item with your own component. Read once. |

### Group

Combobox's Group: a <div role="group"> for suggestions that belong together, named by its GroupLabel.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the group with your own component. Read once. |

### GroupLabel

Combobox's GroupLabel: a <div> that names its Group. The keys do not reach it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the label with your own component. Read once. |

### Status

Combobox's Status: a <div role="status">, a polite live region, with what its function returns for the number of suggestions while the list is open, and nothing while it is closed. Beside the List, it is the message for no suggestions; visually hidden beside the Input, it tells a screen reader how many match.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `(count: number) => JSX.Element` | — | What it says for the number of suggestions, such as (count) => count === 0 && "No suggestions". Menhir writes no text of its own. |
| `render` | `(props) => JSX.Element` | — | Renders the status with your own component. Read once. |

## Keyboard

| Keys | Action |
| --- | --- |
| `A character` | Types it and opens the list, with no suggestion active: filter the suggestions by the text. |
| `Down Arrow` | Closed, opens the list on the first suggestion; with Alt, opens it with none active. Open, moves to the next suggestion, and from the last to the first. |
| `Up Arrow` | Closed, opens the list on the last suggestion. Open, moves to the previous one, and from the first to the last; with Alt, closes the list. |
| `Enter` | Puts the active suggestion in the input and closes the list. With none active, closes the list, and a form submits. |
| `Escape` | Closes the list and keeps the text. On a closed list, empties the text. |
| `Home, End, Left Arrow, Right Arrow` | Move the caret in the text, as in any text input. |
| `Tab, Shift + Tab` | Closes the list, keeps the text and moves focus on. |
