ModalOverlay.jsx (1497B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 import React, { useEffect, useCallback, useRef } from "react"; 6 7 function ModalOverlayWrapper({ 8 // eslint-disable-next-line no-shadow 9 document = globalThis.document, 10 unstyled, 11 innerClassName, 12 onClose, 13 children, 14 headerId, 15 id, 16 }) { 17 const modalRef = useRef(null); 18 19 let className = unstyled ? "" : "modalOverlayInner active"; 20 if (innerClassName) { 21 className += ` ${innerClassName}`; 22 } 23 24 // The intended behaviour is to listen for an escape key 25 // but not for a click; see Bug 1582242 26 const onKeyDown = useCallback( 27 event => { 28 if (event.key === "Escape") { 29 onClose(event); 30 } 31 }, 32 [onClose] 33 ); 34 35 useEffect(() => { 36 document.addEventListener("keydown", onKeyDown); 37 document.body.classList.add("modal-open"); 38 39 return () => { 40 document.removeEventListener("keydown", onKeyDown); 41 document.body.classList.remove("modal-open"); 42 }; 43 }, [document, onKeyDown]); 44 45 return ( 46 <div 47 className="modalOverlayOuter active" 48 onKeyDown={onKeyDown} 49 role="presentation" 50 > 51 <div 52 className={className} 53 aria-labelledby={headerId} 54 id={id} 55 role="dialog" 56 ref={modalRef} 57 > 58 {children} 59 </div> 60 </div> 61 ); 62 } 63 64 export { ModalOverlayWrapper };