index.tsx
99 lines
| 1 | import {MouseEventHandler, useCallback, useEffect} from 'react'; |
| 2 | import {createPortal} from 'react-dom'; |
| 3 | import {__} from '@wordpress/i18n'; |
| 4 | import {ExitIcon} from '@givewp/components/AdminUI/Icons'; |
| 5 | import './style.scss'; |
| 6 | |
| 7 | export interface ModalProps { |
| 8 | children: JSX.Element | JSX.Element[]; |
| 9 | title: string; |
| 10 | isOpen?: boolean; |
| 11 | icon?: JSX.Element | JSX.Element[]; |
| 12 | insertInto?: string; |
| 13 | handleClose?: MouseEventHandler; |
| 14 | showHeader?: boolean; |
| 15 | showCloseIcon?: boolean; |
| 16 | } |
| 17 | |
| 18 | export default function Modal |
| 19 | ({ |
| 20 | title, |
| 21 | icon, |
| 22 | children, |
| 23 | insertInto, |
| 24 | handleClose, |
| 25 | isOpen = true, |
| 26 | showHeader = true, |
| 27 | showCloseIcon = true |
| 28 | }: ModalProps) { |
| 29 | // ESC key closes modal |
| 30 | const closeModal = useCallback(e => { |
| 31 | if (e.keyCode === 27 && typeof handleClose === 'function') { |
| 32 | handleClose(e); |
| 33 | } |
| 34 | }, []); |
| 35 | |
| 36 | useEffect(() => { |
| 37 | document.addEventListener('keydown', closeModal, false); |
| 38 | |
| 39 | return () => { |
| 40 | document.removeEventListener('keydown', closeModal, false); |
| 41 | }; |
| 42 | }, []); |
| 43 | |
| 44 | if (!isOpen) return null; |
| 45 | |
| 46 | return createPortal( |
| 47 | <div className="givewp-modal-wrapper"> |
| 48 | <div |
| 49 | role="dialog" |
| 50 | aria-label={title} |
| 51 | className="givewp-modal-dialog" |
| 52 | > |
| 53 | {showHeader ? ( |
| 54 | <div className="givewp-modal-header"> |
| 55 | {icon && ( |
| 56 | <div className="givewp-modal-icon-header"> |
| 57 | {icon} |
| 58 | </div> |
| 59 | )} |
| 60 | {title} |
| 61 | {showCloseIcon && handleClose && ( |
| 62 | <button |
| 63 | aria-label={__('Close dialog', 'give')} |
| 64 | className="givewp-modal-close" |
| 65 | onClick={handleClose} |
| 66 | > |
| 67 | <ExitIcon aria-label={__('Close dialog icon', 'give')} /> |
| 68 | </button> |
| 69 | )} |
| 70 | </div> |
| 71 | ) : ( |
| 72 | <> |
| 73 | {showCloseIcon && handleClose && ( |
| 74 | <button |
| 75 | aria-label={__('Close dialog', 'give')} |
| 76 | className="givewp-modal-close-headless" |
| 77 | onClick={handleClose} |
| 78 | > |
| 79 | <ExitIcon aria-label={__('Close dialog icon', 'give')} /> |
| 80 | </button> |
| 81 | )} |
| 82 | {icon && ( |
| 83 | <div className="givewp-modal-icon-center"> |
| 84 | {icon} |
| 85 | </div> |
| 86 | )} |
| 87 | </> |
| 88 | )} |
| 89 | |
| 90 | <div className="givewp-modal-content"> |
| 91 | {children} |
| 92 | </div> |
| 93 | </div> |
| 94 | </div>, |
| 95 | insertInto ? document.querySelector(insertInto) : document.body |
| 96 | ); |
| 97 | } |
| 98 | |
| 99 |