Skip to content

Commit

Permalink
Prevent multiple tooltips, add escape to close
Browse files Browse the repository at this point in the history
  • Loading branch information
microbit-robert committed Nov 18, 2024
1 parent cf8824b commit 9d49403
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/components/ClickableTooltip.tsx
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -15,11 +15,38 @@ const ClickableTooltip = ({
...rest
}: ClickableTooltipProps) => {
const label = useDisclosure();
const ref = useRef<HTMLDivElement>(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<HTMLDivElement>) => {
if (e.key === "Escape") {
label.onClose();
}
},
[label]
);
return (
<Tooltip isOpen={label.isOpen} {...rest}>
<Tooltip isOpen={label.isOpen} {...rest} closeOnEsc={true}>
<Flex
onMouseEnter={label.onOpen}
onMouseLeave={label.onClose}
onKeyDown={handleKeydown}
ref={ref}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onClick={label.onOpen}
tabIndex={0}
onFocus={isFocusable ? label.onOpen : undefined}
Expand Down

0 comments on commit 9d49403

Please sign in to comment.