@gravity-ui/uikit
Version:
Gravity UI base styling and components
59 lines (58 loc) • 2.5 kB
JavaScript
import * as React from 'react';
import { KeyCode } from "../../../constants.js";
import { useBoolean } from "../useBoolean/index.js";
export const useTooltipVisible = (anchor, { openDelay = 250, closeDelay, preventTriggerOnFocus = false, }) => {
const [tooltipVisible, showTooltip, hideTooltip] = useBoolean(false);
const timeoutRef = React.useRef();
const isFocusWithinRef = React.useRef(false);
React.useEffect(() => {
if (!anchor) {
return undefined;
}
function handleMouseEnter() {
clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(showTooltip, openDelay);
}
function handleMouseLeave() {
clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(hideTooltip, closeDelay);
}
function handleFocusWithin(e) {
if (!isFocusWithinRef.current && document.activeElement === e.target) {
isFocusWithinRef.current = true;
clearTimeout(timeoutRef.current);
showTooltip();
}
}
function handleBlurWithin(e) {
if (isFocusWithinRef.current &&
!e.currentTarget.contains(e.relatedTarget)) {
isFocusWithinRef.current = false;
clearTimeout(timeoutRef.current);
hideTooltip();
}
}
function handleKeyDown(e) {
if (e.key === KeyCode.ESCAPE) {
clearTimeout(timeoutRef.current);
hideTooltip();
}
}
anchor.addEventListener('mouseenter', handleMouseEnter);
anchor.addEventListener('mouseleave', handleMouseLeave);
anchor.addEventListener('keydown', handleKeyDown);
if (!preventTriggerOnFocus) {
anchor.addEventListener('focus', handleFocusWithin);
anchor.addEventListener('blur', handleBlurWithin);
}
return () => {
anchor.removeEventListener('mouseenter', handleMouseEnter);
anchor.removeEventListener('mouseleave', handleMouseLeave);
anchor.removeEventListener('focus', handleFocusWithin);
anchor.removeEventListener('blur', handleBlurWithin);
anchor.removeEventListener('keydown', handleKeyDown);
};
}, [anchor, showTooltip, hideTooltip, openDelay, closeDelay, preventTriggerOnFocus]);
return tooltipVisible;
};
//# sourceMappingURL=index.js.map