"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.ViewportBase = exports.Viewport = void 0;
var _handle = require("@enact/core/handle");
var _spotlight = _interopRequireDefault(require("@enact/spotlight"));
var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause"));
var _ViewManager = _interopRequireWildcard(require("@enact/ui/ViewManager"));
var _classnames = _interopRequireDefault(require("classnames"));
var _invariant = _interopRequireDefault(require("invariant"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _SharedStateDecorator = _interopRequireWildcard(require("./SharedStateDecorator"));
var _PanelsModule = _interopRequireDefault(require("./Panels.module.css"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["children", "duration", "generateId", "index", "noAnimation"];
var _Class;
/**
 * The container for a set of Panels
 *
 * @class Viewport
 * @memberof agate/Panels
 * @ui
 * @private
 */
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 ViewportBase = exports.ViewportBase = (_Class = /*#__PURE__*/function (_Component) {
  function ViewportBase() {
    var _this;
    _classCallCheck(this, ViewportBase);
    _this = _callSuper(this, ViewportBase);
    _this.addTransitioningClass = function () {
      if (_this.node) {
        _this.node.classList.add(_PanelsModule["default"].transitioning);
      }
      return true;
    };
    _this.removeTransitioningClass = function () {
      if (_this.node) {
        _this.node.classList.remove(_PanelsModule["default"].transitioning);
      }
      return true;
    };
    _this.pause = function () {
      return _this.paused.pause();
    };
    _this.resume = function () {
      return _this.paused.resume();
    };
    _this.handle = _handle.handle.bind(_this);
    _this.handleTransition = _this.handle((0, _handle.forward)('onTransition'), _this.removeTransitioningClass, _this.resume);
    _this.handleWillTransition = _this.handle((0, _handle.forward)('onWillTransition'), _this.addTransitioningClass, _this.pause);
    _this.mapChildren = function (children, generateId) {
      return _react.Children.map(children, function (child, index) {
        if (child) {
          var _child$props$spotligh = child.props.spotlightId,
            spotlightId = _child$props$spotligh === void 0 ? generateId(index, 'panel-container', _spotlight["default"].remove) : _child$props$spotligh;
          var props = {
            spotlightId: spotlightId,
            'data-index': index
          };
          if (child.props.autoFocus == null && _this.state.direction === 'forward') {
            props.autoFocus = 'default-element';
          }
          return /*#__PURE__*/(0, _react.cloneElement)(child, props);
        } else {
          return null;
        }
      });
    };
    _this.getArranger = function () {
      var _this$props = _this.props,
        arranger = _this$props.arranger,
        orientation = _this$props.orientation;
      if (arranger) return arranger;
      if (orientation === 'vertical') return _ViewManager.SlideBottomArranger;else return _ViewManager.SlideRightArranger;
    };
    _this.getEnteringProp = function (noAnimation) {
      return noAnimation ? null : 'hideChildren';
    };
    _this.nodeRef = /*#__PURE__*/(0, _react.createRef)();
    _this.paused = new _Pause["default"]('Viewport');
    _this.state = {
      prevIndex: -1,
      direction: 'forward'
    };
    return _this;
  }
  _inherits(ViewportBase, _Component);
  return _createClass(ViewportBase, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.node = this.nodeRef.current;
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      for (var i = prevProps.index; this.context && i > this.props.index; i--) {
        this.context["delete"](i);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.paused.resume();
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
        children = _this$props2.children,
        duration = _this$props2.duration,
        generateId = _this$props2.generateId,
        index = _this$props2.index,
        noAnimation = _this$props2.noAnimation,
        rest = _objectWithoutProperties(_this$props2, _excluded);
      var arranger = this.getArranger();
      var enteringProp = this.getEnteringProp(noAnimation);
      var mappedChildren = this.mapChildren(children, generateId);
      var className = (0, _classnames["default"])(_PanelsModule["default"].viewport, rest.className);
      var count = _react.Children.count(mappedChildren);
      !(index === 0 && count === 0 || index < count) ? process.env.NODE_ENV !== "production" ? (0, _invariant["default"])(false, "Panels index, ".concat(index, ", is invalid for number of children, ").concat(count)) : (0, _invariant["default"])(false) : void 0;
      delete rest.arranger;
      delete rest.orientation;
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ViewManager["default"], _objectSpread(_objectSpread({}, rest), {}, {
        arranger: arranger,
        className: className,
        component: "main",
        duration: duration,
        enteringDelay: 100 // TODO: Can we remove this?
        ,
        enteringProp: enteringProp,
        index: index,
        noAnimation: noAnimation,
        onTransition: this.handleTransition,
        onWillTransition: this.handleWillTransition,
        ref: this.nodeRef,
        children: mappedChildren
      }));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      return {
        prevIndex: props.index,
        direction: state.prevIndex > props.index ? 'backward' : 'forward'
      };
    }
  }]);
}(_react.Component), _Class.displayName = 'Viewport', _Class.contextType = _SharedStateDecorator.SharedState, _Class.propTypes = /** @lends agate/Panels.Viewport.prototype */{
  /**
   * A function that generates a globally-unique identifier for a panel index
   *
   * @type {Function}
   * @required
   */
  generateId: _propTypes["default"].func.isRequired,
  /**
   * Set of functions that control how the panels are transitioned into and out of the
   * viewport
   *
   * @type {Arranger}
   */
  arranger: _ViewManager.shape,
  /**
   * Panels to be rendered
   *
   * @type {Panel}
   */
  children: _propTypes["default"].node,
  /**
   * Duration of the animation (in ms) when transitioning between `Panel` components.
   *
   * @type {Number}
   * @default 500
   * @public
   */
  duration: _propTypes["default"].number,
  /**
   * Index of the active panel
   *
   * @type {Number}
   * @default 0
   */
  index: _propTypes["default"].number,
  /**
   * Disable panel transitions
   *
   * @type {Boolean}
   * @default false
   */
  noAnimation: _propTypes["default"].bool,
  /**
   * Direction of the animation when transitioning between `Panel` components.
   *
   * This is only applied when no arranger has been set. When using `'horizontal'`, a `SlideRightArranger` is used.
   * When using `'vertical'`, a `SlideBottomArranger` is used.
   *
   * Valid values are:
   * * `'horizontal'`, and
   * * `'vertical'`.
   *
   * @type {String}
   * @public
   */
  orientation: _propTypes["default"].string
}, _Class.defaultProps = {
  duration: 500,
  index: 0,
  noAnimation: false
}, _Class);
var Viewport = exports.Viewport = (0, _SharedStateDecorator["default"])(ViewportBase);
var _default = exports["default"] = Viewport;