"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const aria = require("../../../constants/aria.js");
const event = require("../../../utils/dom/event.js");
const objects = require("../../../utils/objects.js");
const index$7 = require("../../teleport/index.js");
const index$1 = require("../../../hooks/use-locale/index.js");
const index$2 = require("../../../hooks/use-namespace/index.js");
const index$5 = require("../../../hooks/use-lockscreen/index.js");
const index$3 = require("../../../hooks/use-z-index/index.js");
const index$9 = require("../../icon/index.js");
const index$8 = require("../../focus-trap/index.js");
const imageViewer = require("./image-viewer.js");
const index$6 = require("../../../../node_modules/@vueuse/core/index.js");
const index = require("../../../../../@element-plus/icons-vue/dist/index.js");
const Vue = require("vue");
const throttle = require("../../../../../lodash-es/throttle.js");
const index$4 = require("../../../../node_modules/@vueuse/shared/index.js");
const _hoisted_1 = ["src", "crossorigin"];
var image_viewer_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ Vue.defineComponent({
  name: "ElImageViewer",
  __name: "image-viewer",
  props: imageViewer.imageViewerProps,
  emits: imageViewer.imageViewerEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const modes = {
      CONTAIN: {
        name: "contain",
        icon: Vue.markRaw(index.FullScreen)
      },
      ORIGINAL: {
        name: "original",
        icon: Vue.markRaw(index.ScaleToOriginal)
      }
    };
    const props = __props;
    const emit = __emit;
    let stopWheelListener;
    const { t } = index$1.useLocale();
    const ns = index$2.useNamespace("image-viewer");
    const { nextZIndex } = index$3.useZIndex();
    const wrapper = Vue.ref();
    const imgRef = Vue.ref();
    const scopeEventListener = Vue.effectScope();
    const scaleClamped = Vue.computed(() => {
      const { scale, minScale, maxScale } = props;
      return index$4.clamp(scale, minScale, maxScale);
    });
    const loading = Vue.ref(true);
    const loadError = Vue.ref(false);
    const visible = Vue.ref(false);
    const activeIndex = Vue.ref(props.initialIndex);
    const mode = Vue.shallowRef(modes.CONTAIN);
    const transform = Vue.ref({
      scale: scaleClamped.value,
      deg: 0,
      offsetX: 0,
      offsetY: 0,
      enableTransition: false
    });
    const zIndex = Vue.ref(props.zIndex ?? nextZIndex());
    index$5.useLockscreen(visible, { ns });
    const isSingle = Vue.computed(() => {
      const { urlList } = props;
      return urlList.length <= 1;
    });
    const isFirst = Vue.computed(() => activeIndex.value === 0);
    const isLast = Vue.computed(() => activeIndex.value === props.urlList.length - 1);
    const currentImg = Vue.computed(() => props.urlList[activeIndex.value]);
    const arrowPrevKls = Vue.computed(() => [
      ns.e("btn"),
      ns.e("prev"),
      ns.is("disabled", !props.infinite && isFirst.value)
    ]);
    const arrowNextKls = Vue.computed(() => [
      ns.e("btn"),
      ns.e("next"),
      ns.is("disabled", !props.infinite && isLast.value)
    ]);
    const imgStyle = Vue.computed(() => {
      const { scale, deg, offsetX, offsetY, enableTransition } = transform.value;
      let translateX = offsetX / scale;
      let translateY = offsetY / scale;
      const radian = deg * Math.PI / 180;
      const cosRadian = Math.cos(radian);
      const sinRadian = Math.sin(radian);
      translateX = translateX * cosRadian + translateY * sinRadian;
      translateY = translateY * cosRadian - offsetX / scale * sinRadian;
      const style = {
        transform: `scale(${scale}) rotate(${deg}deg) translate(${translateX}px, ${translateY}px)`,
        transition: enableTransition ? "transform .3s" : ""
      };
      if (mode.value.name === modes.CONTAIN.name) style.maxWidth = style.maxHeight = "100%";
      return style;
    });
    const progress = Vue.computed(() => `${activeIndex.value + 1} / ${props.urlList.length}`);
    function hide() {
      unregisterEventListener();
      stopWheelListener == null ? void 0 : stopWheelListener();
      visible.value = false;
      emit("close");
    }
    function registerEventListener() {
      const keydownHandler = throttle.default((e) => {
        switch (event.getEventCode(e)) {
          case aria.EVENT_CODE.esc:
            props.closeOnPressEscape && hide();
            break;
          case aria.EVENT_CODE.space:
            toggleMode();
            break;
          case aria.EVENT_CODE.left:
            prev();
            break;
          case aria.EVENT_CODE.up:
            handleActions("zoomIn");
            break;
          case aria.EVENT_CODE.right:
            next();
            break;
          case aria.EVENT_CODE.down:
            handleActions("zoomOut");
            break;
        }
      });
      const mousewheelHandler = throttle.default((e) => {
        handleActions((e.deltaY || e.deltaX) < 0 ? "zoomIn" : "zoomOut", {
          zoomRate: props.zoomRate,
          enableTransition: false
        });
      });
      scopeEventListener.run(() => {
        index$6.useEventListener(document, "keydown", keydownHandler);
        index$6.useEventListener(wrapper, "wheel", mousewheelHandler);
      });
    }
    function unregisterEventListener() {
      scopeEventListener.stop();
    }
    function handleImgLoad() {
      loading.value = false;
    }
    function handleImgError(e) {
      loadError.value = true;
      loading.value = false;
      emit("error", e);
      e.target.alt = t("el.image.error");
    }
    function handleMouseDown(e) {
      if (loading.value || e.button !== 0 || !wrapper.value) return;
      transform.value.enableTransition = false;
      const { offsetX, offsetY } = transform.value;
      const startX = e.pageX;
      const startY = e.pageY;
      const dragHandler = throttle.default((ev) => {
        transform.value = {
          ...transform.value,
          offsetX: offsetX + ev.pageX - startX,
          offsetY: offsetY + ev.pageY - startY
        };
      });
      const removeMousemove = index$6.useEventListener(document, "mousemove", dragHandler);
      const removeMouseup = index$6.useEventListener(document, "mouseup", () => {
        removeMousemove();
        removeMouseup();
      });
      e.preventDefault();
    }
    function handleTouchStart(e) {
      if (loading.value || !wrapper.value || e.touches.length !== 1) return;
      transform.value.enableTransition = false;
      const { offsetX, offsetY } = transform.value;
      const { pageX: startX, pageY: startY } = e.touches[0];
      const dragHandler = throttle.default((ev) => {
        const targetTouch = ev.touches[0];
        transform.value = {
          ...transform.value,
          offsetX: offsetX + targetTouch.pageX - startX,
          offsetY: offsetY + targetTouch.pageY - startY
        };
      });
      const removeTouchmove = index$6.useEventListener(document, "touchmove", dragHandler);
      const removeTouchend = index$6.useEventListener(document, "touchend", () => {
        removeTouchmove();
        removeTouchend();
      });
      e.preventDefault();
    }
    function reset() {
      transform.value = {
        scale: scaleClamped.value,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      };
    }
    function toggleMode() {
      if (loading.value || loadError.value) return;
      const modeNames = objects.keysOf(modes);
      const modeValues = Object.values(modes);
      const currentMode = mode.value.name;
      mode.value = modes[modeNames[(modeValues.findIndex((i) => i.name === currentMode) + 1) % modeNames.length]];
      reset();
    }
    function setActiveItem(index2) {
      loadError.value = false;
      const len = props.urlList.length;
      activeIndex.value = (index2 + len) % len;
    }
    function prev() {
      if (isFirst.value && !props.infinite) return;
      setActiveItem(activeIndex.value - 1);
    }
    function next() {
      if (isLast.value && !props.infinite) return;
      setActiveItem(activeIndex.value + 1);
    }
    function handleActions(action, options = {}) {
      if (loading.value || loadError.value) return;
      const { minScale, maxScale } = props;
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: props.zoomRate,
        rotateDeg: 90,
        enableTransition: true,
        ...options
      };
      switch (action) {
        case "zoomOut":
          if (transform.value.scale > minScale) transform.value.scale = Number.parseFloat((transform.value.scale / zoomRate).toFixed(3));
          break;
        case "zoomIn":
          if (transform.value.scale < maxScale) transform.value.scale = Number.parseFloat((transform.value.scale * zoomRate).toFixed(3));
          break;
        case "clockwise":
          transform.value.deg += rotateDeg;
          emit("rotate", transform.value.deg);
          break;
        case "anticlockwise":
          transform.value.deg -= rotateDeg;
          emit("rotate", transform.value.deg);
          break;
      }
      transform.value.enableTransition = enableTransition;
    }
    function onFocusoutPrevented(event2) {
      var _a;
      if (((_a = event2.detail) == null ? void 0 : _a.focusReason) === "pointer") event2.preventDefault();
    }
    function onCloseRequested() {
      if (props.closeOnPressEscape) hide();
    }
    function wheelHandler(e) {
      if (!e.ctrlKey) return;
      if (e.deltaY < 0) {
        e.preventDefault();
        return false;
      } else if (e.deltaY > 0) {
        e.preventDefault();
        return false;
      }
    }
    Vue.watch(() => scaleClamped.value, (val) => {
      transform.value.scale = val;
    });
    Vue.watch(currentImg, () => {
      Vue.nextTick(() => {
        var _a;
        if (!((_a = imgRef.value) == null ? void 0 : _a.complete)) loading.value = true;
      });
    });
    Vue.watch(activeIndex, (val) => {
      reset();
      emit("switch", val);
    });
    Vue.onMounted(() => {
      visible.value = true;
      registerEventListener();
      stopWheelListener = index$6.useEventListener("wheel", wheelHandler, { passive: false });
    });
    __expose({ setActiveItem });
    return (_ctx, _cache) => {
      return Vue.openBlock(), Vue.createBlock(Vue.unref(index$7.ElTeleport), {
        to: "body",
        disabled: !__props.teleported
      }, {
        default: Vue.withCtx(() => [Vue.createVNode(Vue.Transition, {
          name: "viewer-fade",
          appear: ""
        }, {
          default: Vue.withCtx(() => [Vue.createElementVNode("div", {
            ref_key: "wrapper",
            ref: wrapper,
            tabindex: -1,
            class: Vue.normalizeClass(Vue.unref(ns).e("wrapper")),
            style: Vue.normalizeStyle({ zIndex: zIndex.value })
          }, [Vue.createVNode(Vue.unref(index$8.default), {
            loop: "",
            trapped: "",
            "focus-trap-el": wrapper.value,
            "focus-start-el": "container",
            onFocusoutPrevented,
            onReleaseRequested: onCloseRequested
          }, {
            default: Vue.withCtx(() => [
              Vue.createElementVNode("div", {
                class: Vue.normalizeClass(Vue.unref(ns).e("mask")),
                onClick: _cache[0] || (_cache[0] = Vue.withModifiers(($event) => __props.hideOnClickModal && hide(), ["self"]))
              }, null, 2),
              Vue.createCommentVNode(" CLOSE "),
              Vue.createElementVNode("span", {
                class: Vue.normalizeClass([Vue.unref(ns).e("btn"), Vue.unref(ns).e("close")]),
                onClick: hide
              }, [Vue.createVNode(Vue.unref(index$9.ElIcon), null, {
                default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.Close))]),
                _: 1
              })], 2),
              Vue.createCommentVNode(" ARROW "),
              !isSingle.value ? (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 0 }, [Vue.createElementVNode("span", {
                class: Vue.normalizeClass(arrowPrevKls.value),
                onClick: prev
              }, [Vue.createVNode(Vue.unref(index$9.ElIcon), null, {
                default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.ArrowLeft))]),
                _: 1
              })], 2), Vue.createElementVNode("span", {
                class: Vue.normalizeClass(arrowNextKls.value),
                onClick: next
              }, [Vue.createVNode(Vue.unref(index$9.ElIcon), null, {
                default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.ArrowRight))]),
                _: 1
              })], 2)], 64)) : Vue.createCommentVNode("v-if", true),
              _ctx.$slots.progress || __props.showProgress ? (Vue.openBlock(), Vue.createElementBlock("div", {
                key: 1,
                class: Vue.normalizeClass([Vue.unref(ns).e("btn"), Vue.unref(ns).e("progress")])
              }, [Vue.renderSlot(_ctx.$slots, "progress", {
                activeIndex: activeIndex.value,
                total: __props.urlList.length
              }, () => [Vue.createTextVNode(Vue.toDisplayString(progress.value), 1)])], 2)) : Vue.createCommentVNode("v-if", true),
              Vue.createCommentVNode(" ACTIONS "),
              Vue.createElementVNode("div", { class: Vue.normalizeClass([Vue.unref(ns).e("btn"), Vue.unref(ns).e("actions")]) }, [Vue.createElementVNode("div", { class: Vue.normalizeClass(Vue.unref(ns).e("actions__inner")) }, [Vue.renderSlot(_ctx.$slots, "toolbar", {
                actions: handleActions,
                prev,
                next,
                reset: toggleMode,
                activeIndex: activeIndex.value,
                setActiveItem
              }, () => [
                Vue.createVNode(Vue.unref(index$9.ElIcon), { onClick: _cache[1] || (_cache[1] = ($event) => handleActions("zoomOut")) }, {
                  default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.ZoomOut))]),
                  _: 1
                }),
                Vue.createVNode(Vue.unref(index$9.ElIcon), { onClick: _cache[2] || (_cache[2] = ($event) => handleActions("zoomIn")) }, {
                  default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.ZoomIn))]),
                  _: 1
                }),
                Vue.createElementVNode("i", { class: Vue.normalizeClass(Vue.unref(ns).e("actions__divider")) }, null, 2),
                Vue.createVNode(Vue.unref(index$9.ElIcon), { onClick: toggleMode }, {
                  default: Vue.withCtx(() => [(Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(mode.value.icon)))]),
                  _: 1
                }),
                Vue.createElementVNode("i", { class: Vue.normalizeClass(Vue.unref(ns).e("actions__divider")) }, null, 2),
                Vue.createVNode(Vue.unref(index$9.ElIcon), { onClick: _cache[3] || (_cache[3] = ($event) => handleActions("anticlockwise")) }, {
                  default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.RefreshLeft))]),
                  _: 1
                }),
                Vue.createVNode(Vue.unref(index$9.ElIcon), { onClick: _cache[4] || (_cache[4] = ($event) => handleActions("clockwise")) }, {
                  default: Vue.withCtx(() => [Vue.createVNode(Vue.unref(index.RefreshRight))]),
                  _: 1
                })
              ])], 2)], 2),
              Vue.createCommentVNode(" CANVAS "),
              Vue.createElementVNode("div", { class: Vue.normalizeClass(Vue.unref(ns).e("canvas")) }, [loadError.value && _ctx.$slots["viewer-error"] ? Vue.renderSlot(_ctx.$slots, "viewer-error", {
                key: 0,
                activeIndex: activeIndex.value,
                src: currentImg.value
              }) : (Vue.openBlock(), Vue.createElementBlock("img", {
                ref_key: "imgRef",
                ref: imgRef,
                key: currentImg.value,
                src: currentImg.value,
                style: Vue.normalizeStyle(imgStyle.value),
                class: Vue.normalizeClass(Vue.unref(ns).e("img")),
                crossorigin: __props.crossorigin,
                onLoad: handleImgLoad,
                onError: handleImgError,
                onMousedown: handleMouseDown,
                onTouchstart: handleTouchStart
              }, null, 46, _hoisted_1))], 2),
              Vue.renderSlot(_ctx.$slots, "default")
            ]),
            _: 3
          }, 8, ["focus-trap-el"])], 6)]),
          _: 3
        })]),
        _: 3
      }, 8, ["disabled"]);
    };
  }
});
exports.default = image_viewer_vue_vue_type_script_setup_true_lang_default;
