import React, { useEffect, useMemo, useRef, useState } from 'react'; import Spinner from '@/components/elements/Spinner'; import tw from 'twin.macro'; import styled, { css } from 'styled-components/macro'; import { breakpoint } from '@/theme'; import Fade from '@/components/elements/Fade'; import { createPortal } from 'react-dom'; export interface RequiredModalProps { visible: boolean; onDismissed: () => void; appear?: boolean; top?: boolean; } export interface ModalProps extends RequiredModalProps { dismissable?: boolean; closeOnEscape?: boolean; closeOnBackground?: boolean; showSpinnerOverlay?: boolean; } export const ModalMask = styled.div` ${tw`fixed z-50 overflow-auto flex w-full inset-0`}; background: rgba(0, 0, 0, 0.7); `; const ModalContainer = styled.div<{ alignTop?: boolean }>` max-width: 95%; max-height: calc(100vh - 8rem); ${breakpoint('md')`max-width: 75%`}; ${breakpoint('lg')`max-width: 50%`}; ${tw`relative flex flex-col w-full m-auto`}; ${(props) => props.alignTop && css` margin-top: 20%; ${breakpoint('md')`margin-top: 10%`}; `}; margin-bottom: auto; & > .close-icon { ${tw`absolute right-0 p-2 text-white cursor-pointer opacity-50 transition-all duration-150 ease-linear hover:opacity-100`}; top: -2.5rem; &:hover { ${tw`transform rotate-90`} } & > svg { ${tw`w-6 h-6`}; } } `; const Modal: React.FC = ({ visible, appear, dismissable, showSpinnerOverlay, top = true, closeOnBackground = true, closeOnEscape = true, onDismissed, children, }) => { const [render, setRender] = useState(visible); const isDismissable = useMemo(() => { return (dismissable || true) && !(showSpinnerOverlay || false); }, [dismissable, showSpinnerOverlay]); useEffect(() => { if (!isDismissable || !closeOnEscape) return; const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') setRender(false); }; window.addEventListener('keydown', handler); return () => { window.removeEventListener('keydown', handler); }; }, [isDismissable, closeOnEscape, render]); useEffect(() => setRender(visible), [visible]); return ( onDismissed()}> e.stopPropagation()} onContextMenu={(e) => e.stopPropagation()} onMouseDown={(e) => { if (isDismissable && closeOnBackground) { e.stopPropagation(); if (e.target === e.currentTarget) { setRender(false); } } }} > {isDismissable && (
setRender(false)}>
)} {showSpinnerOverlay && (
)}
{children}
); }; const PortaledModal: React.FC = ({ children, ...props }) => { const element = useRef(document.getElementById('modal-portal')); return createPortal({children}, element.current!); }; export default PortaledModal;