/**
 * tdesign v0.46.4
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isNumber = require('lodash/isNumber');
var throttle = require('lodash/throttle');
var tdesignIconsVue = require('tdesign-icons-vue');
var button_index = require('../button/index.js');
var dialog_actions = require('./actions.js');
var dialog_props = require('./props.js');
var utils_renderTnode = require('../utils/render-tnode.js');
var utils_mixins = require('../utils/mixins.js');
var configProvider_configReceiver = require('../config-provider/config-receiver.js');
var utils_transferDom = require('../utils/transfer-dom.js');
var utils_event = require('../utils/event.js');
var utils_dom = require('../utils/dom.js');
var hooks_useDestroyOnClose = require('../hooks/useDestroyOnClose.js');
var dialog_stack = require('./stack.js');
require('../button/button.js');
require('../loading/index.js');
require('../loading/loading.js');
require('../loading/icon/gradient.js');
require('../_common/js/loading/circle-adapter.js');
require('../_common/js/utils/set-style.js');
require('../_common/js/utils/helper.js');
require('@babel/runtime/helpers/toConsumableArray');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/slicedToArray');
require('../loading/props.js');
require('vue');
require('raf');
require('lodash/isString');
require('../utils/easing.js');
require('@babel/runtime/helpers/typeof');
require('lodash/camelCase');
require('lodash/kebabCase');
require('lodash/mergeWith');
require('../config-provider/context.js');
require('lodash/merge');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('../utils/withInstall.js');
require('lodash/capitalize');
require('../loading/plugin.js');
require('../config.js');
require('../button/props.js');
require('../utils/ripple.js');
require('../_chunks/dep-d7a1e02c.js');
require('lodash/isObject');
require('../utils/helper.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var isNumber__default = /*#__PURE__*/_interopDefaultLegacy(isNumber);
var throttle__default = /*#__PURE__*/_interopDefaultLegacy(throttle);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getCSSValue(v) {
  return isNaN(Number(v)) ? v : "".concat(Number(v), "px");
}

var mousePosition;

var getClickPosition = function getClickPosition(e) {
  mousePosition = {
    x: e.clientX,
    y: e.clientY
  };
  setTimeout(function () {
    mousePosition = null;
  }, 100);
};

if (typeof window !== "undefined" && window.document && window.document.documentElement) {
  document.documentElement.addEventListener("click", getClickPosition, true);
}

var _Dialog = utils_mixins["default"](dialog_actions["default"], configProvider_configReceiver["default"]("dialog"), configProvider_configReceiver.getGlobalIconMixins()).extend({
  name: "TDialog",
  components: {
    TButton: button_index.Button
  },
  data: function data() {
    return {
      uid: 0,
      scrollWidth: 0,
      disX: 0,
      disY: 0,
      windowInnerWidth: 0,
      windowInnerHeight: 0,
      dialogW: 0,
      dialogH: 0,
      dLeft: 0,
      dTop: 0
    };
  },
  props: _objectSpread({}, dialog_props["default"]),
  computed: {
    isModal: function isModal() {
      return this.mode === "modal";
    },
    isModeLess: function isModeLess() {
      return this.mode === "modeless";
    },
    isNormal: function isNormal() {
      return this.mode === "normal";
    },
    maskClass: function maskClass() {
      return ["".concat(this.componentName, "__mask"), !this.showOverlay && "".concat(this.classPrefix, "-is-hidden")];
    },
    dialogClass: function dialogClass() {
      var dialogClass = ["".concat(this.componentName), "".concat(this.componentName, "--default"), "".concat(this.componentName, "__modal-").concat(this.theme)];
      return dialogClass;
    },
    positionClass: function positionClass() {
      if (this.isNormal) return [];
      var dialogClass = ["".concat(this.componentName, "__position"), !!this.top && "".concat(this.componentName, "--top"), "".concat(this.placement && !this.top ? "".concat(this.componentName, "--").concat(this.placement) : "")];
      return dialogClass;
    },
    wrapClass: function wrapClass() {
      return [!this.isNormal && "".concat(this.componentName, "__wrap")];
    },
    positionStyle: function positionStyle() {
      var topStyle = {};

      if (this.top !== void 0) {
        if (isNumber__default["default"](this.top) && this.top < 0) {
          topStyle.paddingTop = "".concat(this.top, "px");
        } else {
          topStyle.paddingTop = this.top;
        }
      }

      return topStyle;
    },
    dialogStyle: function dialogStyle() {
      return {
        width: getCSSValue(this.width)
      };
    }
  },
  watch: {
    visible: function visible(value) {
      var _this = this;

      if (value) {
        var scrollWidth = this.scrollWidth;

        if (this.isModal && !this.showInAttachedElement) {
          if (scrollWidth > 0 && this.preventScrollThrough) {
            var bodyCssText = "position: relative;width: calc(100% - ".concat(scrollWidth, "px);");
            document.body.style.cssText = bodyCssText;
          }

          this.preventScrollThrough && utils_dom.addClass(document.body, "".concat(this.componentName, "--lock"));
          this.$nextTick(function () {
            var target = _this.$refs.dialog;

            if (mousePosition && target) {
              target.style.transformOrigin = "".concat(mousePosition.x - target.offsetLeft, "px ").concat(mousePosition.y - target.offsetTop, "px");
            }
          });
        }

        document.activeElement.blur();
      } else {
        document.body.style.cssText = "";
        utils_dom.removeClass(document.body, "".concat(this.componentName, "--lock"));
      }

      this.storeUid(value);
      this.addKeyboardEvent(value);

      if (this.isModeLess && this.draggable) {
        this.initDragEvent(value);
      }

      if (value && !this.destroyOnClose && requestAnimationFrame) {
        requestAnimationFrame(function () {
          hooks_useDestroyOnClose.updateElement(_this);
        });
      }
    }
  },
  mounted: function mounted() {
    this.scrollWidth = window.innerWidth - document.body.offsetWidth;

    if (this.draggable) {
      window.addEventListener("resize", throttle__default["default"](this.resizeAdjustPosition, 1e3));
    }

    if (this.visible && this.isModal && this.preventScrollThrough) {
      utils_dom.addClass(document.body, "".concat(this.componentName, "--lock"));
    }

    this.uid = this._uid;
  },
  beforeDestroy: function beforeDestroy() {
    this.addKeyboardEvent(false);
  },
  directives: {
    TransferDom: utils_transferDom["default"]
  },
  methods: {
    storeUid: function storeUid(flag) {
      if (flag) {
        dialog_stack["default"].push(this.uid);
      } else {
        dialog_stack["default"].pop();
      }
    },
    addKeyboardEvent: function addKeyboardEvent(status) {
      if (status) {
        document.addEventListener("keydown", this.keyboardEvent);
        this.confirmOnEnter && document.addEventListener("keydown", this.keyboardEnterEvent);
      } else {
        document.removeEventListener("keydown", this.keyboardEvent);
        this.confirmOnEnter && document.removeEventListener("keydown", this.keyboardEnterEvent);
      }
    },
    keyboardEvent: function keyboardEvent(e) {
      if (e.code === "Escape" && dialog_stack["default"].top === this.uid) {
        var _this$closeOnEscKeydo;

        utils_event.emitEvent(this, "esc-keydown", {
          e: e
        });

        if ((_this$closeOnEscKeydo = this.closeOnEscKeydown) !== null && _this$closeOnEscKeydo !== void 0 ? _this$closeOnEscKeydo : this.global.closeOnEscKeydown) {
          this.emitCloseEvent({
            e: e,
            trigger: "esc"
          });
        }
      }
    },
    keyboardEnterEvent: function keyboardEnterEvent(e) {
      var code = e.code;

      if ((code === "Enter" || code === "NumpadEnter") && dialog_stack["default"].top === this.uid) {
        utils_event.emitEvent(this, "confirm", {
          e: e
        });
      }
    },
    overlayAction: function overlayAction(e) {
      var _this$closeOnOverlayC;

      if (this.showOverlay && ((_this$closeOnOverlayC = this.closeOnOverlayClick) !== null && _this$closeOnOverlayC !== void 0 ? _this$closeOnOverlayC : this.global.closeOnOverlayClick)) {
        if (e.target === this.$refs.dialogPosition) {
          utils_event.emitEvent(this, "overlay-click", {
            e: e
          });
          this.emitCloseEvent({
            e: e,
            trigger: "overlay"
          });
        }
      }
    },
    closeBtnAction: function closeBtnAction(e) {
      utils_event.emitEvent(this, "close-btn-click", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "close-btn",
        e: e
      });
    },
    cancelBtnAction: function cancelBtnAction(e) {
      utils_event.emitEvent(this, "cancel", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "cancel",
        e: e
      });
    },
    confirmBtnAction: function confirmBtnAction(e) {
      utils_event.emitEvent(this, "confirm", {
        e: e
      });
    },
    afterEnter: function afterEnter() {
      utils_event.emitEvent(this, "opened");
    },
    afterLeave: function afterLeave() {
      if (this.isModeLess && this.draggable) {
        var target = this.$refs.dialog;
        target.style.position = "relative";
        target.style.left = "unset";
        target.style.top = "unset";
      }

      utils_event.emitEvent(this, "closed");
    },
    emitCloseEvent: function emitCloseEvent(context) {
      utils_event.emitEvent(this, "close", context);
      this.$emit("update:visible", false);
    },
    hasEventOn: function hasEventOn(name) {
      var _this$_events;

      var eventFuncs = (_this$_events = this["_events"]) === null || _this$_events === void 0 ? void 0 : _this$_events[name];
      return !!(eventFuncs !== null && eventFuncs !== void 0 && eventFuncs.length);
    },
    getIcon: function getIcon() {
      var h = this.$createElement;

      var _this$useGlobalIcon = this.useGlobalIcon({
        InfoCircleFilledIcon: tdesignIconsVue.InfoCircleFilledIcon,
        CheckCircleFilledIcon: tdesignIconsVue.CheckCircleFilledIcon,
        ErrorCircleFilledIcon: tdesignIconsVue.ErrorCircleFilledIcon
      }),
          InfoCircleFilledIcon = _this$useGlobalIcon.InfoCircleFilledIcon,
          CheckCircleFilledIcon = _this$useGlobalIcon.CheckCircleFilledIcon,
          ErrorCircleFilledIcon = _this$useGlobalIcon.ErrorCircleFilledIcon;

      var icon = {
        info: h(InfoCircleFilledIcon, {
          "class": "".concat(this.classPrefix, "-is-info")
        }),
        warning: h(ErrorCircleFilledIcon, {
          "class": "".concat(this.classPrefix, "-is-warning")
        }),
        danger: h(ErrorCircleFilledIcon, {
          "class": "".concat(this.classPrefix, "-is-error")
        }),
        success: h(CheckCircleFilledIcon, {
          "class": "".concat(this.classPrefix, "-is-success")
        })
      };
      return icon[this.theme];
    },
    mousedownHandler: function mousedownHandler(targetEvent) {
      var target = this.$refs.dialog;
      this.disX = targetEvent.clientX - target.offsetLeft;
      this.disY = targetEvent.clientY - target.offsetTop;
      this.dialogW = target.offsetWidth;
      this.dialogH = target.offsetHeight;
      this.windowInnerWidth = window.innerWidth || document.documentElement.clientWidth;
      this.windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
      if (this.dialogW > this.windowInnerWidth || this.dialogH > this.windowInnerHeight) return;
      document.addEventListener("mousemove", this.mouseMoverHandler);
      document.addEventListener("mouseup", this.mouseUpHandler);
      document.addEventListener("dragend", this.mouseUpHandler);
    },
    mouseMoverHandler: function mouseMoverHandler(documentEvent) {
      var target = this.$refs.dialog;
      var left = documentEvent.clientX - this.disX;
      var top = documentEvent.clientY - this.disY;
      if (left < 0) left = 0;
      if (top < 0) top = 0;
      if (this.windowInnerWidth - target.offsetWidth - left < 0) left = this.windowInnerWidth - target.offsetWidth;
      if (this.windowInnerHeight - target.offsetHeight - top < 0) top = this.windowInnerHeight - target.offsetHeight;
      target.style.position = "absolute";
      target.style.left = "".concat(left, "px");
      target.style.top = "".concat(top, "px");
    },
    mouseUpHandler: function mouseUpHandler() {
      document.removeEventListener("mousemove", this.mouseMoverHandler);
      document.removeEventListener("mouseup", this.mouseUpHandler);
      document.removeEventListener("dragend", this.mouseUpHandler);
    },
    initDragEvent: function initDragEvent(status) {
      var target = this.$refs.dialog;

      if (status) {
        target.addEventListener("mousedown", this.mousedownHandler);
      } else {
        target.removeEventListener("mousedown", this.mousedownHandler);
      }
    },
    resizeAdjustPosition: function resizeAdjustPosition() {
      if (this.visible) {
        var target = this.$refs.dialog;
        target.style.left = "".concat(this.dLeft * (window.innerWidth / this.windowInnerWidth), "px");
        target.style.top = "".concat(this.dTop * (window.innerHeight / this.windowInnerHeight), "px");
      }
    },
    renderDialog: function renderDialog() {
      var h = this.$createElement;

      var _this$useGlobalIcon2 = this.useGlobalIcon({
        CloseIcon: tdesignIconsVue.CloseIcon
      }),
          CloseIcon = _this$useGlobalIcon2.CloseIcon;

      var defaultHeader = h("h5", {
        "class": "title"
      });
      var defaultCloseBtn = h(CloseIcon);
      var body = utils_renderTnode.renderContent(this, "default", "body");
      var defaultFooter = h("div", [this.getCancelBtn({
        cancelBtn: this.cancelBtn,
        globalCancel: this.global.cancel,
        className: "".concat(this.componentName, "__cancel")
      }), this.getConfirmBtn({
        theme: this.theme,
        confirmBtn: this.confirmBtn,
        globalConfirm: this.global.confirm,
        globalConfirmBtnTheme: this.global.confirmBtnTheme,
        className: "".concat(this.componentName, "__confirm")
      })]);
      var bodyClassName = this.theme === "default" ? "".concat(this.componentName, "__body") : "".concat(this.componentName, "__body__icon");
      return h("div", {
        "class": this.wrapClass
      }, [h("div", {
        "class": this.positionClass,
        "style": this.positionStyle,
        "on": {
          "click": this.overlayAction
        },
        "ref": "dialogPosition"
      }, [h("div", {
        "key": "dialog",
        "ref": "dialog",
        "class": this.dialogClass,
        "style": this.dialogStyle
      }, [h("div", {
        "class": "".concat(this.componentName, "__header")
      }, [this.getIcon(), utils_renderTnode.renderTNodeJSX(this, "header", defaultHeader)]), this.closeBtn ? h("span", {
        "class": "".concat(this.componentName, "__close"),
        "on": {
          "click": this.closeBtnAction
        }
      }, [utils_renderTnode.renderTNodeJSX(this, "closeBtn", defaultCloseBtn)]) : null, h("div", {
        "class": bodyClassName
      }, [body]), h("div", {
        "class": "".concat(this.componentName, "__footer")
      }, [utils_renderTnode.renderTNodeJSX(this, "footer", defaultFooter)])])])]);
    }
  },
  render: function render() {
    var _ref;

    var h = arguments[0];
    var maskView = this.isModal && h("div", {
      "key": "mask",
      "class": this.maskClass
    });
    var dialogView = this.renderDialog();
    var view = [maskView, dialogView];
    var ctxStyle = {
      zIndex: this.zIndex
    };
    var ctxClass = ["".concat(this.componentName, "__ctx"), (_ref = {}, _defineProperty__default["default"](_ref, "".concat(this.classPrefix, "-dialog__ctx--fixed"), this.mode === "modal"), _defineProperty__default["default"](_ref, "".concat(this.classPrefix, "-dialog__ctx--absolute"), this.isModal && this.showInAttachedElement), _defineProperty__default["default"](_ref, "".concat(this.componentName, "__ctx--modeless"), this.isModeLess), _ref)];
    return h("transition", {
      "attrs": {
        "duration": 300,
        "name": "".concat(this.componentName, "-zoom__vue")
      },
      "on": {
        "afterEnter": this.afterEnter,
        "afterLeave": this.afterLeave
      }
    }, [(!this.destroyOnClose || this.visible) && h("div", {
      "directives": [{
        name: "show",
        value: this.visible
      }, {
        name: "transfer-dom",
        value: this.attach
      }],
      "class": ctxClass,
      "style": ctxStyle
    }, [view])]);
  }
});

exports["default"] = _Dialog;
//# sourceMappingURL=dialog.js.map
