{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "typed-combobox",
  "type": "registry:component",
  "title": "TypedCombobox",
  "description": "A headless, type-safe combobox component with search functionality, full TypeScript inference, and customizable rendering.",
  "registryDependencies": [
    "button",
    "command",
    "popover",
    "https://typedora-ui.netlify.app/r/typed-utils.json"
  ],
  "files": [
    {
      "path": "registry/default/typed-combobox/typed-combobox.tsx",
      "content": "\"use client\";\n\nimport { CheckIcon, ChevronsUpDownIcon } from \"lucide-react\";\nimport * as React from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n  Command,\n  CommandEmpty,\n  CommandGroup,\n  CommandInput,\n  CommandItem,\n  CommandList,\n} from \"@/components/ui/command\";\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\";\nimport type { ExtractOption, ExtractOptionValue } from \"@/lib/typed-utils\";\nimport { cn } from \"@/lib/utils\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Supported value types for TypedCombobox.\n * Values are serialized to strings internally but typed correctly externally.\n */\nexport type ComboboxValueType = string | number | boolean;\n\n/**\n * Default option type with value and label.\n * Use this as a reference for your custom option types.\n */\nexport type ComboboxOption<T extends ComboboxValueType = string> = {\n  value: T;\n  label: string;\n  disabled?: boolean;\n};\n\n/**\n * A group of combobox options with a label.\n * @template TOption - The full option type including custom properties\n */\nexport type ComboboxOptionGroup<TOption> = {\n  label: string;\n  options: TOption[];\n};\n\n// =============================================================================\n// Render Props Types\n// =============================================================================\n\n/**\n * Props passed to renderTrigger function.\n * @template TOption - The full option type including custom properties\n */\nexport type ComboboxTriggerRenderProps<TOption> = {\n  /** Currently selected option (undefined if none) */\n  selectedOption: TOption | undefined;\n  /** Placeholder text */\n  placeholder: string;\n  /** Whether the combobox is open */\n  open: boolean;\n  /** Whether the combobox is disabled */\n  disabled: boolean;\n  /** Default Button component */\n  Button: typeof Button;\n};\n\n/**\n * Props passed to renderItem function.\n * @template TOption - The full option type including custom properties\n */\nexport type ComboboxItemRenderProps<TOption> = {\n  /** The option data */\n  option: TOption;\n  /** Whether this option is currently selected */\n  isSelected: boolean;\n  /** Whether this option is disabled */\n  isDisabled: boolean;\n  /** Group this option belongs to (undefined if ungrouped) */\n  group: ComboboxOptionGroup<TOption> | undefined;\n  /** Props to spread on CommandItem */\n  itemProps: {\n    value: string;\n    disabled?: boolean;\n    onSelect: () => void;\n  };\n  /** Default item component */\n  Item: typeof CommandItem;\n};\n\n/**\n * Props passed to renderGroup function.\n * @template TOption - The full option type including custom properties\n */\nexport type ComboboxGroupRenderProps<TOption> = {\n  /** The group data */\n  group: ComboboxOptionGroup<TOption>;\n  /** Rendered items inside this group */\n  children: React.ReactNode;\n  /** Default group component */\n  Group: typeof CommandGroup;\n};\n\n/**\n * Props passed to renderEmpty function.\n */\nexport type ComboboxEmptyRenderProps = {\n  /** The current search query */\n  searchQuery: string;\n  /** Default empty component */\n  Empty: typeof CommandEmpty;\n};\n\n/**\n * Props passed to renderContent function.\n */\nexport type ComboboxContentRenderProps = {\n  /** Rendered items/groups */\n  children: React.ReactNode;\n  /** Default content components */\n  Command: typeof Command;\n  CommandInput: typeof CommandInput;\n  CommandList: typeof CommandList;\n  /** Current search query */\n  searchQuery: string;\n  /** Update search query */\n  setSearchQuery: (query: string) => void;\n  /** Search input placeholder */\n  searchPlaceholder: string;\n  /** Empty state component */\n  emptyState: React.ReactNode;\n};\n\n/**\n * Core props for TypedCombobox (for documentation).\n */\nexport interface TypedComboboxBaseProps<\n  TOptions extends\n    | readonly Record<string, unknown>[]\n    | readonly ComboboxOptionGroup<Record<string, unknown>>[],\n  TValueKey extends string = \"value\",\n  TLabelKey extends string = \"label\",\n> {\n  /** Array of options or grouped options */\n  options: TOptions;\n  /** The key to use for the option value (default: \"value\") */\n  valueKey?: TValueKey;\n  /** The key to use for the option label (default: \"label\") */\n  labelKey?: TLabelKey;\n  /** Controlled value */\n  value?: ExtractOptionValue<TOptions, TValueKey>;\n  /** Default value for uncontrolled usage */\n  defaultValue?: ExtractOptionValue<TOptions, TValueKey>;\n  /** Callback when value changes - receives the typed value */\n  onValueChange?: (value: ExtractOptionValue<TOptions, TValueKey>) => void;\n  /** Placeholder text for the trigger button */\n  placeholder?: string;\n  /** Placeholder text for the search input */\n  searchPlaceholder?: string;\n  /** Text to show when no options match the search */\n  emptyText?: string;\n  /** Custom render for trigger */\n  renderTrigger?: (\n    props: ComboboxTriggerRenderProps<ExtractOption<TOptions>>,\n  ) => React.ReactNode;\n  /** Custom render for each item */\n  renderItem?: (\n    props: ComboboxItemRenderProps<ExtractOption<TOptions>>,\n  ) => React.ReactNode;\n  /** Custom render for each group */\n  renderGroup?: (\n    props: ComboboxGroupRenderProps<ExtractOption<TOptions>>,\n  ) => React.ReactNode;\n  /** Custom render for empty state */\n  renderEmpty?: (props: ComboboxEmptyRenderProps) => React.ReactNode;\n  /** Custom render for content wrapper */\n  renderContent?: (props: ComboboxContentRenderProps) => React.ReactNode;\n  /** Whether the combobox is disabled */\n  disabled?: boolean;\n  /** Whether the combobox is open (controlled) */\n  open?: boolean;\n  /** Callback when open state changes */\n  onOpenChange?: (open: boolean) => void;\n  /** Custom filter function for search */\n  filterFn?: (option: ExtractOption<TOptions>, searchQuery: string) => boolean;\n  /** Width of the popover content */\n  popoverWidth?: string | number;\n  /** Class name for the trigger button */\n  triggerClassName?: string;\n  /** Class name for the popover content */\n  contentClassName?: string;\n}\n\n/**\n * Props for the TypedCombobox component.\n * @template TOptions - The options array type\n * @template TValueKey - The key used for the value property (default: \"value\")\n * @template TLabelKey - The key used for the label property (default: \"label\")\n */\nexport interface TypedComboboxProps<\n  TOptions extends\n    | readonly Record<string, unknown>[]\n    | readonly ComboboxOptionGroup<Record<string, unknown>>[],\n  TValueKey extends string = \"value\",\n  TLabelKey extends string = \"label\",\n> extends TypedComboboxBaseProps<TOptions, TValueKey, TLabelKey> {}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Type guard to check if options are grouped\n */\nfunction isGroupedOptions<TOption>(\n  options: readonly TOption[] | readonly ComboboxOptionGroup<TOption>[],\n): options is readonly ComboboxOptionGroup<TOption>[] {\n  return options.length > 0 && \"options\" in (options[0] as object);\n}\n\n/**\n * Serialize a value to string for internal use\n */\nfunction serializeValue<T extends ComboboxValueType>(value: T): string {\n  if (typeof value === \"boolean\") {\n    return value ? \"__boolean_true__\" : \"__boolean_false__\";\n  }\n  if (typeof value === \"number\") {\n    return `__number_${value}__`;\n  }\n  return String(value);\n}\n\n/**\n * Deserialize a string value back to its original type\n */\nfunction deserializeValue<TOption extends Record<string, unknown>>(\n  serialized: string,\n  options: readonly TOption[] | readonly ComboboxOptionGroup<TOption>[],\n  valueKey: keyof TOption,\n): TOption[keyof TOption] {\n  const allOptions = isGroupedOptions(options)\n    ? options.flatMap((group) => group.options)\n    : options;\n\n  const found = allOptions.find(\n    (opt) => serializeValue(opt[valueKey] as ComboboxValueType) === serialized,\n  );\n\n  return found?.[valueKey] as TOption[keyof TOption];\n}\n\n/**\n * Find the selected option object from the current value.\n * Handles both flat and grouped options.\n */\nfunction findSelectedOption<TOption extends Record<string, unknown>>(\n  value: TOption[keyof TOption] | undefined,\n  options: readonly TOption[] | readonly ComboboxOptionGroup<TOption>[],\n  valueKey: keyof TOption,\n): TOption | undefined {\n  if (value === undefined) return undefined;\n\n  const allOptions = isGroupedOptions(options)\n    ? options.flatMap((group) => group.options)\n    : options;\n\n  return allOptions.find((opt) => opt[valueKey] === value);\n}\n\n/**\n * Default filter function - matches label against search query\n */\nfunction defaultFilterFn<TOption extends Record<string, unknown>>(\n  option: TOption,\n  searchQuery: string,\n  labelKey: keyof TOption,\n): boolean {\n  const label = String(option[labelKey] ?? \"\").toLowerCase();\n  return label.includes(searchQuery.toLowerCase());\n}\n\n// =============================================================================\n// Default Render Functions\n// =============================================================================\n\nfunction createDefaultRenderTrigger<\n  TOption extends Record<string, unknown>,\n  TLabelKey extends keyof TOption,\n>(labelKey: TLabelKey, triggerClassName?: string) {\n  return function defaultRenderTrigger({\n    selectedOption,\n    placeholder,\n    open,\n    disabled,\n    Button: ButtonComponent,\n  }: ComboboxTriggerRenderProps<TOption>): React.ReactNode {\n    const label = selectedOption\n      ? String(selectedOption[labelKey] ?? \"\")\n      : placeholder;\n\n    return (\n      <ButtonComponent\n        variant=\"outline\"\n        role=\"combobox\"\n        aria-expanded={open}\n        disabled={disabled}\n        className={cn(\"w-[200px] justify-between\", triggerClassName)}\n      >\n        <span className=\"truncate\">{label}</span>\n        <ChevronsUpDownIcon className=\"ml-2 h-4 w-4 shrink-0 opacity-50\" />\n      </ButtonComponent>\n    );\n  };\n}\n\nfunction createDefaultRenderItem<\n  TOption extends Record<string, unknown>,\n  TLabelKey extends keyof TOption,\n>(labelKey: TLabelKey) {\n  return function defaultRenderItem({\n    option,\n    isSelected,\n    itemProps,\n    Item,\n  }: ComboboxItemRenderProps<TOption>): React.ReactNode {\n    const label = String(option[labelKey] ?? \"\");\n    return (\n      <Item {...itemProps}>\n        <CheckIcon\n          className={cn(\n            \"mr-2 h-4 w-4\",\n            isSelected ? \"opacity-100\" : \"opacity-0\",\n          )}\n        />\n        {label}\n      </Item>\n    );\n  };\n}\n\nfunction defaultRenderEmpty({\n  Empty,\n}: ComboboxEmptyRenderProps): React.ReactNode {\n  return <Empty>No results found.</Empty>;\n}\n\nfunction defaultRenderContent({\n  children,\n  Command: CommandComponent,\n  CommandInput: CommandInputComponent,\n  CommandList: CommandListComponent,\n  searchQuery,\n  setSearchQuery,\n  searchPlaceholder,\n  emptyState,\n}: ComboboxContentRenderProps): React.ReactNode {\n  return (\n    <CommandComponent shouldFilter={false}>\n      <CommandInputComponent\n        placeholder={searchPlaceholder}\n        value={searchQuery}\n        onValueChange={setSearchQuery}\n      />\n      <CommandListComponent>\n        {emptyState}\n        {children}\n      </CommandListComponent>\n    </CommandComponent>\n  );\n}\n\n// =============================================================================\n// Component\n// =============================================================================\n\n/**\n * A headless, type-safe combobox component with full TypeScript inference\n * and customizable rendering via render props.\n *\n * @example\n * ```tsx\n * // Default usage with value/label keys\n * <TypedCombobox\n *   placeholder=\"Select framework...\"\n *   searchPlaceholder=\"Search frameworks...\"\n *   options={[\n *     { value: \"next\", label: \"Next.js\" },\n *     { value: \"remix\", label: \"Remix\" },\n *     { value: \"astro\", label: \"Astro\" },\n *   ] as const}\n *   onValueChange={(value) => {\n *     // value: \"next\" | \"remix\" | \"astro\"\n *   }}\n * />\n *\n * // Custom keys usage with id/name\n * <TypedCombobox\n *   placeholder=\"Select user...\"\n *   options={[\n *     { id: 1, name: \"John Doe\", email: \"john@example.com\" },\n *     { id: 2, name: \"Jane Smith\", email: \"jane@example.com\" },\n *   ] as const}\n *   valueKey=\"id\"\n *   labelKey=\"name\"\n *   onValueChange={(value) => {\n *     // value: 1 | 2\n *   }}\n * />\n * ```\n */\nfunction TypedCombobox<\n  TOptions extends\n    | readonly Record<string, unknown>[]\n    | readonly ComboboxOptionGroup<Record<string, unknown>>[],\n  TValueKey extends string = \"value\",\n  TLabelKey extends string = \"label\",\n>({\n  options,\n  valueKey = \"value\" as TValueKey,\n  labelKey = \"label\" as TLabelKey,\n  value,\n  defaultValue,\n  onValueChange,\n  placeholder = \"Select an option...\",\n  searchPlaceholder = \"Search...\",\n  emptyText: _emptyText = \"No results found.\",\n  open: controlledOpen,\n  onOpenChange,\n  disabled = false,\n  filterFn,\n  popoverWidth = 200,\n  triggerClassName,\n  contentClassName,\n  renderTrigger,\n  renderItem,\n  renderGroup,\n  renderEmpty = defaultRenderEmpty,\n  renderContent = defaultRenderContent,\n}: TypedComboboxProps<TOptions, TValueKey, TLabelKey>) {\n  // Extract the actual option type for internal use\n  type TOption = ExtractOption<TOptions> & Record<string, unknown>;\n  type TValue = ExtractOptionValue<TOptions, TValueKey>;\n\n  // Track open state internally\n  const [internalOpen, setInternalOpen] = React.useState(false);\n  const open = controlledOpen ?? internalOpen;\n\n  // Track internal value for uncontrolled mode\n  const [internalValue, setInternalValue] = React.useState<TValue | undefined>(\n    defaultValue,\n  );\n\n  // Track search query\n  const [searchQuery, setSearchQuery] = React.useState(\"\");\n\n  // Use controlled value if provided, otherwise use internal state\n  const currentValue = value !== undefined ? value : internalValue;\n\n  const handleOpenChange = (newOpen: boolean) => {\n    setInternalOpen(newOpen);\n    onOpenChange?.(newOpen);\n    // Reset search when closing\n    if (!newOpen) {\n      setSearchQuery(\"\");\n    }\n  };\n\n  const handleSelect = (serialized: string) => {\n    const deserialized = deserializeValue(\n      serialized,\n      options as readonly TOption[] | readonly ComboboxOptionGroup<TOption>[],\n      valueKey as keyof TOption,\n    );\n\n    // Toggle selection - if same value is selected, deselect\n    const newValue =\n      currentValue === deserialized ? undefined : (deserialized as TValue);\n\n    // Update internal state for uncontrolled mode\n    if (value === undefined) {\n      setInternalValue(newValue);\n    }\n\n    if (onValueChange && newValue !== undefined) {\n      onValueChange(newValue);\n    }\n\n    handleOpenChange(false);\n  };\n\n  const selectedOption = findSelectedOption(\n    currentValue as TOption[keyof TOption] | undefined,\n    options as readonly TOption[] | readonly ComboboxOptionGroup<TOption>[],\n    valueKey as keyof TOption,\n  );\n\n  const serializedValue =\n    currentValue !== undefined\n      ? serializeValue(currentValue as ComboboxValueType)\n      : undefined;\n\n  // Use provided renderTrigger or create default with labelKey\n  const actualRenderTrigger: (\n    props: ComboboxTriggerRenderProps<ExtractOption<TOptions>>,\n  ) => React.ReactNode =\n    renderTrigger ??\n    (createDefaultRenderTrigger<TOption, keyof TOption>(\n      labelKey as keyof TOption,\n      triggerClassName,\n    ) as (\n      props: ComboboxTriggerRenderProps<ExtractOption<TOptions>>,\n    ) => React.ReactNode);\n\n  // Use provided renderItem or create default with labelKey\n  const actualRenderItem =\n    renderItem ??\n    createDefaultRenderItem<TOption, keyof TOption>(labelKey as keyof TOption);\n\n  // Filter options based on search query\n  const filterOption = (option: TOption): boolean => {\n    if (!searchQuery) return true;\n    if (filterFn) {\n      return filterFn(option as ExtractOption<TOptions>, searchQuery);\n    }\n    return defaultFilterFn(option, searchQuery, labelKey as keyof TOption);\n  };\n\n  // Get filtered options\n  const getFilteredOptions = ():\n    | readonly TOption[]\n    | readonly ComboboxOptionGroup<TOption>[] => {\n    const opts = options as\n      | readonly TOption[]\n      | readonly ComboboxOptionGroup<TOption>[];\n\n    if (isGroupedOptions(opts)) {\n      return opts\n        .map((group) => ({\n          ...group,\n          options: group.options.filter(filterOption),\n        }))\n        .filter((group) => group.options.length > 0);\n    }\n\n    return (opts as readonly TOption[]).filter(filterOption);\n  };\n\n  const filteredOptions = getFilteredOptions();\n\n  // Check if there are any results\n  const hasResults = isGroupedOptions(filteredOptions)\n    ? filteredOptions.some((g) => g.options.length > 0)\n    : filteredOptions.length > 0;\n\n  // Render a single item\n  const renderSingleItem = (\n    option: TOption,\n    group: ComboboxOptionGroup<TOption> | undefined,\n  ) => {\n    const optionValue = option[valueKey as keyof TOption] as ComboboxValueType;\n    const serialized = serializeValue(optionValue);\n    const isSelected = serializedValue === serialized;\n    const isDisabled = (option as { disabled?: boolean }).disabled ?? false;\n\n    return (\n      <React.Fragment key={serialized}>\n        {actualRenderItem({\n          option,\n          isSelected,\n          isDisabled,\n          group,\n          itemProps: {\n            value: serialized,\n            disabled: isDisabled,\n            onSelect: () => handleSelect(serialized),\n          },\n          Item: CommandItem,\n        })}\n      </React.Fragment>\n    );\n  };\n\n  // Render all items (grouped or flat)\n  const renderItems = () => {\n    if (isGroupedOptions(filteredOptions)) {\n      return filteredOptions.map((group) => {\n        const groupChildren = group.options.map((option) =>\n          renderSingleItem(\n            option as TOption,\n            group as ComboboxOptionGroup<TOption>,\n          ),\n        );\n\n        if (renderGroup) {\n          return (\n            <React.Fragment key={group.label}>\n              {renderGroup({\n                group: group as ComboboxOptionGroup<ExtractOption<TOptions>>,\n                children: groupChildren,\n                Group: CommandGroup,\n              })}\n            </React.Fragment>\n          );\n        }\n\n        // Default group rendering if renderGroup not provided\n        return (\n          <CommandGroup key={group.label} heading={group.label}>\n            {groupChildren}\n          </CommandGroup>\n        );\n      });\n    }\n\n    return (filteredOptions as readonly TOption[]).map((option) =>\n      renderSingleItem(option, undefined),\n    );\n  };\n\n  // Render empty state\n  const emptyState = !hasResults\n    ? renderEmpty({\n        searchQuery,\n        Empty: CommandEmpty,\n      })\n    : null;\n\n  const popoverWidthStyle =\n    typeof popoverWidth === \"number\" ? `${popoverWidth}px` : popoverWidth;\n\n  return (\n    <Popover open={open} onOpenChange={handleOpenChange}>\n      <PopoverTrigger asChild>\n        {actualRenderTrigger({\n          selectedOption: selectedOption as unknown as\n            | ExtractOption<TOptions>\n            | undefined,\n          placeholder,\n          open,\n          disabled,\n          Button,\n        })}\n      </PopoverTrigger>\n      <PopoverContent\n        className={cn(\"p-0\", contentClassName)}\n        style={{ width: popoverWidthStyle }}\n      >\n        {renderContent({\n          children: renderItems(),\n          Command,\n          CommandInput,\n          CommandList,\n          searchQuery,\n          setSearchQuery,\n          searchPlaceholder,\n          emptyState,\n        })}\n      </PopoverContent>\n    </Popover>\n  );\n}\n\nexport { TypedCombobox };\n",
      "type": "registry:component"
    }
  ]
}