# Combobox

> A text input that filters a list of Options as you type.

`<slab-combobox>` · Selection · built on `<input role=combobox>`

## Install

```sh
pnpm add slab-elements lit
```

## Usage

```html
<script type="module">
  import 'slab-elements/combobox.js';
</script>

<slab-combobox label="Language" name="language">
  <slab-option value="en">English</slab-option>
  <slab-option value="es">Spanish</slab-option>
  <slab-option value="fr">French</slab-option>
</slab-combobox>
```

## Example

Here's a styled version, `<slab-styled-combobox>`. It's not in the package — it's an example of what you can build with the headless element. Copy it and make it yours at the bottom of this page.

```html
<slab-styled-combobox label="Supplier" placeholder="Start typing a name">
  <slab-styled-option value="alder">Alder Ready-Mix</slab-styled-option>
  <slab-styled-option value="basalt">Basalt Concrete Co.</slab-styled-option>
  <slab-styled-option value="cascade">Cascade Aggregates</slab-styled-option>
  <slab-styled-option value="delta">Delta Batch Plant</slab-styled-option>
  <slab-styled-option value="eagle" disabled>Eagle Rock Materials</slab-styled-option>
</slab-styled-combobox>
```

Swap `slab-styled-` for `slab-` in that markup and you've got the same example as it ships: the headless elements with no CSS at all. That's your starting point.

Its Options are the same ones [Listbox](listbox.md) uses.

## Keyboard

| Key       | What it does                                                                                    |
| --------- | ----------------------------------------------------------------------------------------------- |
| Up, Down  | Opens the listbox and moves the active Option, stopping at each end and skipping disabled ones. |
| Alt+Down  | Opens the listbox without moving.                                                               |
| Alt+Up    | Closes the listbox.                                                                             |
| Enter     | Selects the active Option and closes the listbox.                                               |
| Escape    | Closes the listbox, and a second Escape clears the input.                                       |
| Home, End | Move the caret, as in any input.                                                                |

## Behavior

A text input that filters a list of Options as it's typed into, with no visual styles. It's the APG's editable combobox with list autocomplete.

Not `<input list>`. A `<datalist>` holds only text, can't be styled, and is drawn differently by every browser, down to whether it filters by prefix or by substring. So this is a real `<input role="combobox">` with a `<div role="listbox">` of slotted Options in a popover beside it.

The listbox is its own rather than a nested Listbox. A Listbox has a label, a Tab stop and a form value of its own, all of which a Combobox would have to switch off. What it shares with Listbox is Option, OptionsController, and the way the active Option is pointed at rather than focused: focus stays in the input, and the input's `aria-activedescendant` is set as an element, since an IDREF can't reach the slotted Options. Read or set it with `activeOption`.

Typing filters the Options by `filter`, a case-insensitive substring of each Option's text unless it's replaced, and opens the listbox. An Option that doesn't match is hidden, so it's out of the accessibility tree and skipped by the arrow keys. With none left, the listbox closes and the host matches `:state(empty)`, for a "no results" message of your own.

ArrowDown and ArrowUp open the listbox and move the active Option, stopping at each end and skipping disabled Options. Alt with ArrowDown opens it without moving, and Alt with ArrowUp closes it. Enter and a click select the active Option and close the listbox. Escape closes it, and a second Escape clears the input. Home, End and the other caret keys stay the input's. A click or Tab elsewhere closes it, since either takes focus from the input.

`value` is the selected Option's value, not what's in the input, which shows that Option's text. Unless `allow-custom` is set, what's typed has to name an Option: when focus leaves, text that matches one's (ignoring case) selects it, an empty input clears the selection, and anything else goes back to the selected Option's text. With `allow-custom`, text that matches no Option is the value as typed. Either way, `value` is what's submitted, and "input" and "change" are dispatched together when it changes, as on a `<select>`, rather than on every keystroke.

Style it through its parts and through `:state(disabled)`, `:state(empty)`, `:state(error)`, `:state(open)` and `:state(required)`, and each Option through `:state(active)`, `:state(disabled)` and `:state(selected)`.

## API

### `<slab-combobox>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  |  |
| `allow-custom` | `boolean` | `false` | Lets the value be text that matches no Option. |
| `disabled` | `boolean` | `false` |  |
| `hide-label` | `boolean` | `false` |  |
| `name` | `string` | `''` |  |
| `open` | `boolean` | `false` |  |
| `placeholder` | `string` |  |  |
| `placement` | `'bottom' \| 'top'` | `'bottom'` | The side of the input the listbox opens on, when there's room. It flips when there isn't. |
| `required` | `boolean` | `false` |  |
| `value` | `string` | `''` | The selected Option's value, or the typed text when `allow-custom` is set and it matches no Option. Setting it selects the Option with that value. Like a native input, the attribute is the default value and the property is the current one. |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `filter` | `(option: Option, query: string) => boolean` | Whether an Option matches what's been typed. A case-insensitive substring of its text by default. |
| `activeOption` | `Option \| null` | The Option the user is on, which Enter selects. It's pointed at rather than focused, so focus stays in the input. |
| `form` (read-only) | `HTMLFormElement \| null` |  |
| `options` (read-only) | `Option[]` |  |
| `selectedOption` (read-only) | `Option \| null` |  |
| `validity` (read-only) | `ValidityState` |  |

#### Methods

| Signature | Description |
| --- | --- |
| `checkValidity(): boolean` |  |
| `focus(options?: FocusOptions): void` |  |
| `reportValidity(): boolean` |  |
| `resetValidityFeedback(): void` | Clears the validity feedback without changing `validity`. |
| `setCustomValidity(message: string): void` |  |
| `setValidity(flags?: ValidityStateFlags, message?: string): void` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `input` | `Event` |  |
| `change` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `Option` |  |
| `description` | `Element \| string` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `description` | Text about the Combobox, and its validity message when it has one |
| `input` |  |
| `label` | The label |
| `listbox` | The Options, in a popover beside the input |
| `validity-message` |  |

## Copy and own it

`<slab-styled-combobox>` isn't in the package. It's an example — copy it into your project and change whatever you want. Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. Keyboard, focus, ARIA, forms, and events all come from the headless element, and the styles only reach in through `::part()` and `:state()`, same as yours would.

To use it, copy these files, swap the tag in `@customElement()` for one of your own, and import it. `tokens.styles.ts` holds the colors and fonts every styled example shares, so you only need it once.

### TypeScript

These files are TypeScript, and `@customElement()` is one of Lit's decorators (TypeScript's experimental flavor). You'll need two options in your tsconfig, per [Lit's docs](https://lit.dev/docs/components/decorators/#decorators-typescript): `experimentalDecorators` to compile them, and `useDefineForClassFields` turned off so class fields don't stomp on the accessors Lit sets up.

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "useDefineForClassFields": false
  }
}
```

Using plain JavaScript? Drop the types and register the class with `customElements.define()` instead of the decorator.

### combobox.ts

```ts
import { customElement } from 'lit/decorators.js';
import Combobox from 'slab-elements/combobox.js';
import textInput from './text-input.styles.js';
import styles from './combobox.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-combobox': StyledCombobox;
  }
}

/**
 * Combobox, styled: Text Field's input, with its Options in a panel that
 * casts a hard shadow, as Select's do.
 */
@customElement('slab-styled-combobox')
export default class StyledCombobox extends Combobox {
  static override styles = [tokens, textInput, styles];
}
```

### text-input.styles.ts

```ts
import { css } from 'lit';

/*
  The look shared by everything typed into: Text Field, Textarea, Number, Date
  Field and Combobox, whose fields are "::part(input)", or "::part(textarea)"
  for Textarea. File Drop starts from it too, for its label and description.
*/
export default css`
  :host {
    color: var(--ink);
    display: grid;
    font-family: var(--font-body);
  }

  [part~='label'] {
    font-family: var(--font-display);
    font-size: 1.0625rem;
    font-weight: 600;
    margin-block-end: 0.375rem;
  }

  :host(:state(required)) [part~='label']::after {
    color: var(--ember-deep);
    content: ' *' / '';
  }

  [part~='input'],
  [part~='textarea'] {
    background-color: var(--paper);
    block-size: 3rem;
    border: var(--border);
    border-radius: 0;
    box-sizing: border-box;
    color: inherit;
    font: inherit;

    /* A fixed height, shared with Select, so fields line up in a row. */
    padding: 0 0.75rem;
    transition:
      background-color 100ms,
      border-color 100ms,
      box-shadow 100ms,
      translate 100ms;

    &::placeholder {
      color: var(--ash);
    }

    /*
      The outline is transparent rather than gone, so it still shows in forced
      colors, where box shadows don't.
    */
    &:focus-visible {
      box-shadow: 4px 4px 0 var(--ember);
      outline: 2px solid transparent;
      translate: -2px -2px;
    }

    &:disabled {
      background-color: var(--chalk);
      border-style: dashed;
      color: var(--ash);
      cursor: not-allowed;
    }
  }

  [part~='textarea'] {
    block-size: auto;
    min-block-size: 7rem;
    padding: 0.625rem 0.75rem;
    resize: vertical;
  }

  :host(:state(readonly)) [part~='input'],
  :host(:state(readonly)) [part~='textarea'] {
    background-color: var(--chalk);
  }

  :host(:state(error)) [part~='input'],
  :host(:state(error)) [part~='textarea'] {
    border-color: var(--ember-deep);
  }

  /*
    Spaced by what's in it rather than by a gap, so a description with
    nothing in it takes no room, and a control beside the field lines up
    with its bottom edge.
  */
  [part~='description'] {
    color: var(--ash);
    display: grid;
    font-size: 0.875rem;
  }

  ::slotted([slot='description']) {
    margin-block-start: 0.375rem;
  }

  [part~='validity-message'] {
    color: var(--ember-deep);
    font-weight: 600;
    margin-block-start: 0.375rem;

    &::before {
      content: '■ ' / '';
    }
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='input'],
    [part~='textarea'] {
      transition: none;
    }
  }
`;
```

### combobox.styles.ts

```ts
import { css } from 'lit';

/*
  Text Field's input, with the listbox in a panel beside it like Select's.
  The listbox is a popover, so a closed one isn't displayed, and its entrance
  runs each time it opens.
*/
export default css`
  [part~='listbox'] {
    animation: drop 150ms ease-out;
    background-color: var(--paper);
    border: var(--border);
    box-shadow: var(--shadow);
    box-sizing: border-box;
    color: var(--ink);
    margin-block: 0.5rem;
    max-block-size: 18rem;
    min-inline-size: anchor-size(inline);
    overflow-y: auto;
    padding: 0.25rem 0;
  }

  @keyframes drop {
    from {
      opacity: 0;
      translate: 0 -0.375rem;
    }
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='listbox'] {
      animation: none;
    }
  }
`;
```

### tokens.styles.ts

```ts
import { css } from 'lit';

/*
  The styled components' palette and type, taken from the logo: ink for the
  courses, ember for the base, paper behind them.

  Each is a short alias for a "--slab-styled-*" property, with the default as
  its fallback. Retheming is "--slab-styled-ember" and the rest on ":root",
  which every shadow root inherits. Were the defaults declared under those
  names here instead, each host's own declaration would shadow the page's.

  Each default is "light-dark()", so the components follow the page's
  "color-scheme": "dark" for dark, "light" for light, and "light dark" to
  follow the operating system. Ink and paper trade places in the dark, so
  ink is always the text and paper always what's behind it. Contrast is given
  as light, then dark.
*/
export default css`
  :host {
    /* Secondary text. 6.8:1 and 6.9:1 on paper. */
    --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
    --border: 2px solid var(--ink);

    /* Behind disabled and read-only controls, and hovered rows. */
    --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

    /*
      The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
      enough for borders, fills and large text, but not always for small text,
      which takes "--ember-deep".
    */
    --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

    /*
      Orange for small text on paper, and for paper text on it. 5.7:1 and
      7.4:1.
    */
    --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
    --font-body: var(
      --slab-styled-font-body,
      'IBM Plex Sans',
      system-ui,
      sans-serif
    );
    --font-display: var(
      --slab-styled-font-display,
      'Zilla Slab',
      rockwell,
      'Roboto Slab',
      serif
    );
    --font-mono: var(
      --slab-styled-font-mono,
      'IBM Plex Mono',
      ui-monospace,
      monospace
    );
    --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
    --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

    /* The hard, offset shadow a raised surface casts. */
    --shadow: 4px 4px 0 var(--ink);
  }
`;
```
