|
| 1 | +import { Options as FocusTrapOptions } from 'focus-trap'; |
| 2 | +import React, { useRef } from 'react'; |
| 3 | +import { createPortal } from 'react-dom'; |
| 4 | + |
| 5 | +import { useBodyScrollLock } from '../hooks/useBodyScrollLock'; |
| 6 | +import { useFocusTrap } from '../hooks/useFocusTrap'; |
| 7 | + |
| 8 | +export interface ModalProps { |
| 9 | + children: React.ReactNode; |
| 10 | + isOpen: boolean; |
| 11 | + close: () => void; |
| 12 | + elementId: 'root' | string; |
| 13 | + preventScroll: boolean; |
| 14 | + focusTrapOptions: FocusTrapOptions; |
| 15 | + closeButton: React.ReactElement | null; |
| 16 | +} |
| 17 | + |
| 18 | +const wrapperStyle: React.CSSProperties = { |
| 19 | + position: 'fixed', |
| 20 | + top: 0, |
| 21 | + left: 0, |
| 22 | + bottom: 0, |
| 23 | + right: 0, |
| 24 | + display: 'flex', |
| 25 | + justifyContent: 'center', |
| 26 | + alignItems: 'center', |
| 27 | + zIndex: 1000, |
| 28 | +}; |
| 29 | + |
| 30 | +const overlayStyle: React.CSSProperties = { |
| 31 | + position: 'fixed', |
| 32 | + top: 0, |
| 33 | + left: 0, |
| 34 | + bottom: 0, |
| 35 | + right: 0, |
| 36 | + backgroundColor: 'rgba(0, 0, 0, 0.5)', |
| 37 | + zIndex: 100000, |
| 38 | +}; |
| 39 | + |
| 40 | +const containerStyle: React.CSSProperties = { |
| 41 | + position: 'relative', |
| 42 | + zIndex: 100001, |
| 43 | +}; |
| 44 | + |
| 45 | +export const Modal: React.FC<ModalProps> = ({ |
| 46 | + children, |
| 47 | + isOpen, |
| 48 | + close, |
| 49 | + elementId = 'root', |
| 50 | + preventScroll, |
| 51 | + focusTrapOptions, |
| 52 | + closeButton, |
| 53 | +}) => { |
| 54 | + const dialogRef = useRef<HTMLDivElement>(null); |
| 55 | + useFocusTrap(dialogRef, isOpen, { |
| 56 | + onDeactivate: close, |
| 57 | + clickOutsideDeactivates: true, |
| 58 | + ...focusTrapOptions, |
| 59 | + }); |
| 60 | + useBodyScrollLock(dialogRef, isOpen, preventScroll); |
| 61 | + |
| 62 | + if (isOpen === false) { |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + return createPortal( |
| 67 | + <div style={wrapperStyle}> |
| 68 | + <div style={overlayStyle} /> |
| 69 | + <div |
| 70 | + ref={dialogRef} |
| 71 | + role="dialog" |
| 72 | + aria-modal="true" |
| 73 | + style={containerStyle} |
| 74 | + tabIndex={-1} |
| 75 | + > |
| 76 | + {children} |
| 77 | + {closeButton} |
| 78 | + </div> |
| 79 | + </div>, |
| 80 | + document.getElementById(elementId) as HTMLElement |
| 81 | + ); |
| 82 | +}; |
0 commit comments