{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "multi-select",
  "type": "registry:component",
  "title": "Multi-select",
  "description": "A combobox for picking many values: chips that fold into +3, grouped options with select all, search, async loading, and creation.",
  "categories": [
    "forms"
  ],
  "dependencies": [
    "@tabler/icons-react",
    "@radix-ui/react-popover"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/multi-select.tsx",
      "type": "registry:component",
      "target": "components/overtrue/multi-select.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport {\n  IconCheck,\n  IconChevronDown,\n  IconLoader2,\n  IconPlus,\n  IconX,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport interface MultiSelectOption {\n  value: string;\n  label: string;\n  /** A second line under the label. */\n  description?: string;\n  /** A glyph shown before the label, such as an icon. */\n  icon?: React.ReactNode;\n  /** An image URL or node shown in a round frame, for people and teams. */\n  avatar?: string | React.ReactNode;\n  /** Options sharing a group render under one heading, in first-seen order. */\n  group?: string;\n  disabled?: boolean;\n  /** Extra words the search matches. */\n  keywords?: string[];\n}\n\nexport type MultiSelectAction =\n  | \"select\"\n  | \"remove\"\n  | \"clear\"\n  | \"create\"\n  | \"select-group\"\n  | \"clear-group\";\n\nexport interface MultiSelectChangeDetails {\n  action: MultiSelectAction;\n  /** The options added or removed by this change. */\n  options: MultiSelectOption[];\n}\n\nexport interface MultiSelectOptionState {\n  selected: boolean;\n  active: boolean;\n  disabled: boolean;\n  query: string;\n}\n\nexport interface MultiSelectChipState {\n  disabled: boolean;\n  remove: () => void;\n}\n\nexport interface MultiSelectLabels {\n  placeholder: string;\n  listbox: string;\n  empty: string;\n  emptyQuery: (query: string) => string;\n  loading: string;\n  loadError: string;\n  create: (query: string) => string;\n  selectAll: string;\n  clearGroup: string;\n  selectGroup: (group: string, count: number) => string;\n  clearGroupLabel: (group: string) => string;\n  clearAll: string;\n  toggle: string;\n  remove: (label: string) => string;\n  more: (count: number) => string;\n  moreLabel: (count: number, names: string) => string;\n  selected: (count: number, max?: number) => string;\n  limitReached: string;\n  results: (count: number) => string;\n  added: (label: string) => string;\n  removed: (label: string) => string;\n  cleared: string;\n}\n\nexport interface MultiSelectProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"defaultValue\" | \"onChange\"\n> {\n  options?: MultiSelectOption[];\n  /** Controlled selection. Leave undefined to let the component manage it. */\n  value?: string[];\n  defaultValue?: string[];\n  onValueChange?: (value: string[], details: MultiSelectChangeDetails) => void;\n  /** Loads options for a query. Results replace `options` while it is in use. */\n  loadOptions?: (\n    query: string,\n    context: { signal: AbortSignal },\n  ) => Promise<MultiSelectOption[]>;\n  /** Debounce for `loadOptions` while typing, in milliseconds. Defaults to 200. */\n  loadDelay?: number;\n  /** Offer to create an option from the query when nothing matches it exactly. */\n  creatable?: boolean;\n  /**\n   * Called with the trimmed query. Return an option, a value string, or nothing\n   * to use the query as both value and label. Async results are awaited.\n   */\n  onCreate?: (\n    query: string,\n  ) =>\n    | MultiSelectOption\n    | string\n    | void\n    | Promise<MultiSelectOption | string | void>;\n  /** Most options that can be selected. */\n  maxSelected?: number;\n  disabled?: boolean;\n  placeholder?: string;\n  /** Controlled or initial open state of the list. */\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** Called as the search text changes, for filtering elsewhere. */\n  onSearchChange?: (query: string) => void;\n  /**\n   * Render the list in place under the field, with no portal, for documentation,\n   * sheets, and previews. It is positioned absolutely, so leave room below.\n   */\n  inline?: boolean;\n  /**\n   * How chips overflow: \"auto\" fits them on one line and folds the rest into\n   * \"+3\"; a number shows at most that many; false wraps every chip.\n   */\n  collapse?: \"auto\" | number | false;\n  /** Offer select all in group headings. Defaults to true. */\n  groupSelectAll?: boolean;\n  /** Keep the list open after a pick. Defaults to true. */\n  keepOpen?: boolean;\n  /** Replaces the search match. Defaults to every word in label, description, value, group, or keywords. */\n  filter?: (option: MultiSelectOption, query: string) => boolean;\n  renderOption?: (option: MultiSelectOption, state: MultiSelectOptionState) => React.ReactNode;\n  /** Replaces a chip's icon and label. The remove button stays. */\n  renderChip?: (option: MultiSelectOption, state: MultiSelectChipState) => React.ReactNode;\n  size?: \"sm\" | \"default\";\n  align?: \"start\" | \"end\";\n  /** Adds one hidden input per value under this name. */\n  name?: string;\n  /** Marks the field invalid. */\n  invalid?: boolean;\n  labels?: Partial<MultiSelectLabels>;\n  /** Classes for the field and the list panel. */\n  fieldClassName?: string;\n  contentClassName?: string;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Helpers                                                                   */\n/* ------------------------------------------------------------------------ */\n\nconst defaultLabels: MultiSelectLabels = {\n  placeholder: \"Select…\",\n  listbox: \"Options\",\n  empty: \"No options\",\n  emptyQuery: (query) => `No matches for “${query}”`,\n  loading: \"Loading…\",\n  loadError: \"Couldn't load options\",\n  create: (query) => `Create “${query}”`,\n  selectAll: \"Select all\",\n  clearGroup: \"Clear\",\n  selectGroup: (group, count) => `Select all ${count} in ${group}`,\n  clearGroupLabel: (group) => `Clear ${group}`,\n  clearAll: \"Clear all\",\n  toggle: \"Show options\",\n  remove: (label) => `Remove ${label}`,\n  more: (count) => `+${count}`,\n  moreLabel: (count, names) => `Show ${count} more: ${names}`,\n  selected: (count, max) =>\n    max !== undefined ? `${count} of ${max} selected` : `${count} selected`,\n  limitReached: \"Limit reached\",\n  results: (count) =>\n    count === 0 ? \"No results\" : `${count} result${count === 1 ? \"\" : \"s\"}`,\n  added: (label) => `${label} added`,\n  removed: (label) => `${label} removed`,\n  cleared: \"Selection cleared\",\n};\n\nfunction searchText(option: MultiSelectOption) {\n  return [\n    option.label,\n    option.description,\n    option.value,\n    option.group,\n    ...(option.keywords ?? []),\n  ]\n    .filter(Boolean)\n    .join(\" \")\n    .toLowerCase();\n}\n\nfunction defaultFilter(option: MultiSelectOption, query: string) {\n  const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n  const text = searchText(option);\n  return words.every((word) => text.includes(word));\n}\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** Bolds the parts of a label the query matched. */\nfunction highlight(text: string, query: string) {\n  const words = query.trim().split(/\\s+/).filter(Boolean).map(escapeRegExp);\n  if (!words.length) return text;\n  const parts = text.split(new RegExp(`(${words.join(\"|\")})`, \"gi\"));\n  return parts.map((part, index) =>\n    index % 2 === 1 ? (\n      <mark key={index} className=\"bg-transparent font-semibold text-foreground\">\n        {part}\n      </mark>\n    ) : (\n      part\n    ),\n  );\n}\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\ntype Row =\n  | { kind: \"group\"; key: string; group: string; options: MultiSelectOption[] }\n  | { kind: \"option\"; key: string; option: MultiSelectOption }\n  | { kind: \"create\"; key: string; query: string };\n\nconst keyframes = `@keyframes multi-select-in{from{opacity:0;transform:translateY(-4px) scale(.98)}to{opacity:1;transform:none}}@keyframes multi-select-chip-in{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:none}}`;\n\nconst panelSurface =\n  \"flex flex-col overflow-hidden rounded-xl border border-border/70 bg-popover/90 text-popover-foreground shadow-xl backdrop-blur-md outline-none motion-safe:animate-[multi-select-in_180ms_cubic-bezier(0.22,1,0.36,1)]\";\n\nfunction Avatar({ avatar, className }: { avatar: string | React.ReactNode; className?: string }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"relative flex shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted [&>*]:size-full\",\n        className,\n      )}\n    >\n      {typeof avatar === \"string\" ? (\n        <img src={avatar} alt=\"\" draggable={false} className=\"size-full object-cover\" />\n      ) : (\n        avatar\n      )}\n      <span className=\"pointer-events-none absolute inset-0 rounded-full ring-1 ring-foreground/10 ring-inset\" />\n    </span>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Multi-select                                                              */\n/* ------------------------------------------------------------------------ */\n\n/** A combobox for picking many values, with chips, grouped options, search, and creation. */\nexport function MultiSelect({\n  options: optionsProp,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  loadOptions,\n  loadDelay = 200,\n  creatable = false,\n  onCreate,\n  maxSelected,\n  disabled = false,\n  placeholder,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  onSearchChange,\n  inline = false,\n  collapse = \"auto\",\n  groupSelectAll = true,\n  keepOpen = true,\n  filter = defaultFilter,\n  renderOption,\n  renderChip,\n  size = \"default\",\n  align = \"start\",\n  name,\n  invalid,\n  labels: labelsProp,\n  className,\n  fieldClassName,\n  contentClassName,\n  id: idProp,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledby,\n  \"aria-describedby\": ariaDescribedby,\n  ...props\n}: MultiSelectProps) {\n  const labels: MultiSelectLabels = { ...defaultLabels, ...labelsProp };\n  const baseId = React.useId();\n  const inputId = idProp ?? `${baseId}-input`;\n  const listboxId = `${baseId}-listbox`;\n  const summaryId = `${baseId}-summary`;\n  const rowId = (index: number) => `${baseId}-row-${index}`;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const fieldRef = React.useRef<HTMLDivElement>(null);\n  const areaRef = React.useRef<HTMLDivElement>(null);\n  const measureRef = React.useRef<HTMLDivElement>(null);\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const panelRef = React.useRef<HTMLDivElement>(null);\n\n  /* ---- Value ---- */\n  const [valueState, setValueState] = React.useState<string[]>(defaultValue ?? []);\n  const value = valueProp ?? valueState;\n  const valueRef = React.useRef(value);\n  valueRef.current = value;\n  const selected = React.useMemo(() => new Set(value), [value]);\n\n  /* ---- Known options, so chips keep their labels after the list changes ---- */\n  const known = React.useRef(new Map<string, MultiSelectOption>());\n  const [created, setCreated] = React.useState<MultiSelectOption[]>([]);\n  for (const option of optionsProp ?? []) known.current.set(option.value, option);\n  for (const option of created) if (!known.current.has(option.value)) known.current.set(option.value, option);\n  const optionFor = (v: string): MultiSelectOption => known.current.get(v) ?? { value: v, label: v };\n\n  /* ---- Open ---- */\n  const [openState, setOpenState] = React.useState(defaultOpen);\n  const open = !disabled && (openProp ?? openState);\n  const openRef = React.useRef(open);\n  openRef.current = open;\n  const setOpen = (next: boolean) => {\n    if (next === openRef.current || (next && disabled)) return;\n    openRef.current = next;\n    if (openProp === undefined) setOpenState(next);\n    onOpenChange?.(next);\n    if (!next) setActiveKey(null);\n  };\n\n  /* ---- Query ---- */\n  const [query, setQueryState] = React.useState(\"\");\n  const setQuery = (next: string) => {\n    setQueryState(next);\n    onSearchChange?.(next);\n  };\n  const trimmed = query.trim();\n\n  /* ---- Async options ---- */\n  const [loaded, setLoaded] = React.useState<MultiSelectOption[] | null>(null);\n  const [loading, setLoading] = React.useState(false);\n  const [loadError, setLoadError] = React.useState(false);\n  const loadRef = React.useRef(loadOptions);\n  loadRef.current = loadOptions;\n  const hasLoader = !!loadOptions;\n  React.useEffect(() => {\n    if (!hasLoader || !open) return;\n    const controller = new AbortController();\n    // Show the spinner while the debounce waits, so typing gets feedback at once.\n    setLoading(true);\n    const timer = window.setTimeout(\n      async () => {\n        setLoadError(false);\n        try {\n          const result = await loadRef.current!(trimmed, { signal: controller.signal });\n          if (controller.signal.aborted) return;\n          for (const option of result) known.current.set(option.value, option);\n          setLoaded(result);\n          setLoading(false);\n        } catch {\n          if (controller.signal.aborted) return;\n          setLoadError(true);\n          setLoading(false);\n        }\n      },\n      trimmed ? loadDelay : 0,\n    );\n    return () => {\n      window.clearTimeout(timer);\n      controller.abort();\n    };\n  }, [hasLoader, open, trimmed, loadDelay]);\n\n  /* ---- Visible options ---- */\n  const source = React.useMemo(() => {\n    const base = hasLoader && loaded ? loaded : (optionsProp ?? []);\n    const seen = new Set(base.map((option) => option.value));\n    return [...base, ...created.filter((option) => !seen.has(option.value))];\n  }, [hasLoader, loaded, optionsProp, created]);\n  const visible =\n    hasLoader && loaded\n      ? source\n      : trimmed\n        ? source.filter((option) => filter(option, trimmed))\n        : source;\n\n  const atLimit = maxSelected !== undefined && value.length >= maxSelected;\n  const exactMatch = trimmed\n    ? [...known.current.values()].some(\n        (option) => option.label.toLowerCase() === trimmed.toLowerCase() || option.value === trimmed,\n      )\n    : true;\n  const canCreate = creatable && !!trimmed && !exactMatch && !loading;\n\n  /* ---- Rows ---- */\n  const { sections, rows, createRow } = React.useMemo(() => {\n    const order: (string | undefined)[] = [];\n    const byGroup = new Map<string | undefined, MultiSelectOption[]>();\n    for (const option of visible) {\n      if (!byGroup.has(option.group)) {\n        byGroup.set(option.group, []);\n        order.push(option.group);\n      }\n      byGroup.get(option.group)!.push(option);\n    }\n    const flat: Row[] = [];\n    const list = order.map((group) => {\n      const groupOptions = byGroup.get(group)!;\n      let header: Row | undefined;\n      if (group && groupSelectAll && groupOptions.filter((option) => !option.disabled).length > 1) {\n        header = { kind: \"group\", key: `g:${group}`, group, options: groupOptions };\n        flat.push(header);\n      }\n      const items = groupOptions.map((option): Row => ({ kind: \"option\", key: `o:${option.value}`, option }));\n      flat.push(...items);\n      return { group, header, items };\n    });\n    let create: Extract<Row, { kind: \"create\" }> | undefined;\n    if (canCreate) {\n      create = { kind: \"create\", key: \"c\", query: trimmed };\n      flat.push(create);\n    }\n    return { sections: list, rows: flat, createRow: create };\n  }, [visible, groupSelectAll, canCreate, trimmed]);\n\n  const groupInfo = (options: MultiSelectOption[]) => {\n    const selectable = options.filter((option) => !option.disabled);\n    const chosen = selectable.filter((option) => selected.has(option.value)).length;\n    const all = chosen === selectable.length;\n    const missing = selectable.length - chosen;\n    const blocked = !all && maxSelected !== undefined && value.length + missing > maxSelected;\n    return { selectable, chosen, all, blocked };\n  };\n\n  const isRowDisabled = (row: Row) => {\n    if (disabled) return true;\n    if (row.kind === \"option\")\n      return !!row.option.disabled || (atLimit && !selected.has(row.option.value));\n    if (row.kind === \"group\") return groupInfo(row.options).blocked;\n    return atLimit;\n  };\n\n  /* ---- Active row ---- */\n  const [activeKey, setActiveKey] = React.useState<string | null>(null);\n  const [engaged, setEngaged] = React.useState(false);\n  const fallbackIndex = (() => {\n    const option = rows.findIndex((row) => row.kind === \"option\" && !isRowDisabled(row));\n    if (option >= 0) return option;\n    return rows.findIndex((row) => !isRowDisabled(row));\n  })();\n  const keyedIndex = activeKey ? rows.findIndex((row) => row.key === activeKey) : -1;\n  const activeIndex = keyedIndex >= 0 ? keyedIndex : fallbackIndex;\n  const activeRow = activeIndex >= 0 ? rows[activeIndex] : undefined;\n  const showActive = engaged && open;\n\n  const scrollToRow = (index: number) => {\n    const list = listRef.current;\n    const el = list?.querySelector<HTMLElement>(`[data-row=\"${index}\"]`);\n    if (!list || !el) return;\n    // Scroll the list only, never the page.\n    const label = el.previousElementSibling?.hasAttribute(\"data-group-label\")\n      ? (el.previousElementSibling as HTMLElement)\n      : el;\n    const top = label.offsetTop - 4;\n    const bottom = el.offsetTop + el.offsetHeight + 4;\n    if (top < list.scrollTop) list.scrollTop = top;\n    else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;\n  };\n\n  const move = (delta: number) => {\n    if (!rows.length) return;\n    let index = activeIndex;\n    for (let step = 0; step < rows.length; step++) {\n      index = (index + delta + rows.length) % rows.length;\n      if (!isRowDisabled(rows[index])) break;\n    }\n    setActiveKey(rows[index].key);\n    setEngaged(true);\n    requestAnimationFrame(() => scrollToRow(index));\n  };\n\n  /* ---- Announcements ---- */\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const announce = (message: string) => setAnnouncement((current) => (current === message ? `${message} ` : message));\n  React.useEffect(() => {\n    if (!open || !trimmed || loading) return;\n    const count = rows.filter((row) => row.kind === \"option\").length;\n    const timer = window.setTimeout(() => announce(labels.results(count)), 450);\n    return () => window.clearTimeout(timer);\n  }, [open, trimmed, loading, rows.length]);\n\n  /* ---- Changes ---- */\n  const commit = (next: string[], details: MultiSelectChangeDetails) => {\n    valueRef.current = next;\n    if (valueProp === undefined) setValueState(next);\n    onValueChange?.(next, details);\n  };\n\n  const afterPick = () => {\n    if (query) setQuery(\"\");\n    if (!keepOpen) setOpen(false);\n  };\n\n  const toggleOption = (option: MultiSelectOption) => {\n    if (disabled || option.disabled) return;\n    const current = valueRef.current;\n    if (current.includes(option.value)) {\n      commit(current.filter((v) => v !== option.value), { action: \"remove\", options: [option] });\n      announce(labels.removed(option.label));\n    } else {\n      if (maxSelected !== undefined && current.length >= maxSelected) {\n        announce(labels.limitReached);\n        return;\n      }\n      commit([...current, option.value], { action: \"select\", options: [option] });\n      announce(labels.added(option.label));\n    }\n    afterPick();\n  };\n\n  const toggleGroup = (group: string, options: MultiSelectOption[]) => {\n    const info = groupInfo(options);\n    const current = valueRef.current;\n    if (info.all) {\n      const leaving = new Set(info.selectable.map((option) => option.value));\n      commit(current.filter((v) => !leaving.has(v)), { action: \"clear-group\", options: info.selectable });\n      announce(labels.clearGroupLabel(group));\n    } else {\n      if (info.blocked) {\n        announce(labels.limitReached);\n        return;\n      }\n      const adding = info.selectable.filter((option) => !current.includes(option.value));\n      commit([...current, ...adding.map((option) => option.value)], { action: \"select-group\", options: adding });\n      announce(labels.selectGroup(group, info.selectable.length));\n    }\n  };\n\n  const createOption = async (text: string) => {\n    if (disabled || atLimit) return;\n    let option: MultiSelectOption = { value: text, label: text };\n    if (onCreate) {\n      const result = await onCreate(text);\n      if (typeof result === \"string\") option = { value: result, label: text };\n      else if (result && typeof result === \"object\") option = result;\n    }\n    known.current.set(option.value, option);\n    setCreated((list) => (list.some((item) => item.value === option.value) ? list : [...list, option]));\n    const current = valueRef.current;\n    if (!current.includes(option.value)) {\n      if (maxSelected !== undefined && current.length >= maxSelected) return;\n      commit([...current, option.value], { action: \"create\", options: [option] });\n    }\n    announce(labels.added(option.label));\n    setActiveKey(`o:${option.value}`);\n    afterPick();\n  };\n\n  const activate = (row: Row) => {\n    if (isRowDisabled(row)) return;\n    if (row.kind === \"option\") toggleOption(row.option);\n    else if (row.kind === \"group\") toggleGroup(row.group, row.options);\n    else void createOption(row.query);\n  };\n\n  const removeValue = (v: string) => {\n    const option = optionFor(v);\n    commit(valueRef.current.filter((item) => item !== v), { action: \"remove\", options: [option] });\n    announce(labels.removed(option.label));\n  };\n\n  const clearAll = () => {\n    const leaving = valueRef.current.map(optionFor);\n    commit([], { action: \"clear\", options: leaving });\n    announce(labels.cleared);\n    setExpanded(false);\n    inputRef.current?.focus();\n  };\n\n  /* ---- Chips ---- */\n  const [expanded, setExpanded] = React.useState(false);\n  const [fit, setFit] = React.useState(Number.POSITIVE_INFINITY);\n  const autoCollapse = collapse === \"auto\" && !expanded;\n  const valueKey = value.join(\"\\u0000\");\n  useIsoLayoutEffect(() => {\n    if (!autoCollapse) return;\n    const area = areaRef.current;\n    const measure = measureRef.current;\n    if (!area || !measure) return;\n    const compute = () => {\n      const widths = Array.from(measure.querySelectorAll<HTMLElement>(\"[data-measure-chip]\")).map(\n        (el) => el.getBoundingClientRect().width,\n      );\n      const more = measure.querySelector<HTMLElement>(\"[data-measure-more]\")?.getBoundingClientRect().width ?? 32;\n      const available = area.clientWidth;\n      const gap = 4;\n      const input = 48;\n      let used = 0;\n      let count = 0;\n      for (let i = 0; i < widths.length; i++) {\n        const next = used + widths[i] + gap;\n        const rest = widths.length - (i + 1);\n        if (next + (rest > 0 ? more + gap : 0) + input > available) break;\n        used = next;\n        count = i + 1;\n      }\n      setFit(Math.max(1, count));\n    };\n    compute();\n    const observer = new ResizeObserver(compute);\n    observer.observe(area);\n    observer.observe(measure);\n    return () => observer.disconnect();\n  }, [autoCollapse, valueKey, size]);\n\n  const wrap = collapse !== \"auto\" || expanded;\n  const visibleCount =\n    collapse === false || expanded\n      ? value.length\n      : collapse === \"auto\"\n        ? Math.min(fit, value.length)\n        : Math.min(Math.max(0, collapse), value.length);\n  const hidden = value.slice(visibleCount);\n\n  const chipTargets = () =>\n    Array.from(fieldRef.current?.querySelectorAll<HTMLElement>(\"[data-chip-target]\") ?? []);\n  const focusChip = (index: number) => {\n    const targets = chipTargets();\n    if (!targets.length || index >= targets.length) inputRef.current?.focus();\n    else targets[Math.max(0, index)]?.focus();\n  };\n\n  const onChipKeyDown = (event: React.KeyboardEvent<HTMLElement>, v?: string) => {\n    const targets = chipTargets();\n    const index = targets.indexOf(event.currentTarget);\n    if (event.key === \"ArrowLeft\") {\n      event.preventDefault();\n      if (index > 0) targets[index - 1].focus();\n    } else if (event.key === \"ArrowRight\") {\n      event.preventDefault();\n      focusChip(index + 1);\n    } else if ((event.key === \"Backspace\" || event.key === \"Delete\") && v !== undefined) {\n      event.preventDefault();\n      removeValue(v);\n      requestAnimationFrame(() => focusChip(event.key === \"Backspace\" ? index - 1 : index));\n    } else if (event.key === \"Escape\" || event.key === \"ArrowDown\") {\n      event.preventDefault();\n      inputRef.current?.focus();\n      if (event.key === \"ArrowDown\") setOpen(true);\n    } else if (event.key.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey) {\n      event.preventDefault();\n      inputRef.current?.focus();\n      setQuery(query + event.key);\n      setOpen(true);\n    }\n  };\n\n  /* ---- Input keys ---- */\n  const onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    if (event.nativeEvent.isComposing) return;\n    const input = event.currentTarget;\n    const atStart = input.selectionStart === 0 && input.selectionEnd === 0;\n    switch (event.key) {\n      case \"ArrowDown\":\n        event.preventDefault();\n        setEngaged(true);\n        if (!open) setOpen(true);\n        else move(1);\n        break;\n      case \"ArrowUp\":\n        event.preventDefault();\n        setEngaged(true);\n        if (!open) {\n          setOpen(true);\n          const last = [...rows].reverse().find((row) => !isRowDisabled(row));\n          if (last) setActiveKey(last.key);\n        } else move(-1);\n        break;\n      case \"PageDown\":\n      case \"PageUp\":\n        if (!open) return;\n        event.preventDefault();\n        move(event.key === \"PageDown\" ? 8 : -8);\n        break;\n      case \"Enter\":\n        if (!open) {\n          if (!query) return;\n          event.preventDefault();\n          setOpen(true);\n          return;\n        }\n        event.preventDefault();\n        if (activeRow) activate(activeRow);\n        break;\n      case \"Escape\":\n        if (open) {\n          event.preventDefault();\n          setOpen(false);\n        } else if (query) {\n          event.preventDefault();\n          setQuery(\"\");\n        }\n        break;\n      case \"Backspace\":\n        if (!query && atStart && value.length) {\n          event.preventDefault();\n          removeValue(value[value.length - 1]);\n        }\n        break;\n      case \"ArrowLeft\":\n        if (atStart && chipTargets().length) {\n          event.preventDefault();\n          const targets = chipTargets();\n          targets[targets.length - 1].focus();\n        }\n        break;\n      case \"Tab\":\n        setOpen(false);\n        break;\n    }\n  };\n\n  /* ---- Outside interaction for the inline list ---- */\n  React.useEffect(() => {\n    if (!inline || !open) return;\n    const onPointerDown = (event: PointerEvent) => {\n      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);\n    };\n    document.addEventListener(\"pointerdown\", onPointerDown);\n    return () => document.removeEventListener(\"pointerdown\", onPointerDown);\n  });\n\n  /* ---- Render pieces ---- */\n  const chipHeight = size === \"sm\" ? \"h-5\" : \"h-6\";\n  const summary = value.length\n    ? `${labels.selected(value.length, maxSelected)}: ${value.map((v) => optionFor(v).label).join(\", \")}`\n    : \"\";\n\n  const renderChipBody = (option: MultiSelectOption, remove: () => void) =>\n    renderChip ? (\n      renderChip(option, { disabled, remove })\n    ) : (\n      <>\n        {option.avatar !== undefined ? (\n          <Avatar avatar={option.avatar} className={size === \"sm\" ? \"size-3.5\" : \"size-4\"} />\n        ) : option.icon ? (\n          <span aria-hidden=\"true\" className=\"flex size-3.5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-3.5\">\n            {option.icon}\n          </span>\n        ) : null}\n        <span className=\"min-w-0 truncate\">{option.label}</span>\n      </>\n    );\n\n  const chipClass = (option: MultiSelectOption) =>\n    cn(\n      \"inline-flex max-w-[12rem] min-w-0 shrink items-center gap-1 rounded-md bg-muted/70 pe-0.5 text-xs font-medium text-foreground ring-1 ring-border/60 transition-[background-color,box-shadow] duration-150 ring-inset dark:bg-muted motion-reduce:transition-none\",\n      // Keyboard focus lands on the remove button; light the whole chip.\n      \"has-[[data-chip-target]:focus-visible]:bg-primary/10 has-[[data-chip-target]:focus-visible]:ring-2 has-[[data-chip-target]:focus-visible]:ring-primary/40\",\n      option.avatar !== undefined ? \"ps-1\" : \"ps-1.5\",\n      disabled && \"pe-1.5\",\n      chipHeight,\n    );\n\n  const chips = value.slice(0, visibleCount).map((v) => {\n    const option = optionFor(v);\n    const remove = () => {\n      removeValue(v);\n      inputRef.current?.focus();\n    };\n    return (\n      <span\n        key={v}\n        data-slot=\"multi-select-chip\"\n        data-value={v}\n        className={cn(chipClass(option), \"motion-safe:animate-[multi-select-chip-in_160ms_cubic-bezier(0.22,1,0.36,1)]\")}\n      >\n        {renderChipBody(option, remove)}\n        {!disabled && (\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          data-chip-target=\"\"\n          disabled={disabled}\n          aria-label={labels.remove(option.label)}\n          onMouseDown={(event) => event.preventDefault()}\n          onClick={remove}\n          onKeyDown={(event) => onChipKeyDown(event, v)}\n          className={cn(\n            \"flex shrink-0 items-center justify-center rounded-[5px] text-muted-foreground transition-colors duration-150 outline-none hover:bg-foreground/10 hover:text-foreground focus-visible:bg-foreground/10 focus-visible:text-foreground disabled:pointer-events-none\",\n            size === \"sm\" ? \"size-4\" : \"size-5\",\n          )}\n        >\n          <IconX aria-hidden=\"true\" className=\"size-3\" stroke={2.25} />\n        </button>\n        )}\n      </span>\n    );\n  });\n\n  const listContent = (\n    <>\n      <div\n        ref={listRef}\n        id={listboxId}\n        role=\"listbox\"\n        aria-multiselectable=\"true\"\n        aria-label={labels.listbox}\n        aria-busy={loading || undefined}\n        className={cn(\n          \"relative max-h-72 min-h-0 overflow-y-auto overscroll-contain p-1 outline-none\",\n          !rows.length && \"hidden\",\n        )}\n      >\n        {sections.map((section, sectionIndex) => {\n          const info = section.group\n            ? groupInfo(section.items.map((row) => (row as Extract<Row, { kind: \"option\" }>).option))\n            : null;\n          const headerId = `${baseId}-group-${sectionIndex}`;\n          const body = section.items.map((row) => {\n            const index = rows.indexOf(row);\n            const option = (row as Extract<Row, { kind: \"option\" }>).option;\n            const isSelected = selected.has(option.value);\n            const isDisabled = isRowDisabled(row);\n            const isActive = showActive && index === activeIndex;\n            return (\n              <div\n                key={row.key}\n                id={rowId(index)}\n                role=\"option\"\n                data-row={index}\n                data-slot=\"multi-select-option\"\n                aria-selected={isSelected}\n                aria-disabled={isDisabled || undefined}\n                data-selected={isSelected ? \"\" : undefined}\n                data-active={isActive ? \"\" : undefined}\n                data-disabled={isDisabled ? \"\" : undefined}\n                onMouseMove={() => {\n                  if (!isDisabled && (activeKey !== row.key || !engaged)) {\n                    setActiveKey(row.key);\n                    setEngaged(true);\n                  }\n                }}\n                onClick={() => {\n                  activate(row);\n                  inputRef.current?.focus();\n                }}\n                className={cn(\n                  \"group/option flex cursor-default items-center gap-2.5 rounded-lg px-2 text-sm transition-colors duration-100 select-none motion-reduce:transition-none\",\n                  option.description ? \"min-h-12 py-1.5 sm:min-h-11\" : \"min-h-10 py-1 sm:min-h-8\",\n                  \"data-[active]:bg-muted data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50\",\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"flex size-4 shrink-0 items-center justify-center rounded-[5px] border transition-[background-color,border-color,box-shadow] duration-150 motion-reduce:transition-none\",\n                    isSelected\n                      ? \"border-primary bg-primary text-primary-foreground shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_2px_6px_-2px_color-mix(in_oklab,var(--color-primary)_70%,transparent)]\"\n                      : \"border-input bg-card group-data-[active]/option:border-foreground/30\",\n                  )}\n                >\n                  {isSelected && <IconCheck className=\"size-3\" stroke={3} />}\n                </span>\n                {renderOption ? (\n                  <span className=\"flex min-w-0 flex-1 items-center gap-2.5\">\n                    {renderOption(option, { selected: isSelected, active: isActive, disabled: isDisabled, query: trimmed })}\n                  </span>\n                ) : (\n                  <>\n                    {option.avatar !== undefined ? (\n                      <Avatar avatar={option.avatar} className={option.description ? \"size-7\" : \"size-5\"} />\n                    ) : option.icon ? (\n                      <span\n                        aria-hidden=\"true\"\n                        className={cn(\n                          \"flex shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4\",\n                          option.description\n                            ? \"size-7 rounded-lg bg-muted/60 ring-1 ring-border/60 ring-inset\"\n                            : \"size-4\",\n                        )}\n                      >\n                        {option.icon}\n                      </span>\n                    ) : null}\n                    <span className=\"flex min-w-0 flex-1 flex-col\">\n                      <span className=\"truncate leading-5\">{highlight(option.label, trimmed)}</span>\n                      {option.description && (\n                        <span className=\"truncate text-xs leading-4 text-muted-foreground\">\n                          {highlight(option.description, trimmed)}\n                        </span>\n                      )}\n                    </span>\n                  </>\n                )}\n              </div>\n            );\n          });\n          if (!section.group) return <React.Fragment key={`section-${sectionIndex}`}>{body}</React.Fragment>;\n          const header = section.header;\n          const headerIndex = header ? rows.indexOf(header) : -1;\n          const headerDisabled = header ? isRowDisabled(header) : true;\n          const headerActive = showActive && headerIndex === activeIndex;\n          return (\n            <div\n              key={`section-${sectionIndex}`}\n              role=\"group\"\n              aria-labelledby={headerId}\n              data-slot=\"multi-select-group\"\n              className={cn(sectionIndex > 0 && \"mt-1 border-t border-border/60 pt-1\")}\n            >\n              {header ? (\n                <div\n                  id={rowId(headerIndex)}\n                  role=\"option\"\n                  data-row={headerIndex}\n                  data-group-label=\"\"\n                  aria-selected={info!.all}\n                  aria-disabled={headerDisabled || undefined}\n                  aria-label={info!.all ? labels.clearGroupLabel(section.group) : labels.selectGroup(section.group, info!.selectable.length)}\n                  data-active={headerActive ? \"\" : undefined}\n                  data-disabled={headerDisabled ? \"\" : undefined}\n                  onMouseMove={() => {\n                    if (!headerDisabled && (activeKey !== header.key || !engaged)) {\n                      setActiveKey(header.key);\n                      setEngaged(true);\n                    }\n                  }}\n                  className=\"group/header flex h-8 cursor-default items-center justify-between gap-2 rounded-lg ps-2 pe-1 select-none\"\n                >\n                  <span id={headerId} className=\"flex min-w-0 items-baseline gap-1.5 text-xs font-medium text-muted-foreground\">\n                    <span className=\"truncate\">{section.group}</span>\n                    <span className=\"font-normal text-muted-foreground/80 tabular-nums\">\n                      {info!.chosen}/{info!.selectable.length}\n                    </span>\n                  </span>\n                  <span\n                    aria-hidden=\"true\"\n                    onClick={() => {\n                      activate(header);\n                      inputRef.current?.focus();\n                    }}\n                    className={cn(\n                      \"inline-flex h-6 shrink-0 items-center rounded-md px-2 text-xs font-medium transition-colors duration-100\",\n                      headerDisabled\n                        ? \"cursor-not-allowed text-muted-foreground/60\"\n                        : \"cursor-pointer text-primary hover:bg-primary/10 group-data-[active]/header:bg-primary/10\",\n                    )}\n                  >\n                    {info!.all ? labels.clearGroup : labels.selectAll}\n                  </span>\n                </div>\n              ) : (\n                <div\n                  id={headerId}\n                  data-group-label=\"\"\n                  role=\"presentation\"\n                  className=\"flex h-8 items-center px-2 text-xs font-medium text-muted-foreground\"\n                >\n                  {section.group}\n                </div>\n              )}\n              {body}\n            </div>\n          );\n        })}\n        {createRow && (\n          <div\n            id={rowId(rows.indexOf(createRow))}\n            role=\"option\"\n            aria-selected={false}\n            aria-disabled={isRowDisabled(createRow) || undefined}\n            data-row={rows.indexOf(createRow)}\n            data-slot=\"multi-select-create\"\n            data-active={showActive && rows.indexOf(createRow) === activeIndex ? \"\" : undefined}\n            data-disabled={isRowDisabled(createRow) ? \"\" : undefined}\n            onMouseMove={() => {\n              if (activeKey !== createRow.key || !engaged) {\n                setActiveKey(createRow.key);\n                setEngaged(true);\n              }\n            }}\n            onClick={() => {\n              activate(createRow);\n              inputRef.current?.focus();\n            }}\n            className={cn(\n              \"flex min-h-10 cursor-default items-center gap-2.5 rounded-lg px-2 text-sm select-none sm:min-h-8\",\n              \"data-[active]:bg-muted data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50\",\n              sections.length > 0 && \"mt-1\",\n            )}\n          >\n            <span aria-hidden=\"true\" className=\"flex size-4 shrink-0 items-center justify-center rounded-[5px] border border-dashed border-foreground/30 text-muted-foreground\">\n              <IconPlus className=\"size-3\" stroke={2.5} />\n            </span>\n            <span className=\"min-w-0 truncate\">\n              {labels.create(createRow.query)}\n            </span>\n          </div>\n        )}\n      </div>\n      {!rows.length && (\n        <div role=\"status\" className=\"flex items-center justify-center gap-2 px-3 py-6 text-center text-sm text-muted-foreground\">\n          {loading ? (\n            <>\n              <IconLoader2 aria-hidden=\"true\" className=\"size-4 animate-spin motion-reduce:animate-none\" />\n              {labels.loading}\n            </>\n          ) : loadError ? (\n            labels.loadError\n          ) : trimmed ? (\n            labels.emptyQuery(trimmed)\n          ) : (\n            labels.empty\n          )}\n        </div>\n      )}\n      {(value.length > 0 || maxSelected !== undefined) && (\n        <div\n          data-slot=\"multi-select-footer\"\n          className=\"flex h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 ps-3 pe-1.5 text-xs text-muted-foreground tabular-nums\"\n        >\n          <span className=\"flex min-w-0 items-center gap-1.5 truncate\">\n            {labels.selected(value.length, maxSelected)}\n            {atLimit && (\n              <>\n                <span aria-hidden=\"true\">·</span>\n                <span className=\"text-amber-700 dark:text-amber-400\">{labels.limitReached}</span>\n              </>\n            )}\n          </span>\n          {value.length > 0 && !disabled && (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              onMouseDown={(event) => event.preventDefault()}\n              onClick={clearAll}\n              className=\"inline-flex h-7 items-center rounded-md px-2 font-medium text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground\"\n            >\n              {labels.clearAll}\n            </button>\n          )}\n        </div>\n      )}\n    </>\n  );\n\n  const panel = (\n    <div\n      ref={panelRef}\n      data-slot=\"multi-select-content\"\n      data-inline={inline ? \"\" : undefined}\n      onMouseDown={(event) => {\n        // Keep focus in the input while the list is used with a pointer.\n        if (!(event.target as HTMLElement).closest(\"input\")) event.preventDefault();\n      }}\n      className={cn(\n        panelSurface,\n        inline\n          ? cn(\"absolute top-full z-30 mt-1.5 w-full origin-top\", align === \"end\" ? \"end-0\" : \"start-0\")\n          : \"max-h-[min(24rem,var(--radix-popover-content-available-height))] origin-(--radix-popover-content-transform-origin)\",\n        contentClassName,\n      )}\n    >\n      {listContent}\n    </div>\n  );\n\n  const field = (\n    <div\n      ref={fieldRef}\n      data-slot=\"multi-select-field\"\n      data-state={open ? \"open\" : \"closed\"}\n      data-disabled={disabled ? \"\" : undefined}\n      data-invalid={invalid ? \"\" : undefined}\n      onMouseDown={(event) => {\n        if (disabled) return;\n        const target = event.target as HTMLElement;\n        if (target.closest(\"button\")) return;\n        if (target !== inputRef.current) {\n          event.preventDefault();\n          inputRef.current?.focus();\n        }\n        if (target === inputRef.current && open) return;\n        setOpen(!open || target === inputRef.current);\n      }}\n      className={cn(\n        \"flex w-full min-w-0 cursor-text items-center gap-1 rounded-lg border border-input bg-card text-foreground shadow-xs transition-[border-color,box-shadow] duration-150 motion-reduce:transition-none\",\n        \"focus-within:border-primary/50 focus-within:ring-2 focus-within:ring-primary/20 data-[state=open]:border-primary/50 data-[state=open]:ring-2 data-[state=open]:ring-primary/20\",\n        \"data-[invalid]:border-destructive/70 data-[invalid]:ring-destructive/20 data-[invalid]:focus-within:ring-2\",\n        \"data-[disabled]:cursor-not-allowed data-[disabled]:bg-muted/40 data-[disabled]:opacity-60 data-[disabled]:shadow-none\",\n        size === \"sm\" ? \"min-h-10 py-[3px] ps-1 pe-1 sm:min-h-8\" : \"min-h-11 py-1 ps-1.5 pe-1 sm:min-h-9\",\n        fieldClassName,\n      )}\n    >\n      <div\n        ref={areaRef}\n        className={cn(\"flex min-w-0 flex-1 items-center gap-1\", wrap ? \"flex-wrap\" : \"flex-nowrap\")}\n      >\n        {chips}\n        {hidden.length > 0 && (\n          <button\n            type=\"button\"\n            tabIndex={-1}\n            data-chip-target=\"\"\n            data-slot=\"multi-select-overflow\"\n            aria-label={labels.moreLabel(hidden.length, hidden.map((v) => optionFor(v).label).join(\", \"))}\n            title={hidden.map((v) => optionFor(v).label).join(\", \")}\n            disabled={disabled}\n            onMouseDown={(event) => event.preventDefault()}\n            onClick={() => {\n              setExpanded(true);\n              inputRef.current?.focus();\n            }}\n            onKeyDown={(event) => {\n              if (event.key === \"Enter\" || event.key === \" \") {\n                event.preventDefault();\n                setExpanded(true);\n                requestAnimationFrame(() => inputRef.current?.focus());\n                return;\n              }\n              onChipKeyDown(event);\n            }}\n            className={cn(\n              \"inline-flex shrink-0 items-center rounded-md px-1.5 text-xs font-medium text-muted-foreground tabular-nums ring-1 ring-border/60 transition-colors duration-150 outline-none ring-inset hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\",\n              chipHeight,\n            )}\n          >\n            {labels.more(hidden.length)}\n          </button>\n        )}\n        <input\n          ref={inputRef}\n          id={inputId}\n          type=\"text\"\n          role=\"combobox\"\n          autoComplete=\"off\"\n          autoCorrect=\"off\"\n          spellCheck={false}\n          disabled={disabled}\n          aria-expanded={open}\n          aria-haspopup=\"listbox\"\n          aria-controls={open ? listboxId : undefined}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={open && showActive && activeIndex >= 0 ? rowId(activeIndex) : undefined}\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabelledby}\n          aria-describedby={[summary ? summaryId : \"\", ariaDescribedby ?? \"\"].filter(Boolean).join(\" \") || undefined}\n          aria-invalid={invalid || undefined}\n          data-slot=\"multi-select-input\"\n          value={query}\n          placeholder={value.length ? undefined : (placeholder ?? labels.placeholder)}\n          onChange={(event) => {\n            setQuery(event.target.value);\n            setActiveKey(null);\n            setEngaged(true);\n            if (!open) setOpen(true);\n          }}\n          onKeyDown={onInputKeyDown}\n          onFocus={() => setEngaged(true)}\n          className={cn(\n            \"min-w-12 flex-1 bg-transparent px-1 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed sm:text-sm\",\n            chipHeight,\n          )}\n        />\n      </div>\n      <div className=\"flex shrink-0 items-center gap-0.5 self-start\" style={{ minHeight: size === \"sm\" ? 20 : 24 }}>\n        {loading && (\n          <IconLoader2\n            aria-hidden=\"true\"\n            className=\"mx-1 size-4 animate-spin text-muted-foreground motion-reduce:animate-none\"\n          />\n        )}\n        {value.length > 0 && !disabled && (\n          <button\n            type=\"button\"\n            aria-label={labels.clearAll}\n            title={labels.clearAll}\n            onMouseDown={(event) => event.preventDefault()}\n            onClick={clearAll}\n            className=\"flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\"\n          >\n            <IconX aria-hidden=\"true\" className=\"size-3.5\" />\n          </button>\n        )}\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label={labels.toggle}\n          disabled={disabled}\n          onMouseDown={(event) => {\n            event.preventDefault();\n            inputRef.current?.focus();\n            setOpen(!open);\n          }}\n          className=\"flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none\"\n        >\n          <IconChevronDown\n            aria-hidden=\"true\"\n            className={cn(\n              \"size-4 transition-transform duration-200 motion-reduce:transition-none\",\n              open && \"rotate-180\",\n            )}\n          />\n        </button>\n      </div>\n    </div>\n  );\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"multi-select\"\n      data-state={open ? \"open\" : \"closed\"}\n      data-disabled={disabled ? \"\" : undefined}\n      onBlur={(event) => {\n        const next = event.relatedTarget as Node | null;\n        if (next && (rootRef.current?.contains(next) || panelRef.current?.contains(next))) return;\n        setExpanded(false);\n        setEngaged(false);\n        if (query) setQuery(\"\");\n        setOpen(false);\n      }}\n      className={cn(\"relative w-full min-w-0\", className)}\n      {...props}\n    >\n      <style>{keyframes}</style>\n      {name && value.map((v) => <input key={v} type=\"hidden\" name={name} value={v} />)}\n      <span id={summaryId} className=\"sr-only\">\n        {summary}\n      </span>\n\n      {/* Measures chip widths for the one-line layout. */}\n      {collapse === \"auto\" && (\n        <div\n          ref={measureRef}\n          aria-hidden=\"true\"\n          inert\n          className=\"pointer-events-none invisible absolute start-0 top-0 flex h-0 items-center gap-1 overflow-hidden whitespace-nowrap\"\n        >\n          {value.map((v) => {\n            const option = optionFor(v);\n            return (\n              <span key={v} data-measure-chip=\"\" className={cn(chipClass(option), \"shrink-0\")}>\n                {renderChipBody(option, () => {})}\n                <span className={size === \"sm\" ? \"size-4\" : \"size-5\"} />\n              </span>\n            );\n          })}\n          <span\n            data-measure-more=\"\"\n            className={cn(\"inline-flex shrink-0 items-center rounded-md px-1.5 text-xs font-medium tabular-nums\", chipHeight)}\n          >\n            {labels.more(value.length)}\n          </span>\n        </div>\n      )}\n\n      {inline ? (\n        <>\n          {field}\n          {open && panel}\n        </>\n      ) : (\n        <PopoverPrimitive.Root open={open} onOpenChange={setOpen}>\n          <PopoverPrimitive.Anchor asChild>{field}</PopoverPrimitive.Anchor>\n          <PopoverPrimitive.Portal>\n            <PopoverPrimitive.Content\n              role=\"presentation\"\n              align={align}\n              side=\"bottom\"\n              sideOffset={6}\n              collisionPadding={8}\n              onOpenAutoFocus={(event) => event.preventDefault()}\n              onCloseAutoFocus={(event) => event.preventDefault()}\n              onInteractOutside={(event) => {\n                if (rootRef.current?.contains(event.target as Node)) event.preventDefault();\n              }}\n              style={{ width: \"var(--radix-popover-trigger-width)\" }}\n              className=\"z-50 min-w-[min(16rem,var(--radix-popover-content-available-width))] outline-none\"\n            >\n              {panel}\n            </PopoverPrimitive.Content>\n          </PopoverPrimitive.Portal>\n        </PopoverPrimitive.Root>\n      )}\n\n      <div aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {announcement}\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/multi-select. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
