From 9d494032e9e20763bb45c2a899ac61e20296ff5b Mon Sep 17 00:00:00 2001 From: Robert Knight Date: Mon, 18 Nov 2024 18:12:37 +0000 Subject: [PATCH] Prevent multiple tooltips, add escape to close --- src/components/ClickableTooltip.tsx | 35 +++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/components/ClickableTooltip.tsx b/src/components/ClickableTooltip.tsx index d4e1ae99d..a879486d3 100644 --- a/src/components/ClickableTooltip.tsx +++ b/src/components/ClickableTooltip.tsx @@ -1,5 +1,5 @@ import { Flex, Tooltip, TooltipProps, useDisclosure } from "@chakra-ui/react"; -import { ReactNode } from "react"; +import { ReactNode, useCallback, useRef } from "react"; interface ClickableTooltipProps extends TooltipProps { children: ReactNode; @@ -15,11 +15,38 @@ const ClickableTooltip = ({ ...rest }: ClickableTooltipProps) => { const label = useDisclosure(); + const ref = useRef(null); + const handleMouseEnter = useCallback(() => { + const openTooltips = document.querySelectorAll( + '[role="tooltip"]:not([hidden])' + ); + if (!openTooltips.length) { + label.onOpen(); + } + }, [label]); + const handleMouseLeave = useCallback(() => { + if ( + !isFocusable || + (ref.current !== document.activeElement && isFocusable) + ) { + label.onClose(); + } + }, [isFocusable, label]); + const handleKeydown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === "Escape") { + label.onClose(); + } + }, + [label] + ); return ( - +