import React, { useState } from "react"; import { useRouter } from "next/router"; import useSWR from "swr"; // react-popper import { usePopper } from "react-popper"; // 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"; import { Placement } from "@popperjs/core"; // 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; projectId: string; className?: string; buttonClassName?: string; optionsClassName?: string; placement?: Placement; hideDropdownArrow?: boolean; disabled?: boolean; }; export const StateSelect: React.FC = ({ value, onChange, projectId, className = "", buttonClassName = "", optionsClassName = "", placement, hideDropdownArrow = false, disabled = false, }) => { const [query, setQuery] = useState(""); const [referenceElement, setReferenceElement] = useState(null); const [popperElement, setPopperElement] = useState(null); const [fetchStates, setFetchStates] = useState(false); const { styles, attributes } = usePopper(referenceElement, popperElement, { placement: placement ?? "bottom-start", }); const router = useRouter(); const { workspaceSlug } = router.query; const { data: stateGroups } = useSWR( workspaceSlug && projectId && fetchStates ? STATES_LIST(projectId) : null, workspaceSlug && projectId && fetchStates ? () => stateService.getStates(workspaceSlug as string, projectId) : 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"}
); return ( { onChange(data, states); }} disabled={disabled} > {({ open }: { open: boolean }) => { if (open) setFetchStates(true); return ( <>
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...

)}
); }}
); };