"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.EuiFocusTrap = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactFocusOn = require("react-focus-on");
var _reactRemoveScrollBar = require("react-remove-scroll-bar");
var _services = require("../../services");
var _component_defaults = require("../provider/component_defaults");
var _react2 = require("@emotion/react");
var _excluded = ["children", "disabled", "clickOutsideDisables", "returnFocus", "noIsolation", "crossFrame", "scrollLock", "initialFocus", "gapMode", "closeOnMouseup", "onClickOutside"];
/*
 * 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 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) { _defineProperty(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 _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 EuiFocusTrap = exports.EuiFocusTrap = function EuiFocusTrap(_props) {
  var props = (0, _component_defaults.usePropsWithComponentDefaults)('EuiFocusTrap', _props);
  var children = props.children,
    disabled = props.disabled,
    _props$clickOutsideDi = props.clickOutsideDisables,
    clickOutsideDisables = _props$clickOutsideDi === void 0 ? false : _props$clickOutsideDi,
    _props$returnFocus = props.returnFocus,
    returnFocus = _props$returnFocus === void 0 ? true : _props$returnFocus,
    _props$noIsolation = props.noIsolation,
    noIsolation = _props$noIsolation === void 0 ? true : _props$noIsolation,
    _props$crossFrame = props.crossFrame,
    crossFrame = _props$crossFrame === void 0 ? false : _props$crossFrame,
    _props$scrollLock = props.scrollLock,
    scrollLock = _props$scrollLock === void 0 ? false : _props$scrollLock,
    initialFocus = props.initialFocus,
    _props$gapMode = props.gapMode,
    gapMode = _props$gapMode === void 0 ? 'padding' : _props$gapMode,
    closeOnMouseup = props.closeOnMouseup,
    onClickOutside = props.onClickOutside,
    rest = _objectWithoutProperties(props, _excluded);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    hasBeenDisabledByClick = _useState2[0],
    setHasBeenDisabledByClick = _useState2[1];
  var isDisabled = disabled || hasBeenDisabledByClick;

  // Programmatically sets focus on a nested DOM node; optional
  var setInitialFocus = function setInitialFocus(initialFocus) {
    if (!initialFocus) return;
    var node = (0, _services.findElementBySelectorOrRef)(initialFocus);
    if (!node) return;
    // `data-autofocus` is part of the 'react-focus-on' API
    node.setAttribute('data-autofocus', 'true');
  };

  // Stabilize the onClickOutside callback
  var onClickOutsideRef = (0, _react.useRef)(onClickOutside);
  onClickOutsideRef.current = onClickOutside;

  // We use a ref to store the listener to prevent circular dependencies
  // while still ensuring the listeners can properly be cleaned up
  var mouseupListenerRef = (0, _react.useRef)(null);
  var removeMouseupListener = (0, _react.useCallback)(function () {
    if (mouseupListenerRef.current) {
      document.removeEventListener('mouseup', mouseupListenerRef.current);
      document.removeEventListener('touchend', mouseupListenerRef.current);
      mouseupListenerRef.current = null;
    }
  }, []);
  var addMouseupListener = (0, _react.useCallback)(function () {
    removeMouseupListener();
    mouseupListenerRef.current = function (e) {
      removeMouseupListener();
      // Timeout gives precedence to the consumer to initiate close if it has toggle behavior.
      // Otherwise this event may occur first and the consumer toggle will reopen the flyout.
      setTimeout(function () {
        var _onClickOutsideRef$cu;
        return (_onClickOutsideRef$cu = onClickOutsideRef.current) === null || _onClickOutsideRef$cu === void 0 ? void 0 : _onClickOutsideRef$cu.call(onClickOutsideRef, e);
      });
    };
    document.addEventListener('mouseup', mouseupListenerRef.current);
    document.addEventListener('touchend', mouseupListenerRef.current);
  }, [removeMouseupListener]);
  var handleOutsideClick = (0, _react.useCallback)(function (event) {
    if (clickOutsideDisables) {
      setHasBeenDisabledByClick(true);
    }
    if (onClickOutside) {
      closeOnMouseup ? addMouseupListener() : onClickOutside(event);
    }
  }, [clickOutsideDisables, closeOnMouseup, onClickOutside, addMouseupListener]);
  (0, _react.useEffect)(function () {
    setInitialFocus(initialFocus);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _services.useUpdateEffect)(function () {
    if (!disabled) {
      setHasBeenDisabledByClick(false);
    }
  }, [disabled]);

  // listener cleanup on unmount
  (0, _react.useEffect)(function () {
    return function () {
      return removeMouseupListener();
    };
  }, [removeMouseupListener]);
  var focusOnProps = _objectSpread(_objectSpread({
    returnFocus: returnFocus,
    noIsolation: noIsolation,
    initialFocus: initialFocus,
    crossFrame: crossFrame,
    enabled: !isDisabled
  }, rest), {}, {
    onClickOutside: handleOutsideClick,
    /**
     * `scrollLock` should always be unset on FocusOn, as it can prevent scrolling on
     * portals (i.e. popovers, comboboxes, dropdown menus, etc.) within modals & flyouts
     * @see https://github.com/theKashey/react-focus-on/issues/49
     */
    scrollLock: false
  });
  return (0, _react2.jsx)(_reactFocusOn.FocusOn, focusOnProps, children, !isDisabled && scrollLock && (0, _react2.jsx)(_reactRemoveScrollBar.RemoveScrollBar, {
    gapMode: gapMode
  }));
};
EuiFocusTrap.propTypes = {
  // For some reason, Storybook doesn't register these props if they're Pick<>'d
  className: _propTypes.default.string,
  css: _propTypes.default.any,
  style: _propTypes.default.any,
  /**
     * @default false
     */
  disabled: _propTypes.default.bool,
  /**
     * Whether `onClickOutside` should be called on mouseup instead of mousedown.
     * This flag can be used to prevent conflicts with outside toggle buttons by delaying the closing click callback.
     */
  closeOnMouseup: _propTypes.default.bool,
  /**
     * Clicking outside the trap area will disable the trap
     * @default false
     */
  clickOutsideDisables: _propTypes.default.bool,
  /**
     * Reference to element that will get focus when the trap is initiated
     */
  initialFocus: _propTypes.default.any,
  /**
     * if `scrollLock` is set to true, the body's scrollbar width will be preserved on lock
     * via the `gapMode` CSS property. Depending on your custom CSS, you may prefer to use
     * `margin` instead of `padding`.
     * @default padding
     */
  gapMode: _propTypes.default.oneOf(["padding", "margin"]),
  /**
     * Configures focus trapping between iframes.
     * By default, EuiFocusTrap allows focus to leave iframes and move to elements outside of it.
     * Set to `true` if you want focus to remain trapped within the iframe.
     * @default false
     */
  crossFrame: _propTypes.default.any,
  /**
     * @default false
     */
  scrollLock: _propTypes.default.any,
  /**
     * @default true
     */
  noIsolation: _propTypes.default.any,
  /**
     * @default true
     */
  returnFocus: _propTypes.default.any
};