import Button from "@components/button" import React, { useCallback, useEffect } from "react" import { useState } from "react" import styles from "./dropdown.module.css" import DownIcon from "@geist-ui/icons/arrowDown" type Props = { type?: "primary" | "secondary" loading?: boolean disabled?: boolean className?: string iconHeight?: number } type Attrs = Omit, keyof Props> type ButtonDropdownProps = Props & Attrs const ButtonDropdown: React.FC< React.PropsWithChildren > = ({ type, className, disabled, loading, iconHeight = 24, ...props }) => { const [visible, setVisible] = useState(false) const [dropdown, setDropdown] = useState(null) const onClick = (e: React.MouseEvent) => { e.stopPropagation() e.nativeEvent.stopImmediatePropagation() setVisible(!visible) } const onBlur = () => { setVisible(false) } const onMouseDown = (e: React.MouseEvent) => { e.stopPropagation() e.nativeEvent.stopImmediatePropagation() } const onMouseUp = (e: React.MouseEvent) => { e.stopPropagation() e.nativeEvent.stopImmediatePropagation() } const onMouseLeave = (e: React.MouseEvent) => { e.stopPropagation() e.nativeEvent.stopImmediatePropagation() setVisible(false) } const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Escape") { setVisible(false) } } const onClickOutside = useCallback( () => (e: React.MouseEvent) => { if (dropdown && !dropdown.contains(e.target as Node)) { setVisible(false) } }, [dropdown] ) useEffect(() => { if (visible) { document.addEventListener("mousedown", onClickOutside) } else { document.removeEventListener("mousedown", onClickOutside) } return () => { document.removeEventListener("mousedown", onClickOutside) } }, [visible, onClickOutside]) if (!Array.isArray(props.children)) { return null } return (
{props.children[0]}
{visible && (
{props.children.slice(1)}
)}
) } export default ButtonDropdown