{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "autocomplete",
  "type": "registry:ui",
  "title": "Autocomplete",
  "author": "Rishabh Bose <https://theb0se.vercel.app/>",
  "description": "Customizable search combobox with instant filtering, grouped categories, keyboard navigation, and spring-animated dropdown results.",
  "dependencies": [
    "framer-motion",
    "lucide-react",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "components/ui/autocomplete.tsx",
      "content": "\"use client\";\n\nimport React, { useState, useRef, useEffect, useMemo, useId } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"framer-motion\";\nimport { Check, ChevronDown, Search, X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AutocompleteOption {\n  value: string;\n  label: string;\n  description?: string;\n  category?: string;\n  icon?: React.ReactNode;\n  disabled?: boolean;\n}\n\nexport interface AutocompleteProps {\n  /** Array of selectable options */\n  options?: AutocompleteOption[];\n  /** Currently selected value (controlled) */\n  value?: string;\n  /** Default selected value (uncontrolled) */\n  defaultValue?: string;\n  /** Callback fired when an option is selected */\n  onChange?: (value: string, option: AutocompleteOption | null) => void;\n  /** Input placeholder text */\n  placeholder?: string;\n  /** Optional label displayed above the control */\n  label?: string;\n  /** Text displayed when no options match the query */\n  emptyMessage?: string;\n  /** Allow clearing the current selection */\n  clearable?: boolean;\n  /** Disable the entire input */\n  disabled?: boolean;\n  /** Additional container class names */\n  className?: string;\n}\n\nconst DEFAULT_OPTIONS: AutocompleteOption[] = [\n  {\n    value: \"nextjs\",\n    label: \"Next.js 14\",\n    category: \"Frameworks\",\n    description: \"App Router, Server Components & Actions\",\n  },\n  {\n    value: \"react\",\n    label: \"React 18\",\n    category: \"Frameworks\",\n    description: \"Concurrent UI library with Hooks\",\n  },\n  {\n    value: \"tailwind\",\n    label: \"Tailwind CSS\",\n    category: \"Styling\",\n    description: \"Utility-first CSS framework\",\n  },\n  {\n    value: \"framer\",\n    label: \"Framer Motion\",\n    category: \"Animation\",\n    description: \"Production-ready spring physics for React\",\n  },\n  {\n    value: \"typescript\",\n    label: \"TypeScript\",\n    category: \"Language\",\n    description: \"Strongly typed JavaScript at any scale\",\n  },\n];\n\nexport function Autocomplete({\n  options = DEFAULT_OPTIONS,\n  value: controlledValue,\n  defaultValue = \"\",\n  onChange,\n  placeholder = \"Search options...\",\n  label,\n  emptyMessage = \"No matching results found.\",\n  clearable = true,\n  disabled = false,\n  className,\n}: AutocompleteProps) {\n  const shouldReduceMotion = useReducedMotion();\n  const listboxId = useId();\n  const [internalValue, setInternalValue] = useState(defaultValue);\n  const selectedValue =\n    controlledValue !== undefined ? controlledValue : internalValue;\n\n  const selectedOption = useMemo(\n    () => (options || []).find((o) => o.value === selectedValue) || null,\n    [options, selectedValue]\n  );\n\n  const [open, setOpen] = useState(false);\n  const [query, setQuery] = useState(\"\");\n  const [activeIndex, setActiveIndex] = useState(0);\n\n  const containerRef = useRef<HTMLDivElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n\n  const filteredOptions = useMemo(() => {\n    const safeOptions = options || [];\n    const q = query.trim().toLowerCase();\n    if (!q) return safeOptions;\n    return safeOptions.filter(\n      (opt) =>\n        opt.label.toLowerCase().includes(q) ||\n        opt.value.toLowerCase().includes(q) ||\n        (opt.description && opt.description.toLowerCase().includes(q)) ||\n        (opt.category && opt.category.toLowerCase().includes(q))\n    );\n  }, [options, query]);\n\n  const groupedOptions = useMemo(() => {\n    const groups = new Map<string, AutocompleteOption[]>();\n    for (const opt of filteredOptions) {\n      const cat = opt.category || \"Options\";\n      if (!groups.has(cat)) groups.set(cat, []);\n      groups.get(cat)!.push(opt);\n    }\n    return Array.from(groups.entries());\n  }, [filteredOptions]);\n\n  useEffect(() => {\n    setActiveIndex(0);\n  }, [query, open]);\n\n  useEffect(() => {\n    if (!open || !listRef.current) return;\n    const activeEl = listRef.current.querySelector<HTMLElement>(\n      `[data-option-index=\"${activeIndex}\"]`\n    );\n    activeEl?.scrollIntoView({ block: \"nearest\" });\n  }, [activeIndex, open]);\n\n  useEffect(() => {\n    if (!open) return;\n    const handleOutside = (e: MouseEvent) => {\n      if (\n        containerRef.current &&\n        !containerRef.current.contains(e.target as Node)\n      ) {\n        setOpen(false);\n        setQuery(\"\");\n      }\n    };\n    document.addEventListener(\"mousedown\", handleOutside);\n    return () => document.removeEventListener(\"mousedown\", handleOutside);\n  }, [open]);\n\n  const handleSelect = (opt: AutocompleteOption) => {\n    if (opt.disabled) return;\n    if (controlledValue === undefined) {\n      setInternalValue(opt.value);\n    }\n    onChange?.(opt.value, opt);\n    setOpen(false);\n    setQuery(\"\");\n  };\n\n  const handleClear = (e: React.MouseEvent) => {\n    e.stopPropagation();\n    if (controlledValue === undefined) {\n      setInternalValue(\"\");\n    }\n    onChange?.(\"\", null);\n    setQuery(\"\");\n    inputRef.current?.focus();\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (!open && (e.key === \"ArrowDown\" || e.key === \"Enter\")) {\n      e.preventDefault();\n      setOpen(true);\n      return;\n    }\n\n    if (!open) return;\n\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      setActiveIndex((prev) =>\n        filteredOptions.length > 0 ? (prev + 1) % filteredOptions.length : 0\n      );\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      setActiveIndex((prev) =>\n        filteredOptions.length > 0\n          ? (prev - 1 + filteredOptions.length) % filteredOptions.length\n          : 0\n      );\n    } else if (e.key === \"Enter\") {\n      e.preventDefault();\n      const target = filteredOptions[activeIndex];\n      if (target && !target.disabled) {\n        handleSelect(target);\n      }\n    } else if (e.key === \"Escape\") {\n      e.preventDefault();\n      setOpen(false);\n      setQuery(\"\");\n      inputRef.current?.blur();\n    }\n  };\n\n  return (\n    <div ref={containerRef} className={cn(\"relative w-full max-w-sm\", className)}>\n      {label && (\n        <label className=\"mb-1.5 block text-xs font-medium text-neutral-700 dark:text-neutral-300\">\n          {label}\n        </label>\n      )}\n\n      {/* Input trigger container */}\n      <div\n        onClick={() => {\n          if (!disabled) {\n            setOpen(true);\n            inputRef.current?.focus();\n          }\n        }}\n        className={cn(\n          \"flex h-10 w-full items-center gap-2 rounded-xl border bg-white px-3 text-sm transition-colors dark:bg-[#0A0A0A]\",\n          open\n            ? \"border-black ring-2 ring-black/10 dark:border-white dark:ring-white/10\"\n            : \"border-neutral-200 hover:border-neutral-400 dark:border-[#262626] dark:hover:border-neutral-600\",\n          disabled && \"cursor-not-allowed opacity-50\"\n        )}\n      >\n        <Search className=\"h-3.5 w-3.5 shrink-0 text-neutral-400\" />\n\n        <input\n          ref={inputRef}\n          type=\"text\"\n          role=\"combobox\"\n          aria-expanded={open}\n          aria-autocomplete=\"list\"\n          aria-controls={listboxId}\n          disabled={disabled}\n          value={open ? query : selectedOption?.label || \"\"}\n          placeholder={selectedOption ? selectedOption.label : placeholder}\n          onChange={(e) => {\n            setQuery(e.target.value);\n            if (!open) setOpen(true);\n          }}\n          onFocus={() => !disabled && setOpen(true)}\n          onKeyDown={handleKeyDown}\n          className=\"h-full w-full bg-transparent text-xs text-black placeholder:text-neutral-400 focus:outline-none dark:text-white dark:placeholder:text-neutral-500\"\n        />\n\n        {clearable && selectedOption && !disabled && (\n          <button\n            type=\"button\"\n            onClick={handleClear}\n            aria-label=\"Clear selection\"\n            className=\"cursor-pointer rounded p-0.5 text-neutral-400 transition-colors hover:text-black dark:hover:text-white\"\n          >\n            <X className=\"h-3.5 w-3.5\" />\n          </button>\n        )}\n\n        <ChevronDown\n          className={cn(\n            \"h-3.5 w-3.5 shrink-0 text-neutral-400 transition-transform duration-200\",\n            open && \"rotate-180 text-black dark:text-white\"\n          )}\n        />\n      </div>\n\n      {/* Dropdown Listbox */}\n      <AnimatePresence>\n        {open && (\n          <motion.div\n            ref={listRef}\n            id={listboxId}\n            role=\"listbox\"\n            initial={\n              shouldReduceMotion ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.98 }\n            }\n            animate={\n              shouldReduceMotion ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }\n            }\n            exit={\n              shouldReduceMotion ? { opacity: 0 } : { opacity: 0, y: -4, scale: 0.98 }\n            }\n            transition={{\n              type: \"spring\",\n              stiffness: 420,\n              damping: 28,\n            }}\n            className=\"absolute left-0 right-0 top-[calc(100%+6px)] z-50 max-h-60 overflow-y-auto rounded-xl border border-neutral-200 bg-white p-1.5 shadow-2xl dark:border-[#262626] dark:bg-[#0A0A0A]\"\n          >\n            {filteredOptions.length === 0 ? (\n              <div className=\"px-3 py-6 text-center text-xs text-neutral-500\">\n                {emptyMessage}\n              </div>\n            ) : (\n              groupedOptions.map(([category, items]) => (\n                <div key={category} className=\"mb-1 last:mb-0\">\n                  {groupedOptions.length > 1 && (\n                    <div className=\"px-2.5 py-1 font-mono text-[10px] uppercase tracking-wider text-neutral-400 dark:text-neutral-500\">\n                      {category}\n                    </div>\n                  )}\n                  {items.map((opt) => {\n                    const flatIndex = filteredOptions.indexOf(opt);\n                    const isActive = flatIndex === activeIndex;\n                    const isSelected = opt.value === selectedValue;\n\n                    return (\n                      <button\n                        key={opt.value}\n                        type=\"button\"\n                        role=\"option\"\n                        data-option-index={flatIndex}\n                        aria-selected={isSelected}\n                        disabled={opt.disabled}\n                        onMouseEnter={() => setActiveIndex(flatIndex)}\n                        onMouseDown={(e) => e.preventDefault()}\n                        onClick={() => handleSelect(opt)}\n                        className={cn(\n                          \"flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-2.5 py-2 text-left text-xs transition-colors\",\n                          isActive\n                            ? \"bg-neutral-100 text-black dark:bg-[#161616] dark:text-white\"\n                            : \"text-neutral-700 dark:text-neutral-300\",\n                          opt.disabled && \"cursor-not-allowed opacity-40\"\n                        )}\n                      >\n                        <div className=\"min-w-0 flex-1\">\n                          <div className=\"flex items-center gap-2 font-medium\">\n                            {opt.icon && (\n                              <span className=\"shrink-0 text-neutral-400\">\n                                {opt.icon}\n                              </span>\n                            )}\n                            <span className=\"truncate\">{opt.label}</span>\n                          </div>\n                          {opt.description && (\n                            <p className=\"mt-0.5 truncate text-[11px] text-neutral-500 dark:text-neutral-400\">\n                              {opt.description}\n                            </p>\n                          )}\n                        </div>\n\n                        {isSelected && (\n                          <Check className=\"h-3.5 w-3.5 shrink-0 text-black dark:text-white\" />\n                        )}\n                      </button>\n                    );\n                  })}\n                </div>\n              ))\n            )}\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nexport default Autocomplete;\n",
      "type": "registry:ui",
      "target": "components/ui/autocomplete.tsx"
    },
    {
      "path": "lib/utils.ts",
      "content": "import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport async function copyToClipboard(text: string): Promise<boolean> {\n  if (typeof window === \"undefined\") return false;\n\n  try {\n    if (navigator.clipboard && window.isSecureContext) {\n      await navigator.clipboard.writeText(text);\n      return true;\n    }\n\n    const textArea = document.createElement(\"textarea\");\n    textArea.value = text;\n    textArea.style.position = \"fixed\";\n    textArea.style.left = \"-999999px\";\n    textArea.style.top = \"-999999px\";\n    document.body.appendChild(textArea);\n    textArea.focus();\n    textArea.select();\n    const succeeded = document.execCommand(\"copy\");\n    textArea.remove();\n    return succeeded;\n  } catch {\n    return false;\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/utils.ts"
    }
  ]
}
