"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.POSITIONS = exports.EuiToolTip = exports.DEFAULT_TOOLTIP_OFFSET = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _reposition_on_scroll = require("../../services/popover/reposition_on_scroll");
var _resize_observer = require("../observer/resize_observer");
var _portal = require("../portal");
var _component_defaults = require("../provider/component_defaults");
var _tool_tip_popover = require("./tool_tip_popover");
var _tool_tip_anchor = require("./tool_tip_anchor");
var _tool_tip_arrow = require("./tool_tip_arrow");
var _tool_tip_manager = require("./tool_tip_manager");
var _react2 = require("@emotion/react");
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.
 */
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }
var POSITIONS = exports.POSITIONS = ['top', 'right', 'bottom', 'left'];
var DISPLAYS = ['inlineBlock', 'block'];
var DEFAULT_TOOLTIP_OFFSET = exports.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'
};
var EuiToolTip = exports.EuiToolTip = /*#__PURE__*/(0, _react.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 = (0, _react.useContext)(_component_defaults.EuiComponentDefaultsContext);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    visible = _useState2[0],
    setVisible = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    hasFocus = _useState4[0],
    setHasFocus = _useState4[1];
  var _useState5 = (0, _react.useState)(positionProp),
    _useState6 = _slicedToArray(_useState5, 2),
    calculatedPosition = _useState6[0],
    setCalculatedPosition = _useState6[1];
  var _useState7 = (0, _react.useState)(DEFAULT_TOOLTIP_STYLES),
    _useState8 = _slicedToArray(_useState7, 2),
    toolTipStyles = _useState8[0],
    setToolTipStyles = _useState8[1];
  var _useState9 = (0, _react.useState)(undefined),
    _useState10 = _slicedToArray(_useState9, 2),
    arrowStyles = _useState10[0],
    setArrowStyles = _useState10[1];
  var generatedId = (0, _react.useRef)((0, _services.htmlIdGenerator)()());
  var id = idProp !== null && idProp !== void 0 ? idProp : generatedId.current;
  var anchorRef = (0, _react.useRef)(null);
  var popoverRef = (0, _react.useRef)(null);
  var positionToolTip = (0, _react.useCallback)(function () {
    if (!anchorRef.current || !popoverRef.current) {
      return;
    }
    var _findPopoverPosition = (0, _services.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 = (0, _react.useCallback)(function (el) {
    anchorRef.current = el;
  }, []);
  var setPopoverRef = (0, _react.useCallback)(function (el) {
    popoverRef.current = el;
    if (el) positionToolTip();
  }, [positionToolTip]);
  var hideToolTip = (0, _react.useCallback)(function () {
    setVisible(false);
    setToolTipStyles(DEFAULT_TOOLTIP_STYLES);
    setArrowStyles(undefined);
    _tool_tip_manager.toolTipManager.deregisterToolTip(hideToolTip);
  }, []);
  var showToolTip = (0, _react.useCallback)(function () {
    if (!content && !title) return;
    setVisible(true);
    _tool_tip_manager.toolTipManager.registerTooltip(hideToolTip);
  }, [content, title, hideToolTip]);
  (0, _react.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.
  (0, _react.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]);
  (0, _react.useEffect)(function () {
    return function () {
      _tool_tip_manager.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
  (0, _react.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
  (0, _react.useEffect)(function () {
    var shouldReposition = (0, _reposition_on_scroll.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 = (0, _react.useCallback)(function (e) {
    if (isFocusVisible(e.target)) {
      setHasFocus(true);
      showToolTip();
    }
  }, [showToolTip]);
  var onBlur = (0, _react.useCallback)(function () {
    setHasFocus(false);
    hideToolTip();
    onBlurProp === null || onBlurProp === void 0 || onBlurProp();
  }, [hideToolTip, onBlurProp]);
  var onEscapeKey = (0, _react.useCallback)(function (event) {
    if (event.key === _services.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 = (0, _react.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 = (0, _classnames.default)('euiToolTip', className);
  var anchorClasses = (0, _classnames.default)(anchorClassName, anchorProps === null || anchorProps === void 0 ? void 0 : anchorProps.className);
  return (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(_tool_tip_anchor.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) && (0, _react2.jsx)(_portal.EuiPortal, null, (0, _react2.jsx)(_tool_tip_popover.EuiToolTipPopover, _extends({
    className: classes,
    style: toolTipStyles,
    positionToolTip: positionToolTip,
    popoverRef: setPopoverRef,
    title: title,
    id: id,
    role: "tooltip",
    calculatedPosition: calculatedPosition
  }, rest), (0, _react2.jsx)(_tool_tip_arrow.EuiToolTipArrow, {
    style: arrowStyles,
    className: "euiToolTip__arrow",
    position: calculatedPosition
  }), (0, _react2.jsx)(_resize_observer.EuiResizeObserver, {
    onResize: positionToolTip
  }, function (resizeRef) {
    return (0, _react2.jsx)("div", {
      ref: resizeRef
    }, content);
  }))));
});
EuiToolTip.propTypes = {
  /**
     * Passes onto the span wrapping the trigger.
     */
  anchorClassName: _propTypes.default.string,
  /**
     * Passes onto the span wrapping the trigger.
     */
  anchorProps: _propTypes.default.shape({
    className: _propTypes.default.string,
    "aria-label": _propTypes.default.string,
    "data-test-subj": _propTypes.default.string,
    css: _propTypes.default.any
  }),
  /**
     * The in-view trigger for your tooltip.
     */
  children: _propTypes.default.element.isRequired,
  /**
     * Passes onto the tooltip itself, not the trigger.
     */
  className: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.string]),
  /**
     * The main content of your tooltip.
     */
  content: _propTypes.default.node,
  /**
     * Common display alternatives for the anchor wrapper
     */
  display: _propTypes.default.any,
  /**
     * An optional title for your tooltip.
     */
  title: _propTypes.default.node,
  /**
     * Unless you provide one, this will be randomly generated.
     */
  id: _propTypes.default.string,
  /**
     * Suggested position. If there is not enough room for it this will be changed.
     */
  position: _propTypes.default.oneOf(["top", "right", "bottom", "left"]),
  /**
     * When `true`, the tooltip's position is re-calculated when the user
     * scrolls. This supports having fixed-position tooltip anchors.
     *
     * When nesting an `EuiTooltip` in a scrollable container, `repositionOnScroll` should be `true`
     */
  repositionOnScroll: _propTypes.default.bool,
  /**
     * Disables the tooltip content being read by screen readers when focusing the trigger element.
     * Do not use when the trigger `aria-label` and tooltip `content` can be rephrased to be standalone
     * information (action & additional information).
     * Enable this prop only when the trigger has a descriptive label that either duplicates or includes
     * the tooltip content and would result in repetitive output.
     * @default false
     */
  disableScreenReaderOutput: _propTypes.default.bool,
  /**
     * If supplied, called when mouse movement causes the tool tip to be
     * hidden.
     */
  onMouseOut: _propTypes.default.func,
  /**
     * If supplied, called when the trigger loses focus.
     */
  onBlur: _propTypes.default.func,
  /**
     * Offset in pixels from the anchor. Defaults to 16.
     */
  offset: _propTypes.default.number,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  css: _propTypes.default.any
};
EuiToolTip.displayName = 'EuiToolTip';