import { useEffect, useId, useRef } from 'react'; import { X } from 'lucide-react'; import { useLanguage } from '../contexts/LanguageContext'; export default function Modal({ title, children, onClose, maxWidth = 'max-w-lg' }) { const { t } = useLanguage(); const titleId = useId(); const dialogRef = useRef(null); const previouslyFocused = useRef(null); // Keep the latest onClose in a ref so the mount-only effect below can call it // without listing onClose as a dependency. Callers pass a fresh inline arrow // each render; depending on it would re-run the effect on every keystroke and // steal focus back to the dialog (kicking the user out of input fields). const onCloseRef = useRef(onClose); onCloseRef.current = onClose; useEffect(() => { previouslyFocused.current = document.activeElement; const handleKey = (e) => { if (e.key === 'Escape') onCloseRef.current?.(); }; document.addEventListener('keydown', handleKey); // Focus the dialog so screen readers announce it and keyboard focus lands inside dialogRef.current?.focus(); return () => { document.removeEventListener('keydown', handleKey); previouslyFocused.current?.focus?.(); }; }, []); return (
); }