import { ReactNode, useEffect, useRef, useState } from "react"; import ArrowDownIcon from "../../assets/arrow-down-icon.svg"; export type DropDownItem = { id: string; text?: string; icon?: ReactNode; onClick?: () => void; isSeparator?: boolean; isDisabled?: boolean; }; export type DropDownProps = { items: DropDownItem[]; }; type PopupState = { isOpen: boolean; X: number; Y: number; }; function DropDown({ items }: DropDownProps) { const [popupState, setPopupState] = useState({ isOpen: false, X: 0, Y: 0, }); const modalRef = useRef(null); useEffect(() => { if (popupState.isOpen) { document.addEventListener("mousedown", handleClickOutside); } else { document.removeEventListener("mousedown", handleClickOutside); } return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [popupState.isOpen]); const handleClickOutside = (event: MouseEvent) => { if (modalRef.current && !modalRef.current.contains(event.target as Node)) { setPopupState((prev) => ({ ...prev, isOpen: false, })); } }; return ( <>
{popupState.isOpen && (
{items.map((item) => ( <> {item.isSeparator ? (
) : (
{ item.onClick?.(); setPopupState((prev) => ({ ...prev, isOpen: false, })); }} className={`cursor-pointer font-normal flex items-center gap-2 py-1 pl-3 pr-7 hover:bg-dropdown ${ item.isDisabled ? "cursor-default hover:bg-transparent text-gray-400" : "" }`} > {item.icon && {item.icon ?? null}} {item.text}
)} ))}
)} ); } export default DropDown;