2026-11-23 09:04:51 +00:00
|
|
|
"use client";
|
|
|
|
|
|
|
|
|
|
import { useEffect, useId, useRef } from "react";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* A modal window (the browser's own <dialog>: focus stays inside, Escape
|
|
|
|
|
* closes it). Shown while mounted; a click on the dimmed backdrop closes it.
|
2026-11-23 11:20:14 +00:00
|
|
|
* `canClose`: asked first (e.g. about unsaved input); false keeps it open.
|
2026-11-23 09:04:51 +00:00
|
|
|
*/
|
|
|
|
|
export function Modal({
|
|
|
|
|
title,
|
|
|
|
|
subtitle,
|
|
|
|
|
onClose,
|
2026-11-23 11:20:14 +00:00
|
|
|
canClose,
|
2026-11-23 09:04:51 +00:00
|
|
|
children,
|
|
|
|
|
}: {
|
|
|
|
|
title: string;
|
|
|
|
|
subtitle?: React.ReactNode;
|
|
|
|
|
onClose: () => void;
|
2026-11-23 11:20:14 +00:00
|
|
|
canClose?: () => boolean;
|
2026-11-23 09:04:51 +00:00
|
|
|
children: React.ReactNode;
|
|
|
|
|
}) {
|
|
|
|
|
const ref = useRef<HTMLDialogElement>(null);
|
|
|
|
|
const titleId = useId();
|
2026-11-23 11:20:14 +00:00
|
|
|
// 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();
|
|
|
|
|
};
|
2026-11-23 09:04:51 +00:00
|
|
|
|
|
|
|
|
// 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 (
|
|
|
|
|
<dialog
|
|
|
|
|
ref={ref}
|
|
|
|
|
className="modal"
|
|
|
|
|
aria-labelledby={titleId}
|
|
|
|
|
onClose={onClose}
|
2026-11-23 11:20:14 +00:00
|
|
|
onCancel={(e) => {
|
|
|
|
|
// Escape: the dialog would close by itself.
|
|
|
|
|
if (canClose && !canClose()) e.preventDefault();
|
|
|
|
|
}}
|
|
|
|
|
onPointerDown={(e) => {
|
|
|
|
|
pressedBackdrop.current = e.target === ref.current;
|
|
|
|
|
}}
|
2026-11-23 09:04:51 +00:00
|
|
|
onClick={(e) => {
|
2026-11-23 11:20:14 +00:00
|
|
|
const onBackdrop = pressedBackdrop.current && e.target === ref.current;
|
|
|
|
|
pressedBackdrop.current = false;
|
|
|
|
|
if (onBackdrop) close();
|
2026-11-23 09:04:51 +00:00
|
|
|
}}
|
|
|
|
|
>
|
|
|
|
|
<div className="modal-inner">
|
|
|
|
|
<div className="modal-head">
|
|
|
|
|
<div>
|
|
|
|
|
<h2 id={titleId}>{title}</h2>
|
|
|
|
|
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
|
|
|
|
</div>
|
2026-11-23 11:20:14 +00:00
|
|
|
<button type="button" className="modal-close" onClick={close} aria-label="Bezárás">
|
2026-11-23 09:04:51 +00:00
|
|
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
|
|
|
|
<path d="M6 6l12 12M18 6L6 18" />
|
|
|
|
|
</svg>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
{children}
|
|
|
|
|
</div>
|
|
|
|
|
</dialog>
|
|
|
|
|
);
|
|
|
|
|
}
|