# Multi Select

> Groups filterable checkboxes in a disclosure and submits each checked value with the same field name.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/multi-select`
- File: `src/components/haze/ui/multi-select.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/checkbox, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/multi-select

## Use when
- A form accepts multiple options from a shared list.
- The selection list should collapse to leave more room for the rest of the form.

## Avoid when
- The form requires exactly one choice.

## Alternatives
- [checkbox](https://hazeui.com/ui/checkbox.md)
- [combobox](https://hazeui.com/ui/combobox.md)
- [tags-input](https://hazeui.com/ui/tags-input.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID that also prefixes checkbox IDs. |
| name | `string` | id | no | Repeated field name for checked options. |
| label | `string` | Share with | no | Title for the disclosure and checkbox group. |
| options | `Option[]` |  | no | Choices with value, label, and optional disabled state. |
| values | `string[]` | [] | no | Initially checked values. |
| disabled | `boolean` |  | no | Disables the checkbox group. |
| form | `string` |  | no | ID of a form outside the component. |
| class | `string` |  | no | Classes for the fieldset. |

## Accessibility
- Checked boxes remain selected while filtering hides other options.
- The disclosure and checkboxes work without JavaScript.
- Key Enter / Space: Toggle the option disclosure.
- Key Tab: Move to the filter and visible checkboxes.
- Key Space: Toggle the focused checkbox.

## Agent prompts

### Install and use

Install the Haze UI component "Multi Select" with `npx shadcn@latest add @haze/multi-select`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import MultiSelect from "@/components/haze/ui/multi-select.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/multi-select.md

### Customize with real content

Adapt the Haze multi-select ui for our product. Replace the demo values of these props with our real content: id, name, label, options, values, disabled, form, class. Keep the layout, the heading level rules and these accessibility details: Checked boxes remain selected while filtering hides other options. The disclosure and checkboxes work without JavaScript. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using multi-select, check it fits: use it when a form accepts multiple options from a shared list.; the selection list should collapse to leave more room for the rest of the form.. Avoid it when the form requires exactly one choice.. Alternatives: @haze/checkbox, @haze/combobox, @haze/tags-input.

## Example requests that should lead here
- Let people share a file with several teams.
- Add searchable region checkboxes to the report filters.

## Source

```astro
---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Checkbox from "./checkbox.astro";
import Input from "./input.astro";

interface Option { value: string; label: string; disabled?: boolean }
interface Props {
  id: string;
  name?: string;
  label?: string;
  options?: Option[];
  values?: string[];
  disabled?: boolean;
  form?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  id, name = id, label = "Share with", values = [], disabled, form, class: className,
  options = [
    { label: "Design", value: "design" },
    { label: "Product", value: "product" },
    { label: "Customer support", value: "support" },
  ], ...rest
} = Astro.props;
---

<fieldset {...rest} id={id} data-haze-multi-select disabled={disabled} form={form} class={cn("min-w-0", className)}>
  <legend class="sr-only">{label}</legend>
  <details class="group rounded-lg border border-frame bg-field text-card-foreground transition-[border-color] duration-150 ease-snappy hover:border-frame-strong">
    <summary class="flex min-h-10 min-w-0 cursor-pointer list-none items-center gap-2 rounded-[calc(var(--radius-lg)-1px)] px-3 py-2 text-[0.8125rem]/5 font-medium tracking-[-0.01em] transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
      <span class="min-w-0 flex-1 wrap-anywhere">{label}</span>
      <span data-multi-count class="hidden shrink-0 rounded-full bg-muted px-2 py-0.5 text-[0.75rem]/4 text-muted-foreground tabular-nums [[data-haze-multi-select][data-enhanced]_&]:inline">0 selected</span>
      <ChevronDown aria-hidden="true" class="size-4 shrink-0 text-muted-foreground transition-[rotate] duration-200 ease-snappy group-open:rotate-180" />
    </summary>
    <div class="grid gap-1 border-t border-border p-1">
      <div class="hidden [[data-haze-multi-select][data-enhanced]_&]:block">
        <Input id={`${id}-search`} name="" type="search" aria-label="Filter options" aria-controls={`${id}-options`}
          placeholder="Filter options" data-multi-search />
      </div>
      <ul id={`${id}-options`} class="grid max-h-48 gap-0.5 overflow-y-auto">
        {options.map((option, index) => (
          <li data-multi-option data-search-label={option.label} class="rounded-sm px-2 py-1 transition-colors duration-75 hover:bg-accent aria-hidden:hidden">
            <Checkbox id={`${id}-option-${index}`} name={name} label={option.label} value={option.value}
              checked={values.includes(option.value)} disabled={option.disabled} form={form} class="[&_label]:block [&_label]:min-h-6 [&_label]:cursor-pointer" />
          </li>
        ))}
      </ul>
      <p data-multi-empty hidden role="status" class="px-2 pb-1 text-[0.8125rem]/5 text-muted-foreground">No matching options.</p>
    </div>
  </details>
</fieldset>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const search = root.querySelector<HTMLInputElement>("[data-multi-search]");
    const count = root.querySelector<HTMLElement>("[data-multi-count]");
    const empty = root.querySelector<HTMLElement>("[data-multi-empty]");
    if (!search || !count || !empty) return;
    const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-multi-option]"));
    const boxes = Array.from(root.querySelectorAll<HTMLInputElement>("input[type=checkbox]"));
    const syncSelection = () => {
      count.textContent = `${boxes.filter((box) => box.checked).length} selected`;
    };
    const filter = () => {
      const query = search.value.toLocaleLowerCase().trim();
      let matches = 0;
      for (const row of rows) {
        const match = (row.dataset.searchLabel ?? "").toLocaleLowerCase().includes(query);
        row.setAttribute("aria-hidden", String(!match));
        if (match) matches += 1;
      }
      empty.hidden = matches > 0;
    };
    search.addEventListener("input", filter);
    root.addEventListener("change", syncSelection);
    boxes[0]?.form?.addEventListener("reset", () => queueMicrotask(() => {
      search.value = "";
      filter();
      syncSelection();
    }));
    root.setAttribute("data-enhanced", "");
    syncSelection();
    filter();
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-multi-select]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-multi-select-listener")) {
    document.documentElement.setAttribute("data-haze-multi-select-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
