import { useEffect, useId, useRef, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; // A pop-out over the page: a centred window on a wide screen, the whole // screen on a phone. Escape, the ✕ and a click outside all close it, and the // page behind stays where it was. export function Modal({ title, subtitle, wide, onClose, children, }: { title: ReactNode; subtitle?: ReactNode; wide?: boolean; onClose: () => void; children: ReactNode; }) { const titleId = useId(); const windowRef = useRef(null); // A click only closes if it both started and ended outside the window, so // dragging to select text in a field never does. const pressedOutside = useRef(false); const close = useRef(onClose); useEffect(() => { close.current = onClose; }); useEffect(() => { const opener = document.activeElement as HTMLElement | null; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') close.current(); }; document.addEventListener('keydown', onKey); const scroll = document.body.style.overflow; document.body.style.overflow = 'hidden'; windowRef.current?.focus(); return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = scroll; opener?.focus?.(); }; }, []); return createPortal(
{ pressedOutside.current = e.target === e.currentTarget; }} onClick={(e) => { if (pressedOutside.current && e.target === e.currentTarget) onClose(); }} >

{title}

{subtitle &&
{subtitle}
}
{children}
, document.body ); }