import React, { useRef, useState } from "react"; // headless ui import { Combobox, Transition } from "@headlessui/react"; // hooks import useOutsideClickDetector from "hooks/use-outside-click-detector"; // icons import { Check, Search } from "lucide-react"; // types import { Props } from "./types"; export const CustomSelectAttribute: React.FC< Props & ( | { multiple?: false; value: string | undefined } | { multiple?: true; value: string[] | undefined } ) > = (props) => { const { attributeDetails, multiple = false, onChange, value } = props; const [isOpen, setIsOpen] = useState(false); const [query, setQuery] = useState(""); const dropdownButtonRef = useRef(null); const dropdownOptionsRef = useRef(null); const selectedOption = attributeDetails.children.find((option) => option.id === value) ?? attributeDetails.children.find((option) => option.is_default); const options = attributeDetails.children.filter((option) => option.display_name.toLowerCase().includes(query.toLowerCase()) ); const handleOnOpen = () => { const dropdownButton = dropdownButtonRef.current; const dropdownOptions = dropdownOptionsRef.current; if (!dropdownButton || !dropdownOptions) return; const dropdownWidth = dropdownOptions.clientWidth; const dropdownHeight = dropdownOptions.clientHeight; const dropdownBtnX = dropdownButton.getBoundingClientRect().x; const dropdownBtnY = dropdownButton.getBoundingClientRect().y; const dropdownBtnHeight = dropdownButton.clientHeight; let top = dropdownBtnY + dropdownBtnHeight; if (dropdownBtnY + dropdownHeight > window.innerHeight) top = dropdownBtnY - dropdownHeight - 10; else top = top + 4; let left = dropdownBtnX; if (dropdownBtnX + dropdownWidth > window.innerWidth) left = dropdownBtnX - dropdownWidth; dropdownOptions.style.top = `${Math.round(top)}px`; dropdownOptions.style.left = `${Math.round(left)}px`; }; useOutsideClickDetector(dropdownOptionsRef, () => { if (isOpen) setIsOpen(false); }); const comboboxProps: any = { value, onChange, }; if (multiple) comboboxProps.multiple = true; return ( {({ open }: { open: boolean }) => { if (open) handleOnOpen(); return ( <> {value ? ( Array.isArray(value) ? ( value.length > 0 ? (
{value.map((v) => { const optionDetails = options.find((o) => o.id === v); return ( {optionDetails?.display_name} ); })}
) : (
Select {attributeDetails.display_name}
) ) : ( o.id === value)?.color}40`, }} > {options.find((o) => o.id === value)?.display_name} ) ) : (
Select {attributeDetails.display_name}
)}
setQuery(e.target.value)} placeholder="Type to search..." displayValue={(assigned: any) => assigned?.name} />
{(options ?? []).map((option) => ( `flex items-center justify-between gap-1 cursor-pointer select-none truncate rounded px-1 py-1.5 w-full ${ active ? "bg-custom-background-80" : "" }` } > {({ selected }) => ( <> {option.display_name} {selected && } )} ))}
); }}
); };