The native <dialog> wrapper rendered its children unconditionally and only called dialog.close() on the underlying element when open went false. The React subtree stayed mounted, so component state (e.g. a ConfirmButton mid-confirm with a red checkmark showing) survived a close/reopen cycle and reappeared the next time the user opened the same dialog. Gate children on open so the subtree unmounts on close. Next open gets a fresh tree with default state.
72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
import { X } from "lucide-react";
|
|
import { type ReactNode, useEffect, useRef } from "react";
|
|
import { cn } from "../../lib/utils.js";
|
|
import { Button } from "./button.js";
|
|
|
|
interface DialogProps {
|
|
open: boolean;
|
|
onClose: () => void;
|
|
className?: string;
|
|
children: ReactNode;
|
|
}
|
|
|
|
export function Dialog({ open, onClose, className, children }: DialogProps) {
|
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
|
|
|
useEffect(() => {
|
|
const dialog = dialogRef.current;
|
|
if (!dialog) return;
|
|
if (open && !dialog.open) dialog.showModal();
|
|
else if (!open && dialog.open) dialog.close();
|
|
}, [open]);
|
|
|
|
useEffect(() => {
|
|
const dialog = dialogRef.current;
|
|
if (!dialog) return;
|
|
function handleCancel(e: Event) {
|
|
e.preventDefault();
|
|
onClose();
|
|
}
|
|
function handleBackdropClick(e: MouseEvent) {
|
|
if (e.target === dialog) onClose();
|
|
}
|
|
dialog.addEventListener("cancel", handleCancel);
|
|
dialog.addEventListener("mousedown", handleBackdropClick);
|
|
return () => {
|
|
dialog.removeEventListener("cancel", handleCancel);
|
|
dialog.removeEventListener("mousedown", handleBackdropClick);
|
|
};
|
|
}, [onClose]);
|
|
|
|
return (
|
|
<dialog
|
|
ref={dialogRef}
|
|
className={cn(
|
|
"m-auto rounded-lg border border-border bg-card text-foreground shadow-xl backdrop:bg-black/50",
|
|
className,
|
|
)}
|
|
>
|
|
{open ? <div className="p-6">{children}</div> : null}
|
|
</dialog>
|
|
);
|
|
}
|
|
|
|
export function DialogHeader({
|
|
title,
|
|
onClose,
|
|
}: Readonly<{ title: string; onClose: () => void }>) {
|
|
return (
|
|
<div className="mb-4 flex items-center justify-between">
|
|
<h2 className="font-semibold text-foreground text-lg">{title}</h2>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
onClick={onClose}
|
|
className="text-muted-foreground"
|
|
>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|