@elastic/eui
Version:
Elastic UI Component Library
276 lines (270 loc) • 11.2 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children", "className", "anchorClassName", "anchorProps", "content", "title", "display", "repositionOnScroll", "disableScreenReaderOutput", "position", "offset", "id", "onMouseOut", "onBlur"];
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React, { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useRef, useState } from 'react';
import classNames from 'classnames';
import { findPopoverPosition, useGeneratedHtmlId, keys } from '../../services';
import { getRepositionOnScroll } from '../../services/popover/reposition_on_scroll';
import { EuiResizeObserver } from '../observer/resize_observer';
import { EuiPortal } from '../portal';
import { EuiComponentDefaultsContext } from '../provider/component_defaults';
import { EuiToolTipPopover } from './tool_tip_popover';
import { EuiToolTipAnchor } from './tool_tip_anchor';
import { EuiToolTipArrow } from './tool_tip_arrow';
import { toolTipManager } from './tool_tip_manager';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var POSITIONS = ['top', 'right', 'bottom', 'left'];
var DISPLAYS = ['inlineBlock', 'block', 'flex'];
export var DEFAULT_TOOLTIP_OFFSET = 16;
/**
* `:focus-visible` may throw in browsers that don't support the selector,
* fall back to treating all focus as visible so tooltips still appear.
*/
var isFocusVisible = function isFocusVisible(element) {
try {
return element.matches(':focus-visible');
} catch (_unused) {
return element.matches(':focus');
}
};
var DEFAULT_TOOLTIP_STYLES = {
// position the tooltip content near the top-left
// corner of the window so it can't create scrollbars
// 50,50 because who knows what negative margins, padding, etc
top: 50,
left: 50,
// just in case, avoid any potential flicker by hiding
// the tooltip before it is positioned
opacity: 0,
// prevent accidental mouse interaction while positioning
visibility: 'hidden'
};
export var EuiToolTip = /*#__PURE__*/forwardRef(function (_ref, ref) {
var children = _ref.children,
className = _ref.className,
anchorClassName = _ref.anchorClassName,
anchorProps = _ref.anchorProps,
content = _ref.content,
title = _ref.title,
_ref$display = _ref.display,
display = _ref$display === void 0 ? 'inlineBlock' : _ref$display,
repositionOnScroll = _ref.repositionOnScroll,
_ref$disableScreenRea = _ref.disableScreenReaderOutput,
disableScreenReaderOutput = _ref$disableScreenRea === void 0 ? false : _ref$disableScreenRea,
_ref$position = _ref.position,
positionProp = _ref$position === void 0 ? 'top' : _ref$position,
offset = _ref.offset,
idProp = _ref.id,
onMouseOutProp = _ref.onMouseOut,
onBlurProp = _ref.onBlur,
rest = _objectWithoutProperties(_ref, _excluded);
var componentDefaultsContext = useContext(EuiComponentDefaultsContext);
var _useState = useState(false),
_useState2 = _slicedToArray(_useState, 2),
visible = _useState2[0],
setVisible = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
hasFocus = _useState4[0],
setHasFocus = _useState4[1];
var _useState5 = useState(positionProp),
_useState6 = _slicedToArray(_useState5, 2),
calculatedPosition = _useState6[0],
setCalculatedPosition = _useState6[1];
var _useState7 = useState(DEFAULT_TOOLTIP_STYLES),
_useState8 = _slicedToArray(_useState7, 2),
toolTipStyles = _useState8[0],
setToolTipStyles = _useState8[1];
var _useState9 = useState(undefined),
_useState10 = _slicedToArray(_useState9, 2),
arrowStyles = _useState10[0],
setArrowStyles = _useState10[1];
var generatedId = useGeneratedHtmlId();
var id = idProp !== null && idProp !== void 0 ? idProp : generatedId;
var anchorRef = useRef(null);
var popoverRef = useRef(null);
var positionToolTip = useCallback(function () {
if (!anchorRef.current || !popoverRef.current) {
return;
}
var _findPopoverPosition = findPopoverPosition({
anchor: anchorRef.current,
popover: popoverRef.current,
position: positionProp,
offset: offset !== null && offset !== void 0 ? offset : DEFAULT_TOOLTIP_OFFSET,
arrowConfig: {
arrowWidth: 12,
arrowBuffer: 4
}
}),
position = _findPopoverPosition.position,
left = _findPopoverPosition.left,
top = _findPopoverPosition.top,
arrow = _findPopoverPosition.arrow;
// If encroaching the right edge of the window:
// When `props.content` changes and is longer than `prevProps.content`, the tooltip width remains and
// the resizeObserver callback will fire twice (once for vertical resize caused by text line wrapping,
// once for a subsequent position correction) and cause a flash rerender and reposition.
// To prevent this, we can orient from the right so that text line wrapping does not occur, negating
// the second resizeObserver callback call.
var windowWidth = document.documentElement.clientWidth || window.innerWidth;
var useRightValue = windowWidth / 2 < left;
var newToolTipStyles = {
top: top,
left: useRightValue ? 'auto' : left,
right: useRightValue ? windowWidth - left - popoverRef.current.offsetWidth : 'auto'
};
setCalculatedPosition(position);
setToolTipStyles(newToolTipStyles);
setArrowStyles(arrow);
}, [positionProp, offset]);
var setAnchorRef = useCallback(function (el) {
anchorRef.current = el;
}, []);
var setPopoverRef = useCallback(function (el) {
popoverRef.current = el;
if (el) positionToolTip();
}, [positionToolTip]);
var hideToolTip = useCallback(function () {
setVisible(false);
setToolTipStyles(DEFAULT_TOOLTIP_STYLES);
setArrowStyles(undefined);
toolTipManager.deregisterToolTip(hideToolTip);
}, []);
var showToolTip = useCallback(function () {
if (!content && !title) return;
setVisible(true);
toolTipManager.registerTooltip(hideToolTip);
}, [content, title, hideToolTip]);
useImperativeHandle(ref, function () {
return {
showToolTip: showToolTip,
hideToolTip: hideToolTip,
id: id
};
}, [showToolTip, hideToolTip, id]);
// If the anchor already has focus on mount (e.g. `autoFocus`), show the tooltip.
// Important for StrictMode double-mount.
useEffect(function () {
var _anchorRef$current;
if ((_anchorRef$current = anchorRef.current) !== null && _anchorRef$current !== void 0 && _anchorRef$current.contains(document.activeElement) && document.activeElement != null && isFocusVisible(document.activeElement)) {
setHasFocus(true);
showToolTip();
}
}, [showToolTip]);
useEffect(function () {
return function () {
toolTipManager.deregisterToolTip(hideToolTip);
};
}, [hideToolTip]);
// When the tooltip is visible, this checks if the anchor is still part of document.
// This fixes when the react root is removed from the DOM without unmounting
// See: https://github.com/elastic/eui/issues/1105
useEffect(function () {
if (!visible) return;
var rafId;
var testAnchor = function testAnchor() {
if (document.body.contains(anchorRef.current) === false) {
// the anchor is no longer part of `document`
hideToolTip();
} else {
rafId = requestAnimationFrame(testAnchor);
}
};
rafId = requestAnimationFrame(testAnchor);
return function () {
cancelAnimationFrame(rafId);
};
}, [visible, hideToolTip]);
// update scroll listener
useEffect(function () {
var shouldReposition = getRepositionOnScroll({
repositionOnScroll: repositionOnScroll,
repositionFn: positionToolTip,
componentDefaults: componentDefaultsContext.EuiToolTip
});
if (shouldReposition) {
window.addEventListener('scroll', positionToolTip, true);
}
return function () {
window.removeEventListener('scroll', positionToolTip, true);
};
}, [repositionOnScroll, positionToolTip, componentDefaultsContext.EuiToolTip]);
var onFocus = useCallback(function (e) {
if (isFocusVisible(e.target)) {
setHasFocus(true);
showToolTip();
}
}, [showToolTip]);
var onBlur = useCallback(function () {
setHasFocus(false);
hideToolTip();
onBlurProp === null || onBlurProp === void 0 || onBlurProp();
}, [hideToolTip, onBlurProp]);
var onEscapeKey = useCallback(function (event) {
if (event.key === keys.ESCAPE) {
// when the tooltip is only visual, we don't want it to add an additional key stop
if (!disableScreenReaderOutput) {
if (visible) event.stopPropagation();
}
setHasFocus(false); // Allows mousing over back into the tooltip to work correctly
hideToolTip();
}
}, [disableScreenReaderOutput, visible, hideToolTip]);
var onMouseOut = useCallback(function (event) {
// Prevent mousing over children from hiding the tooltip by testing for whether the mouse has
// left the anchor for a non-child.
if (anchorRef.current === event.relatedTarget || anchorRef.current != null && !anchorRef.current.contains(event.relatedTarget)) {
if (!hasFocus) {
hideToolTip();
}
}
if (onMouseOutProp) {
onMouseOutProp(event);
}
}, [hasFocus, hideToolTip, onMouseOutProp]);
var classes = classNames('euiToolTip', className);
var anchorClasses = classNames(anchorClassName, anchorProps === null || anchorProps === void 0 ? void 0 : anchorProps.className);
return ___EmotionJSX(React.Fragment, null, ___EmotionJSX(EuiToolTipAnchor, _extends({}, anchorProps, {
ref: setAnchorRef,
onBlur: onBlur,
onFocus: onFocus,
onKeyDown: onEscapeKey,
onMouseOver: showToolTip,
onMouseOut: onMouseOut
// `id` defines if the trigger and tooltip are automatically linked via `aria-describedby`.
,
id: !disableScreenReaderOutput ? id : undefined,
className: anchorClasses,
display: display,
isVisible: visible
}), children), visible && (content || title) && ___EmotionJSX(EuiPortal, null, ___EmotionJSX(EuiToolTipPopover, _extends({
className: classes,
style: toolTipStyles,
positionToolTip: positionToolTip,
popoverRef: setPopoverRef,
title: title,
id: id,
role: "tooltip",
calculatedPosition: calculatedPosition
}, rest), ___EmotionJSX(EuiToolTipArrow, {
style: arrowStyles,
className: "euiToolTip__arrow",
position: calculatedPosition
}), ___EmotionJSX(EuiResizeObserver, {
onResize: positionToolTip
}, function (resizeRef) {
return ___EmotionJSX("div", {
ref: resizeRef
}, content);
}))));
});
EuiToolTip.displayName = 'EuiToolTip';