{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "multiselect",
  "title": "Multiselect",
  "description": "Searchable async multiselect, a preset over Combobox's parts with Base UI's multiple: chips are cells in the field frame, the list docks to it.",
  "dependencies": [
    "@base-ui/react@1.9.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/combobox"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/multiselect.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport type { Combobox as ComboboxPrimitive } from \"@base-ui/react/combobox\";\nimport { Field as FieldPrimitive } from \"@base-ui/react/field\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  ComboboxChip,\n  ComboboxChipRemove,\n  ComboboxChips,\n  ComboboxClear,\n  ComboboxEmpty,\n  ComboboxInput,\n  ComboboxInputGroup,\n  ComboboxItem,\n  ComboboxList,\n  ComboboxPopup,\n  ComboboxRoot,\n  ComboboxStatus,\n  ComboboxTrigger,\n} from \"./combobox\";\n\n/*\n * Multiselect: a preset over Combobox's parts with Base UI's `multiple`. Selection, filtering, chips, keyboard\n * (Backspace removes the last chip, arrows walk the chips) and focus are Base UI Combobox's; this file adds the async\n * source, the count cell and the list's head and foot.\n *\n *   ┌──────────────────────────────────┬────┬────┐\n *   │ [MSC ×] [Maersk ×] search…       │  2 │ ⌄  │   chips and the input · count cell · caret cell\n *   └──────────────────────────────────┴────┴────┘\n */\n\nexport type MultiselectOption = {\n  value: string;\n  label: string;\n  description?: string;\n  count?: number;\n  disabled?: boolean;\n};\n\ntype MultiselectProps = {\n  label: React.ReactNode;\n  value?: MultiselectOption[];\n  defaultValue?: MultiselectOption[];\n  /** Called with the chosen options and Base UI's event details (the reason, the event). */\n  onValueChange?: (value: MultiselectOption[], eventDetails: ComboboxPrimitive.Root.ChangeEventDetails) => void;\n  /** Async source. Called on open (query \"\") and on every input change; earlier requests are aborted. */\n  loadOptions: (query: string, signal: AbortSignal) => Promise<MultiselectOption[]>;\n  placeholder?: string;\n  noun?: [singular: string, plural: string];\n  /** control: its own 2px frame. cell: a cell of an enclosing frame (e.g. a toolbar); the label is visually hidden. */\n  layout?: \"control\" | \"cell\";\n  disabled?: boolean;\n  className?: string;\n  /** Where the list's portal renders (defaults to <body>). */\n  container?: ComboboxPrimitive.Portal.Props[\"container\"];\n};\n\n/* the typed text, underlined in each match */\nfunction highlight(text: string, q: string) {\n  const i = q ? text.toLowerCase().indexOf(q.toLowerCase()) : -1;\n  if (i < 0) return text;\n  return (\n    <>\n      {text.slice(0, i)}\n      <mark\n        className={cn(\n          \"bg-transparent font-[inherit] text-inherit underline decoration-kl-cobalt-text decoration-2 underline-offset-3\",\n          \"group-data-highlighted/combobox-item:decoration-kl-yellow\",\n        )}\n      >\n        {text.slice(i, i + q.length)}\n      </mark>\n      {text.slice(i + q.length)}\n    </>\n  );\n}\n\n/*\n * A row of a list that holds several values. ComboboxItem's mark is the exclusive-choice square; several values take\n * a check box instead: the box is always drawn (dashed while the row is out of service), a chosen row floods its mark\n * cell yellow (the working set) and the box's inner square turns into a tick drawn from two borders, which never\n * mirrors. The trailing cell is a count in the plain voice, not a code.\n */\nconst row = cn(\n  \"grid-cols-[40px_minmax(0,1fr)_auto] **:data-[slot=combobox-item-label]:py-1\",\n  \"data-selected:*:first:bg-kl-yellow data-selected:*:first:text-kl-on-yellow\",\n  \"data-highlighted:data-selected:*:first:border-e-kl-on-yellow\",\n  \"**:data-[slot=combobox-item-indicator]:border-[1.5px] **:data-[slot=combobox-item-indicator]:not-data-selected:visible\",\n  \"data-disabled:**:data-[slot=combobox-item-indicator]:border-dashed\",\n  \"not-data-selected:**:data-[slot=combobox-item-indicator]:*:invisible\",\n  \"**:data-[slot=combobox-item-indicator]:*:mb-0.5 **:data-[slot=combobox-item-indicator]:*:h-2.5\",\n  \"**:data-[slot=combobox-item-indicator]:*:w-[5px] **:data-[slot=combobox-item-indicator]:*:rotate-45\",\n  \"**:data-[slot=combobox-item-indicator]:*:border-current **:data-[slot=combobox-item-indicator]:*:bg-transparent\",\n  \"**:data-[slot=combobox-item-indicator]:*:border-r-2 **:data-[slot=combobox-item-indicator]:*:border-b-2\",\n  \"**:data-[slot=combobox-item-code]:font-(family-name:--kl-font) **:data-[slot=combobox-item-code]:font-normal\",\n  \"**:data-[slot=combobox-item-code]:text-(length:--kl-text-label) **:data-[slot=combobox-item-code]:leading-[inherit]\",\n  \"**:data-[slot=combobox-item-code]:tabular-nums\",\n);\n\n/**\n * Searchable async multiselect. Chips are yellow cells in the field frame; the list docks to the frame.\n * Selected options stay listed while new matches stream in; requests are aborted when superseded.\n * Escape closes the list; on a closed field it clears only typed text, never the chips (Base UI would\n * clear them all): a chip's remove cell, Backspace and Clear remove.\n */\nfunction Multiselect({\n  label,\n  value,\n  defaultValue = [],\n  onValueChange,\n  loadOptions,\n  placeholder = \"Search…\",\n  noun = [\"item\", \"items\"],\n  layout = \"control\",\n  disabled,\n  className,\n  container,\n}: MultiselectProps) {\n  const id = React.useId();\n  const [inner, setInner] = React.useState(defaultValue);\n  const selected = value ?? inner;\n  const [query, setQuery] = React.useState(\"\");\n  const [results, setResults] = React.useState<MultiselectOption[]>([]);\n  const [error, setError] = React.useState<string | null>(null);\n  const [pending, setPending] = React.useState(false);\n  const ctrl = React.useRef<AbortController | null>(null);\n  // The open handler runs in the same event as the input change that opened the list (a paste opens and\n  // searches at once), before React re-renders: it reads the latest query and the request in flight from\n  // refs, so it never supersedes that search with the query of the previous render.\n  const latest = React.useRef(\"\");\n  const inflight = React.useRef<string | null>(null);\n\n  const load = React.useCallback(\n    (q: string) => {\n      ctrl.current?.abort();\n      const c = new AbortController();\n      ctrl.current = c;\n      inflight.current = q;\n      setPending(true);\n      setError(null);\n      loadOptions(q, c.signal).then(\n        (r) => {\n          if (c.signal.aborted) return;\n          inflight.current = null;\n          setResults(r);\n          setPending(false);\n        },\n        (e: unknown) => {\n          if (c.signal.aborted) return;\n          inflight.current = null;\n          setError(e instanceof Error ? e.message : \"Couldn't load options\");\n          setPending(false);\n        },\n      );\n    },\n    [loadOptions],\n  );\n  React.useEffect(() => () => ctrl.current?.abort(), []);\n\n  const items = React.useMemo(() => {\n    const merged = [...results];\n    if (!query) selected.forEach((s) => merged.some((m) => m.value === s.value) || merged.unshift(s));\n    return merged;\n  }, [results, selected, query]);\n\n  const n = selected.length;\n\n  return (\n    // a Base UI Field, as Combobox's own field is: its label stays the input's name while the list is open\n    <FieldPrimitive.Root\n      data-slot=\"multiselect\"\n      data-kl-layout={layout}\n      disabled={disabled}\n      className={cn(\"kl-field\", className)}\n    >\n      <ComboboxRoot<MultiselectOption, true>\n        items={items}\n        multiple\n        value={selected}\n        onValueChange={(v, details) => {\n          // Escape on a closed field: Base UI clears every chip; keep them\n          if (details.reason === \"escape-key\") return details.cancel();\n          setInner(v);\n          onValueChange?.(v, details);\n        }}\n        itemToStringLabel={(o) => o.label}\n        isItemEqualToValue={(a, b) => a.value === b.value}\n        filter={null}\n        disabled={disabled}\n        onOpenChange={(o) => {\n          // every open refreshes the list, unless this event already started the search for the current query\n          if (o && inflight.current !== latest.current) load(latest.current);\n        }}\n        onInputValueChange={(q, { reason, allowPropagation }) => {\n          if (reason === \"escape-key\" && !latest.current) {\n            // nothing typed: Escape changes nothing here, so it reaches an enclosing overlay\n            allowPropagation();\n            return;\n          }\n          latest.current = q;\n          setQuery(q);\n          if (reason !== \"item-press\") load(q);\n        }}\n      >\n        <FieldPrimitive.Label htmlFor={id} className={cn(\"kl-field-label\", layout === \"cell\" && \"kl-sr\")}>\n          {label}\n        </FieldPrimitive.Label>\n        <ComboboxInputGroup layout={layout} className=\"min-h-[calc(var(--kl-ctl)+8px)]\">\n          <ComboboxChips>\n            {selected.map((o) => (\n              <ComboboxChip key={o.value} aria-label={o.label}>\n                <span>{o.label}</span>\n                <ComboboxChipRemove aria-label={`Remove ${o.label}`} />\n              </ComboboxChip>\n            ))}\n            <ComboboxInput\n              id={id}\n              placeholder={n ? \"\" : placeholder}\n              className={cn(\"h-[26px] flex-1 px-1\", n ? \"min-w-7\" : \"min-w-16\")}\n              aria-description={n ? `${n} selected. Backspace removes the last.` : undefined}\n            />\n          </ComboboxChips>\n          {/* the count: how many are chosen, in the Count voice (tabular), dimmed at zero */}\n          <span\n            className={cn(\n              \"grid min-w-10 flex-none place-items-center text-[18px] font-(--kl-weight-display) tabular-nums\",\n              \"data-zero:font-medium data-zero:text-kl-ink-3\",\n            )}\n            aria-hidden\n            data-zero={n === 0 || undefined}\n            data-slot=\"multiselect-count\"\n          >\n            {n}\n          </span>\n          <ComboboxTrigger aria-label={`Open ${noun[1]}`} />\n        </ComboboxInputGroup>\n        <ComboboxPopup\n          layout={layout}\n          container={container}\n          aria-busy={pending || undefined}\n          className=\"max-h-[min(var(--available-height),420px)]\"\n        >\n          <div\n            className={cn(\n              \"relative flex min-h-8 flex-none items-center justify-between gap-2 px-(--kl-inset)\",\n              \"border-b-(length:--kl-k1) border-b-kl-seam text-kl-ink-2\",\n              \"font-(family-name:--kl-font-mono) text-(length:--kl-text-code)/[1.2] font-medium not-italic normal-nums\",\n            )}\n            data-slot=\"multiselect-head\"\n          >\n            <ComboboxStatus>\n              {pending\n                ? \"Searching…\"\n                : error\n                  ? error\n                  : query\n                    ? `${results.length} ${results.length === 1 ? \"match\" : \"matches\"} for “${query}”`\n                    : `${results.length} ${noun[1]}`}\n            </ComboboxStatus>\n            {error ? (\n              <button\n                type=\"button\"\n                className={cn(\n                  \"cursor-pointer bg-transparent py-1.5 text-kl-cobalt-text underline decoration-[1.5px] underline-offset-3\",\n                  \"font-(family-name:--kl-font) text-(length:--kl-text-label)/none font-bold\",\n                )}\n                onClick={() => load(query)}\n              >\n                Retry\n              </button>\n            ) : null}\n            {pending ? <span className=\"kl-pending [inset-block-end:-1px] h-0.5\" aria-hidden /> : null}\n          </div>\n          <ComboboxEmpty className=\"not-empty:border-b-(length:--kl-k1) not-empty:border-b-kl-line-soft\">\n            {!pending && !error ? (\n              <>\n                <span\n                  className={cn(\n                    \"kl-count grid place-items-center self-stretch border-e-(length:--kl-k1) border-e-kl-seam\",\n                    \"text-(length:--kl-text-display)\",\n                  )}\n                >\n                  0\n                </span>\n                <span className=\"px-(--kl-inset) text-kl-ink-2\">\n                  No {noun[1]} match “{query}”.\n                </span>\n              </>\n            ) : null}\n          </ComboboxEmpty>\n          <ComboboxList>\n            {(o: MultiselectOption) => (\n              <ComboboxItem\n                key={o.value}\n                value={o}\n                disabled={o.disabled}\n                description={o.description}\n                code={o.count?.toLocaleString()}\n                className={row}\n              >\n                {highlight(o.label, query)}\n              </ComboboxItem>\n            )}\n          </ComboboxList>\n          <div\n            className=\"kl-cells border-t-(length:--kl-k1) border-t-kl-seam text-(length:--kl-text-label)\"\n            data-slot=\"multiselect-foot\"\n          >\n            <span className=\"kl-cell min-h-9 flex-1\">\n              <b>{n}</b>&nbsp;selected\n            </span>\n            {/* Base UI's clear: empties the value (and the typed text) through onValueChange */}\n            <ComboboxClear\n              keepMounted\n              disabled={!n}\n              aria-label={`Clear ${noun[1]}`}\n              className={cn(\n                \"kl-cell min-h-9 w-auto px-(--kl-inset) font-(--kl-weight-strong) text-kl-ink hover:text-kl-ink\",\n                \"active:[&>span]:translate-y-px\",\n              )}\n            >\n              <span>Clear</span>\n            </ComboboxClear>\n          </div>\n        </ComboboxPopup>\n      </ComboboxRoot>\n    </FieldPrimitive.Root>\n  );\n}\n\nexport { Multiselect, type MultiselectProps };\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/multiselect.tsx"
    }
  ],
  "type": "registry:ui"
}