@gravity-ui/uikit
Version:
Gravity UI base styling and components
64 lines (63 loc) • 2.75 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTooltipVisible = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const constants_1 = require("../../../constants.js");
const useBoolean_1 = require("../useBoolean/index.js");
const useTooltipVisible = (anchor, { openDelay = 250, closeDelay, preventTriggerOnFocus = false, }) => {
const [tooltipVisible, showTooltip, hideTooltip] = (0, useBoolean_1.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 === constants_1.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;
};
exports.useTooltipVisible = useTooltipVisible;
//# sourceMappingURL=index.js.map
;