All files / src/components/ui confirm-dialog.tsx

95.34% Statements 41/43
92.59% Branches 25/27
100% Functions 8/8
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                                                1943x 1943x 1943x 1943x     1943x 874x 93x   93x 36x     36x   93x     781x       1943x 1804x 93x 5x 1x 1x     93x 93x       1943x   4x 3x 3x   3x     3x   3x 3x   3x 1x 1x 2x 1x 1x           1943x   93x                                                                                                                
import { useEffect, useRef, useCallback, useId } from "react";
import { Button } from "./button";
 
interface ConfirmDialogProps {
	open: boolean;
	onConfirm: () => void;
	onCancel: () => void;
	title: string;
	description: string;
	confirmLabel?: string;
	cancelLabel?: string;
	variant?: "default" | "destructive";
}
 
export function ConfirmDialog({
	open,
	onConfirm,
	onCancel,
	title,
	description,
	confirmLabel = "Confirm",
	cancelLabel = "Cancel",
	variant = "default",
}: ConfirmDialogProps) {
	const dialogRef = useRef<HTMLDivElement>(null);
	const previousFocusRef = useRef<HTMLElement | null>(null);
	const titleId = useId();
	const descriptionId = useId();
 
	// Store previously focused element and manage focus
	useEffect(() => {
		if (open) {
			previousFocusRef.current = document.activeElement as HTMLElement;
			// Focus the cancel button (safer default) after render
			const timer = setTimeout(() => {
				const cancelBtn = dialogRef.current?.querySelector<HTMLButtonElement>(
					"[data-cancel-btn]",
				);
				cancelBtn?.focus();
			}, 0);
			return () => clearTimeout(timer);
		}
		// Restore focus when closing
		previousFocusRef.current?.focus();
	}, [open]);
 
	// Escape key handler
	useEffect(() => {
		if (!open) return;
		const handleKeyDown = (e: KeyboardEvent) => {
			if (e.key === "Escape") {
				e.stopPropagation();
				onCancel();
			}
		};
		document.addEventListener("keydown", handleKeyDown);
		return () => document.removeEventListener("keydown", handleKeyDown);
	}, [open, onCancel]);
 
	// Focus trap
	const handleKeyDown = useCallback(
		(e: React.KeyboardEvent) => {
			if (e.key !== "Tab") return;
			const dialog = dialogRef.current;
			Iif (!dialog) return;
 
			const focusable = dialog.querySelectorAll<HTMLElement>(
				'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
			);
			Iif (focusable.length === 0) return;
 
			const first = focusable[0];
			const last = focusable[focusable.length - 1];
 
			if (e.shiftKey && document.activeElement === first) {
				e.preventDefault();
				last.focus();
			} else if (!e.shiftKey && document.activeElement === last) {
				e.preventDefault();
				first.focus();
			}
		},
		[],
	);
 
	if (!open) return null;
 
	return (
		<div
			role="dialog"
			className="fixed inset-0 z-[60] flex items-center justify-center"
			onKeyDown={handleKeyDown}
		>
			{/* Backdrop */}
			<button
				type="button"
				aria-label="Close dialog"
				className="fixed inset-0 bg-black/50 cursor-default"
				onClick={onCancel}
				tabIndex={-1}
			/>
			{/* Dialog */}
			<div
				ref={dialogRef}
				role="alertdialog"
				aria-modal="true"
				aria-labelledby={titleId}
				aria-describedby={descriptionId}
				className="relative z-10 bg-background-elevated rounded-lg shadow-xl w-full max-w-sm mx-4 p-6"
			>
				<h2
					id={titleId}
					className="text-lg font-semibold text-foreground-default"
				>
					{title}
				</h2>
				<p
					id={descriptionId}
					className="mt-2 text-sm text-foreground-muted"
				>
					{description}
				</p>
				<div className="mt-6 flex justify-end gap-3">
					<Button
						data-cancel-btn
						type="button"
						variant="outline"
						onClick={onCancel}
					>
						{cancelLabel}
					</Button>
					<Button
						type="button"
						variant={variant === "destructive" ? "destructive" : "default"}
						onClick={onConfirm}
					>
						{confirmLabel}
					</Button>
				</div>
			</div>
		</div>
	);
}