/**
 * ldesign v0.2.2
 * (c) 2022年9月20日 swimly
 * @license MIT
 */

import _defineProperty from '@babel/runtime/helpers/defineProperty';
import isNumber from 'lodash/isNumber';
import throttle from 'lodash/throttle';
import { InfoCircleFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon, CloseIcon } from '@ldesign/icons-vue';
import { Button } from '../button/index.js';
import ActionMixin from './mixins/action.js';
import props from './props.js';
import { renderContent, renderLNodeJSX } from '../../utils/render-node.js';
import mixins from '../../utils/mixins.js';
import getConfigReceiverMixins, { getGlobalIconMixins } from '../config-provider/config-receiver.js';
import TransferDom from '../../utils/transfer-dom.js';
import { emitEvent } from '../../utils/event.js';
import { addClass, removeClass } from '../../utils/dom.js';
import { updateElement } from '../../hooks/use-destroy-onclose.js';
import stack from './stack.js';
import '../button/button.js';
import '../loading/index.js';
import '../loading/loading.js';
import '../loading/icon/gradient.js';
import 'vue';
import '../../chunks/defineProperty-28395935.js';
import '../../chunks/set-style.js';
import '../../chunks/helper2.js';
import '@babel/runtime/helpers/toConsumableArray';
import '@babel/runtime/helpers/slicedToArray';
import '../../config.js';
import '../loading/props.js';
import 'raf';
import 'lodash/isString';
import '../../utils/easing.js';
import '@babel/runtime/helpers/typeof';
import 'lodash/camelCase';
import 'lodash/kebabCase';
import 'lodash/mergeWith';
import 'lodash';
import '../config-provider/context.js';
import '../../chunks/zh_CN.js';
import '../config-provider/type.js';
import '../../utils/with-install.js';
import '../loading/style/css.js';
import '../loading/type.js';
import '../loading/plugin.js';
import '../button/props.js';
import '../../utils/ripple.js';
import '../button/style/css.js';
import '../button/type.js';
import '../../chunks/helper.js';
import '../../chunks/_commonjsHelpers.js';
import 'lodash/isObject';
import '../../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';

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(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 = mixins(ActionMixin, getConfigReceiverMixins("dialog"), getGlobalIconMixins()).extend({
  name: "LDialog",
  components: {
    TButton: 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({}, props),
  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(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 && 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 = "";
        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 () {
          updateElement(_this);
        });
      }
    }
  },
  mounted: function mounted() {
    this.scrollWidth = window.innerWidth - document.body.offsetWidth;

    if (this.draggable) {
      window.addEventListener("resize", throttle(this.resizeAdjustPosition, 1e3));
    }

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

    this.uid = this._uid;
  },
  beforeDestroy: function beforeDestroy() {
    this.addKeyboardEvent(false);
  },
  directives: {
    TransferDom: TransferDom
  },
  methods: {
    storeUid: function storeUid(flag) {
      if (flag) {
        stack.push(this.uid);
      } else {
        stack.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" && stack.top === this.uid) {
        var _this$closeOnEscKeydo;

        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") && stack.top === this.uid) {
        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) {
          emitEvent(this, "overlay-click", {
            e: e
          });
          this.emitCloseEvent({
            e: e,
            trigger: "overlay"
          });
        }
      }
    },
    closeBtnAction: function closeBtnAction(e) {
      emitEvent(this, "close-btn-click", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "close-btn",
        e: e
      });
    },
    cancelBtnAction: function cancelBtnAction(e) {
      emitEvent(this, "cancel", {
        e: e
      });
      this.emitCloseEvent({
        trigger: "cancel",
        e: e
      });
    },
    confirmBtnAction: function confirmBtnAction(e) {
      emitEvent(this, "confirm", {
        e: e
      });
    },
    afterEnter: function afterEnter() {
      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";
      }

      emitEvent(this, "closed");
    },
    emitCloseEvent: function emitCloseEvent(context) {
      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: InfoCircleFilledIcon,
        CheckCircleFilledIcon: CheckCircleFilledIcon,
        ErrorCircleFilledIcon: ErrorCircleFilledIcon
      }),
          InfoCircleFilledIcon$1 = _this$useGlobalIcon.InfoCircleFilledIcon,
          CheckCircleFilledIcon$1 = _this$useGlobalIcon.CheckCircleFilledIcon,
          ErrorCircleFilledIcon$1 = _this$useGlobalIcon.ErrorCircleFilledIcon;

      var icon = {
        info: h(InfoCircleFilledIcon$1, {
          "class": "".concat(this.classPrefix, "-is-info")
        }),
        warning: h(ErrorCircleFilledIcon$1, {
          "class": "".concat(this.classPrefix, "-is-warning")
        }),
        danger: h(ErrorCircleFilledIcon$1, {
          "class": "".concat(this.classPrefix, "-is-error")
        }),
        success: h(CheckCircleFilledIcon$1, {
          "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: CloseIcon
      }),
          CloseIcon$1 = _this$useGlobalIcon2.CloseIcon;

      var defaultHeader = h("h5", {
        "class": "title"
      });
      var defaultCloseBtn = h(CloseIcon$1);
      var body = 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(), renderLNodeJSX(this, "header", defaultHeader)]), this.closeBtn ? h("span", {
        "class": "".concat(this.componentName, "__close"),
        "on": {
          "click": this.closeBtnAction
        }
      }, [renderLNodeJSX(this, "closeBtn", defaultCloseBtn)]) : null, h("div", {
        "class": bodyClassName
      }, [body]), h("div", {
        "class": "".concat(this.componentName, "__footer")
      }, [renderLNodeJSX(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(_ref, "".concat(this.classPrefix, "-dialog__ctx--fixed"), this.mode === "modal"), _defineProperty(_ref, "".concat(this.classPrefix, "-dialog__ctx--absolute"), this.isModal && this.showInAttachedElement), _defineProperty(_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])]);
  }
});

export { _Dialog as default };
//# sourceMappingURL=dialog.js.map
