"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

var _classnames = _interopRequireDefault(require("classnames"));

var _drawer = _interopRequireDefault(require("../drawer"));

var _useForceUpdate = _interopRequireDefault(require("./utils/useForceUpdate"));

var _context2 = _interopRequireDefault(require("./context"));

require("./index.css");

var _utils = require("./utils");

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var DrawerStatus;
exports.DrawerStatus = DrawerStatus;

(function (DrawerStatus) {
  DrawerStatus[DrawerStatus["closed"] = 0] = "closed";
  DrawerStatus[DrawerStatus["opening"] = 1] = "opening";
  DrawerStatus[DrawerStatus["opened"] = 2] = "opened";
  DrawerStatus[DrawerStatus["closing"] = 3] = "closing";
})(DrawerStatus || (exports.DrawerStatus = DrawerStatus = {}));

var prefixCls = "titaui-drawer-wrapper";
var transDuration = 200;

function DrawerWrapper(_ref, ref) {
  var _classNames;

  var getContainer = _ref.getContainer;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(null),
      _useState4 = _slicedToArray(_useState3, 2),
      child = _useState4[0],
      setChild = _useState4[1];

  var _useState5 = (0, _react.useState)({}),
      _useState6 = _slicedToArray(_useState5, 2),
      drawerProps = _useState6[0],
      setDrawerProps = _useState6[1];

  var status = (0, _react.useRef)(DrawerStatus.closed);
  var manager = (0, _react.useContext)(_context2["default"]);
  var forceUpdate = (0, _useForceUpdate["default"])();
  var transitionStatus = (0, _react.useRef)("actived");
  var displayInfirst = (0, _react.useRef)(true);
  var next = (0, _react.useRef)(null);
  var waiting = (0, _react.useRef)(null);
  var afterVisibleChange = (0, _react.useCallback)(function (visible) {
    status.current = visible ? DrawerStatus.opened : DrawerStatus.closed;
    drawerProps.afterVisibleChange && drawerProps.afterVisibleChange(visible);
  }, [drawerProps]);

  var toggleChild = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(newChild, newDrawerProps) {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              // 就推屏退场动画
              transitionStatus.current = "leaving";
              next.current = newChild;
              forceUpdate();
              _context.next = 5;
              return (0, _utils.sleep)(transDuration);

            case 5:
              // 新推屏由preload进入展示容器
              transitionStatus.current = "leaved"; // 交换预加载和展示区

              displayInfirst.current = !displayInfirst.current;
              next.current = null;
              setChild(newChild);

              if (drawerProps != newDrawerProps) {
                setDrawerProps(newDrawerProps);
              }

              _context.next = 12;
              return (0, _utils.sleep)(0);

            case 12:
              // 新推屏入场动画
              transitionStatus.current = "entering";
              forceUpdate();
              _context.next = 16;
              return (0, _utils.sleep)(transDuration);

            case 16:
              transitionStatus.current = "actived";
              forceUpdate(); // 如果等待位有推屏 由等待位入场

              if (waiting.current) {
                toggleChild(waiting.current.child, waiting.current.newDrawerProps);
                waiting.current = null;
              }

            case 19:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function toggleChild(_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }();

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      open: function open() {
        var comp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
        var newDrawerProps = arguments.length > 1 ? arguments[1] : undefined;

        if (status.current == DrawerStatus.closed) {
          status.current = DrawerStatus.opening;
        }

        if (transitionStatus.current != "actived") {
          // 如果动画过程中请求打开其他推屏 进入等待位 基本不会出现这种情况
          waiting.current = {
            child: comp,
            drawerProps: newDrawerProps
          };
        } else if (child && status.current == DrawerStatus.opened) {
          // 推屏切换动画
          toggleChild(comp, newDrawerProps);
        } else {
          setChild(comp);

          if (newDrawerProps != drawerProps) {
            setDrawerProps(newDrawerProps);
          }
        }

        setVisible(true);
      },
      close: function close() {
        if (status.current == DrawerStatus.opened) {
          status.current = DrawerStatus.closing;
        }

        setVisible(false);
      },
      getStatus: function getStatus() {
        return status.current;
      }
    };
  }, [child]);
  var displayCls = (0, _classnames["default"])("".concat(prefixCls, "-display"), "".concat(prefixCls, "-display__").concat(transitionStatus.current), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-display__actived"), transitionStatus.current == "leaving"), _defineProperty(_classNames, "".concat(prefixCls, "-display__leaved"), transitionStatus.current == "entering"), _classNames));
  var preloadCls = "".concat(prefixCls, "-preload");
  return /*#__PURE__*/_react["default"].createElement(_drawer["default"], _extends({}, drawerProps, {
    visible: visible,
    onClose: function onClose() {
      return manager && manager.close();
    },
    afterVisibleChange: afterVisibleChange,
    getContainer: getContainer
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: prefixCls
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: displayInfirst.current ? displayCls : preloadCls
  }, displayInfirst.current ? child : next.current), /*#__PURE__*/_react["default"].createElement("div", {
    className: !displayInfirst.current ? displayCls : preloadCls
  }, !displayInfirst.current ? child : next.current)));
}

var _default = /*#__PURE__*/(0, _react.forwardRef)(DrawerWrapper);

exports["default"] = _default;