{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "combobox-async",
  "title": "Async combobox",
  "description": "Styled combobox: the Async set. 5 decorative combobox variations (LoadingCombobox, EmptyCombobox, ErrorCombobox, RecentCombobox, SuggestCombobox) on the ai2 token system, powered by framer-motion, reduced-motion aware and sized sm to xl. Part of the free styled layer.",
  "dependencies": [
    "motion@^12.42.2",
    "lucide-react@^1.23.0"
  ],
  "registryDependencies": [
    "@ai2/tokens"
  ],
  "files": [
    {
      "path": "registry/ai2/styled/combobox-async.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  AlertTriangle,\n  Check,\n  ChevronsUpDown,\n  Clock,\n  Lightbulb,\n  Loader2,\n  RotateCw,\n  Search,\n  SearchX,\n} from \"lucide-react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/* Async combobox family: 5 decorative SELF-CONTAINED searchable selects. NO\n   radix, NO portal, NO cmdk. This family shows the UNHAPPY states: loading, empty\n   result, error, recent searches, suggestion. Every state is reachable BY TYPING.\n   The timing uses a FIXED timeout constant (NO Date.now/Math.random) and is\n   cleared in the effect cleanup. Each export is a complete combobox: a real\n   <input> carrying role=\"combobox\" filters, the arrow keys move the highlight,\n   Enter selects, Escape closes. Color comes ONLY from tokens. */\n\nexport type StyledSize = \"sm\" | \"md\" | \"lg\" | \"xl\"\n\n/* Sahte agdaki gecikme: sabit, deterministik. */\nconst LOADING_MS = 600\n\nconst triggerHeight: Record<StyledSize, string> = {\n  sm: \"h-8\",\n  md: \"h-9\",\n  lg: \"h-10\",\n  xl: \"h-12\",\n}\n\nconst panelWidth: Record<StyledSize, string> = {\n  sm: \"w-56\",\n  md: \"w-64\",\n  lg: \"w-72\",\n  xl: \"w-80\",\n}\n\nexport interface ComboboxOption {\n  value: string\n  label: React.ReactNode\n}\n\ninterface ComboboxProps {\n  className?: string\n  size?: StyledSize\n  placeholder?: string\n  options?: ComboboxOption[]\n  value?: string\n  defaultValue?: string\n  onValueChange?: (v: string) => void\n}\n\nconst defaultOptions: ComboboxOption[] = [\n  { value: \"next\", label: \"Next.js\" },\n  { value: \"react\", label: \"React\" },\n  { value: \"vue\", label: \"Vue\" },\n  { value: \"svelte\", label: \"Svelte\" },\n  { value: \"solid\", label: \"Solid\" },\n  { value: \"astro\", label: \"Astro\" },\n]\n\nfunction nodeText(node: React.ReactNode): string {\n  if (node === null || node === undefined || typeof node === \"boolean\") return \"\"\n  if (typeof node === \"string\" || typeof node === \"number\") return String(node)\n  if (Array.isArray(node)) return node.map(nodeText).join(\"\")\n  if (React.isValidElement(node)) {\n    return nodeText((node.props as { children?: React.ReactNode }).children)\n  }\n  return \"\"\n}\n\nfunction filterOptions(options: ComboboxOption[], query: string): ComboboxOption[] {\n  const q = query.trim().toLowerCase()\n  if (q.length === 0) return options\n  return options.filter((o) => nodeText(o.label).toLowerCase().includes(q))\n}\n\nconst rootBase = \"relative\"\n\nconst inputBase =\n  \"w-full rounded-lg border border-field-border bg-transparent pl-9 pr-9 text-sm text-foreground shadow-xs outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-danger aria-invalid:ring-danger/20 dark:aria-invalid:ring-danger/40\"\n\nconst panelBase =\n  \"absolute left-0 right-0 top-full z-50 mt-2 min-w-56 origin-top overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-lg outline-none\"\n\nconst listBase = \"max-h-60 overflow-y-auto p-1.5\"\n\nconst optionBase =\n  \"flex cursor-pointer select-none items-center gap-2 rounded-lg px-2.5 py-2 text-sm outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:size-4 [&_svg]:shrink-0 [&_i]:text-base [&_i]:leading-none\"\n\nconst stateBase = \"flex flex-col items-center gap-2 px-4 py-7 text-center\"\n\nconst sectionLabel =\n  \"px-2.5 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground\"\n\nconst panelMotion = {\n  initial: { opacity: 0, scale: 0.98, y: -6 },\n  animate: { opacity: 1, scale: 1, y: 0 },\n  exit: { opacity: 0, scale: 0.98, y: -6 },\n}\n\nfunction useCombobox(props: ComboboxProps) {\n  const { options = defaultOptions, value, defaultValue, onValueChange } = props\n  const isControlled = value !== undefined\n  const [internal, setInternal] = React.useState<string | undefined>(defaultValue)\n  const current = isControlled ? value : internal\n\n  const [open, setOpen] = React.useState(false)\n  const [editing, setEditing] = React.useState(false)\n  const [query, setQuery] = React.useState(\"\")\n  const [active, setActive] = React.useState(0)\n\n  const wrapperRef = React.useRef<HTMLDivElement>(null)\n  const uid = React.useId()\n  const listId = `${uid}-list`\n  const optionId = React.useCallback((i: number) => `${uid}-option-${i}`, [uid])\n\n  const selected = React.useMemo(\n    () => (current === undefined ? undefined : options.find((o) => o.value === current)),\n    [options, current]\n  )\n\n  const filtered = React.useMemo(\n    () => (editing ? filterOptions(options, query) : options),\n    [editing, options, query]\n  )\n\n  React.useEffect(() => {\n    setActive((prev) => (prev >= filtered.length ? 0 : prev))\n  }, [filtered.length])\n\n  const close = React.useCallback(() => {\n    setOpen(false)\n    setEditing(false)\n    setQuery(\"\")\n    setActive(0)\n  }, [])\n\n  React.useEffect(() => {\n    if (!open) return\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") close()\n    }\n    const onPointer = (e: PointerEvent) => {\n      const node = wrapperRef.current\n      if (node && e.target instanceof Node && !node.contains(e.target)) close()\n    }\n    window.addEventListener(\"keydown\", onKey)\n    window.addEventListener(\"pointerdown\", onPointer)\n    return () => {\n      window.removeEventListener(\"keydown\", onKey)\n      window.removeEventListener(\"pointerdown\", onPointer)\n    }\n  }, [open, close])\n\n  const commit = React.useCallback(\n    (next: string) => {\n      if (!isControlled) setInternal(next)\n      onValueChange?.(next)\n      close()\n    },\n    [isControlled, onValueChange, close]\n  )\n\n  const onInputKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLInputElement>) => {\n      if (e.key === \"ArrowDown\") {\n        e.preventDefault()\n        setOpen(true)\n        setActive((prev) => (filtered.length === 0 ? 0 : (prev + 1) % filtered.length))\n      } else if (e.key === \"ArrowUp\") {\n        e.preventDefault()\n        setOpen(true)\n        setActive((prev) =>\n          filtered.length === 0 ? 0 : (prev - 1 + filtered.length) % filtered.length\n        )\n      } else if (e.key === \"Enter\") {\n        e.preventDefault()\n        const item = filtered[active]\n        if (item) commit(item.value)\n      } else if (e.key === \"Escape\") {\n        e.preventDefault()\n        close()\n      }\n    },\n    [filtered, active, commit, close]\n  )\n\n  const inputValue = editing ? query : selected ? nodeText(selected.label) : \"\"\n\n  return {\n    open,\n    setOpen,\n    editing,\n    setEditing,\n    query,\n    setQuery,\n    active,\n    setActive,\n    filtered,\n    current,\n    commit,\n    close,\n    onInputKeyDown,\n    wrapperRef,\n    inputValue,\n    listId,\n    optionId,\n  }\n}\n\ntype ComboboxState = ReturnType<typeof useCombobox>\n\n/* Presentation shell: input plus panel. The panel body arrives through children, so every variant draws its own loading, empty and error state. */\nfunction ComboboxField({\n  state,\n  size,\n  className,\n  placeholder,\n  trailing,\n  children,\n}: {\n  state: ComboboxState\n  size: StyledSize\n  className?: string\n  placeholder: string\n  trailing?: React.ReactNode\n  children: React.ReactNode\n}) {\n  const reduce = useReducedMotion() ?? false\n  const {\n    open,\n    setOpen,\n    setEditing,\n    setQuery,\n    active,\n    filtered,\n    onInputKeyDown,\n    wrapperRef,\n    inputValue,\n    listId,\n    optionId,\n  } = state\n\n  const activeId = open && filtered[active] ? optionId(active) : undefined\n\n  return (\n    <div\n      ref={wrapperRef}\n      data-slot=\"styled-combobox\"\n      className={cn(rootBase, panelWidth[size], className)}\n    >\n      <div className=\"relative\">\n        <Search className=\"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground\" />\n        <input\n          role=\"combobox\"\n          aria-expanded={open}\n          aria-controls={listId}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={activeId}\n          value={inputValue}\n          placeholder={placeholder}\n          onFocus={() => {\n            setOpen(true)\n            setEditing(false)\n          }}\n          onChange={(e) => {\n            setOpen(true)\n            setEditing(true)\n            setQuery(e.target.value)\n          }}\n          onKeyDown={onInputKeyDown}\n          className={cn(inputBase, triggerHeight[size])}\n        />\n        <span className=\"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground [&_svg]:size-4 [&_i]:text-base [&_i]:leading-none\">\n          {trailing ?? <ChevronsUpDown className=\"opacity-70\" />}\n        </span>\n      </div>\n\n      <AnimatePresence>\n        {open ? (\n          <motion.div\n            id={listId}\n            role=\"listbox\"\n            className={panelBase}\n            initial={reduce ? { opacity: 0 } : panelMotion.initial}\n            animate={reduce ? { opacity: 1 } : panelMotion.animate}\n            exit={reduce ? { opacity: 0 } : panelMotion.exit}\n            transition={reduce ? { duration: 0 } : { duration: 0.16, ease: \"easeOut\" }}\n          >\n            {children}\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  )\n}\n\n/* Ortak secenek satiri cizimi. */\nfunction OptionRows({ state }: { state: ComboboxState }) {\n  const { filtered, active, setActive, current, commit, optionId } = state\n  return (\n    <>\n      {filtered.map((option, i) => {\n        const isActive = i === active\n        const isSelected = option.value === current\n        return (\n          <div\n            key={option.value}\n            id={optionId(i)}\n            role=\"option\"\n            tabIndex={-1}\n            aria-selected={isSelected}\n            onMouseEnter={() => setActive(i)}\n            onClick={() => commit(option.value)}\n            className={cn(optionBase, (isActive || isSelected) && \"bg-accent text-accent-foreground\")}\n          >\n            <span className=\"flex-1 truncate\">{option.label}</span>\n            {isSelected ? <Check className=\"text-foreground\" /> : null}\n          </div>\n        )\n      })}\n    </>\n  )\n}\n\n/* LoadingCombobox: on every keystroke it shows a skeleton for a FIXED LOADING_MS,\n   then opens the results. The timeout is cleared in the effect cleanup. */\nexport function LoadingCombobox(props: ComboboxProps) {\n  const { className, size = \"md\", placeholder = \"Search framework...\" } = props\n  const state = useCombobox(props)\n  const reduce = useReducedMotion() ?? false\n  const { query, editing, filtered } = state\n\n  const [loading, setLoading] = React.useState(false)\n\n  React.useEffect(() => {\n    if (!editing) return\n    setLoading(true)\n    const id = window.setTimeout(() => setLoading(false), LOADING_MS)\n    return () => {\n      window.clearTimeout(id)\n    }\n  }, [query, editing])\n\n  return (\n    <ComboboxField\n      state={state}\n      size={size}\n      className={className}\n      placeholder={placeholder}\n      trailing={\n        loading ? (\n          <Loader2 className={cn(\"text-muted-foreground\", !reduce && \"animate-spin\")} />\n        ) : undefined\n      }\n    >\n      <div className={listBase}>\n        {loading ? (\n          <div className=\"space-y-1.5 p-1\" aria-live=\"polite\">\n            {[0, 1, 2].map((i) => (\n              <div key={i} className=\"flex items-center gap-2 rounded-lg px-1.5 py-2\">\n                <span\n                  className={cn(\n                    \"h-3 flex-1 rounded-md bg-[color-mix(in_oklab,var(--color-foreground)_10%,transparent)]\",\n                    !reduce && \"animate-pulse motion-reduce:animate-none\"\n                  )}\n                />\n              </div>\n            ))}\n            <p className=\"pt-1 text-center text-xs text-muted-foreground\">Loading results...</p>\n          </div>\n        ) : filtered.length === 0 ? (\n          <p className={cn(stateBase, \"text-sm text-muted-foreground\")}>No results found.</p>\n        ) : (\n          <OptionRows state={state} />\n        )}\n      </div>\n    </ComboboxField>\n  )\n}\n\n/* EmptyCombobox: with no match it shows an empty-state card with an icon and a\n   description. */\nexport function EmptyCombobox(props: ComboboxProps) {\n  const { className, size = \"md\", placeholder = \"Search framework...\" } = props\n  const state = useCombobox(props)\n  const { filtered, query } = state\n\n  return (\n    <ComboboxField state={state} size={size} className={className} placeholder={placeholder}>\n      <div className={listBase}>\n        {filtered.length === 0 ? (\n          <div className={stateBase}>\n            <span className=\"flex size-9 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--color-foreground)_8%,transparent)] text-muted-foreground [&_svg]:size-4 [&_i]:text-base [&_i]:leading-none\">\n              <SearchX />\n            </span>\n            <p className=\"text-sm font-medium text-foreground\">No matches</p>\n            <p className=\"text-xs text-muted-foreground\">\n              Nothing matches {query.trim().length > 0 ? `\"${query.trim()}\"` : \"your search\"}. Try a\n              shorter term.\n            </p>\n          </div>\n        ) : (\n          <OptionRows state={state} />\n        )}\n      </div>\n    </ComboboxField>\n  )\n}\n\n/* ErrorCombobox: an error state plus Retry when there is no match. Retry clears the query and the list comes back. It uses the danger token (NOT destructive). */\nexport function ErrorCombobox(props: ComboboxProps) {\n  const { className, size = \"md\", placeholder = \"Search framework...\" } = props\n  const state = useCombobox(props)\n  const { filtered, setQuery, setEditing, setActive } = state\n\n  const retry = React.useCallback(() => {\n    setQuery(\"\")\n    setEditing(false)\n    setActive(0)\n  }, [setQuery, setEditing, setActive])\n\n  return (\n    <ComboboxField state={state} size={size} className={className} placeholder={placeholder}>\n      <div className={listBase}>\n        {filtered.length === 0 ? (\n          <div className={stateBase}>\n            <span className=\"flex size-9 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--color-danger)_14%,transparent)] text-danger [&_svg]:size-4 [&_i]:text-base [&_i]:leading-none\">\n              <AlertTriangle />\n            </span>\n            <p className=\"text-sm font-medium text-foreground\">Search failed</p>\n            <p className=\"text-xs text-muted-foreground\">\n              We could not reach the index for that term.\n            </p>\n            <button\n              type=\"button\"\n              onClick={retry}\n              className=\"mt-1 inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-transparent px-3 text-xs font-medium text-foreground outline-none transition-colors hover:bg-[color-mix(in_oklab,var(--color-foreground)_6%,transparent)] focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:size-3.5 [&_svg]:shrink-0 [&_i]:text-sm [&_i]:leading-none\"\n            >\n              <RotateCw />\n              Retry\n            </button>\n          </div>\n        ) : (\n          <OptionRows state={state} />\n        )}\n      </div>\n    </ComboboxField>\n  )\n}\n\n/* RecentCombobox: while the query is empty it shows the most recent selections under\n   a \"Recent\" heading; typing switches to the normal filtered list. */\nexport function RecentCombobox(props: ComboboxProps) {\n  const { className, size = \"md\", placeholder = \"Search framework...\" } = props\n  const state = useCombobox(props)\n  const { filtered, editing, query } = state\n\n  const showRecent = !editing || query.trim().length === 0\n\n  return (\n    <ComboboxField state={state} size={size} className={className} placeholder={placeholder}>\n      <div className={listBase}>\n        {showRecent ? (\n          <p className={sectionLabel}>\n            <span className=\"inline-flex items-center gap-1.5\">\n              <Clock className=\"size-3\" />\n              Recent\n            </span>\n          </p>\n        ) : null}\n        {filtered.length === 0 ? (\n          <p className={cn(stateBase, \"text-sm text-muted-foreground\")}>No results found.</p>\n        ) : (\n          <OptionRows state={state} />\n        )}\n      </div>\n    </ComboboxField>\n  )\n}\n\n/* SuggestCombobox: eslesme yoksa DETERMINISTIK bir oneri sunar (ilk harfi\n   paylasan ilk secenek, yoksa listenin ilki). Tiklayinca onu secer. */\nexport function SuggestCombobox(props: ComboboxProps) {\n  const { className, size = \"md\", placeholder = \"Search framework...\", options = defaultOptions } = props\n  const state = useCombobox(props)\n  const { filtered, query, commit } = state\n\n  const suggestion = React.useMemo(() => {\n    const q = query.trim().toLowerCase()\n    if (q.length === 0) return options[0]\n    const byFirstChar = options.find((o) => nodeText(o.label).toLowerCase().startsWith(q[0]))\n    return byFirstChar ?? options[0]\n  }, [options, query])\n\n  return (\n    <ComboboxField state={state} size={size} className={className} placeholder={placeholder}>\n      <div className={listBase}>\n        {filtered.length === 0 ? (\n          <div className={stateBase}>\n            <span className=\"flex size-9 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--color-info)_14%,transparent)] text-info [&_svg]:size-4 [&_i]:text-base [&_i]:leading-none\">\n              <Lightbulb />\n            </span>\n            <p className=\"text-sm font-medium text-foreground\">No exact match</p>\n            {suggestion ? (\n              <button\n                type=\"button\"\n                onClick={() => commit(suggestion.value)}\n                className=\"mt-1 inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-transparent px-3 text-xs font-medium text-foreground outline-none transition-colors hover:bg-[color-mix(in_oklab,var(--color-foreground)_6%,transparent)] focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n              >\n                Did you mean {nodeText(suggestion.label)}?\n              </button>\n            ) : null}\n          </div>\n        ) : (\n          <OptionRows state={state} />\n        )}\n      </div>\n    </ComboboxField>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/ui/combobox-async.tsx"
    }
  ],
  "categories": [
    "styled",
    "combobox"
  ],
  "type": "registry:component"
}