import * as React from "react"; import ReactDOM from "react-dom"; import { Menu } from "@headlessui/react"; import { usePopper } from "react-popper"; import { ChevronDown, MoreHorizontal } from "lucide-react"; // hooks import { useDropdownKeyDown } from "../hooks/use-dropdown-key-down"; import useOutsideClickDetector from "../hooks/use-outside-click-detector"; // helpers import { cn } from "../../helpers"; // types import { ICustomMenuDropdownProps, ICustomMenuItemProps } from "./helper"; const CustomMenu = (props: ICustomMenuDropdownProps) => { const { buttonClassName = "", customButtonClassName = "", customButtonTabIndex = 0, placement, children, className = "", customButton, disabled = false, ellipsis = false, label, maxHeight = "md", noBorder = false, noChevron = false, optionsClassName = "", verticalEllipsis = false, portalElement, menuButtonOnClick, onMenuClose, tabIndex, closeOnSelect, } = props; const [referenceElement, setReferenceElement] = React.useState(null); const [popperElement, setPopperElement] = React.useState(null); const [isOpen, setIsOpen] = React.useState(false); // refs const dropdownRef = React.useRef(null); const { styles, attributes } = usePopper(referenceElement, popperElement, { placement: placement ?? "auto", }); const openDropdown = () => { setIsOpen(true); if (referenceElement) referenceElement.focus(); }; const closeDropdown = () => { isOpen && onMenuClose && onMenuClose(); setIsOpen(false); }; const selectActiveItem = () => { const activeItem: HTMLElement | undefined | null = dropdownRef.current?.querySelector( `[data-headlessui-state="active"] button` ); activeItem?.click(); }; const handleKeyDown = useDropdownKeyDown(openDropdown, closeDropdown, isOpen, selectActiveItem); const handleOnClick = () => { if (closeOnSelect) closeDropdown(); }; useOutsideClickDetector(dropdownRef, closeDropdown); let menuItems = (
{children}
); if (portalElement) { menuItems = ReactDOM.createPortal(menuItems, portalElement); } return ( {({ open }) => ( <> {customButton ? ( ) : ( <> {ellipsis || verticalEllipsis ? ( ) : ( )} )} {isOpen && menuItems} )} ); }; const MenuItem: React.FC = (props) => { const { children, disabled = false, onClick, className } = props; return ( {({ active, close }) => ( )} ); }; CustomMenu.MenuItem = MenuItem; export { CustomMenu };