"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.PopupState = void 0;
var _dispatcher = require("@enact/core/dispatcher");
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _keymap = require("@enact/core/keymap");
var _spotlight = _interopRequireWildcard(require("@enact/spotlight"));
var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause"));
var _FloatingLayer = _interopRequireDefault(require("@enact/ui/FloatingLayer"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _warning = _interopRequireDefault(require("warning"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["noAutoDismiss", "onClose", "scrimType"];
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 _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.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.includes(n)) continue; t[n] = r[n]; } return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), 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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var isDown = (0, _keymap.is)('down');
var isLeft = (0, _keymap.is)('left');
var isRight = (0, _keymap.is)('right');
var isUp = (0, _keymap.is)('up');
var getContainerNode = function getContainerNode(containerId) {
  return document.querySelector("[data-spotlight-id='".concat(containerId, "']"));
};

// Deprecate using scrimType 'none' with spotlightRestrict of 'self-only'
var checkScrimNone = function checkScrimNone(props) {
  var validScrim = !(props.scrimType === 'none' && props.spotlightRestrict === 'self-only');
  process.env.NODE_ENV !== "production" ? (0, _warning["default"])(validScrim, "Using 'spotlightRestrict' of 'self-only' without a scrim " + 'is not supported. Use a transparent scrim to prevent spotlight focus outside of the popup') : void 0;
};
var OpenState = {
  CLOSED: 0,
  OPENING: 1,
  OPEN: 2
};
var forwardHide = (0, _handle.forward)('onHide');
var forwardShow = (0, _handle.forward)('onShow');

/**
 * A hoc component that renders a popup in a
 * {@link ui/FloatingLayer.FloatingLayer|FloatingLayer}.
 *
 * @hoc PopupState
 * @memberof agate/Popup
 * @ui
 * @public
 */
var PopupState = exports.PopupState = (0, _hoc["default"])(function (config, Wrapped) {
  var _Class;
  return _Class = /*#__PURE__*/function (_Component) {
    function _Class(props) {
      var _this;
      _classCallCheck(this, _Class);
      _this = _callSuper(this, _Class, [props]);
      _this.handleFloatingLayerOpen = function () {
        if (!_this.props.noAnimation && _this.state.popupOpen !== OpenState.OPEN) {
          _this.setState({
            popupOpen: OpenState.OPENING
          });
        } else if (_this.state.popupOpen === OpenState.OPEN && _this.props.open) {
          _this.spotPopupContent();
        }
      };
      _this.handleKeyDown = function (ev) {
        var _this$props = _this.props,
          onClose = _this$props.onClose,
          no5WayClose = _this$props.no5WayClose,
          position = _this$props.position,
          spotlightRestrict = _this$props.spotlightRestrict;
        if (no5WayClose) return;
        var containerId = _this.state.containerId;
        var keyCode = ev.keyCode;
        var direction = (0, _spotlight.getDirection)(keyCode);
        var spottables = _spotlight["default"].getSpottableDescendants(containerId).length;
        var current = _spotlight["default"].getCurrent();
        if (direction && (!spottables || current && getContainerNode(containerId).contains(current))) {
          // explicitly restrict navigation in order to manage focus state when attempting to leave the popup
          _spotlight["default"].set(containerId, {
            restrict: 'self-only'
          });
          if (onClose) {
            var focusChanged;
            if (spottables && current && spotlightRestrict !== 'self-only') {
              focusChanged = _spotlight["default"].move(direction);
              if (focusChanged) {
                // stop propagation to prevent default spotlight behavior
                ev.stopPropagation();
              }
            }
            if (!spottables || focusChanged === false && (position === 'center' || isUp(keyCode) && position === 'bottom' || isDown(keyCode) && position === 'top' || isRight(keyCode) && position === 'left' || isLeft(keyCode) && position === 'right')) {
              // prevent default page scrolling
              ev.preventDefault();
              // stop propagation to prevent default spotlight behavior
              ev.stopPropagation();
              // set the pointer mode to false on keydown
              _spotlight["default"].setPointerMode(false);
              onClose(ev);
            }
          }
        }
      };
      _this.handlePopupHide = function (ev) {
        forwardHide(ev, _this.props);
        _this.setState({
          floatLayerOpen: false,
          activator: null
        });
        if (!ev.currentTarget || ev.currentTarget.getAttribute('data-spotlight-id') === _this.state.containerId) {
          _this.spotActivator(_this.state.activator);
        }
      };
      _this.handlePopupShow = function (ev) {
        forwardShow(ev, _this.props);
        _this.setState({
          popupOpen: OpenState.OPEN
        });
        if (!ev.currentTarget || ev.currentTarget.getAttribute('data-spotlight-id') === _this.state.containerId) {
          _this.spotPopupContent();
        }
      };
      _this.spotActivator = function (activator) {
        _this.paused.resume();

        // only spot the activator if the popup is closed
        if (_this.props.open) return;
        var current = _spotlight["default"].getCurrent();
        var containerNode = getContainerNode(_this.state.containerId);
        (0, _dispatcher.off)('keydown', _this.handleKeyDown);

        // if there is no currently-spotted control or it is wrapped by the popup's container, we
        // know it's safe to change focus
        if (!current || containerNode && containerNode.contains(current)) {
          // attempt to set focus to the activator, if available
          if (!_spotlight["default"].isPaused() && !_spotlight["default"].focus(activator)) {
            _spotlight["default"].focus();
          }
        }
      };
      _this.spotPopupContent = function () {
        _this.paused.resume();

        // only spot the activator if the popup is open
        if (!_this.props.open) return;
        var containerId = _this.state.containerId;
        (0, _dispatcher.on)('keydown', _this.handleKeyDown);
        if (!_spotlight["default"].isPaused() && !_spotlight["default"].focus(containerId)) {
          var current = _spotlight["default"].getCurrent();

          // In cases where the container contains no spottable controls or we're in pointer-mode, focus
          // cannot inherently set the active container or blur the active control, so we must do that
          // here.
          if (current) {
            current.blur();
          }
          _spotlight["default"].setActiveContainer(containerId);
        }
      };
      _this.paused = new _Pause["default"]('Popup');
      _this.state = {
        floatLayerOpen: _this.props.open,
        popupOpen: _this.props.open ? OpenState.OPEN : OpenState.CLOSED,
        prevOpen: _this.props.open,
        containerId: _spotlight["default"].add(),
        activator: null
      };
      checkScrimNone(_this.props);
      return _this;
    }

    // Spot the content after it's mounted.
    _inherits(_Class, _Component);
    return _createClass(_Class, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        if (this.props.open) {
          // If the popup is open on mount, we need to pause spotlight so nothing steals focus
          // while the popup is rendering.
          this.paused.pause();
          if (getContainerNode(this.state.containerId)) {
            this.spotPopupContent();
          }
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps, prevState) {
        if (this.props.open !== prevProps.open) {
          if (!this.props.noAnimation) {
            if (!this.props.open && this.state.popupOpen === OpenState.CLOSED) {
              // If the popup is supposed to be closed (!this.props.open) and is actually
              // fully closed (OpenState.CLOSED), we must resume spotlight navigation. This
              // can occur when quickly toggling a Popup open and closed.
              this.paused.resume();
            } else {
              // Otherwise, we pause spotlight so it is locked until the popup is ready
              this.paused.pause();
            }
          } else if (this.props.open) {
            forwardShow({}, this.props);
            this.spotPopupContent();
          } else if (prevProps.open) {
            forwardHide({}, this.props);
            this.spotActivator(prevState.activator);
          }
        }
        checkScrimNone(this.props);
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        if (this.props.open) {
          (0, _dispatcher.off)('keydown', this.handleKeyDown);
        }
        _spotlight["default"].remove(this.state.containerId);
      }
    }, {
      key: "render",
      value: function render() {
        var _this$props2 = this.props,
          noAutoDismiss = _this$props2.noAutoDismiss,
          onClose = _this$props2.onClose,
          scrimType = _this$props2.scrimType,
          rest = _objectWithoutProperties(_this$props2, _excluded);
        delete rest.spotlightId;
        delete rest.spotlightRestrict;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_FloatingLayer["default"], {
          noAutoDismiss: noAutoDismiss,
          open: this.state.floatLayerOpen,
          onOpen: this.handleFloatingLayerOpen,
          onDismiss: onClose,
          scrimType: scrimType,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, rest), {}, {
            open: this.state.popupOpen >= OpenState.OPENING,
            onClose: onClose,
            onHide: this.handlePopupHide,
            onShow: this.handlePopupShow,
            spotlightId: this.state.containerId
          }))
        });
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(props, state) {
        if (props.open !== state.prevOpen) {
          if (props.open) {
            return {
              popupOpen: props.noAnimation || state.floatLayerOpen ? OpenState.OPEN : OpenState.CLOSED,
              floatLayerOpen: true,
              activator: _spotlight["default"].getCurrent(),
              prevOpen: props.open
            };
          } else {
            return {
              popupOpen: OpenState.CLOSED,
              floatLayerOpen: state.popupOpen === OpenState.OPEN ? !props.noAnimation : false,
              activator: props.noAnimation ? null : state.activator,
              prevOpen: props.open
            };
          }
        }
        return null;
      }
    }]);
  }(_react.Component), _Class.displayName = 'PopupState', _Class.propTypes = /** @lends agate/Popup.PopupState.prototype */{
    /**
     * Hint string read when focusing the popup close button.
     *
     * @type {String}
     * @default 'Close'
     * @public
     */
    closeButtonAriaLabel: _propTypes["default"].string,
    /**
     * Prevents closing the popup via 5-way navigation out of the content.
     *
     * @type {Boolean}
     * @default false
     * @private
     */
    no5WayClose: _propTypes["default"].bool,
    /**
     * Disables transition animation.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    noAnimation: _propTypes["default"].bool,
    /**
     * Indicates that the popup will not trigger `onClose` on the *ESC* key press.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    noAutoDismiss: _propTypes["default"].bool,
    /**
     * Called on:
     *
     * * pressing `ESC` key,
     * * clicking on the close button, or
     * * moving spotlight focus outside the boundary of the popup when `spotlightRestrict` is
     *   `'self-first'`.
     *
     * It is the responsibility of the callback to set the `open` property to `false`.
     *
     * @type {Function}
     * @public
     */
    onClose: _propTypes["default"].func,
    /**
     * Called after hide transition has completed, and immediately with no transition.
     *
     * @type {Function}
     * @public
     */
    onHide: _propTypes["default"].func,
    /**
     * Called when a key is pressed.
     *
     * @type {Function}
     * @public
     */
    onKeyDown: _propTypes["default"].func,
    /**
     * Called after show transition has completed, and immediately with no transition.
     *
     * Note: The function does not run if Popup is initially opened and
     * {@link agate/Popup.PopupBase#noAnimation|noAnimation} is `true`.
     *
     * @type {Function}
     * @public
     */
    onShow: _propTypes["default"].func,
    /**
     * Controls the visibility of the Popup.
     *
     * By default, the Popup and its contents are not rendered until `open`.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    open: _propTypes["default"].bool,
    /**
     * Position of the Popup on the screen.
     *
     * @type {('bottom'|'center'|'fullscreen'|'left'|'right'|'top')}
     * @default 'center'
     * @public
     */
    position: _propTypes["default"].oneOf(['bottom', 'center', 'fullscreen', 'left', 'right', 'top']),
    /**
     * Scrim type.
     *
     * * Values: `'transparent'`, `'translucent'`, or `'none'`.
     *
     * `'none'` is not compatible with `spotlightRestrict` of `'self-only'`, use a transparent scrim
     * to prevent mouse focus when using popup.
     *
     * @type {('transparent'|'translucent'|'none')}
     * @default 'translucent'
     * @public
     */
    scrimType: _propTypes["default"].oneOf(['transparent', 'translucent', 'none']),
    /**
     * Restricts or prioritizes navigation when focus attempts to leave the popup.
     *
     * * Values: `'self-first'`, or `'self-only'`.
     *
     * When using `self-first`, attempts to leave the popup via 5-way will fire `onClose` based
     * on the following values of `position`:
     *
     * * `'bottom'` - When leaving via 5-way up
     * * `'top'` - When leaving via 5-way down
     * * `'left'` - When leaving via 5-way right
     * * `'right'` - When leaving via 5-way left
     * * `'center'` - When leaving via any 5-way direction
     *
     * Note: If `onClose` is not set, then this has no effect on 5-way navigation. If the popup
     * has no spottable children, 5-way navigation will cause the Popup to fire `onClose`.
     *
     * @type {('self-first'|'self-only')}
     * @default 'self-only'
     * @public
     */
    spotlightRestrict: _propTypes["default"].oneOf(['self-first', 'self-only'])
  }, _Class.defaultProps = {
    noAnimation: false,
    noAutoDismiss: false,
    open: false,
    position: 'center',
    scrimType: 'translucent',
    spotlightRestrict: 'self-only'
  }, _Class;
});
var _default = exports["default"] = PopupState;