Menhir

Combobox

View as Markdown

An input that picks one value out of a list: the WAI-ARIA combobox pattern, with list autocomplete and manual selection. Typing opens the list and you filter it: render the items that match the text, 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 item in aria-activedescendant: Down and Up move through the items, Enter selects the active one and puts its label in the input, Escape closes the list and, once it is closed, empties the input. When focus leaves, the text goes back to the selected item's label. A form control: a visually hidden input beside the Input submits the selected value under name, not the text, blocks a submission while required and empty, and follows a form reset. 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 keeps it shown until its exit animation has ended. It writes --anchor-width and --available-height on the Popup: use them for its min-width and max-height. Name the Combobox with a <label> for the Input, and the List with aria-labelledby.

Size
11.6 kB

Example

Styling
Apple
Apricot
Banana
Blueberry
Cherry
Grape
Lemon
Mango
Pear
ComboboxExample.tsx
import { Combobox, includesText } from "menhir/combobox";
import { createMemo, createSignal, For } from "solid-js";

const fruits = [
  { value: "apple", label: "Apple" },
  { value: "apricot", label: "Apricot" },
  { value: "banana", label: "Banana" },
  { value: "blueberry", label: "Blueberry" },
  { value: "cherry", label: "Cherry" },
  { value: "grape", label: "Grape" },
  { value: "lemon", label: "Lemon" },
  { value: "mango", label: "Mango" },
  { value: "pear", label: "Pear" },
];

const button = "cursor-pointer border-0 bg-transparent px-2 text-inherit";

export default function ComboboxExample() {
  // The text the user typed, which the list is filtered by. A label the
  // Combobox puts in the input, after a selection, filters nothing.
  const [query, setQuery] = createSignal("");
  const shown = createMemo(() =>
    fruits.filter((fruit) => includesText(fruit.label, query())),
  );
  let field!: HTMLDivElement;
  return (
    <div class="flex flex-col gap-1.5 text-sm">
      <label for="combobox-fruit-tailwind" id="combobox-fruit-tailwind-label">
        Fruit
      </label>
      <Combobox.Root
        name="fruit"
        onInputValueChange={(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"
        >
          <Combobox.Input
            id="combobox-fruit-tailwind"
            placeholder="Pick a fruit"
            class="min-w-0 flex-1 border-0 bg-transparent px-3 py-1.5 text-inherit outline-none"
          />
          <Combobox.Clear class={button} aria-label="Clear">
            ×
          </Combobox.Clear>
          <Combobox.Trigger class={button} aria-label="Show fruits">
            ▾
          </Combobox.Trigger>
        </div>
        <Combobox.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"
        >
          <Combobox.List aria-labelledby="combobox-fruit-tailwind-label">
            <For each={shown()}>
              {(fruit) => (
                <Combobox.Item
                  value={fruit.value}
                  class="flex cursor-default items-center gap-2 rounded px-2 py-1.5 select-none data-active:bg-stone-100 dark:data-active:bg-stone-800"
                >
                  <Combobox.ItemIndicator class="w-3 data-unselected:invisible">
                    ✓
                  </Combobox.ItemIndicator>
                  {fruit.label}
                </Combobox.Item>
              )}
            </For>
          </Combobox.List>
          <Combobox.Status class="px-2 py-1.5 opacity-70 empty:hidden">
            {(count) => count === 0 && "No fruit found"}
          </Combobox.Status>
        </Combobox.Popup>
      </Combobox.Root>
    </div>
  );
}

Anatomy

<label for="fruit" id="fruit-label" />
<Combobox.Root>
  <Combobox.Input id="fruit" />
  <Combobox.Trigger />
  <Combobox.Clear />
  <Combobox.Popup>
    <Combobox.List aria-labelledby="fruit-label">
      <Combobox.Item>
        <Combobox.ItemIndicator />
      </Combobox.Item>
      <Combobox.Group>
        <Combobox.GroupLabel />
        <Combobox.Item />
      </Combobox.Group>
    </Combobox.List>
    <Combobox.Status />
  </Combobox.Popup>
</Combobox.Root>

API reference

Root

Holds the value, the text in the input 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.

PropTypeDefaultDescription
valuestring | null—The selected item's value, when controlled; null selects none. Pair it with onValueChange.
defaultValuestring | nullnullThe selected item's value at first, when uncontrolled. A form reset goes back to it.
onValueChange(value: string | null) => void—Called with the new value when the user selects an item or empties the Combobox, or the form is reset. A controlled Combobox changes only if value does.
inputValuestring—The text in the input, when controlled. Pair it with onInputValueChange.
defaultInputValuestring—The text at first, when uncontrolled. Without it, the input shows the selected item's label once the items have mounted, and nothing in the server HTML: give it the label of defaultValue when you render on the server.
onInputValueChange(text: string, details: { reason, event }) => void—Called with the new text, and why: "input-change" (the user typed), "item-press" (an item was selected, and the text is its label), "escape-key" or "clear-press" (emptied), "focus-out" (focus left, and the text went back to the selected item's label) or "reset". Filter by the text for "input-change" only, and show every item otherwise, so the list shows them all after a selection. A controlled Combobox changes only if inputValue does.
openboolean—Whether the list is open, when controlled. Pair it with onOpenChange.
defaultOpenbooleanfalseWhether 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" (an item was selected), "enter-key" (Enter with no item active), "escape-key" or "focus-out" (focus left the input, as a press outside does). A controlled Combobox changes only if open does.
namestring—The name the selected value is submitted under, with the form.
formstring—The id of the form the Combobox belongs to, when it is not inside it.
requiredboolean—Whether the form can be submitted only once an item is selected; text alone is not enough. The Input has aria-required.
disabledboolean—Whether the Combobox ignores the user: the Input and the buttons are disabled, and the value 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 item. It keeps focus while the list is open. Takes your id, for a <label for>. The hidden input follows it.

PropTypeDefaultDescription
autocompletestring"off"What the browser may suggest. Off by default, so its own list does not cover the Combobox's.
render(props) => JSX.Element—Renders the input with your own component. Read once.

Trigger

<button type="button" tabindex="-1"> that opens and closes the list and focuses the input, for the pointer and touch, with aria-expanded and aria-controls naming the List. Out of the tab order, since the input takes the keys; a press leaves focus in the input. Name it with aria-label. Its render function must render a <button>.

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the trigger with your own button component. Read once.

Clear

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

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the button with your own button component. Read once.

Popup

<div popover="manual">, placed against the Input, around the List and the Status. It takes no focus, and a press in it moves none. It has the CSS variables --anchor-width, the Input's width, and --available-height, the space left in the viewport.

PropTypeDefaultDescription
side"top" | "right" | "bottom" | "left""bottom"The side of the Input it is placed against. It moves to the other side when it does not fit, and data-side says where it went.
align"start" | "center" | "end""start"Where along that side it sits. start and end follow the writing direction.
sideOffsetnumber0The gap between the Input and the Popup, in pixels.
alignOffsetnumber0The shift along the Input's side, in pixels.
collisionPaddingnumber5The space it keeps from the viewport's edges, in pixels.
anchorElement | VirtualElement | (() => Element | VirtualElement | undefined)—What it is placed against instead of the Input, such as a box around the Input and its buttons: an element, a virtual element with a getBoundingClientRect(), or a function returning one, for an element you hold in a ref.
render(props) => JSX.Element—Renders the popup with your own component. Read once.

List

<div role="listbox"> around the items, 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: labelled by the input, it would be named by the text.

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the list with your own component. Read once.

Item

<div role="option"> with aria-selected and data-selected or data-unselected. A click selects it, puts its label in the input and closes the list. Takes your id, else a generated one. Render the items that match the text; an item that leaves the list leaves the keys.

PropTypeDefaultDescription
valuestring—The Combobox's value while this item is selected. Required, and not an empty string.
disabledboolean—Whether it is disabled: the keys and the pointer still reach it, but it is not selected.
labelstring—Its text, when its content is not its label, such as an icon beside it: what the input shows once it is selected.
render(props) => JSX.Element—Renders the item with your own component. Read once.

ItemIndicator

aria-hidden <span> with its item's data-selected or data-unselected, always rendered: show a check mark by state with CSS.

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the indicator with your own component. Read once.

Group

<div role="group"> for items that belong together, named by its GroupLabel.

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the group with your own component. Read once.

GroupLabel

<div> that names its Group. The keys do not reach it. Takes your id, else a generated one.

PropTypeDefaultDescription
render(props) => JSX.Element—Renders the label with your own component. Read once.

Status

<div role="status">, a polite live region, with what its function returns for the number of items while the list is open, and nothing while it is closed. Beside the List, it is the message for an empty list; visually hidden beside the Input, it tells a screen reader how many items match. For items that load, put it in a <Loading> and read isPending(() => results()) in its function to say a search is in flight.

PropTypeDefaultDescription
children(count: number) => JSX.Element—What it says for the number of items, such as (count) => count === 0 && "No fruit found". Menhir writes no text of its own.
render(props) => JSX.Element—Renders the status with your own component. Read once.

Keyboard

KeysAction
A characterTypes it and opens the list, with no item active: filter the items by the text.
Down ArrowClosed, opens the list on the first item; with Alt, opens it with no item active. Open, moves to the next item, and from the last to the first.
Up ArrowClosed, opens the list on the last item. Open, moves to the previous item, and from the first to the last; with Alt, closes the list.
EnterSelects the active item, puts its label in the input and closes the list. With no item active, closes the list, and a form submits.
EscapeCloses the list and keeps the text. On a closed list, empties the text and the value.
Home, End, Left Arrow, Right ArrowMove the caret in the text, as in any text input.
Tab, Shift + TabCloses the list without selecting and moves focus on; the text goes back to the selected item's label.