import React, { useRef, useState } from "react"; import { useRouter } from "next/router"; import useSWR from "swr"; // hooks import useDynamicDropdownPosition from "hooks/use-dynamic-dropdown"; // services import stateService from "services/state.service"; // headless ui import { Combobox } from "@headlessui/react"; // icons import { ChevronDownIcon } from "@heroicons/react/20/solid"; import { CheckIcon, MagnifyingGlassIcon } from "@heroicons/react/24/outline"; import { StateGroupIcon } from "components/icons"; // types import { Tooltip } from "components/ui"; // constants import { IState } from "types"; import { STATES_LIST } from "constants/fetch-keys"; // helper import { getStatesList } from "helpers/state.helper"; type Props = { value: IState; onChange: (data: any, states: IState[] | undefined) => void; className?: string; buttonClassName?: string; optionsClassName?: string; hideDropdownArrow?: boolean; disabled?: boolean; }; export const StateSelect: React.FC = ({ value, onChange, className = "", buttonClassName = "", optionsClassName = "", hideDropdownArrow = false, disabled = false, }) => { const [query, setQuery] = useState(""); const [isOpen, setIsOpen] = useState(false); const dropdownBtn = useRef(null); const dropdownOptions = useRef(null); const [fetchStates, setFetchStates] = useState(false); const router = useRouter(); const { workspaceSlug, projectId } = router.query; const { data: stateGroups } = useSWR( workspaceSlug && projectId && fetchStates ? STATES_LIST(projectId as string) : null, workspaceSlug && projectId && fetchStates ? () => stateService.getStates(workspaceSlug as string, projectId as string) : null ); const states = getStatesList(stateGroups); const options = states?.map((state) => ({ value: state.id, query: state.name, content: (
{state.name}
), })); const filteredOptions = query === "" ? options : options?.filter((option) => option.query.toLowerCase().includes(query.toLowerCase())); const label = (
{value && } {value?.name ?? "State"}
); useDynamicDropdownPosition(isOpen, () => setIsOpen(false), dropdownBtn, dropdownOptions); return ( { onChange(data, states); }} disabled={disabled} > {({ open }: { open: boolean }) => { if (open) { if (!isOpen) setIsOpen(true); setFetchStates(true); } else if (isOpen) setIsOpen(false); return ( <> {label} {!hideDropdownArrow && !disabled && (
setQuery(e.target.value)} placeholder="Search" displayValue={(assigned: any) => assigned?.name} />
{filteredOptions ? ( filteredOptions.length > 0 ? ( filteredOptions.map((option) => ( `flex items-center justify-between gap-2 cursor-pointer select-none truncate rounded px-1 py-1.5 ${ active && !selected ? "bg-custom-background-80" : "" } ${selected ? "text-custom-text-100" : "text-custom-text-200"}` } > {({ selected }) => ( <> {option.content} {selected && } )} )) ) : (

No matching results

) ) : (

Loading...

)}
); }}
); };