"use client"; import { useEffect, useId, useRef } from "react"; /** * A modal window (the browser's own : focus stays inside, Escape * closes it). Shown while mounted; a click on the dimmed backdrop closes it. * `canClose`: asked first (e.g. about unsaved input); false keeps it open. */ export function Modal({ title, subtitle, onClose, canClose, children, }: { title: string; subtitle?: React.ReactNode; onClose: () => void; canClose?: () => boolean; children: React.ReactNode; }) { const ref = useRef(null); const titleId = useId(); // Where the press started: only a press and release both on the backdrop close // it (not a text selection dragged out, nor a pick from a select's list that // hangs over the backdrop). const pressedBackdrop = useRef(false); const close = () => { if (!canClose || canClose()) onClose(); }; // No close() on unmount: that would fire onClose; a removed dialog is gone anyway. useEffect(() => { const dialog = ref.current; if (dialog && !dialog.open) dialog.showModal(); }, []); return ( { // Escape: the dialog would close by itself. if (canClose && !canClose()) e.preventDefault(); }} onPointerDown={(e) => { pressedBackdrop.current = e.target === ref.current; }} onClick={(e) => { const onBackdrop = pressedBackdrop.current && e.target === ref.current; pressedBackdrop.current = false; if (onBackdrop) close(); }} >

{title}

{subtitle &&
{subtitle}
}
{children}
); }