'use client' import { ChevronsUpDownIcon } from 'lucide-react' import { useEffect, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { Command, CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList, } from '@/components/ui/Command' import { Spinner } from '@/components/ui/Spinner' export type AsyncSearchOption = { id: number label: string } type AsyncSearchComboboxProps = { name?: string label: string value: AsyncSearchOption | null onChange?: (option: AsyncSearchOption | null) => void search: (query: string) => Promise emptyOptionLabel?: string dialogDescription?: string isQueryReady?: (query: string) => boolean queryTooShortMessage?: string pinnedOptions?: AsyncSearchOption[] pinnedGroupHeading?: string } export const AsyncSearchCombobox = ({ name, label, value, onChange, search, emptyOptionLabel = 'Nenhum', dialogDescription = 'Digite para buscar.', isQueryReady = () => true, queryTooShortMessage = 'Digite para buscar.', pinnedOptions = [], pinnedGroupHeading = 'Sugestões', }: AsyncSearchComboboxProps) => { const [open, setOpen] = useState(false) const [query, setQuery] = useState('') const [selected, setSelected] = useState(value) const [options, setOptions] = useState([]) const [loading, setLoading] = useState(false) const [failed, setFailed] = useState(false) const requestId = useRef(0) const searchRef = useRef(search) const isQueryReadyRef = useRef(isQueryReady) searchRef.current = search isQueryReadyRef.current = isQueryReady useEffect(() => { setSelected(value) }, [value]) useEffect(() => { if (!open) return if (!isQueryReadyRef.current(query)) { setOptions([]) setLoading(false) setFailed(false) return } const currentRequestId = ++requestId.current const timeout = window.setTimeout(() => { setLoading(true) setFailed(false) void searchRef .current(query.trim()) .then((nextOptions) => { if (requestId.current !== currentRequestId) return setOptions(nextOptions) }) .catch(() => { if (requestId.current !== currentRequestId) return setFailed(true) }) .finally(() => { if (requestId.current === currentRequestId) setLoading(false) }) }, 250) return () => window.clearTimeout(timeout) }, [open, query]) const choose = (option: AsyncSearchOption | null) => { setSelected(option) setOpen(false) setQuery('') onChange?.(option) } const visibleOptions = options.filter((option) => option.id !== selected?.id) const visiblePinned = pinnedOptions.filter((option) => option.id !== selected?.id) return ( <> {name ? : null} {loading ? (
) : failed ? (

Não foi possível concluir a busca.

) : ( <> choose(null)}> {emptyOptionLabel} {selected ? ( choose(selected)} > {selected.label} ) : null} {visiblePinned.length ? ( {visiblePinned.map((option) => ( choose(option)} > {option.label} ))} ) : null} {visibleOptions.length ? ( {visibleOptions.map((option) => ( choose(option)} > {option.label} ))} ) : (

{!isQueryReady(query) ? queryTooShortMessage : 'Nenhum resultado encontrado.'}

)} )}
) }