import { useEffect, useRef } from 'react' import type { MouseEvent } from 'react' const isClickInsideRectangle = (e: MouseEvent, element: HTMLElement) => { const r = element.getBoundingClientRect() return e.clientX > r.left && e.clientX < r.right && e.clientY > r.top && e.clientY < r.bottom } interface Props { title?: string isOpened: boolean onClose: () => void children: React.ReactNode showCloseButton?: boolean closeOnClickOutside?: boolean className?: string } const DialogModal = ({ title, isOpened, onClose, children, showCloseButton = true, closeOnClickOutside = true, className, }: Props) => { const ref = useRef(null) useEffect(() => { if (isOpened) { ref.current?.showModal() ref.current?.classList.remove('tw:hidden') document.body.style.overflow = 'hidden' } else { ref.current?.close() ref.current?.classList.add('tw:hidden') document.body.style.overflow = '' } }, [isOpened]) if (isOpened) { return ( { if (ref.current && !isClickInsideRectangle(e, ref.current) && closeOnClickOutside) { onClose() } }} >
{title && (

{title}

)} {children} {showCloseButton && ( )}
) } else return <> } export default DialogModal