import { useEffect, useId, useRef } from "react"; /** * @param {{ * open: boolean, * onClose: () => void, * title: string, * description?: string, * children?: React.ReactNode, * actions?: React.ReactNode * }} props */ export function Dialog({ open, onClose, title, description, children, actions, }) { const dialogRef = useRef(/** @type {HTMLDialogElement | null} */ (null)); const previousFocusRef = useRef(/** @type {HTMLElement | null} */ (null)); const titleId = useId(); const descriptionId = useId(); useEffect(() => { const dialog = dialogRef.current; if (!dialog) return; if (open) { previousFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; if (!dialog.open) { if (typeof dialog.showModal === "function") dialog.showModal(); else dialog.setAttribute("open", ""); } const firstFocusable = dialog.querySelector( "[autofocus], button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])", ); if (firstFocusable instanceof HTMLElement) firstFocusable.focus(); return; } if (dialog.open) { if (typeof dialog.close === "function") dialog.close(); else dialog.removeAttribute("open"); } previousFocusRef.current?.focus(); previousFocusRef.current = null; }, [open]); return ( { event.preventDefault(); onClose(); }} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }} >

{title}

{description ?

{description}

: null}
{children ?
{children}
: null} {actions ? : null}
); }