-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomSheet.tsx
More file actions
63 lines (56 loc) · 1.84 KB
/
BottomSheet.tsx
File metadata and controls
63 lines (56 loc) · 1.84 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
import { useEffect, useRef, useCallback } from 'react';
import './BottomSheet.css';
/**
* BUG FIX: Stale closure fix for onClose callback
* See docs/bug-patterns/POINTER-CAPTURE-AND-STALE-CLOSURES.md
*/
interface BottomSheetProps {
isOpen: boolean;
onClose: () => void;
title?: string;
children: React.ReactNode;
}
export function BottomSheet({ isOpen, onClose, title, children }: BottomSheetProps) {
const sheetRef = useRef<HTMLDivElement>(null);
// BUG FIX: Use refs to avoid stale closures
const onCloseRef = useRef(onClose);
const isOpenRef = useRef(isOpen);
useEffect(() => { onCloseRef.current = onClose; }, [onClose]);
useEffect(() => { isOpenRef.current = isOpen; }, [isOpen]);
// Close on escape key
// BUG FIX: Register once on mount, use refs for current state
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpenRef.current) {
onCloseRef.current();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []); // Empty deps - register once
// Close on click outside
const handleBackdropClick = useCallback((e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
}
}, [onClose]);
if (!isOpen) return null;
return (
<div
className="bottom-sheet-backdrop"
onClick={handleBackdropClick}
onKeyDown={(e) => { if (e.key === 'Escape') onClose(); }}
role="dialog"
aria-modal="true"
aria-label={title || 'Bottom sheet'}
>
<div className="bottom-sheet" ref={sheetRef}>
<div className="bottom-sheet-handle" />
{title && <div className="bottom-sheet-title">{title}</div>}
<div className="bottom-sheet-content">
{children}
</div>
</div>
</div>
);
}