var _excluded = ["children", "className", "anchorClassName", "anchorProps", "content", "title", "display", "repositionOnScroll", "disableScreenReaderOutput", "position", "offset", "id", "onMouseOut", "onBlur"];
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; }
/*
 * 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 PropTypes from "prop-types";
import classNames from 'classnames';
import { findPopoverPosition, htmlIdGenerator, 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'];
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 = useRef(htmlIdGenerator()());
  var id = idProp !== null && idProp !== void 0 ? idProp : generatedId.current;
  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.propTypes = {
  /**
     * Passes onto the span wrapping the trigger.
     */
  anchorClassName: PropTypes.string,
  /**
     * Passes onto the span wrapping the trigger.
     */
  anchorProps: PropTypes.shape({
    className: PropTypes.string,
    "aria-label": PropTypes.string,
    "data-test-subj": PropTypes.string,
    css: PropTypes.any
  }),
  /**
     * The in-view trigger for your tooltip.
     */
  children: PropTypes.element.isRequired,
  /**
     * Passes onto the tooltip itself, not the trigger.
     */
  className: PropTypes.string,
  /**
     * The main content of your tooltip.
     */
  content: PropTypes.node,
  /**
     * Common display alternatives for the anchor wrapper
     */
  display: PropTypes.any,
  /**
     * An optional title for your tooltip.
     */
  title: PropTypes.node,
  /**
     * Unless you provide one, this will be randomly generated.
     */
  id: PropTypes.string,
  /**
     * Suggested position. If there is not enough room for it this will be changed.
     */
  position: PropTypes.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.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.bool,
  /**
     * If supplied, called when mouse movement causes the tool tip to be
     * hidden.
     */
  onMouseOut: PropTypes.func,
  /**
     * If supplied, called when the trigger loses focus.
     */
  onBlur: PropTypes.func,
  /**
     * Offset in pixels from the anchor. Defaults to 16.
     */
  offset: PropTypes.number,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string,
  css: PropTypes.any
};
EuiToolTip.displayName = 'EuiToolTip';