-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModal.tsx
More file actions
75 lines (70 loc) · 1.96 KB
/
Copy pathModal.tsx
File metadata and controls
75 lines (70 loc) · 1.96 KB
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
'use client';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
interface ModalProps {
open: boolean;
onClose: () => void;
title: string;
children: React.ReactNode;
}
/**
* Lightweight accessible modal: portals to <body>, closes on Escape and on
* backdrop click, locks background scroll while open, and exposes dialog ARIA.
* No modal library — just the primitives done correctly.
*/
export function Modal({ open, onClose, title, children }: ModalProps) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', onKey);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.removeEventListener('keydown', onKey);
document.body.style.overflow = prevOverflow;
};
}, [open, onClose]);
if (!open || typeof document === 'undefined') return null;
return createPortal(
<div
className="modal-overlay"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label={title}
>
<header className="modal-header">
<h2 className="modal-title">{title}</h2>
<button
type="button"
className="modal-close"
aria-label="Close"
onClick={onClose}
>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
aria-hidden="true"
>
<path d="M4 4l8 8M12 4l-8 8" />
</svg>
</button>
</header>
<div className="modal-body">{children}</div>
</div>
</div>,
document.body,
);
}