import { useState, useRef, useEffect, useCallback } from 'react' import { cn } from '@/lib/utils' import { ChevronDown, X } from 'lucide-react' export interface ComboboxOption { value: string label: string description?: string group?: string } interface ComboboxProps { value: string onChange: (value: string) => void options: ComboboxOption[] placeholder?: string disabled?: boolean className?: string allowCustomValue?: boolean showClear?: boolean } export function Combobox({ value, onChange, options, placeholder = 'Select or type...', disabled = false, className, allowCustomValue = true, showClear = false, }: ComboboxProps) { const [isOpen, setIsOpen] = useState(false) const [inputValue, setInputValue] = useState(() => { const selectedOption = options.find(o => o.value === value) return selectedOption?.label || value }) const [selectedIndex, setSelectedIndex] = useState(0) const [isUserTyping, setIsUserTyping] = useState(false) const inputRef = useRef(null) const listRef = useRef(null) const containerRef = useRef(null) useEffect(() => { if (!isUserTyping) { const selectedOption = options.find(o => o.value === value) setInputValue(selectedOption?.label || value) } }, [value, options, isUserTyping]) const isExactMatch = options.some(o => o.value === value || o.label === inputValue) const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option => option.value.toLowerCase().includes(inputValue.toLowerCase()) || option.label.toLowerCase().includes(inputValue.toLowerCase()) || (option.description?.toLowerCase().includes(inputValue.toLowerCase())) ) const groupedOptions = filteredOptions.reduce((acc, option) => { const group = option.group || '' if (!acc[group]) acc[group] = [] acc[group].push(option) return acc }, {} as Record) const flatFilteredOptions = Object.values(groupedOptions).flat() useEffect(() => { setSelectedIndex(0) }, [inputValue]) useEffect(() => { if (!isOpen) return const handleClickOutside = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setIsOpen(false) if (allowCustomValue) { onChange(inputValue) } else if (!options.some(o => o.value === inputValue)) { setInputValue(value) } } } document.addEventListener('mousedown', handleClickOutside) return () => document.removeEventListener('mousedown', handleClickOutside) }, [isOpen, inputValue, value, onChange, options, allowCustomValue]) useEffect(() => { if (!isOpen || !listRef.current) return const items = listRef.current.querySelectorAll('[data-option]') const selectedItem = items[selectedIndex] as HTMLElement if (selectedItem) { selectedItem.scrollIntoView({ block: 'nearest' }) } }, [selectedIndex, isOpen]) const handleSelect = useCallback((optionValue: string) => { const selectedOption = options.find(o => o.value === optionValue) setInputValue(selectedOption?.label || optionValue) onChange(optionValue) setIsOpen(false) setIsUserTyping(false) inputRef.current?.blur() }, [onChange, options]) const handleKeyDown = useCallback((e: React.KeyboardEvent) => { if (!isOpen) { if (e.key === 'ArrowDown' || e.key === 'Enter') { setIsOpen(true) e.preventDefault() } return } switch (e.key) { case 'ArrowDown': e.preventDefault() setSelectedIndex(prev => Math.min(prev + 1, flatFilteredOptions.length - 1)) break case 'ArrowUp': e.preventDefault() setSelectedIndex(prev => Math.max(prev - 1, 0)) break case 'Enter': e.preventDefault() if (flatFilteredOptions[selectedIndex]) { handleSelect(flatFilteredOptions[selectedIndex].value) } else if (allowCustomValue && inputValue) { handleSelect(inputValue) } break case 'Escape': e.preventDefault() setIsOpen(false) setInputValue(value) break case 'Tab': setIsOpen(false) if (allowCustomValue) { onChange(inputValue) } break } }, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, value, onChange]) const handleInputChange = useCallback((e: React.ChangeEvent) => { const newValue = e.target.value setInputValue(newValue) setIsOpen(true) setIsUserTyping(true) if (allowCustomValue) { onChange(newValue) } }, [allowCustomValue, onChange]) const handleFocus = useCallback(() => { setIsOpen(true) }, []) let optionIndex = -1 return (
{showClear && value && ( )}
{isOpen && flatFilteredOptions.length > 0 && (
{Object.entries(groupedOptions).map(([group, groupOptions]) => (
{group && (
{group}
)} {groupOptions.map((option) => { optionIndex++ const currentIndex = optionIndex const isSelected = currentIndex === selectedIndex return ( ) })}
))}
)} {isOpen && flatFilteredOptions.length === 0 && inputValue && allowCustomValue && (
Press Enter to use "{inputValue}"
)}
) }