import React, { forwardRef, useRef, useEffect } from 'react'; import classnames from 'classnames'; import { BackgroundColor, BorderRadius, BLOCK_SIZES, DISPLAY, JustifyContent, AlignItems, } from '../../../helpers/constants/design-system'; import Box from '../../ui/box/box'; import { ModalFocus, useModalContext } from '..'; import { ModalContentProps, ModalContentSize } from './modal-content.types'; export const ModalContent = forwardRef( ( { className = '', children, size = ModalContentSize.Sm, modalDialogProps, ...props }: ModalContentProps, ref: React.Ref, ) => { const { onClose, isClosedOnEscapeKey, isClosedOnOutsideClick, initialFocusRef, finalFocusRef, restoreFocus, autoFocus, } = useModalContext(); const modalDialogRef = useRef(null); const handleEscKey = (event: KeyboardEvent) => { if (isClosedOnEscapeKey && event.key === 'Escape') { onClose(); } }; const handleClickOutside = (event: MouseEvent) => { // Popover should be launched from within Modal but // the Popover containing element is a sibling to modal, // so this is required to ensure `onClose` isn't triggered // when clicking on a popover item if ( isClosedOnOutsideClick && (event.target as HTMLElement).closest('.mm-popover') ) { return; } if ( isClosedOnOutsideClick && modalDialogRef?.current && !modalDialogRef.current.contains(event.target as Node) ) { onClose(); } }; useEffect(() => { document.addEventListener('keydown', handleEscKey); document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('keydown', handleEscKey); document.removeEventListener('mousedown', handleClickOutside); }; }, []); return ( {children} ); }, );