diff --git a/src/components/FeaturePanel/Coordinates.tsx b/src/components/FeaturePanel/Coordinates.tsx index b110249c..cf02c8c8 100644 --- a/src/components/FeaturePanel/Coordinates.tsx +++ b/src/components/FeaturePanel/Coordinates.tsx @@ -28,8 +28,7 @@ const StyledMenuItem = styled(MenuItem)` ` as unknown as any; // expects "li", but it as "a" const StyledToggleButton = styled(IconButton)` - position: absolute !important; - margin: -5px 0 0 0 !important; + margin: -10px 0 -5px 0 !important; svg { font-size: 17px; diff --git a/src/components/utils/TooltipButton.tsx b/src/components/utils/TooltipButton.tsx index 93e31fb4..dce695d6 100644 --- a/src/components/utils/TooltipButton.tsx +++ b/src/components/utils/TooltipButton.tsx @@ -1,9 +1,8 @@ -import React from 'react'; +import React, { useEffect, useRef } from 'react'; import { IconButton, Tooltip } from '@mui/material'; import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined'; -import CloseIcon from '@mui/icons-material/Close'; import { SvgIconOwnProps } from '@mui/material/SvgIcon/SvgIcon'; -import { isMobileDevice, useToggleState } from '../helpers'; +import { isMobileDevice, useBoolState } from '../helpers'; import styled from '@emotion/styled'; type Props = { @@ -12,34 +11,59 @@ type Props = { color?: SvgIconOwnProps['color']; }; +const useClickAwayListener = ( + tooltipRef: React.MutableRefObject, + hide: () => void, + isMobile: boolean, +) => { + useEffect(() => { + const clickAway = (e: MouseEvent) => { + if (e.target instanceof Node && !tooltipRef.current.contains(e.target)) { + hide(); + } + }; + + if (isMobile) { + window.addEventListener('click', clickAway); + } + + return () => { + if (isMobile) { + window.removeEventListener('click', clickAway); + } + }; + }, [hide, isMobile, tooltipRef]); +}; + const StyledIconButton = styled(IconButton)` font-size: inherit; `; export const TooltipButton = ({ tooltip, onClick, color }: Props) => { const isMobile = isMobileDevice(); - const [mobileTooltipShown, toggleMobileTooltip] = useToggleState(false); + const tooltipRef = useRef(null); + const [mobileTooltipShown, show, hide] = useBoolState(false); const handleClick = (e: React.MouseEvent) => { onClick?.(e); if (isMobile) { - toggleMobileTooltip(); + show(); } e.stopPropagation(); }; + useClickAwayListener(tooltipRef, hide, isMobile); + return ( - {!mobileTooltipShown && ( - - )} - {mobileTooltipShown && } + );