"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof3 = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getPopoverPositionFromAnchorPosition = getPopoverPositionFromAnchorPosition;
exports.getPopoverAlignFromAnchorPosition = getPopoverAlignFromAnchorPosition;
exports.EuiPopover = exports.DISPLAY = exports.ANCHOR_POSITIONS = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _tabbable = require("tabbable");
var _focus_trap = require("../focus_trap");
var _services = require("../../services");
var _accessibility = require("../accessibility");
var _panel = require("../panel");
var _portal = require("../portal");
var _mutation_observer = require("../observer/mutation_observer");
var _popover = require("../../services/popover");
var _i18n = require("../i18n");
var _outside_click_detector = require("../outside_click_detector");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof3(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = (0, _getPrototypeOf2.default)(t); if (r) { var s = (0, _getPrototypeOf2.default)(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return (0, _possibleConstructorReturn2.default)(this, e); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var generateId = (0, _services.htmlIdGenerator)();
var anchorPositionToPopoverPositionMap = {
  up: 'top',
  right: 'right',
  down: 'bottom',
  left: 'left'
};
function getPopoverPositionFromAnchorPosition(anchorPosition) {
  // maps the anchor position to the matching popover position
  // e.g. "upLeft" -> "top", "downRight" -> "bottom"
  // extract the first positional word from anchorPosition:
  // starts at the beginning (" ^ ") of anchorPosition and
  // captures all of the characters (" (.*?) ") until the
  // first capital letter (" [A-Z] ") is encountered
  var _ref = anchorPosition.match(/^(.*?)[A-Z]/),
    _ref2 = (0, _slicedToArray2.default)(_ref, 2),
    primaryPosition = _ref2[1];
  return anchorPositionToPopoverPositionMap[primaryPosition];
}
function getPopoverAlignFromAnchorPosition(anchorPosition) {
  // maps the gravity to the matching popover position
  // e.g. "upLeft" -> "left", "rightDown" -> "bottom"
  // extract the second positional word from anchorPosition:
  // starts a capture group at the first capital letter
  // and includes everything after it
  var _ref3 = anchorPosition.match(/([A-Z].*)/),
    _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
    align = _ref4[1]; // this performs two tasks:
  // 1. normalizes the align position by lowercasing it
  // 2. `center` doesn't exist in the lookup map which converts it to `undefined` meaning no align
  return anchorPositionToPopoverPositionMap[align.toLowerCase()];
}
var anchorPositionToClassNameMap = {
  upCenter: 'euiPopover--anchorUpCenter',
  upLeft: 'euiPopover--anchorUpLeft',
  upRight: 'euiPopover--anchorUpRight',
  downCenter: 'euiPopover--anchorDownCenter',
  downLeft: 'euiPopover--anchorDownLeft',
  downRight: 'euiPopover--anchorDownRight',
  leftCenter: 'euiPopover--anchorLeftCenter',
  leftUp: 'euiPopover--anchorLeftUp',
  leftDown: 'euiPopover--anchorLeftDown',
  rightCenter: 'euiPopover--anchorRightCenter',
  rightUp: 'euiPopover--anchorRightUp',
  rightDown: 'euiPopover--anchorRightDown'
};
var ANCHOR_POSITIONS = Object.keys(anchorPositionToClassNameMap);
exports.ANCHOR_POSITIONS = ANCHOR_POSITIONS;
var displayToClassNameMap = {
  inlineBlock: undefined,
  block: 'euiPopover--displayBlock'
};
var DISPLAY = Object.keys(displayToClassNameMap);
exports.DISPLAY = DISPLAY;
var DEFAULT_POPOVER_STYLES = {
  top: 50,
  left: 50
};
function getElementFromInitialFocus(initialFocus) {
  var initialFocusType = (0, _typeof2.default)(initialFocus);
  if (initialFocusType === 'string') {
    return document.querySelector(initialFocus);
  }
  if (initialFocusType === 'function') {
    return initialFocus();
  }
  return initialFocus;
}
var returnFocusConfig = {
  preventScroll: true
};
var EuiPopover = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(EuiPopover, _Component);
  var _super = _createSuper(EuiPopover);
  (0, _createClass2.default)(EuiPopover, null, [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      if (prevState.prevProps.isOpen && !nextProps.isOpen) {
        return {
          prevProps: {
            isOpen: nextProps.isOpen
          },
          isClosing: true,
          isOpening: false
        };
      }
      if (prevState.prevProps.isOpen !== nextProps.isOpen) {
        return {
          prevProps: {
            isOpen: nextProps.isOpen
          }
        };
      }
      return null;
    }
  }]);
  function EuiPopover(props) {
    var _this;
    (0, _classCallCheck2.default)(this, EuiPopover);
    _this = _super.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "respositionTimeout", void 0);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "closingTransitionTimeout", void 0);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "closingTransitionAnimationFrame", void 0);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "updateFocusAnimationFrame", void 0);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "button", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "panel", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "hasSetInitialFocus", false);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleDocumentClick", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "popoverId", generateId());
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "closePopover", function () {
      if (_this.props.isOpen) {
        _this.props.closePopover();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onEscapeKey", function (event) {
      if (_this.props.isOpen) {
        event.preventDefault();
        event.stopPropagation();
        _this.closePopover();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onKeyDown", function (event) {
      if (event.key === _services.cascadingMenuKeys.ESCAPE) {
        _this.onEscapeKey(event);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleOutsideClickAndFocus", function (clickTarget) {
      _this.closePopover();

      // After popover closes, restore focus to the clicked element
      // This ensures clicks on focusable elements (like editors) work properly
      // even when a focus trap was active
      requestAnimationFrame(function () {
        if (clickTarget && typeof clickTarget.focus === 'function') {
          // Check if the target is focusable
          var isFocusable = clickTarget.tabIndex >= 0 || clickTarget.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'A'].includes(clickTarget.tagName);
          if (isFocusable) {
            clickTarget.focus();
          } else {
            // Try to find a focusable parent
            var parent = clickTarget.parentElement;
            while (parent) {
              if (typeof parent.focus === 'function' && (parent.tabIndex >= 0 || parent.isContentEditable)) {
                parent.focus();
                break;
              }
              parent = parent.parentElement;
            }
          }
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onClickOutside", function (event) {
      // only close the popover if the event source isn't the anchor button
      // otherwise, it is up to the anchor to toggle the popover's open status
      if (_this.button && _this.button.contains(event.target) === false) {
        _this.handleOutsideClickAndFocus(event.target);
      }
    });
    // Event stamping for portal detection:
    //
    // React synthetic events (onMouseDown) fire BEFORE native bubble-phase listeners,
    // so this stamps the event before our backup detection runs. This works even for
    // portaled children because React guarantees virtual DOM bubbling.
    //
    // Fallback: If stamping doesn't work, isElementInPopoverTree() uses ARIA relationships
    // to detect portaled elements (generic approach for any accessible component).
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onChildMouseDown", function (event) {
      var euiEvent = event.nativeEvent;
      if (euiEvent.hasOwnProperty('euiGeneratedBy')) {
        euiEvent.euiGeneratedBy.push(_this.popoverId);
      } else {
        euiEvent.euiGeneratedBy = [_this.popoverId];
      }
    });
    // Helper to check if an element is part of a portaled component from this popover
    // This uses ARIA relationships to detect portaled elements that logically belong to the popover
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "isElementInPopoverTree", function (element) {
      if (!_this.panel) {
        return false;
      }
      var current = element;
      while (current) {
        // Check if current element is controlled by something inside the popover
        // This works for any accessible component that uses aria-controls (ComboBox, Select, etc.)
        var currentId = current.getAttribute('id');
        if (currentId) {
          var controller = _this.panel.querySelector("[aria-controls=\"".concat(currentId, "\"]"));
          if (controller) {
            return true;
          }
        }
        current = current.parentElement;
      }
      return false;
    });
    // Backup click detection for when react-focus-on fails to detect outside clicks
    // This can happen with certain DOM structures or complex components like Monaco editor
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "setupBackupClickDetection", function () {
      if (_this.handleDocumentClick) {
        return; // Already set up
      }
      _this.handleDocumentClick = function (event) {
        var target = event.target;
        var euiEvent = event;

        // Check if click is outside both button and panel
        var isOutsideButton = _this.button && !_this.button.contains(target);
        var isOutsidePanel = _this.panel && !_this.panel.contains(target);

        // Check if the click came from a portaled child element (like a dropdown inside the popover)
        // We need to check this because portaled elements are rendered outside the panel DOM
        // but are logically children of components inside the popover
        var isFromPopoverChild = euiEvent.euiGeneratedBy && euiEvent.euiGeneratedBy.includes(_this.popoverId) || _this.isElementInPopoverTree(target);
        if (isOutsideButton && isOutsidePanel && !isFromPopoverChild && _this.props.isOpen) {
          _this.handleOutsideClickAndFocus(target);
        }
      };

      // Use bubble phase - React synthetic events fire first and stamp the event,
      // then our native listener sees the stamp. Simple and effective!
      document.addEventListener('mousedown', _this.handleDocumentClick, false);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "removeBackupClickDetection", function () {
      if (_this.handleDocumentClick) {
        document.removeEventListener('mousedown', _this.handleDocumentClick, false);
        _this.handleDocumentClick = null;
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onOpenPopover", function () {
      clearTimeout(_this.closingTransitionTimeout);
      if (_this.closingTransitionAnimationFrame) {
        cancelAnimationFrame(_this.closingTransitionAnimationFrame);
      }
      // We need to set this state a beat after the render takes place, so that the CSS
      // transition can take effect.
      _this.closingTransitionAnimationFrame = window.requestAnimationFrame(function () {
        _this.setState({
          isOpening: true
        });
      });

      // for each child element of `this.panel`, find any transition duration we should wait for before stabilizing
      var _Array$prototype$slic = Array.prototype.slice.call(_this.panel ? [_this.panel].concat((0, _toConsumableArray2.default)(Array.from(_this.panel.children))) : []).reduce(function (_ref5, element) {
          var durationMatch = _ref5.durationMatch,
            delayMatch = _ref5.delayMatch;
          var transitionTimings = (0, _services.getTransitionTimings)(element);
          return {
            durationMatch: Math.max(durationMatch, transitionTimings.durationMatch),
            delayMatch: Math.max(delayMatch, transitionTimings.delayMatch)
          };
        }, {
          durationMatch: 0,
          delayMatch: 0
        }),
        durationMatch = _Array$prototype$slic.durationMatch,
        delayMatch = _Array$prototype$slic.delayMatch;
      clearTimeout(_this.respositionTimeout);
      _this.respositionTimeout = window.setTimeout(function () {
        _this.setState({
          isOpenStable: true
        }, function () {
          _this.positionPopoverFixed();
          _this.updateFocus();
        });
      }, durationMatch + delayMatch);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onMutation", function (records) {
      var waitDuration = (0, _services.getWaitDuration)(records);
      _this.positionPopoverFixed();
      (0, _services.performOnFrame)(waitDuration, _this.positionPopoverFixed);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "positionPopover", function (allowEnforcePosition) {
      if (_this.button == null || _this.panel == null) return;
      var _ref6 = _this.props,
        anchorPosition = _ref6.anchorPosition;
      var position = getPopoverPositionFromAnchorPosition(anchorPosition);
      var forcePosition = undefined;
      if (allowEnforcePosition && _this.state.isOpenStable && _this.state.openPosition != null) {
        position = _this.state.openPosition;
        forcePosition = true;
      }
      var _findPopoverPosition = (0, _popover.findPopoverPosition)({
          container: _this.props.container,
          position: position,
          forcePosition: forcePosition,
          align: getPopoverAlignFromAnchorPosition(anchorPosition),
          anchor: _this.button,
          popover: _this.panel,
          offset: !_this.props.attachToAnchor && _this.props.hasArrow ? 16 + (_this.props.offset || 0) : 8 + (_this.props.offset || 0),
          arrowConfig: {
            arrowWidth: 24,
            arrowBuffer: 10
          },
          returnBoundingBox: _this.props.attachToAnchor,
          buffer: _this.props.buffer
        }),
        top = _findPopoverPosition.top,
        left = _findPopoverPosition.left,
        foundPosition = _findPopoverPosition.position,
        arrow = _findPopoverPosition.arrow,
        anchorBoundingBox = _findPopoverPosition.anchorBoundingBox; // the popover's z-index must inherit from the button
      // this keeps a button's popover under a flyout that would cover the button
      // but a popover triggered inside a flyout will appear over that flyout
      var zIndexProp = _this.props.zIndex;
      var zIndex = zIndexProp == null ? (0, _popover.getElementZIndex)(_this.button, _this.panel) + 2000 : zIndexProp;
      var popoverStyles = _objectSpread(_objectSpread({}, _this.props.panelStyle), {}, {
        top: top,
        left: _this.props.attachToAnchor && anchorBoundingBox ? anchorBoundingBox.left : left,
        zIndex: zIndex
      });
      var willRenderArrow = !_this.props.attachToAnchor && _this.props.hasArrow;
      var arrowStyles = willRenderArrow ? arrow : undefined;
      var arrowPosition = foundPosition;
      _this.setState({
        popoverStyles: popoverStyles,
        arrowStyles: arrowStyles,
        arrowPosition: arrowPosition,
        openPosition: foundPosition
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "positionPopoverFixed", function () {
      _this.positionPopover(true);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "positionPopoverFluid", function () {
      _this.positionPopover(false);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "panelRef", function (node) {
      _this.panel = node;
      _this.props.panelRef && _this.props.panelRef(node);
      if (node == null) {
        // panel has unmounted, restore the state defaults
        _this.setState({
          popoverStyles: DEFAULT_POPOVER_STYLES,
          arrowStyles: {},
          arrowPosition: null,
          openPosition: null,
          isOpenStable: false
        });
        window.removeEventListener('resize', _this.positionPopoverFluid);
      } else {
        // panel is coming into existence
        _this.positionPopoverFluid();
        window.addEventListener('resize', _this.positionPopoverFluid);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "buttonRef", function (node) {
      _this.button = node;
      _this.props.buttonRef && _this.props.buttonRef(node);
    });
    _this.state = {
      prevProps: {
        isOpen: props.isOpen
      },
      suppressingPopover: props.isOpen,
      // only suppress if created with isOpen=true
      isClosing: false,
      isOpening: false,
      popoverStyles: DEFAULT_POPOVER_STYLES,
      arrowStyles: {},
      arrowPosition: null,
      openPosition: null,
      // once a stable position has been found, keep the contents on that side
      isOpenStable: false // wait for any initial opening transitions to finish before marking as stable
    };
    return _this;
  }
  (0, _createClass2.default)(EuiPopover, [{
    key: "updateFocus",
    value: function updateFocus() {
      var _this2 = this;
      // Wait for the DOM to update.
      this.updateFocusAnimationFrame = window.requestAnimationFrame(function () {
        if (!_this2.props.ownFocus || !_this2.panel || _this2.props.initialFocus === false) {
          return;
        }

        // If we've already focused on something inside the panel, everything's fine.
        if (_this2.hasSetInitialFocus && _this2.panel.contains(document.activeElement)) {
          return;
        }

        // Otherwise let's focus the first tabbable item and expedite input from the user.
        var focusTarget;
        if (_this2.props.initialFocus != null) {
          focusTarget = getElementFromInitialFocus(_this2.props.initialFocus);
        } else {
          var tabbableItems = (0, _tabbable.tabbable)(_this2.panel);
          if (tabbableItems.length) {
            focusTarget = tabbableItems[0];
          }
        }

        // there's a race condition between the popover content becoming visible and this function call
        // if the element isn't visible yet (due to css styling) then it can't accept focus
        // so wait for another render and try again
        if (focusTarget == null) {
          // there isn't a focus target, one of two reasons:
          // #1 is the whole panel hidden? If so, schedule another check
          // #2 panel is visible but no tabbables exist, move focus to the panel
          var panelVisibility = window.getComputedStyle(_this2.panel).visibility;
          if (panelVisibility === 'hidden') {
            // #1
            _this2.updateFocus();
          } else {
            // #2
            focusTarget = _this2.panel;
          }
        } else {
          // found an element to focus, but is it visible?
          var visibility = window.getComputedStyle(focusTarget).visibility;
          if (visibility === 'hidden') {
            // not visible, check again next render frame
            _this2.updateFocus();
          }
        }
        if (focusTarget != null) {
          _this2.hasSetInitialFocus = true;
          focusTarget.focus();
        }
      });
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this3 = this;
      if (this.state.suppressingPopover) {
        // component was created with isOpen=true; now that it's mounted
        // stop suppressing and start opening
        // eslint-disable-next-line react/no-did-mount-set-state
        this.setState({
          suppressingPopover: false,
          isOpening: true
        }, function () {
          _this3.onOpenPopover();

          // Set up backup click detection for focus trap
          if (_this3.props.ownFocus) {
            _this3.setupBackupClickDetection();
          }
        });
      }
      if (this.props.repositionOnScroll) {
        window.addEventListener('scroll', this.positionPopoverFixed);
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this4 = this;
      // The popover is being opened.
      if (!prevProps.isOpen && this.props.isOpen) {
        this.onOpenPopover();

        // Set up backup click detection when using focus trap
        // This ensures outside clicks work even if react-focus-on fails to detect them
        if (this.props.ownFocus) {
          this.setupBackupClickDetection();
        }
      }

      // update scroll listener
      if (prevProps.repositionOnScroll !== this.props.repositionOnScroll) {
        if (this.props.repositionOnScroll) {
          window.addEventListener('scroll', this.positionPopoverFixed);
        } else {
          window.removeEventListener('scroll', this.positionPopoverFixed);
        }
      }

      // The popover is being closed.
      if (prevProps.isOpen && !this.props.isOpen) {
        // Remove backup click detection
        this.removeBackupClickDetection();

        // If the user has just closed the popover, queue up the removal of the content after the
        // transition is complete.
        this.closingTransitionTimeout = window.setTimeout(function () {
          _this4.hasSetInitialFocus = false;
          _this4.setState({
            isClosing: false
          });
        }, 250);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      window.removeEventListener('scroll', this.positionPopoverFixed);
      this.removeBackupClickDetection();
      clearTimeout(this.respositionTimeout);
      clearTimeout(this.closingTransitionTimeout);
      cancelAnimationFrame(this.closingTransitionAnimationFrame);
      cancelAnimationFrame(this.updateFocusAnimationFrame);
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;
      var _this$props = this.props,
        anchorClassName = _this$props.anchorClassName,
        anchorPosition = _this$props.anchorPosition,
        button = _this$props.button,
        buttonRef = _this$props.buttonRef,
        insert = _this$props.insert,
        isOpen = _this$props.isOpen,
        ownFocus = _this$props.ownFocus,
        children = _this$props.children,
        className = _this$props.className,
        closePopover = _this$props.closePopover,
        panelClassName = _this$props.panelClassName,
        panelPaddingSize = _this$props.panelPaddingSize,
        panelProps = _this$props.panelProps,
        panelRef = _this$props.panelRef,
        panelStyle = _this$props.panelStyle,
        popoverRef = _this$props.popoverRef,
        hasArrow = _this$props.hasArrow,
        arrowChildren = _this$props.arrowChildren,
        repositionOnScroll = _this$props.repositionOnScroll,
        zIndex = _this$props.zIndex,
        initialFocus = _this$props.initialFocus,
        attachToAnchor = _this$props.attachToAnchor,
        display = _this$props.display,
        onTrapDeactivation = _this$props.onTrapDeactivation,
        buffer = _this$props.buffer,
        ariaLabel = _this$props['aria-label'],
        ariaLabelledBy = _this$props['aria-labelledby'],
        container = _this$props.container,
        focusTrapProps = _this$props.focusTrapProps,
        rest = (0, _objectWithoutProperties2.default)(_this$props, ["anchorClassName", "anchorPosition", "button", "buttonRef", "insert", "isOpen", "ownFocus", "children", "className", "closePopover", "panelClassName", "panelPaddingSize", "panelProps", "panelRef", "panelStyle", "popoverRef", "hasArrow", "arrowChildren", "repositionOnScroll", "zIndex", "initialFocus", "attachToAnchor", "display", "onTrapDeactivation", "buffer", "aria-label", "aria-labelledby", "container", "focusTrapProps"]);
      var descriptionId = generateId();
      var classes = (0, _classnames.default)('euiPopover', anchorPosition ? anchorPositionToClassNameMap[anchorPosition] : null, display ? displayToClassNameMap[display] : null, {
        'euiPopover-isOpen': this.state.isOpening
      }, className);
      var anchorClasses = (0, _classnames.default)('euiPopover__anchor', anchorClassName);
      var panelClasses = (0, _classnames.default)('euiPopover__panel', "euiPopover__panel--".concat(this.state.arrowPosition), {
        'euiPopover__panel-isOpen': this.state.isOpening
      }, {
        'euiPopover__panel-noArrow': !hasArrow || attachToAnchor
      }, {
        'euiPopover__panel-isAttached': attachToAnchor
      }, panelClassName, panelProps === null || panelProps === void 0 ? void 0 : panelProps.className);
      var panel;
      if (!this.state.suppressingPopover && (isOpen || this.state.isClosing)) {
        var tabIndex;
        var _initialFocus;
        var ariaDescribedby;
        var ariaLive;
        if (ownFocus) {
          tabIndex = 0;
          ariaLive = 'off';
          _initialFocus = function _initialFocus() {
            return _this5.panel;
          };
        } else {
          ariaLive = 'assertive';
        }
        var focusTrapScreenReaderText;
        if (ownFocus) {
          ariaDescribedby = descriptionId;
          focusTrapScreenReaderText = /*#__PURE__*/_react.default.createElement(_accessibility.EuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("p", {
            id: descriptionId
          }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
            token: "euiPopover.screenReaderAnnouncement",
            default: "You are in a dialog. To close this dialog, hit escape."
          })));
        }
        var arrowClassNames = (0, _classnames.default)('euiPopover__panelArrow', "euiPopover__panelArrow--".concat(this.state.arrowPosition));
        var returnFocus = this.state.isOpenStable ? returnFocusConfig : false;
        panel = /*#__PURE__*/_react.default.createElement(_portal.EuiPortal, {
          insert: insert
        }, /*#__PURE__*/_react.default.createElement(_focus_trap.EuiFocusTrap, (0, _extends2.default)({
          clickOutsideDisables: true
        }, focusTrapProps, {
          returnFocus: returnFocus // Ignore temporary state of indecisive focus
          ,
          initialFocus: _initialFocus,
          onDeactivation: onTrapDeactivation,
          onClickOutside: this.onClickOutside,
          onEscapeKey: this.onEscapeKey,
          disabled: !ownFocus || !this.state.isOpenStable || this.state.isClosing
        }), /*#__PURE__*/_react.default.createElement(_panel.EuiPanel, (0, _extends2.default)({}, panelProps, {
          panelRef: this.panelRef,
          className: panelClasses,
          hasShadow: false,
          paddingSize: panelPaddingSize,
          tabIndex: tabIndex,
          "aria-live": ariaLive,
          role: "dialog",
          "aria-label": ariaLabel,
          "aria-labelledby": ariaLabelledBy,
          "aria-modal": "true",
          "aria-describedby": ariaDescribedby,
          style: _objectSpread(_objectSpread({}, this.state.popoverStyles), {}, {
            // Adding `will-change` to reduce risk of a blurry animation in Chrome 86+
            willChange: !this.state.isOpenStable ? 'transform, opacity' : undefined
          })
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: arrowClassNames,
          style: this.state.arrowStyles
        }, arrowChildren), focusTrapScreenReaderText, /*#__PURE__*/_react.default.createElement(_mutation_observer.EuiMutationObserver, {
          observerOptions: {
            attributes: true,
            // element attribute changes
            childList: true,
            // added/removed elements
            characterData: true,
            // text changes
            subtree: true // watch all child elements
          },
          onMutation: this.onMutation
        }, function (mutationRef) {
          return /*#__PURE__*/_react.default.createElement("div", {
            ref: mutationRef,
            onMouseDown: _this5.onChildMouseDown
          }, children);
        }))));
      }

      // react-focus-on and relataed do not register outside click detection
      // when disabled, so we still need to conditionally check for that ourselves
      if (ownFocus) {
        return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
          className: classes,
          ref: popoverRef
        }, rest), /*#__PURE__*/_react.default.createElement("div", {
          className: anchorClasses,
          ref: this.buttonRef
        }, button instanceof HTMLElement ? null : button), panel);
      } else {
        return /*#__PURE__*/_react.default.createElement(_outside_click_detector.EuiOutsideClickDetector, {
          onOutsideClick: this.closePopover
        }, /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
          className: classes,
          ref: popoverRef,
          onKeyDown: this.onKeyDown
        }, rest), /*#__PURE__*/_react.default.createElement("div", {
          className: anchorClasses,
          ref: this.buttonRef
        }, button instanceof HTMLElement ? null : button), panel));
      }
    }
  }]);
  return EuiPopover;
}(_react.Component);
exports.EuiPopover = EuiPopover;
(0, _defineProperty2.default)(EuiPopover, "defaultProps", {
  isOpen: false,
  ownFocus: true,
  anchorPosition: 'downCenter',
  panelPaddingSize: 'm',
  hasArrow: true,
  display: 'inlineBlock'
});
EuiPopover.propTypes = {
  className: _propTypes.default.string,
  /**
     * Provide a name to the popover panel
     */
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  /**
     * Class name passed to the direct parent of the button
     */
  anchorClassName: _propTypes.default.string,
  /**
     * Alignment of the popover and arrow relative to the button
     */
  anchorPosition: _propTypes.default.oneOf(["upCenter", "upLeft", "upRight", "downCenter", "downLeft", "downRight", "leftCenter", "leftUp", "leftDown", "rightCenter", "rightUp", "rightDown"]),
  /**
     * Style and position alteration for arrow-less, left-aligned
     * attachment. Intended for use with inputs as anchors, e.g.
     * EuiInputPopover
     */
  attachToAnchor: _propTypes.default.bool,
  /**
     * Triggering element for which to align the popover to
     */
  button: _propTypes.default.any.isRequired,
  buttonRef: _propTypes.default.any,
  /**
     * Callback to handle hiding of the popover
     */
  closePopover: _propTypes.default.func.isRequired,
  /**
     * Restrict the popover's position within this element
     */
  container: _propTypes.default.any,
  /**
     * CSS display type for both the popover and anchor
     */
  display: _propTypes.default.oneOf(["inlineBlock", "block"]),
  /**
     * Object of props passed to EuiFocusTrap
     */
  focusTrapProps: _propTypes.default.any,
  /**
     * Show arrow indicating to originating button
     */
  hasArrow: _propTypes.default.bool,
  /**
     * Specifies what element should initially have focus; Can be a DOM
     * node, or a selector string (which will be passed to
     * document.querySelector() to find the DOM node), or a function that
     * returns a DOM node
     * Set to `false` to prevent initial auto-focus. Use only
     * when your app handles setting initial focus state.
     */
  initialFocus: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.string.isRequired, _propTypes.default.func.isRequired]).isRequired, _propTypes.default.oneOf([false])]),
  /**
     * Passed directly to EuiPortal for DOM positioning. Both properties are
     * required if prop is specified
     */
  insert: _propTypes.default.shape({
    sibling: _propTypes.default.any.isRequired,
    position: _propTypes.default.oneOf(["before", "after"]).isRequired
  }),
  /**
     * Visibility state of the popover
     */
  isOpen: _propTypes.default.bool,
  /**
     * Traps tab focus within the popover contents
     */
  ownFocus: _propTypes.default.bool,
  /**
     * Custom class added to the EuiPanel containing the popover contents
     */
  panelClassName: _propTypes.default.string,
  /**
     * EuiPanel padding on all sides
     */
  panelPaddingSize: _propTypes.default.any,
  /**
     * Standard DOM `style` attribute. Passed to the EuiPanel
     */
  panelStyle: _propTypes.default.any,
  /**
     * Object of props passed to EuiPanel
     */
  panelProps: _propTypes.default.any,
  panelRef: _propTypes.default.any,
  popoverRef: _propTypes.default.any,
  /**
     * When `true`, the popover's position is re-calculated when the user
     * scrolls, this supports having fixed-position popover anchors
     */
  repositionOnScroll: _propTypes.default.bool,
  /**
     * By default, popover content inherits the z-index of the anchor
     * component; pass `zIndex` to override
     */
  zIndex: _propTypes.default.number,
  /**
     * Function callback for when the focus trap is deactivated
     */
  onTrapDeactivation: _propTypes.default.any,
  /**
     * Distance away from the anchor that the popover will render
     */
  offset: _propTypes.default.number,
  /**
     * Minimum distance between the popover and the bounding container;
     * Pass an array of 4 values to adjust each side differently: `[top, right, bottom, left]`
     * Default is 16
     */
  buffer: _propTypes.default.oneOfType([_propTypes.default.number.isRequired, _propTypes.default.any.isRequired]),
  /**
     * Element to pass as the child element of the arrow;
     * Use case is typically limited to an accompanying `EuiBeacon`
     */
  arrowChildren: _propTypes.default.node,
  /**
     * Alternative option to `aria-label` that takes an `id`.
     * Usually takes the `id` of the popover title
     */
  "aria-labelledby": _propTypes.default.string
};