/**
 * tdesign v0.39.1-alpha.1
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

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

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var throttle = require('lodash/throttle');
var tdesignIconsVue = require('tdesign-icons-vue');
var config = require('../config.js');
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');
require('../button/button.js');
require('../_chunks/dep-33ee4bce.js');
require('../utils/classnames.js');
require('../loading/index.js');
require('../loading/loading.js');
require('vue');
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/objectWithoutProperties');
require('../loading/props.js');
require('raf');
require('lodash/isString');
require('../utils/easing.js');
require('@babel/runtime/helpers/typeof');
require('lodash/isObject');
require('../utils/withInstall.js');
require('lodash/capitalize');
require('../loading/plugin.js');
require('../button/props.js');
require('../utils/ripple.js');
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/helper.js');
require('lodash/camelCase');

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

var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
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; }
var name = "".concat(config.prefix, "-dialog");
var lockClass = "".concat(config.prefix, "-dialog--lock");

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

var _Dialog = utils_mixins["default"](dialog_actions["default"], configProvider_configReceiver["default"]("dialog")).extend({
  name: "TDialog",
  components: {
    CloseIcon: tdesignIconsVue.CloseIcon,
    InfoCircleFilledIcon: tdesignIconsVue.InfoCircleFilledIcon,
    CheckCircleFilledIcon: tdesignIconsVue.CheckCircleFilledIcon,
    ErrorCircleFilledIcon: tdesignIconsVue.ErrorCircleFilledIcon,
    TButton: button_index.Button
  },
  data: function data() {
    return {
      scrollWidth: 0,
      disX: 0,
      disY: 0,
      windowInnerWidth: 0,
      windowInnerHeight: 0,
      offsetX: 0,
      offsetY: 0,
      diaglogW: 0,
      diaglogH: 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";
    },
    maskClass: function maskClass() {
      return ["".concat(name, "__mask"), !this.showOverlay && "".concat(config.prefix, "-is-hidden")];
    },
    dialogClass: function dialogClass() {
      var dialogClass = ["".concat(name), "".concat(name, "--default"), "".concat(name, "--").concat(this.placement), "".concat(name, "__modal-").concat(this.theme)];

      if (["modeless", "modal"].includes(this.mode)) {
        dialogClass.push("".concat(name, "--fixed"));
      }

      return dialogClass;
    },
    dialogStyle: function dialogStyle() {
      var top = this.top,
          placement = this.placement;
      var topStyle = {};

      if (top) {
        var topValue = getCSSValue(top);
        topStyle = {
          top: topValue,
          transform: "translate(-50%, 0)",
          transformOrigin: "25% 25%",
          maxHeight: "calc(100% - ".concat(topValue, ")"),
          zIndex: this.zIndex
        };
      } else if (placement === "top") {
        topStyle = {
          maxHeight: "calc(100% - 20%)"
        };
      }

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

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

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

        utils_dom.addClass(document.body, lockClass);
      } else {
        document.body.style.cssText = "";
        utils_dom.removeClass(document.body, lockClass);
      }

      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));
    }
  },
  beforeDestroy: function beforeDestroy() {
    this.addKeyboardEvent(false);
  },
  directives: {
    TransferDom: utils_transferDom["default"]
  },
  methods: {
    addKeyboardEvent: function addKeyboardEvent(status) {
      if (status) {
        document.addEventListener("keydown", this.keyboardEvent);
      } else {
        document.removeEventListener("keydown", this.keyboardEvent);
      }
    },
    keyboardEvent: function keyboardEvent(e) {
      if (e.code === "Escape") {
        utils_event.emitEvent(this, "esc-keydown", {
          e: e
        });

        if (this.closeOnEscKeydown) {
          this.emitCloseEvent({
            trigger: "esc",
            e: e
          });
        }
      }
    },
    overlayAction: function overlayAction(e) {
      utils_event.emitEvent(this, "overlay-click", {
        e: e
      });

      if (this.closeOnOverlayClick) {
        this.emitCloseEvent({
          trigger: "overlay",
          e: e
        });
      }
    },
    closeBtnAcion: function closeBtnAcion(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() {
      utils_event.emitEvent(this, "closed");
    },
    emitCloseEvent: function emitCloseEvent(context) {
      utils_event.emitEvent(this, "close", context);
      this.$emit("update:visible", false);
    },
    hasEventOn: function hasEventOn(name2) {
      var _this$_events;

      var eventFuncs = (_this$_events = this["_events"]) === null || _this$_events === void 0 ? void 0 : _this$_events[name2];
      return !!(eventFuncs !== null && eventFuncs !== void 0 && eventFuncs.length);
    },
    getIcon: function getIcon() {
      var h = this.$createElement;
      var icon = {
        info: h(tdesignIconsVue.InfoCircleFilledIcon, {
          "class": "".concat(config.prefix, "-is-info")
        }),
        warning: h(tdesignIconsVue.ErrorCircleFilledIcon, {
          "class": "".concat(config.prefix, "-is-warning")
        }),
        danger: h(tdesignIconsVue.ErrorCircleFilledIcon, {
          "class": "".concat(config.prefix, "-is-error")
        }),
        success: h(tdesignIconsVue.CheckCircleFilledIcon, {
          "class": "".concat(config.prefix, "-is-success")
        })
      };
      return icon[this.theme];
    },
    mousedownHanler: function mousedownHanler(targetEvent) {
      var target = this.$refs.dialog;
      this.disX = targetEvent.clientX - target.offsetLeft;
      this.disY = targetEvent.clientY - target.offsetTop;
      this.diaglogW = target.offsetWidth;
      this.diaglogH = target.offsetHeight;

      var _this$getTranslateXY = this.getTranslateXY(target),
          _this$getTranslateXY2 = _slicedToArray__default["default"](_this$getTranslateXY, 2),
          x = _this$getTranslateXY2[0],
          y = _this$getTranslateXY2[1];

      this.offsetX = x;
      this.offsetY = y;
      this.windowInnerWidth = window.innerWidth;
      this.windowInnerHeight = window.innerHeight;
      document.addEventListener("mousemove", this.mouseMoverHander);
      document.addEventListener("mouseup", this.mouseUpHandler);
      document.addEventListener("dragend", this.mouseUpHandler);
    },
    mouseMoverHander: function mouseMoverHander(documentEvent) {
      var target = this.$refs.dialog;
      var left = documentEvent.clientX - this.disX;
      var top = documentEvent.clientY - this.disY;

      if (left + this.diaglogW - this.offsetX > this.windowInnerWidth) {
        this.dLeft = this.windowInnerWidth - this.diaglogW + this.offsetX;
      } else {
        this.dLeft = target.offsetLeft < this.offsetX || left <= this.offsetX ? this.offsetX : left;
      }

      target.style.left = "".concat(this.dLeft, "px");

      if (top + this.diaglogH - this.offsetY > this.windowInnerHeight) {
        this.dTop = this.windowInnerHeight - this.diaglogH + this.offsetY;
      } else {
        this.dTop = top < this.offsetY ? this.offsetY : top;
      }

      target.style.top = "".concat(this.dTop, "px");
    },
    mouseUpHandler: function mouseUpHandler() {
      document.removeEventListener("mousemove", this.mouseMoverHander);
      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.mousedownHanler);
      } else {
        target.removeEventListener("mousedown", this.mousedownHanler);
      }
    },
    getTranslateXY: function getTranslateXY(target) {
      var transformStyle = document.defaultView.getComputedStyle(target).transform;
      var reg = /(\d+(\.\d+)?)/g;
      var tarnsArr = transformStyle.match(reg);
      return [parseFloat(tarnsArr[4]), parseFloat(tarnsArr[5])];
    },
    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 defaultHeader = h("h5", {
        "class": "title"
      });
      var defaultCloseBtn = h("close-icon");
      var body = utils_renderTnode.renderContent(this, "default", "body");
      var defaultFooter = h("div", [this.getCancelBtn({
        cancelBtn: this.cancelBtn,
        globalCancel: this.global.cancel,
        className: "".concat(config.prefix, "-dialog__cancel")
      }), this.getConfirmBtn({
        theme: this.theme,
        confirmBtn: this.confirmBtn,
        globalConfirm: this.global.confirm,
        globalConfirmBtnTheme: this.global.confirmBtnTheme,
        className: "".concat(config.prefix, "-dialog__confirm")
      })]);
      var bodyClassName = this.theme === "default" ? "".concat(name, "__body") : "".concat(name, "__body__icon");
      return h("div", {
        "key": "dialog",
        "ref": "dialog",
        "class": this.dialogClass,
        "style": this.dialogStyle
      }, [h("div", {
        "class": "".concat(name, "__header")
      }, [this.getIcon(), utils_renderTnode.renderTNodeJSX(this, "header", defaultHeader)]), this.closeBtn ? h("span", {
        "class": "".concat(name, "__close"),
        "on": {
          "click": this.closeBtnAcion
        }
      }, [utils_renderTnode.renderTNodeJSX(this, "closeBtn", defaultCloseBtn)]) : null, h("div", {
        "class": bodyClassName
      }, [body]), h("div", {
        "class": "".concat(name, "__footer")
      }, [utils_renderTnode.renderTNodeJSX(this, "footer", defaultFooter)])]);
    }
  },
  render: function render() {
    var h = arguments[0];
    var maskView = this.isModal && h("div", {
      "key": "mask",
      "class": this.maskClass,
      "on": {
        "click": this.overlayAction
      }
    });
    var dialogView = this.renderDialog();
    var view = [maskView, dialogView];
    var ctxStyle = {
      zIndex: this.zIndex
    };
    var ctxClass = ["".concat(name, "__ctx"), _defineProperty__default["default"]({}, "".concat(config.prefix, "-dialog__ctx--fixed"), this.mode === "modal")];
    return h("transition", {
      "attrs": {
        "duration": 300,
        "name": "".concat(name, "-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
