"use strict";

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

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

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

var _overlay = _interopRequireDefault(require("../overlay"));

var _zhCn = _interopRequireDefault(require("../locale/zh-cn"));

var _util = require("../util");

var _inner = _interopRequireDefault(require("./inner"));

var _util2 = require("./util");

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return 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, writable: true, configurable: true } }); 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 _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; }

var noop = function noop() {};

var limitTabRange = _util.focus.limitTabRange;
var pickOthers = _util.obj.pickOthers;
var getStyle = _util.dom.getStyle,
    setStyle = _util.dom.setStyle;
var mousePosition = {};

var getClickPosition = function getClickPosition(e) {
  mousePosition = {
    x: e.pageX,
    y: e.pageY
  }; // 100ms 内发生过点击事件，则从点击位置动画展示
  // 否则直接 zoom 展示
  // 这样可以兼容非点击方式展开
  // setTimeout(() => {
  //   mousePosition = null;
  // }, 100);
}; // 只有点击事件支持从鼠标位置动画展开


if (typeof window !== 'undefined' && window.document && window.document.documentElement) {
  document.documentElement.addEventListener('click', getClickPosition);
}
/**
 * Dialog
 */


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

  function Dialog(props) {
    var _this;

    _classCallCheck(this, Dialog);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Dialog).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "getBodyMinHeight", function () {
      var size = _this.props.size;

      if (size === 'small') {
        return 168;
      }

      return 224;
    });

    _defineProperty(_assertThisInitialized(_this), "getBodyHeight", function () {
      var visible = _this.props.visible;

      var inner = _this.getInner();

      if (visible && inner) {
        var bodyNode = inner.bodyNode;
        var bodyHeight = bodyNode ? bodyNode.offsetHeight : 0;
        return bodyHeight;
      }

      return 0;
    });

    _defineProperty(_assertThisInitialized(_this), "handleResize", function () {
      (0, _util.clearNextFrameAction)(_this.resizeTimeout);
      _this.resizeTimeout = (0, _util.onNextFrame)(function () {
        _this.adjustPosition();
      }, 200);
    });

    _defineProperty(_assertThisInitialized(_this), "onKeyDown", function (e) {
      var node = _this.getInnerNode();

      if (node) {
        limitTabRange(node, e);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "adjustPosition", function () {
      var _this$props = _this.props,
          minMargin = _this$props.minMargin,
          visible = _this$props.visible,
          className = _this$props.className,
          prefix = _this$props.prefix;

      var inner = _this.getInner();

      var isQuick = className && className.includes("".concat(prefix, "dialog-quick"));

      if (visible && inner) {
        var innerNode = _this.getInnerNode();

        var headerNode = inner.headerNode,
            bodyNode = inner.bodyNode,
            footerNode = inner.footerNode; // 先去除掉高度限制，重置补偿外边距

        bodyNode && setStyle(bodyNode, {
          'min-height': 'none',
          'max-height': 'none',
          'margin-right': 0
        });
        setStyle(innerNode, {
          left: "calc(50% - ".concat(getStyle(innerNode, 'width') / 2, "px)"),
          top: "".concat(minMargin, "px")
        }); // 快捷调用不适用该规则

        if (!isQuick) {
          bodyNode && setStyle(bodyNode, {
            'min-height': "".concat(_this.getBodyMinHeight(), "px")
          });
          var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
          var headerHeight = headerNode ? getStyle(headerNode, 'height') : 0;
          var bodyHeight = bodyNode ? getStyle(bodyNode, 'height') : 0;
          var footerHeight = footerNode ? getStyle(footerNode, 'height') : 0;

          if (viewportHeight - headerHeight - bodyHeight - footerHeight < 2 * minMargin) {
            bodyNode && setStyle(bodyNode, {
              'max-height': "".concat(Math.max(viewportHeight - headerHeight - 2 * minMargin - footerHeight, 0), "px")
            });
          } // 添加滚动条宽度补偿


          if (bodyHeight > viewportHeight - headerHeight - 2 * minMargin - footerHeight && bodyHeight > _this.getBodyMinHeight()) {
            bodyNode && setStyle(bodyNode, {
              'overflow-y': 'auto',
              'margin-right': "-".concat(_util.dom.scrollbar().width, "px")
            });
          }
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "mapcloseableToConfig", function (closeable) {
      return ['esc', 'close', 'mask'].reduce(function (ret, option) {
        var key = option.charAt(0).toUpperCase() + option.substr(1);
        var value = typeof closeable === 'boolean' ? closeable : closeable.split(',').indexOf(option) > -1;

        if (option === 'esc' || option === 'mask') {
          ret["canCloseBy".concat(key)] = value;
        } else {
          ret["canCloseBy".concat(key, "Click")] = value;
        }

        return ret;
      }, {});
    });

    _defineProperty(_assertThisInitialized(_this), "getOverlayRef", function (ref) {
      _this.overlay = ref;
    });

    _defineProperty(_assertThisInitialized(_this), "getInner", function () {
      if (_this.overlay && _this.overlay.getInstance()) {
        return _this.overlay.getInstance().getContent();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "getInnerNode", function () {
      if (_this.overlay && _this.overlay.getInstance()) {
        return _this.overlay.getInstance().getContentNode();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "renderInner", function (closeable) {
      var _this$props2 = _this.props,
          prefix = _this$props2.prefix,
          className = _this$props2.className,
          size = _this$props2.size,
          title = _this$props2.title,
          children = _this$props2.children,
          footer = _this$props2.footer,
          footerAlign = _this$props2.footerAlign,
          footerActions = _this$props2.footerActions,
          onOk = _this$props2.onOk,
          onCancel = _this$props2.onCancel,
          okProps = _this$props2.okProps,
          cancelProps = _this$props2.cancelProps,
          onClose = _this$props2.onClose,
          locale = _this$props2.locale,
          visible = _this$props2.visible,
          rtl = _this$props2.rtl,
          height = _this$props2.height,
          noBodyPadding = _this$props2.noBodyPadding,
          loading = _this$props2.loading,
          loadingTip = _this$props2.loadingTip;
      var others = pickOthers(Object.keys(Dialog.propTypes), _this.props);
      return _react["default"].createElement(_inner["default"], _extends({
        prefix: prefix,
        className: className,
        size: size,
        title: title,
        footer: footer,
        footerAlign: footerAlign,
        footerActions: footerActions,
        onOk: visible ? onOk : noop,
        onCancel: visible ? onCancel : noop,
        okProps: okProps,
        cancelProps: cancelProps,
        locale: locale,
        closeable: closeable,
        rtl: rtl,
        onClose: onClose.bind(_assertThisInitialized(_this), 'closeClick'),
        height: height,
        noBodyPadding: noBodyPadding,
        loading: loading,
        loadingTip: loadingTip
      }, others), children);
    });

    _defineProperty(_assertThisInitialized(_this), "getAnimation", function () {
      if (_this.props.animation !== undefined) {
        return _this.props.animation;
      }

      if (_this.mousePosition.x === undefined || _this.mousePosition.y === undefined) {
        return Dialog.fallbackAnimation;
      }

      var regin = (0, _util2.getPosRegion)(_this.mousePosition);
      return {
        "in": "".concat(_this.props.prefix, "dialog-zoomIn").concat(regin),
        out: "".concat(_this.props.prefix, "dialog-zoomOut").concat(regin)
      };
    });

    _this.resizeTimeout = null;
    _this.lastBodyHeight = 0;
    _this.mousePosition = _objectSpread({}, mousePosition);
    return _this;
  }

  _createClass(Dialog, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      _util.events.on(document, 'keydown', this.onKeyDown);

      _util.events.on(window, 'resize', this.handleResize);

      this.resizeTimeout = (0, _util.onNextFrame)(function () {
        _this2.adjustPosition();

        _this2.lastBodyHeight = _this2.getBodyHeight();
      });
      this.mousePosition = _objectSpread({}, mousePosition);
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      // 显式置零this.lastBodyHeight，否则如果显式设置bodyHeight（通过height属性或者样式）
      // 那么在重新显示时，会因为componentDidUpdate中定位触发条件不满足而不进行定位调整
      if (!nextProps.visible) {
        this.lastBodyHeight = 0;
      }

      if (nextProps.visible && !this.props.visible) {
        this.mousePosition = _objectSpread({}, mousePosition);
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(preProps) {
      var _this3 = this;

      // 如何让可滚动内容滚动到顶部：滚动一段距离，设置overflow使其不滚动，正常展开，再设置可滚动(下面adjustPosition逻辑)，即可滚动到顶部（双刃剑）
      // 加层判断，防止重新渲染时滚到页面顶部
      var bodyHeight = this.getBodyHeight();

      if (this.props.visible && (preProps.minMargin !== this.props.minMargin || bodyHeight !== this.lastBodyHeight)) {
        (0, _util.clearNextFrameAction)(this.resizeTimeout);
        this.resizeTimeout = (0, _util.onNextFrame)(function () {
          _this3.adjustPosition(); // const node = this.getInnerNode();
          // const elOffset = offset(node);
          // setTransformOrigin(
          //   node,
          //   `${mousePosition.x - elOffset.left}px ${mousePosition.y - elOffset.top + 100}px`,
          // );


          _this3.lastBodyHeight = _this3.getBodyHeight();
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      _util.events.off(document, 'keydown', this.onKeyDown);

      _util.events.off(window, 'resize', this.handleResize);

      (0, _util.clearNextFrameAction)(this.resizeTimeout);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          prefix = _this$props3.prefix,
          visible = _this$props3.visible,
          hasMask = _this$props3.hasMask,
          autoFocus = _this$props3.autoFocus,
          closeable = _this$props3.closeable,
          onClose = _this$props3.onClose,
          afterClose = _this$props3.afterClose,
          overlayProps = _this$props3.overlayProps,
          rtl = _this$props3.rtl;
      var animation = this.getAnimation();

      var _this$mapcloseableToC = this.mapcloseableToConfig(closeable),
          canCloseByCloseClick = _this$mapcloseableToC.canCloseByCloseClick,
          closeConfig = _objectWithoutProperties(_this$mapcloseableToC, ["canCloseByCloseClick"]);

      var newOverlayProps = _objectSpread({}, overlayProps, {
        prefix: prefix,
        visible: visible,
        animation: animation,
        hasMask: hasMask,
        autoFocus: autoFocus,
        afterClose: afterClose
      }, closeConfig, {
        align: false,
        canCloseByOutSideClick: false,
        onRequestClose: onClose,
        needAdjust: false,
        needListenResize: false,
        disableScroll: true,
        ref: this.getOverlayRef,
        rtl: rtl
      });

      var inner = this.renderInner(canCloseByCloseClick); // setTransformOrigin(inner, `${mousePosition.x}px ${mousePosition.y}px`);

      return _react["default"].createElement(_overlay["default"], newOverlayProps, inner);
    }
  }]);

  return Dialog;
}(_react.Component);

exports["default"] = Dialog;

_defineProperty(Dialog, "displayName", 'Dialog');

_defineProperty(Dialog, "propTypes", {
  prefix: _propTypes["default"].string,
  pure: _propTypes["default"].bool,
  rtl: _propTypes["default"].bool,
  className: _propTypes["default"].string,
  size: _propTypes["default"].oneOf(['small', 'medium']),

  /**
   * 是否显示
   */
  visible: _propTypes["default"].bool,

  /**
   * 标题
   */
  title: _propTypes["default"].node,

  /**
   * 内容
   */
  children: _propTypes["default"].node,

  /**
   * 底部内容，设置为 false，则不进行显示
   * @default [<Button type="primary">确定</Button>, <Button>取消</Button>]
   */
  footer: _propTypes["default"].oneOfType([_propTypes["default"].bool, _propTypes["default"].node]),

  /**
   * 底部按钮的对齐方式
   */
  footerAlign: _propTypes["default"].oneOf(['left', 'center', 'right']),

  /**
   * 指定确定按钮和取消按钮是否存在以及如何排列,<br><br>**可选值**：
   * ['ok', 'cancel']（确认取消按钮同时存在，确认按钮在左）
   * ['cancel', 'ok']（确认取消按钮同时存在，确认按钮在右）
   * ['ok']（只存在确认按钮）
   * ['cancel']（只存在取消按钮）
   */
  footerActions: _propTypes["default"].array,

  /**
   * 在点击确定按钮时触发的回调函数
   * @param {Object} event 点击事件对象
   */
  onOk: _propTypes["default"].func,

  /**
   * 在点击取消按钮时触发的回调函数
   * @param {Object} event 点击事件对象
   */
  onCancel: _propTypes["default"].func,

  /**
   * 应用于确定按钮的属性对象
   */
  okProps: _propTypes["default"].object,

  /**
   * 应用于取消按钮的属性对象
   */
  cancelProps: _propTypes["default"].object,

  /**
   * 控制对话框关闭的方式，值可以为字符串或者布尔值，其中字符串是由以下值组成：
   * **close** 表示点击关闭按钮可以关闭对话框
   * **mask** 表示点击遮罩区域可以关闭对话框
   * **esc** 表示按下 esc 键可以关闭对话框
   * 如 'close' 或 'close,esc,mask'
   * 如果设置为 true，则以上关闭方式全部生效
   * 如果设置为 false，则以上关闭方式全部失效
   */
  closeable: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].bool]),

  /**
   * 对话框关闭时触发的回调函数
   * @param {String} trigger 关闭触发行为的描述字符串
   * @param {Object} event 关闭时事件对象
   */
  onClose: _propTypes["default"].func,

  /**
   * 对话框关闭后触发的回调函数, 如果有动画，则在动画结束后触发
   */
  afterClose: _propTypes["default"].func,

  /**
   * 是否显示遮罩
   */
  hasMask: _propTypes["default"].bool,

  /**
   * 显示隐藏时动画的播放方式
   * @property {String} in 进场动画
   * @property {String} out 出场动画
   */
  animation: _propTypes["default"].oneOfType([_propTypes["default"].object, _propTypes["default"].bool]),

  /**
   * 对话框弹出时是否自动获得焦点
   */
  autoFocus: _propTypes["default"].bool,

  /**
   * 对话框距离浏览器顶部和底部的最小间距
   */
  minMargin: _propTypes["default"].number,

  /**
   * 透传到弹层组件的属性对象
   */
  overlayProps: _propTypes["default"].object,

  /**
   * 自定义国际化文案对象
   * @property {String} ok 确认按钮文案
   * @property {String} cancel 取消按钮文案
   */
  locale: _propTypes["default"].object,

  /**
   * 对话框的高度样式属性
   */
  height: _propTypes["default"].string,

  /**
   * 没有内容区的padding
   */
  noBodyPadding: _propTypes["default"].bool,

  /**
   * 是否处于加载状态
   */
  loading: _propTypes["default"].bool,

  /**
   * 加载提示
   */
  loadingTip: _propTypes["default"].node
});

_defineProperty(Dialog, "defaultProps", {
  prefix: 'next-',
  pure: false,
  size: 'medium',
  visible: false,
  footerAlign: 'right',
  footerActions: ['cancel', 'ok'],
  onOk: noop,
  onCancel: noop,
  okProps: {},
  cancelProps: {},
  closeable: 'esc,close,mask',
  onClose: noop,
  afterClose: noop,
  hasMask: true,
  autoFocus: false,
  minMargin: 56,
  overlayProps: {},
  locale: _zhCn["default"].Dialog,
  noBodyPadding: false,
  loading: false
});

_defineProperty(Dialog, "fallbackAnimation", {
  "in": 'fadeInDown',
  out: 'fadeOutUp'
});