# MultiSelect

A button that shows what is selected and opens a listbox in which each pick toggles one option (the WAI-ARIA "select-only combobox" with a multi-select listbox). The platform has no styleable multi-select drop-down in any stable engine yet, so this is the library's own listbox on a `popover="auto"`, built on the machinery of [Combobox multiple](combobox.md#multiple) without the text input. Focus stays on the button; the active option moves with `aria-activedescendant`.

## Anatomy

```tsx
import { MultiSelect } from "@funstack/ui/multi-select";

<MultiSelect.Root name="toppings" defaultValue={["ham"]} required valueChangeAction={saveToppings}>
  <MultiSelect.Label>Toppings</MultiSelect.Label>                 {/* label[for] */}
  <MultiSelect.Trigger className="select">                         {/* button[role=combobox] */}
    <MultiSelect.Value placeholder="Choose toppings">              {/* span */}
      {({ value }) => value.map((v) => toppingNames[v]).join(", ")}
    </MultiSelect.Value>
  </MultiSelect.Trigger>
  <MultiSelect.Popup className="listbox">                          {/* div[popover=auto] */}
    <MultiSelect.List>                                             {/* div[role=listbox][aria-multiselectable] */}
      <Suspense fallback={<MultiSelect.Status>Loading…</MultiSelect.Status>}>
        <ToppingOptions />                                         {/* MultiSelect.Option… */}
      </Suspense>
    </MultiSelect.List>
    <MultiSelect.Empty>No toppings today.</MultiSelect.Empty>
  </MultiSelect.Popup>
</MultiSelect.Root>
```

- **The Trigger is the combobox.** A `<button>` with `role="combobox"`: the one Tab stop, named by the Label (its content is its _value_, so it needs a Label or an `aria-label`; development warns). Keep its content non-interactive: a button may not contain buttons, which is why there are no removable chips here.
- **Value shows what you render.** The library keeps no item list and the options are not rendered while the listbox is closed, so for a preselected value it does not know a name until the option was seen once (never in the server HTML). Pass function `children` with your own names, as above. While the selection is empty it shows `placeholder` when you give one, whatever `children` is (a function is not called), so the function needs no empty branch: `children` describes the selection, `placeholder` its absence. Without children it shows the labels it has seen joined with `", "` (the raw value for one it has not). After a language switch those are the old names until the listbox shows the options again: render your own names, or remount the Root with `key={locale}`.
- **Popup and List are separate** because a listbox may contain only options and groups: `Empty` and a hint `Status` go in the Popup, outside the List. A `Status` inside the List (the Suspense fallback) marks it as loading: `aria-busy="true"`, `Empty` hidden, and the first active option set once the options arrive.
- **No portal, no positioner.** The Popup is shown with `showPopover({ source: trigger })`: the Trigger is its implicit anchor, and after hydration it is the popup's [invoker](../concepts/browser-owned-state.md#popup-triggers) (every click cancelled), so pressing it while the listbox is open closes it as a request instead of a light dismiss.

```tsx title="MultiSelectToppings.tsx"
"use client";
import { Suspense, startTransition, use, useState } from "react";
import { MultiSelect } from "@funstack/ui/multi-select";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave, sleep } from "./fake-api.js";

interface Topping {
  readonly id: string;
  readonly name: string;
  readonly soldOut?: boolean;
}

// The names the Trigger shows, known on the server before the listbox ever opens: the library
// keeps no item list, so a preselected value has no label until its option was rendered once.
const NAMES: Record<string, string> = {
  ham: "Ham",
  mushroom: "Mushroom",
  olive: "Olive",
  onion: "Onion",
  pepper: "Pepper",
  pineapple: "Pineapple",
};

// A pretend menu API, loaded when the listbox first opens. One cached promise, read with `use()`.
let menu: Promise<readonly Topping[]> | null = null;
function loadToppings(): Promise<readonly Topping[]> {
  menu ??= sleep(1200).then(() => [
    { id: "ham", name: "Ham" },
    { id: "mushroom", name: "Mushroom" },
    { id: "olive", name: "Olive" },
    { id: "onion", name: "Onion" },
    { id: "pepper", name: "Pepper", soldOut: true },
    { id: "pineapple", name: "Pineapple" },
  ]);
  return menu;
}

function ToppingOptions() {
  const toppings = use(loadToppings());
  return toppings.map((t) => (
    <MultiSelect.Option
      key={t.id}
      value={t.id}
      disabled={t.soldOut}
      className="demo-multi-select-option"
    >
      {({ pending }) => (
        <>
          {t.name}
          {t.soldOut && <span className="demo-multi-select-note"> (sold out)</span>}
          {pending && <span className="demo-spinner" aria-hidden />}
        </>
      )}
    </MultiSelect.Option>
  ));
}

// The options suspend the first time the listbox opens: the List shows the Status fallback and is
// `aria-busy`; when they arrive the first selected option becomes active. A pick toggles one
// option, the listbox stays open, and each pick is its own save with the option `data-pending`.
// A failed save rolls back that pick only.
export function MultiSelectToppings() {
  const [saved, setSaved] = useState<string[]>(["ham", "olive"]);
  const [fail, setFail] = useState(false);
  return (
    <div className="demo-stack">
      <DemoErrorBoundary>
        <MultiSelect.Root
          name="toppings"
          defaultValue={["ham", "olive"]}
          valueChangeAction={async (_next, { added, removed }) => {
            // Persist the diff, not `next`: an earlier pick may still fail.
            await fakeSave(`+${added.join(",")} -${removed.join(",")}`, { fail });
            startTransition(() =>
              setSaved((prev) => [
                ...prev.filter((v) => !removed.includes(v)),
                ...added.filter((v) => !prev.includes(v)),
              ]),
            );
          }}
        >
          <MultiSelect.Label className="demo-field">Toppings</MultiSelect.Label>
          <MultiSelect.Trigger className="demo-multi-select-trigger">
            <MultiSelect.Value placeholder="Choose toppings">
              {({ value }) => value.map((v) => NAMES[v] ?? v).join(", ")}
            </MultiSelect.Value>
            <span className="demo-multi-select-chevron" aria-hidden>
              ▾
            </span>
          </MultiSelect.Trigger>
          <MultiSelect.Popup className="demo-multi-select-popup">
            <MultiSelect.List>
              <Suspense
                fallback={
                  <MultiSelect.Status className="demo-multi-select-status">
                    Loading the menu…
                  </MultiSelect.Status>
                }
              >
                <ToppingOptions />
              </Suspense>
            </MultiSelect.List>
          </MultiSelect.Popup>
        </MultiSelect.Root>
      </DemoErrorBoundary>
      <label>
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> Make
        the save fail
      </label>
      <output className="demo-readout">
        saved: <code>{JSON.stringify(saved)}</code>
      </output>
    </div>
  );
}
```

```css title="multi-select.css"
/* MultiSelect: the Trigger is a <button role="combobox"> that shows the selection; the Popup is a
   <div popover="auto"> placed below it by the library's inline anchor positioning; the List inside
   is a multiselectable listbox. The active option (virtual focus) carries `data-active`, a
   selected one `data-selected`, one being saved `data-pending`. */

.demo-multi-select-trigger {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.6em;
  min-inline-size: 16rem;
  max-inline-size: 24rem;
  padding: 0.4em 0.6em;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-bg);
  color: var(--color-text);
  font: inherit;
  text-align: start;
  cursor: pointer;
}
.demo-multi-select-trigger > [data-empty] {
  color: var(--color-text-secondary);
}
/* The summary is one line: long selections are cut with an ellipsis. */
.demo-multi-select-trigger > span:first-child {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.demo-multi-select-trigger:focus-visible,
.demo-multi-select-trigger[data-open] {
  outline: 2px solid var(--color-primary);
  outline-offset: 1px;
}
.demo-multi-select-trigger[data-pending] {
  cursor: progress;
}
/* Inside a Field: after a submit attempt with nothing selected. */
.demo-multi-select-trigger[data-invalid] {
  border-color: #dc2626;
}
.demo-multi-select-chevron {
  color: var(--color-text-secondary);
}

.demo-multi-select-popup {
  /* The popover UA stylesheet sets `inset: 0; margin: auto`: reset both for anchored placement. */
  margin: 0;
  margin-block-start: 4px;
  inset: auto;
  padding: 4px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  background: var(--color-bg);
  color: var(--color-text);
  box-shadow: 0 12px 40px rgb(0 0 0 / 0.25);
  /* CSS enter / exit, used by dismissals (Escape, a click outside) and the library's closes. */
  opacity: 0;
  transition:
    opacity 120ms,
    display 120ms allow-discrete,
    overlay 120ms allow-discrete;
}
.demo-multi-select-popup:popover-open {
  opacity: 1;
}
@starting-style {
  .demo-multi-select-popup:popover-open {
    opacity: 0;
  }
}
/* The List scrolls, not the Popup: a scrolling Popup is a scrollable region with no focusable
   content (axe `scrollable-region-focusable`). */
.demo-multi-select-popup [role="listbox"] {
  max-block-size: 16rem;
  overflow: auto;
}

.demo-multi-select-option {
  display: flex;
  align-items: center;
  gap: 0.5em;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: default;
}
/* A check box drawn from `data-selected`: the selection is visible without colour. */
.demo-multi-select-option::before {
  content: "";
  inline-size: 0.9em;
  block-size: 0.9em;
  border: 1px solid var(--color-border);
  border-radius: 3px;
}
.demo-multi-select-option[data-selected]::before {
  border-color: var(--color-primary);
  background: var(--color-primary);
  box-shadow: inset 0 0 0 2px var(--color-bg);
}
/* Virtual focus; hovering makes an option active too, so this is the hover style as well. */
.demo-multi-select-option[data-active] {
  background: var(--color-bg-secondary);
}
.demo-multi-select-option[data-pending] {
  cursor: progress;
}
.demo-multi-select-option[aria-disabled="true"] {
  color: var(--color-text-secondary);
}
.demo-multi-select-note {
  font-size: 0.85em;
}
.demo-multi-select-status {
  padding: 6px 10px;
  color: var(--color-text-secondary);
}

@media (prefers-reduced-motion: reduce) {
  .demo-multi-select-popup {
    transition: none;
  }
}
```

> **Select or MultiSelect**
>
> [Select](select.md) is the browser's own control, a real `<select>` that works without JavaScript. MultiSelect is the library's, because the browser has no multi-select drop-down yet. It needs JavaScript (nothing opens before hydration), and in exchange it can do what a native select cannot: a controlled open, options that load when it opens, a view transition on the popup. `<Select.Root multiple>` is a type error and warns in development. For a short list shown in the page, use [CheckboxGroup](checkbox-group.md); to search and show removable chips, use [Combobox multiple](combobox.md#multiple).

## How it works

### A pick toggles

Enter or Space on the active option, or a click, toggles it: `aria-selected`, `data-selected`, the hidden inputs and the Value change at once (optimistic), the option shows `data-pending` until its change commits, and the listbox **stays open** for the next pick. There is no no-op pick: a selected option is removed. A rejection rolls back that one change; the listbox, the active option and focus do not move.

The value is a set in **pick order**, under the set rules of CheckboxGroup: each dispatch is one change, with `details.added` and `details.removed`; picks made while an earlier save runs stack, and only the changes whose action resolved are kept. Persist the diff, not `next`, which can contain a change that fails later. A controlled "update on success" parent applies the diff as a functional update:

```tsx
<MultiSelect.Root value={toppings} valueChangeAction={async (_next, { added, removed }) => {
  await saveToppings({ added, removed });
  startTransition(() =>
    setToppings((prev) => [...prev.filter((t) => !removed.includes(t)), ...added.filter((t) => !prev.includes(t))]),
  );
}}>
```

The order is the order of the picks (and of `value` / `defaultValue`), which is also the order of `formData.getAll(name)`. A native `<select multiple>` posts in list order instead; to show the list order, sort in Value's function, where you have your list.

### Opening and closing

Opening is a request: `openChangeAction(true)`, awaited, with the Trigger `data-pending` while it runs. A click on the Trigger while open, and Alt+ArrowUp, close the same way. Escape, a click outside, focus leaving the Trigger and another popover opening are facts, reported to `onOpenChange(false)` with `reason: "dismiss"`. A pick never closes the listbox.

### Prior art

Headless UI makes the same split: its `Select` is a thin wrapper around the native element, and the custom one that takes `multiple` is `Listbox`, which stays open while you pick. Mantine, PrimeReact and Carbon name the component `MultiSelect` (Mantine's is searchable with pills, PrimeReact's shows a comma-separated list by default, Carbon's shows a count tag). Radix has no multi-select. Chips with remove buttons and a search field are [Combobox multiple](combobox.md#multiple) here.

## Props

### `MultiSelect.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `readonly V[]` | – | Controlled selection. `[]`: nothing selected. `undefined` means uncontrolled. Duplicates are ignored. `V` is the item value type: a declared union you pass is kept, a literal is `string` ([Typed values](../concepts/action-props.md#typed-values)). |
| `defaultValue` | `readonly V[]` | `[]` | Initial selection when uncontrolled; what a form reset returns to (the latest value). |
| `valueChangeAction` | `ChangeAction<V[], MultiSelectValueChangeDetails<V>>` | – | Runs in the Root's transition for every change of the selection (a pick, a form reset). `next` is the whole intended selection; `details.added` / `details.removed` say what this dispatch changed. Awaited; a rejection undoes that change only. May be a Server Function. A `setState` after your own `await` needs `startTransition`. |
| `open` | `boolean` | – | Controlled open state. `undefined` means uncontrolled. Pass `onOpenChange` too (development warns). |
| `defaultOpen` | `boolean` | `false` | Initial open state; opens after hydration. |
| `openChangeAction` | `ChangeAction<boolean, MultiSelectOpenChangeDetails>` | – | Requests only: awaited for opens and for the closes a part asks for (the Trigger, Alt+ArrowUp). Never called for a dismissal. `details.reason`: `"activate"` (the Trigger, the opening keys, Alt+ArrowUp, a foreign `showPopover()`) or `"platform"` (found open on mount). |
| `onOpenChange` | `UrgentChangeHandler<boolean, MultiSelectOpenChangeDetails>` | – | Facts only: the listbox was closed without the library closing it on request. Always `false`. `details.reason`: `"dismiss"` (Escape, a click outside, focus leaving the Trigger, another popover opening, script) or `"activate"` (a [foreign invoker](../concepts/browser-owned-state.md#foreign-invoker): a `popovertarget` / `commandfor` button of yours that toggles the listbox). Called synchronously, outside any transition, and not awaited. In controlled mode set state directly here (`onOpenChange={setOpen}`). May return a promise; a rejection or a throw goes to `reportError`. On a controlled Root with no `openChangeAction`, also a part's close (the Trigger while open): the library performs it at once and calls this with `"activate"` ([nothing waits](../concepts/action-props.md#urgent-open)). |
| `loop` | `boolean` | `false` | ArrowDown / ArrowUp wrap from the last option to the first and back. |
| `name` | `string` | – | One `<input type="hidden" name>` per value, in value order (`formData.getAll(name)`); nothing posted for an empty selection. |
| `form` | `string` | – | The `form` attribute of the hidden inputs and of the validity element. |
| `required` | `boolean` | `false` | At least one value: a hidden validity element blocks the submit while the optimistic selection is empty, and the Trigger has `aria-required`. The browser shows no bubble: show the message with `Field.Error` ([Forms](#forms)). |
| `disabled` | `boolean` | `false` | Disables the Trigger natively; nothing opens or dispatches. A disabled MultiSelect (this prop or the Field's) is not submitted: every hidden input is `disabled` too, as a disabled native `<select>` posts nothing. A form reset still reaches it. A click on a disabled control runs no `onClick`, a `render` element's included ([unavailable parts](../concepts/render.md#unavailable)). |
| `readOnly` | `boolean` | `false` | The selection is shown, focusable and submitted, and cannot be changed, or the enclosing `Field.Root`'s: the Trigger stays an enabled button with `aria-readonly="true"` and `data-readonly`, the popup never opens (a press, Enter, Space, the arrows and typeahead request nothing; `aria-expanded` stays `"false"`), and nothing dispatches. The hidden inputs are not disabled, and the validity element's `required` is not rendered: a read-only MultiSelect never blocks a submission. When it turns on, an open listbox gets a close request (a controlled `open` parent decides); Escape and Alt+ArrowUp still close a listbox a parent keeps open. |
| `children` | `ReactNode \| ((state: MultiSelectRootState) => ReactNode)` | – | The parts, or a function of the Root's state. |

- **State**: `MultiSelectRootState` is `{ value, activeValue, open, pending, disabled, readOnly, required }`; `value` (pick order) and `open` are optimistic; `pending` covers the value and the open transitions; `required` is the prop or the Field's.
- **Owned**: none: the Root renders no element (no `ref`, `className` or `style`), only the hidden inputs when `name` is given.

`MultiSelectValueChangeDetails`: `{ reason, added, removed, valid, event }`. `valid`: the selection would be valid (`required`: not empty, and the Field's `validate` for the next set; see [details.valid](field.md#details-valid)). `reason` is `"activate"` for a pick (`event` is the `keydown` or `click`) and `"platform"` for a form reset ( the `reset` event; it can add and remove at once). `added` is in the order the values join, `removed` in value order.

### `MultiSelect.Label`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: MultiSelectLabelState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectLabelState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectLabelState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MultiSelectLabelState) => ReactNode)` | – | Replace the default \<label> (element form) or take over rendering (function form). |

- **State**: `MultiSelectLabelState` is `{ disabled, readOnly, pending }`, the Root's; the Label renders them as `data-disabled`, `data-readonly` and `data-pending`.
- **Owned**: `id`, `htmlFor`, `onClick`.

A `<label for>` of the Trigger whose click focuses the Trigger without opening the listbox, as a label on a `<select>` does. Its id also names the List, only while a Label is mounted. Inside a `Field.Root`, `Field.Label` takes its role and does the same.

### `MultiSelect.Trigger`

| Prop | Type | Default | Description |
| - | - | - | - |
| `disabled` | `boolean` | `false` | Native `disabled`; the Root's `disabled` applies too. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: MultiSelectTriggerState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectTriggerState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectTriggerState) => ReactNode)` | – | Non-interactive content, usually a `MultiSelect.Value` and a decorative `aria-hidden` icon. Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: MultiSelectTriggerState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `MultiSelectTriggerState` is `{ value, open, pending, disabled, readOnly, invalid, required }`; `value` and `open` are optimistic, `pending` is the Root's; `invalid` is `true` while the enclosing `Field.Root` shows an error (`data-invalid`), `false` outside a Field; `required` is the Root's or the Field's (`data-required`: a button has no `:required`).
- **Owned**: `id`, `type` (`"button"`), `role` (`"combobox"`), `disabled`, `aria-expanded` (the shown listbox), `aria-controls` (token-merged; the List id only while the List is rendered), `aria-activedescendant`, `aria-required`, `aria-readonly` (while read-only), `popovertarget` (written as an attribute after hydration), `form` (from the Root), `onClick`, `onKeyDown`, `onFocus`, `onBlur`, `data-open`, `data-pending`, `data-disabled`, `data-readonly`, `data-required`; inside a `Field.Root` also `aria-invalid`, `aria-describedby` (token-merged) and `data-invalid`. Owned and never written: `popoverTarget`, `popoverTargetAction`, `commandfor`, `command`.

With `required` it renders the validity element right after itself: a visually hidden one-option `<select>` with no name. A `render` element must stay a `<button>` (development warns). `ref` goes to the button.

### `MultiSelect.Value`

| Prop | Type | Default | Description |
| - | - | - | - |
| `placeholder` | `ReactNode` | – | Shown while the selection is empty, instead of `children` (a function `children` is not called then). `null` counts as not given; without it, `children` renders the empty selection too. |
| `className` | `string \| ((state: MultiSelectValueState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectValueState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectValueState) => ReactNode)` | `the labels joined with ", "` | The summary, usually a function of `{ value }` with your own names. Not used while the selection is empty and `placeholder` is given. `labels[i]` is the text of the option for `value[i]` as the library last saw it, `undefined` if it never saw one. Must not suspend. |
| `render` | `ReactElement \| ((props, state: MultiSelectValueState) => ReactNode)` | – | Replace the default \<span> (element form) or take over rendering (function form). |

- **State**: `MultiSelectValueState` is `{ value, labels, empty, disabled, readOnly }`; `value` is optimistic; `empty` is `value.length === 0`.
- **Owned**: `data-empty` (while the selection is empty, the library's one word for it: there is no `data-placeholder`), `data-disabled`, `data-readonly`.

Optional: any Trigger content rendered from the Trigger's state works. A function cannot come from a Server Component; render the Trigger's content from a client component, or use the default content.

### `MultiSelect.Popup`

| Prop | Type | Default | Description |
| - | - | - | - |
| `keepMounted` | `boolean` | `false` | `false`: the children render only while open. `true`: they stay mounted in a hidden `<Activity>`. |
| `transition` | `ViewTransitionClass` | – | The class of the `<ViewTransition>` around the popup element; without it no boundary is rendered. A string animates this MultiSelect's own opens and closes that the library dispatched (the Trigger, the keys) and its own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)), in all engines; nothing else (not another MultiSelect, not an unrelated transition, not content that changes inside). A value dispatch that keeps the popup open starts none. A controlled `open` you change in your own transition needs a map keyed on `fsui-multi-select-open` / `fsui-multi-select-close` plus `addTransitionType` ([recipe](../concepts/transitions.md#controlled)). A type map is React's: it names every MultiSelect that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). Dismissals animate with CSS only. Keep it static. A closed Popup renders its element one commit after its mount, before paint, so placing it starts no view transition and its `ref` is still empty in the mount effects of the component that renders it ([two-step mount](../concepts/transitions.md#closed-popups)). |
| `className` | `string \| ((state: MultiSelectPopupState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectPopupState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectPopupState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MultiSelectPopupState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MultiSelectPopupState` is `{ open }` (committed).
- **Owned**: `id`, `popover` (`"auto"`), `onPointerDown` and `onMouseDown` (a press anywhere in it keeps focus on the Trigger); no role.

Inline style `position-area: self-block-end span-self-inline-end; position-try-fallbacks: flip-block; min-width: anchor-size(width)` places it below the Trigger (above when it does not fit), at least as wide; your `style` wins per property. A `render` element must stay a `<div>`.

### `MultiSelect.List`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: MultiSelectListState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectListState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectListState) => ReactNode)` | – | The Options and Groups, under your own `<Suspense>` for options that load on open. |
| `render` | `ReactElement \| ((props, state: MultiSelectListState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MultiSelectListState` is `{ empty }`.
- **Owned**: `id`, `role` (`"listbox"`), `aria-multiselectable` (`"true"`), `aria-labelledby` (token-merged; the Label, else the enclosing `Field.Label` while one is mounted; absent with neither), `aria-busy` (while a `Status` is mounted inside it), `data-empty`.

Without a Label give the List an `aria-label` (development warns otherwise).

### `MultiSelect.Option`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required and unique within the MultiSelect; the option's id is derived from it. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `label` | `string` | – | The text for typeahead and for Value's labels. Default: the option's trimmed text at that moment. Renders nothing. |
| `disabled` | `boolean` | `false` | `aria-disabled`: shown, skipped by the keys and typeahead, never toggled. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: MultiSelectOptionState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MultiSelectOptionState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MultiSelectOptionState) => ReactNode)` | – | Content, or a function of the option's state; must not suspend. |
| `render` | `ReactElement \| ((props, state: MultiSelectOptionState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MultiSelectOptionState` is `{ value, selected, active, pending, disabled }`; `selected` is optimistic, `active` is virtual focus, `pending` is true while this option is being added or removed.
- **Owned**: `id` (derived from `value`), `role`, `aria-selected` (on every option), `aria-disabled`, `onClick`, `onPointerDown`, `onMouseDown`, `onPointerMove`, `data-selected`, `data-active`, `data-pending`, `data-disabled`.

Never focused, no `tabindex`; hovering makes it active.

### `MultiSelect.Group`, `MultiSelect.GroupLabel`, `MultiSelect.Empty`, `MultiSelect.Status`

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: {} (Empty: MultiSelectListState)) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: {} (Empty: MultiSelectListState)) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: {} (Empty: MultiSelectListState)) => ReactNode)` | – | Content. Empty renders only when the List has no options and none are loading. |
| `render` | `ReactElement \| ((props, state) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: none (Empty: `MultiSelectListState`).
- **Owned**: Group: `role` (`"group"`), `aria-labelledby` (while a GroupLabel is mounted); GroupLabel: `id`; Status: `role` (`"none"` inside the List, `"status"` in the Popup).

`Group` is named by the `GroupLabel` inside it. `Status` inside the List (as a Suspense fallback) marks the List as loading; in the Popup it is a plain hint.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-open` | Trigger | Optimistic open state. `aria-expanded` follows the shown listbox instead. |
| `data-pending` | Trigger | A value or an open transition is in flight (the Root's `pending`). |
| `data-pending` | Option | This option is being added or removed. |
| `data-selected` | Option | In the optimistic selection. |
| `data-active` | Option | `aria-activedescendant` points here (keyboard or hover). |
| `data-empty` | Value | Nothing is selected (`:not([data-empty])`: something is). |
| `data-empty` | List | No options and not loading. |
| `data-disabled` | Label, Trigger, Value, Option | Disabled. |
| `data-readonly` | Label, Trigger, Value | The Root's `readOnly` (or the Field's). |
| `data-pending` | Label | The Root's `pending`. |
| `data-required` | Trigger | `required` (the Root's or the Field's). |
| `data-invalid` | Trigger | Inside a `Field.Root`, while its error is shown. |
| `:popover-open` | Popup | The listbox is shown (browser-owned, no attribute). |

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| Enter / Space / ArrowDown / Alt+ArrowDown | listbox closed | Opens with the first selected option active, else the first enabled one. |
| ArrowUp | listbox closed | Opens with the first selected option active, else the last one. |
| Home / End | listbox closed | Opens with the first / last enabled option active. |
| A printable character | listbox closed | Opens with the first option starting with it active. |
| ArrowDown / ArrowUp | listbox open | Next / previous enabled option; stops at the ends (wraps with `loop`). |
| Home / End | listbox open | First / last enabled option. |
| PageDown / PageUp | listbox open | Ten options forward / back. |
| Enter / Space | listbox open | Toggles the active option; the listbox stays open. |
| A printable character | listbox open | Typeahead: the active option moves to the next option starting with the typed text (500 ms buffer; a repeated letter cycles). A Space while you are typing is part of the text. |
| Alt+ArrowUp | listbox open | Closes; nothing is toggled. |
| Escape | listbox open | The platform closes the listbox; focus stays. A second Escape reaches an enclosing Dialog or Popover. |
| Tab / Shift+Tab | listbox open | Focus moves on and the listbox closes. Tab never toggles the active option. |
| Every key but Tab, Escape and Alt+ArrowUp | read-only | Nothing: the listbox does not open. Escape and Alt+ArrowUp close one a controlled parent keeps open. |

Disabled options are skipped. Ctrl and Meta combinations are left alone. Shift+arrow range selection and Ctrl+A (the optional multi-select keys of the APG listbox) are not in v1.

- The Trigger is `role="combobox"` with `aria-expanded`, `aria-controls` (the List, only while it is rendered: not while closed), `aria-activedescendant` and, with `required`, `aria-required`. Its text content is the combobox's value for assistive technology; give decorative icons `aria-hidden`.
- The List is `aria-multiselectable`, every option carries `aria-selected`; a toggle is heard through that state under `aria-activedescendant`, so nothing extra is announced.
- The Trigger is the popup's invoker after hydration and still renders `aria-expanded` from the shown listbox: the `combobox` role requires the state, and before hydration the button is not an invoker yet.

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

Every value dispatch: `fsui-multi-select`, plus `fsui-multi-select-select` when something is added and `fsui-multi-select-deselect` when something is removed (a reset can carry both). Opens and closes: `fsui-multi-select` plus `fsui-multi-select-open` or `fsui-multi-select-close`. These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

The selection and the open state are optimistic: an option's `aria-selected` and `data-selected`, the Value and the hidden inputs change at once, and come back if the save fails. `data-pending` is on the Trigger while a value or an open transition is in flight, and on each option whose change is not committed yet (one being added and one being removed).

## Suspense

Concept: [Suspense](../concepts/suspense.md)

Put the boundary inside the List and the popup opens at once with your `MultiSelect.Status` fallback (the List is `aria-busy`); the first selected option becomes active when the options arrive. With the boundary outside the Popup, React holds the open instead and the Trigger shows `data-pending`. Option and Value content must not suspend.

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

The listbox is a popover: Escape, a click outside and another popover opening are the browser's. Focus leaving the Trigger is closed by the library at once, which it cannot hold either. Either way it is a fact: `onOpenChange(false)` with `reason: "dismiss"`, nothing pending. A form reset is reported as a `"platform"` value change.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

The server HTML has the hidden inputs of the default selection, the Trigger with its Value content and the empty popover. Before hydration nothing opens; a form submitted then posts the default selection, and `required` is already enforced by the server-rendered validity element.

## Forms

```tsx title="MultiSelectForm.tsx"
"use client";
import { startTransition, useState } from "react";
import { useFormStatus } from "react-dom";
import { Field } from "@funstack/ui/field";
import { MultiSelect } from "@funstack/ui/multi-select";
import { fakeSave } from "./fake-api.js";

const DAYS = [
  ["mon", "Monday"],
  ["tue", "Tuesday"],
  ["wed", "Wednesday"],
  ["thu", "Thursday"],
  ["fri", "Friday"],
] as const;
const NAMES: Record<string, string> = Object.fromEntries(DAYS);

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" className="demo-button demo-primary">
      {pending && <span className="demo-spinner" aria-hidden />}
      Save
    </button>
  );
}

// `required` means at least one day. A hidden validity element blocks the submit while nothing is
// selected; the browser shows no bubble of its own, so the message is `Field.Error`'s and focus
// lands on the Trigger. The form posts one `days` entry per value, in pick order.
export function MultiSelectForm() {
  const [posted, setPosted] = useState<string[] | null>(null);
  return (
    <form
      className="demo-stack"
      action={async (formData) => {
        await fakeSave("the schedule");
        const days = formData.getAll("days").map(String);
        startTransition(() => setPosted(days));
      }}
    >
      <Field.Root name="days" required className="demo-stack">
        <Field.Label className="demo-field">Office days</Field.Label>
        <MultiSelect.Root>
          <MultiSelect.Trigger className="demo-multi-select-trigger">
            <MultiSelect.Value placeholder="Choose days">
              {({ value }) => value.map((v) => NAMES[v] ?? v).join(", ")}
            </MultiSelect.Value>
            <span className="demo-multi-select-chevron" aria-hidden>
              ▾
            </span>
          </MultiSelect.Trigger>
          <MultiSelect.Popup className="demo-multi-select-popup">
            <MultiSelect.List>
              {DAYS.map(([value, name]) => (
                <MultiSelect.Option key={value} value={value} className="demo-multi-select-option">
                  {name}
                </MultiSelect.Option>
              ))}
            </MultiSelect.List>
          </MultiSelect.Popup>
        </MultiSelect.Root>
        <Field.Description className="demo-description">Pick one or more.</Field.Description>
        <Field.Error className="demo-field-error" />
      </Field.Root>
      <div className="demo-row">
        <SubmitButton />
        <button type="reset" className="demo-button">
          Reset
        </button>
      </div>
      <output className="demo-readout">
        posted: <code>{posted === null ? "(nothing yet)" : JSON.stringify(posted)}</code>
      </output>
    </form>
  );
}
```

`multi-select.css`: the same file as above.

- `name` on the Root posts one entry per value, in pick order (`formData.getAll(name)`), nothing for an empty selection.
- `required` means at least one value. Neither a button nor a hidden input can take part in constraint validation, so the Trigger renders a hidden one-option `<select>` after itself that is `required` exactly while the optimistic selection is empty (removing the last value marks it at once, a rollback un-marks it). A submit with nothing selected is blocked and focus moves to the Trigger.
- **The message is `Field.Error`'s.** The browser's bubble is turned off: it would point at the hidden element, and in Firefox it stays over the place where the listbox opens and takes the clicks meant for the first options. Wrap the MultiSelect in a [Field.Root](field.md) with a `Field.Error`, as above; `Field.Label` then names it and focuses it without opening the listbox. Outside a Field a blocked submit only moves focus.
- A form reset (the Reset button, `form.reset()`, React's reset after a form action) dispatches the reset target whole with `reason: "platform"`: uncontrolled, the latest `defaultValue`; controlled, the mount-time `value`. It works without `name` as well.
- Inside a `Field.Root`, `validate` gets the first value; read the others from `formData.getAll(name)`. `name`, `disabled` and `required` default from the Field.
- A disabled MultiSelect (its `disabled` or the Field's) is not submitted, as a disabled native select posts nothing: the hidden inputs are `disabled` too.

## Styling

```css
.select[data-open] { outline: 2px solid Highlight; }
.select[data-pending] { cursor: progress; }
.select [data-empty] { color: GrayText; }                 /* MultiSelect.Value: nothing chosen */
.select[data-invalid] { border-color: var(--danger); }   /* inside a Field */

.listbox { margin: 0; inset: auto; }                            /* the Popup */
.listbox [role="listbox"] { max-block-size: 20rem; overflow: auto; }  /* the List scrolls */
.listbox [role="option"][data-active] { background: var(--accent-weak); }
.listbox [role="option"][data-selected]::before { content: "✓" / ""; }
.listbox [role="option"][data-pending] { cursor: progress; }
.listbox [role="option"][aria-disabled="true"] { color: GrayText; }

/* Enter / exit for dismissals too (Escape, a click outside). */
.listbox { opacity: 0; transition: opacity 120ms, display 120ms allow-discrete, overlay 120ms allow-discrete; }
.listbox:popover-open { opacity: 1; }
@starting-style { .listbox:popover-open { opacity: 0; } }
```

Put the scroll on the List (`[role="listbox"]`), not on the Popup. Nothing in a scrolling Popup takes focus (the options are `aria-activedescendant` targets), so axe reports the Popup as `scrollable-region-focusable`; with the scroll on the List it reports nothing (checked in Chromium and Firefox). The active option is scrolled into view either way.

`transition` on the Popup animates the library's own opens and closes with a view transition; dismissals are the CSS above. The library turns the popup's CSS transitions off for the moment of its own show and hide while a view transition runs ([A popup with a CSS exit and a view transition](../concepts/transitions.md#css-exit)).

## Browser notes

- Inside a Dialog or a Popover the listbox nests in the top layer: the first Escape closes the listbox, the next the outer overlay. Inside a `Menu.Popup` it is not supported.
- Safari: a WebKit bug (302008) can hang a page that opens a popover with position fallbacks inside another popover. Inside a Popover or Dialog in Safari, turn the flip off: `style={{ positionTryFallbacks: "none" }}` on `MultiSelect.Popup`.
- WebKit does not focus a button on a mouse press; the Trigger focuses itself on click, so the keys work after a click in every engine.
