"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ExpandableSpotlightDecorator = exports.default = void 0;

var _container = require("@enact/spotlight/src/container");

var _handle = require("@enact/core/handle");

var _hoc = _interopRequireDefault(require("@enact/core/hoc"));

var _spotlight = _interopRequireDefault(require("@enact/spotlight"));

var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause"));

var _react = _interopRequireDefault(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _propTypes = _interopRequireDefault(require("prop-types"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

/**
 * Default config for {@link mooonstone/ExpandableItem.ExpandableSpotlightDecorator}
 *
 * @memberof moonstone/ExpandableItem.ExpandableSpotlightDecorator
 * @hocconfig
 * @private
 */
var defaultConfig = {
  /**
   * Returns the child -- either a node or a CSS selector -- to focus after expanding.
   *
   * If this function is defined, it will be passed the container node and the current set of
   * props and should return either a node or a CSS selector to be passed to
   * {@link spotlight/Spotlight.focus}.
   *
   * @type {Function}
   * @default null
   * @memberof moonstone/ExpandableItem.ExpandableSpotlightDecorator.defaultConfig
   * @private
   */
  getChildFocusTarget: null,

  /**
   * When `true` and used in conjunction with `noAutoFocus` when `false`, the contents of the
   * container will receive spotlight focus expanded, even in pointer mode.
   *
   * @type {Boolean}
   * @default false
   * @memberof moonstone/ExpandableItem.ExpandableSpotlightDecorator.defaultConfig
   * @private
   */
  noPointerMode: false
};
/**
 * Restores spotlight focus to root container when closing the container if the previously focused
 * component is contained.
 *
 * @class ExpandableSpotlightDecorator
 * @memberof moonstone/ExpandableItem
 * @private
 */

var ExpandableSpotlightDecorator = (0, _hoc.default)(defaultConfig, function (config, Wrapped) {
  var _class, _temp;

  var getChildFocusTarget = config.getChildFocusTarget,
      noPointerMode = config.noPointerMode;
  return _temp = _class =
  /*#__PURE__*/
  function (_React$Component) {
    _inherits(_class, _React$Component);

    function _class() {
      var _this;

      _classCallCheck(this, _class);

      _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this));
      Object.defineProperty(_assertThisInitialized(_this), "highlightContents", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          var current = _spotlight.default.getCurrent();

          if (_this.containerNode.contains(current) || document.activeElement === document.body) {
            var contents = _this.containerNode.querySelector('[data-expandable-container]');

            if (contents && !_this.props.noAutoFocus && !contents.contains(current)) {
              var focused = false; // Attempt to retrieve the Expandable-configured child focus target

              if (getChildFocusTarget) {
                var selectedNode = getChildFocusTarget(contents, _this.props);

                if (selectedNode) {
                  focused = _spotlight.default.focus(selectedNode);
                }
              }

              if (!focused) {
                _spotlight.default.focus(contents.dataset.spotlightId);
              }
            }
          }
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "highlightLabeledItem", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          var current = _spotlight.default.getCurrent();

          var label = _this.containerNode.querySelector('[data-expandable-label]');

          if (current === label) return;

          if (_this.containerNode.contains(current)) {
            if (_spotlight.default.getPointerMode()) {
              // If we don't clear the focus, switching back to 5-way before focusing anything
              // will result in what appears to be lost focus
              current.blur();
            }

            _spotlight.default.focus(label);
          } else {
            var containerIds = (0, _container.getContainersForNode)(label); // when focus is not within the expandable (due to a cancel event or the close
            // on blur from ExpandableInput, or some quick key presses), we need to fix the last
            // focused element config so that focus can be restored to the label rather than
            // spotlight getting lost.
            //
            // If there is focus or active container somewhere else, then we only need to fix
            // the nearest containers to the label that arent also containing the currently
            // focused element.

            var node = current || _spotlight.default.getPointerMode() && (0, _container.getContainerNode)(_spotlight.default.getActiveContainer());

            if (node) {
              var ids = (0, _container.getContainersForNode)(node);
              containerIds = containerIds.filter(function (id) {
                return !ids.includes(id);
              });
            }

            (0, _container.setContainerLastFocusedElement)(label, containerIds);
          }
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "highlight", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value(callback) {
          if (_spotlight.default.isPaused()) return;

          var pointerMode = _spotlight.default.getPointerMode();

          var changePointerMode = pointerMode && noPointerMode;

          if (changePointerMode) {
            // we temporarily set pointer mode to `false` to ensure that focus is forced away
            // from the collapsing expandable.
            _spotlight.default.setPointerMode(false);
          }

          callback();

          if (changePointerMode) {
            _spotlight.default.setPointerMode(pointerMode);
          }
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "pause", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          _this.paused.pause();
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "resume", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          _this.paused.resume();
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "handleHide", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          _this.resume();

          _this.highlight(_this.highlightLabeledItem);
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "handle", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: _handle.handle.bind(_assertThisInitialized(_this))
      });
      Object.defineProperty(_assertThisInitialized(_this), "handleClose", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: _this.handle((0, _handle.forward)('onClose'), _this.pause)
      });
      Object.defineProperty(_assertThisInitialized(_this), "handleOpen", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: _this.handle((0, _handle.forward)('onOpen'), _this.pause)
      });
      Object.defineProperty(_assertThisInitialized(_this), "handleShow", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value() {
          _this.resume();

          _this.highlight(_this.highlightContents);
        }
      });
      Object.defineProperty(_assertThisInitialized(_this), "setContainerNode", {
        configurable: true,
        enumerable: true,
        writable: true,
        value: function value(node) {
          _this.containerNode = _reactDom.default.findDOMNode(node); // eslint-disable-line react/no-find-dom-node
        }
      });
      _this.paused = new _Pause.default('ExpandableItem');
      return _this;
    }

    _createClass(_class, [{
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.resume();
      }
    }, {
      key: "render",
      value: function render() {
        var props = Object.assign({}, this.props);
        delete props.noAutoFocus;
        return _react.default.createElement(Wrapped, _extends({}, props, {
          onHide: this.handleHide,
          onShow: this.handleShow,
          onOpen: this.handleOpen,
          onClose: this.handleClose,
          setContainerNode: this.setContainerNode
        }));
      }
    }]);

    return _class;
  }(_react.default.Component), Object.defineProperty(_class, "displayName", {
    configurable: true,
    enumerable: true,
    writable: true,
    value: 'ExpandableSpotlightDecorator'
  }), Object.defineProperty(_class, "propTypes", {
    configurable: true,
    enumerable: true,
    writable: true,
    value:
    /** @lends moonstone/ExpandableItem.ExpandableSpotlightDecorator.prototype */
    {
      /**
       * When `true`, the contents of the container will not receive spotlight focus when becoming
       * expanded.
       *
       * @type {Boolean}
       * @default false
       * @public
       */
      noAutoFocus: _propTypes.default.bool,

      /**
       * Set the open state of the component, which determines whether it's expanded or not.
       *
       * @type {Boolean}
       * @default true
       * @public
       */
      open: _propTypes.default.bool
    }
  }), Object.defineProperty(_class, "defaultProps", {
    configurable: true,
    enumerable: true,
    writable: true,
    value: {
      noAutoFocus: false
    }
  }), _temp;
});
exports.ExpandableSpotlightDecorator = ExpandableSpotlightDecorator;
var _default = ExpandableSpotlightDecorator;
exports.default = _default;