"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"] = void 0;

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

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

var _uuid = require("uuid");

var _animate = _interopRequireDefault(require("../animate"));

var _placement = _interopRequireDefault(require("../placement"));

var _PopInner = _interopRequireDefault(require("./PopInner"));

require("./index.css");

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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

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 _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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

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, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

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

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var suspend = /*#__PURE__*/function (_Component) {
  _inherits(suspend, _Component);

  var _super = _createSuper(suspend);

  function suspend(props) {
    var _this;

    _classCallCheck(this, suspend);

    _this = _super.call(this, props);

    _this.resetPosition = function () {
      _this.refs.inner.resetPosition();
    };

    _this.getBindNode = function () {
      return _this.state.bindNode;
    };

    _this.bindBlurHandle = function () {
      // 给document绑定事件，实现点击弹框以外区域隐藏弹框
      if (_this.blurHandler) return;
      _this.blurHandler = window.document.addEventListener("mousedown", _this.handleBlur);
    };

    _this.handleBlur = function (e) {
      var _this$props = _this.props,
          shouldHide = _this$props.shouldHide,
          hideing = _this$props.hideing;

      var el = _this.refs.inner.getEl();

      if (shouldHide && !shouldHide(e, el)) {
        return;
      }

      if (!shouldHide) {
        if (el.contains(e.target)) return;
        var popArr = document.querySelectorAll("[data-uid=".concat(_this.popId, "] [data-tita-pop]"));

        var _iterator = _createForOfIteratorHelper(popArr),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var pcEl = _step.value;
            var popEl = document.querySelector("[data-uid=".concat(pcEl.getAttribute("data-tita-pop"), "]"));
            if (popEl && popEl.contains(e.target)) return;
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }

      var titaPopWrappers = document.getElementsByClassName("titaui-popup");

      var _iterator2 = _createForOfIteratorHelper(titaPopWrappers),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var titaPopEl = _step2.value;
          if (titaPopEl && titaPopEl.contains(e.target)) return;
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      var noShadowPops = document.querySelectorAll(".tita-common-pop-no-shadow");

      var _iterator3 = _createForOfIteratorHelper(noShadowPops),
          _step3;

      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var _titaPopEl = _step3.value;
          if (_titaPopEl && _titaPopEl.contains(e.target)) return;
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }

      hideing && hideing(e, false);

      _this.setState({
        visible: false
      });
    };

    _this.show = function (bindNode) {
      // 提供给父组件调用，用于显示弹框
      _this.setState({
        visible: true,
        bindNode: bindNode
      });
    };

    _this.hide = function () {
      // 提供给父组件调用，用于显示隐藏弹框
      _this.setState({
        visible: false
      });
    };

    _this.clearBlurHandle = function () {
      // 清除事件
      window.document.removeEventListener("mousedown", _this.handleBlur);
      _this.blurHandler = null;
    };

    _this.isVisible = function () {
      return _this.state.visible;
    };

    _this.state = {
      visible: false
    };
    _this.innerRef = /*#__PURE__*/_react["default"].createRef();
    _this.popId = "t-pop-".concat((0, _uuid.v1)());
    return _this;
  }

  _createClass(suspend, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          onBeforeShow = _this$props2.onBeforeShow,
          onAfterShow = _this$props2.onAfterShow;

      var children = this.state.visible && /*#__PURE__*/_react["default"].createElement(_placement["default"], {
        ref: "inner",
        autoAdjust: this.props.autoAdjust,
        container: this.props.container,
        style: this.props.style,
        className: this.props.className || "tita-common-pop",
        align: this.props.align,
        uid: this.popId,
        cover: this.props.cover,
        dragCls: this.props.dragCls,
        getBindNode: this.getBindNode
      }, this.props.children);

      return [/*#__PURE__*/_react["default"].createElement(_animate["default"], {
        key: "body-".concat(this.popId),
        onEnter: {
          start: onBeforeShow,
          end: onAfterShow
        },
        transitionName: this.props.transitionName || "tita-common-pop",
        onLeave: {
          start: this.props.onBeforeHide
        }
      }, children) // <div style={{ display: 'block' }} key={`noop-${this.popId}`}></div>, //  这空div是干啥的？？？
      ];
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      (0, _reactDom.findDOMNode)(this) && (0, _reactDom.findDOMNode)(this).parentNode.setAttribute("data-tita-pop", this.popId);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      if (this.props.blurToHide) {
        this.state.visible ? this.bindBlurHandle() : this.clearBlurHandle();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.clearBlurHandle();
      this.blurHandler = null;
    }
  }]);

  return suspend;
}(_react.Component);

exports["default"] = suspend;
suspend.defaultProps = {
  align: "bottom",
  autoAdjust: "x y",
  blurToHide: true
};