import React, { useEffect, useState, useContext } from "react"; import Modal from "react-modal"; import { useThemeUI } from "theme-ui"; import MapInteractionContext from "../../contexts/MapInteractionContext"; function MapMenu({ isOpen, onRequestClose, onModalContent, top, left, bottom, right, children, style, // A node to exclude from the pointer event for closing excludeNode, }) { // Save modal node in state to ensure that the pointer listeners // are removed if the open state changed not from the onRequestClose // callback const [modalContentNode, setModalContentNode] = useState(null); const { setPreventMapInteraction } = useContext(MapInteractionContext); useEffect(() => { // Close modal if interacting with any other element function handlePointerDown(event) { const path = event.composedPath(); if ( !path.includes(modalContentNode) && !(excludeNode && path.includes(excludeNode)) ) { setPreventMapInteraction(false); onRequestClose(); document.body.removeEventListener("pointerdown", handlePointerDown); } } if (modalContentNode) { setPreventMapInteraction(true); document.body.addEventListener("pointerdown", handlePointerDown); // Check for wheel event to close modal as well document.body.addEventListener( "wheel", () => { setPreventMapInteraction(false); onRequestClose(); }, { once: true } ); } return () => { if (modalContentNode) { document.body.removeEventListener("pointerdown", handlePointerDown); } }; }, [modalContentNode, excludeNode, onRequestClose, setPreventMapInteraction]); function handleModalContent(node) { setModalContentNode(node); onModalContent(node); } const { theme } = useThemeUI(); return ( {children} ); } MapMenu.defaultProps = { onModalContent: () => {}, top: "initial", left: "initial", right: "initial", bottom: "initial", style: {}, excludeNode: null, }; export default MapMenu;