"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiFocusTrap = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
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 _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) { (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; }
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 = (0, _objectWithoutProperties2.default)(props, _excluded);
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2.default)(_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
  }));
};