"use strict";
const React = require("react");
const ReactDOM = require("react-dom");
const useMergeProps = require("../_util/hooks/useMergeProps.js");
const useMergeValue = require("../_util/hooks/useMergeValue.js");
const classNames = require("../_util/classNames.js");
const dom = require("../_util/dom.js");
const resizeObserver = require("../_util/resizeObserver.js");
const index$7 = require("../../icon/react-icon/IconLoading/index.js");
const index$5 = require("../../icon/react-icon/IconZoomOut/index.js");
const index$4 = require("../../icon/react-icon/IconZoomIn/index.js");
const index$1 = require("../../icon/react-icon/IconFullscreen/index.js");
const index$8 = require("../../icon/react-icon/IconClose/index.js");
const index$3 = require("../../icon/react-icon/IconRotateLeft/index.js");
const index$2 = require("../../icon/react-icon/IconRotateRight/index.js");
const index$6 = require("../../icon/react-icon/IconOriginalSize/index.js");
const index = require("../ConfigProvider/index.js");
const useImageStatus = require("./utils/hooks/useImageStatus.js");
const getScale = require("./utils/getScale.js");
const getFixTranslate = require("./utils/getFixTranslate.js");
const imagePreviewToolbar = require("./image-preview-toolbar.js");
const index$9 = require("../Portal/index.js");
const previewGroupContext = require("./previewGroupContext.js");
const imagePreviewArrow = require("./image-preview-arrow.js");
const useOverflowHidden = require("../_util/hooks/useOverflowHidden.js");
const keycode = require("../_util/keycode.js");
const useUpdate = require("../_util/hooks/useUpdate.js");
const is = require("../_util/is.js");
const emotionReactJsxRuntime_browser_esm = require("../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js");
const CSSTransition = require("../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/CSSTransition.js");
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var ROTATE_STEP = 90;
var defaultProps = {
  maskClosable: true,
  closable: true,
  breakPoint: 316,
  actionsLayout: ["fullScreen", "rotateRight", "rotateLeft", "zoomIn", "zoomOut", "originalSize", "extra"],
  getPopupContainer: function() {
    return document.body;
  },
  escToExit: true,
  scales: getScale.defaultScales
};
function Preview(baseProps, ref) {
  var _a, _b;
  var _c = React.useContext(previewGroupContext.PreviewGroupContext), previewGroup = _c.previewGroup, previewUrlMap = _c.previewUrlMap, currentIndex = _c.currentIndex, setCurrentIndex = _c.setCurrentIndex, infinite = _c.infinite, previewPropsMap = _c.previewPropsMap;
  var mergedPreviewProps = previewGroup ? previewPropsMap.get(currentIndex) : {};
  var mergedProps = useMergeProps(baseProps, defaultProps, mergedPreviewProps);
  var className = mergedProps.className, style = mergedProps.style, src = mergedProps.src, defaultVisible = mergedProps.defaultVisible, maskClosable = mergedProps.maskClosable, closable = mergedProps.closable, breakPoint = mergedProps.breakPoint, actions = mergedProps.actions, actionsLayout = mergedProps.actionsLayout, getPopupContainer = mergedProps.getPopupContainer, onVisibleChange = mergedProps.onVisibleChange, scales = mergedProps.scales, escToExit = mergedProps.escToExit, _d = mergedProps.imgAttributes, imgAttributes = _d === void 0 ? {} : _d;
  var mergedSrc = previewGroup ? previewUrlMap.get(currentIndex) : src;
  var _e = __read(React.useState(mergedSrc), 2), previewImgSrc = _e[0], setPreviewImgSrc = _e[1];
  var _f = __read(useMergeValue(false, {
    defaultValue: defaultVisible,
    value: mergedProps.visible
  }), 2), visible = _f[0], setVisible = _f[1];
  var globalContext = React.useContext(index.ConfigContext);
  var getPrefixCls = globalContext.getPrefixCls, locale = globalContext.locale, rtl = globalContext.rtl;
  var prefixCls = getPrefixCls("image");
  var previewPrefixCls = prefixCls + "-preview";
  var classNames$1 = classNames(previewPrefixCls, (_a = {}, _a[previewPrefixCls + "-hide"] = !visible, _a[previewPrefixCls + "-rtl"] = rtl, _a), className);
  var refImage = React.useRef();
  var refImageContainer = React.useRef();
  var refWrapper = React.useRef();
  var keyboardEventOn = React.useRef(false);
  var refMoveData = React.useRef({
    pageX: 0,
    pageY: 0,
    originX: 0,
    originY: 0
  });
  var _g = useImageStatus("loading"), isLoading = _g.isLoading, isLoaded = _g.isLoaded, setStatus = _g.setStatus;
  var _h = __read(React.useState(false), 2), toolbarSimple = _h[0], setToolbarSimple = _h[1];
  var _j = __read(React.useState({
    x: 0,
    y: 0
  }), 2), translate = _j[0], setTranslate = _j[1];
  var _k = __read(React.useState(1), 2), scale = _k[0], setScale = _k[1];
  var _l = __read(React.useState(false), 2), scaleValueVisible = _l[0], setScaleValueVisible = _l[1];
  var _m = __read(React.useState(0), 2), rotate = _m[0], setRotate = _m[1];
  var _o = __read(React.useState(false), 2), moving = _o[0], setMoving = _o[1];
  var previewScales = React.useMemo(function() {
    return new getScale.default(scales);
  }, []);
  var onLoad = imgAttributes.onLoad, onError = imgAttributes.onError, onMouseDown = imgAttributes.onMouseDown, imgStyle = imgAttributes.style, imgClassName = imgAttributes.className, restImgAttributes = __rest(imgAttributes, ["onLoad", "onError", "onMouseDown", "style", "className"]);
  function reset() {
    setTranslate({
      x: 0,
      y: 0
    });
    setScale(1);
    setRotate(0);
  }
  React.useImperativeHandle(ref, function() {
    return {
      reset
    };
  });
  var _p = __read(React.useState(), 2), container = _p[0], setContainer = _p[1];
  var getContainer = React.useCallback(function() {
    return container;
  }, [container]);
  React.useEffect(function() {
    var container2 = getPopupContainer && getPopupContainer();
    var containerDom = ReactDOM.findDOMNode(container2) || document.body;
    setContainer(containerDom);
  }, [getPopupContainer]);
  useOverflowHidden(getContainer, {
    hidden: visible
  });
  var isFixed = React.useMemo(function() {
    return !dom.isServerRendering && container === document.body;
  }, [container]);
  function jumpTo(index2) {
    var previewListLen = previewUrlMap.size;
    if (infinite) {
      index2 %= previewListLen;
      if (index2 < 0)
        index2 = previewListLen - Math.abs(index2);
    }
    if (index2 !== currentIndex && index2 >= 0 && index2 <= previewListLen - 1) {
      setCurrentIndex(index2);
    }
  }
  function onPrev() {
    jumpTo(currentIndex - 1);
  }
  function onNext() {
    jumpTo(currentIndex + 1);
  }
  function onRotateLeft() {
    setRotate(rotate === 0 ? 360 - ROTATE_STEP : rotate - ROTATE_STEP);
  }
  function onRotateRight() {
    setRotate((rotate + ROTATE_STEP) % 360);
  }
  var hideScaleTimer = React.useRef(null);
  var showScaleValue = function() {
    !scaleValueVisible && setScaleValueVisible(true);
    hideScaleTimer.current && clearTimeout(hideScaleTimer.current);
    hideScaleTimer.current = setTimeout(function() {
      setScaleValueVisible(false);
    }, 1e3);
  };
  var onScaleChange = function(newScale) {
    if (scale !== newScale) {
      setScale(newScale);
      showScaleValue();
    }
  };
  function onZoomIn() {
    var newScale = previewScales.getNextScale(scale, "zoomIn");
    onScaleChange(newScale);
  }
  function onZoomOut() {
    var newScale = previewScales.getNextScale(scale, "zoomOut");
    onScaleChange(newScale);
  }
  function onResetScale() {
    onScaleChange(1);
  }
  function onFullScreen() {
    var wrapperRect = refWrapper.current.getBoundingClientRect();
    var imgRect = refImage.current.getBoundingClientRect();
    var newHeightScale = wrapperRect.height / (imgRect.height / scale);
    var newWidthScale = wrapperRect.width / (imgRect.width / scale);
    var newScale = Math.max(newHeightScale, newWidthScale);
    onScaleChange(newScale);
  }
  function onOutsideImgClick(e) {
    if (e.target === e.currentTarget && maskClosable) {
      close();
    }
  }
  function onCloseClick() {
    close();
  }
  function close() {
    if (visible) {
      onVisibleChange && onVisibleChange(false, visible);
      is.isUndefined(mergedProps.visible) && setVisible(false);
    }
  }
  function onWrapperResize(entry) {
    if (entry && entry.length) {
      var wrapperRect = entry[0].contentRect;
      var nextSimple = wrapperRect.width < breakPoint;
      setToolbarSimple(nextSimple);
    }
  }
  var checkAndFixTranslate = function() {
    if (!refWrapper.current || !refImage.current)
      return;
    var wrapperRect = refWrapper.current.getBoundingClientRect();
    var imgRect = refImage.current.getBoundingClientRect();
    var _a2 = __read(getFixTranslate(wrapperRect, imgRect, translate.x, translate.y, scale), 2), x = _a2[0], y = _a2[1];
    if (x !== translate.x || y !== translate.y) {
      setTranslate({
        x,
        y
      });
    }
  };
  var onMoving = function(e) {
    if (visible && moving) {
      e.preventDefault && e.preventDefault();
      var _a2 = refMoveData.current, originX = _a2.originX, originY = _a2.originY, pageX = _a2.pageX, pageY = _a2.pageY;
      var nextX = originX + (e.pageX - pageX) / scale;
      var nextY = originY + (e.pageY - pageY) / scale;
      setTranslate({
        x: nextX,
        y: nextY
      });
    }
  };
  var onMoveEnd = function(e) {
    e.preventDefault && e.preventDefault();
    setMoving(false);
  };
  function onImgLoaded(e) {
    setStatus("loaded");
    onLoad && onLoad(e);
  }
  function onImgLoadError(e) {
    setStatus("error");
    onError && onError(e);
  }
  var onMoveStart = function(e) {
    e.preventDefault && e.preventDefault();
    setMoving(true);
    var ev = e.type === "touchstart" ? e.touches[0] : e;
    refMoveData.current.pageX = ev.pageX;
    refMoveData.current.pageY = ev.pageY;
    refMoveData.current.originX = translate.x;
    refMoveData.current.originY = translate.y;
    onMouseDown && onMouseDown(e);
  };
  React.useEffect(function() {
    if (visible && moving) {
      dom.on(document, "mousemove", onMoving, false);
      dom.on(document, "mouseup", onMoveEnd, false);
    }
    return function() {
      dom.off(document, "mousemove", onMoving, false);
      dom.off(document, "mouseup", onMoveEnd, false);
    };
  }, [visible, moving]);
  React.useEffect(function() {
    if (!moving) {
      checkAndFixTranslate();
    }
  }, [moving, translate]);
  React.useEffect(function() {
    checkAndFixTranslate();
  }, [scale]);
  React.useEffect(function() {
    if (visible) {
      reset();
    }
  }, [visible]);
  React.useEffect(function() {
    setPreviewImgSrc(mergedSrc);
    setStatus(mergedSrc ? "loading" : "loaded");
    reset();
  }, [mergedSrc]);
  useUpdate(function() {
    previewScales.updateScale(scales);
    setScale(1);
  }, [scales]);
  React.useEffect(function() {
    var onKeyDown = function(e) {
      if (escToExit && e && e.key === keycode.Esc.key) {
        close();
      }
    };
    if (visible && !moving && !keyboardEventOn.current) {
      keyboardEventOn.current = true;
      dom.on(document, "keydown", onKeyDown);
    }
    return function() {
      keyboardEventOn.current = false;
      dom.off(document, "keydown", onKeyDown);
    };
  }, [visible, escToExit, moving]);
  var defaultActions = [{
    key: "fullScreen",
    name: locale.ImagePreview.fullScreen,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$1, {}),
    onClick: onFullScreen
  }, {
    key: "rotateRight",
    name: locale.ImagePreview.rotateRight,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$2, {}),
    onClick: onRotateRight
  }, {
    key: "rotateLeft",
    name: locale.ImagePreview.rotateLeft,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$3, {}),
    onClick: onRotateLeft
  }, {
    key: "zoomIn",
    name: locale.ImagePreview.zoomIn,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$4, {}),
    onClick: onZoomIn,
    disabled: scale === previewScales.maxScale
  }, {
    key: "zoomOut",
    name: locale.ImagePreview.zoomOut,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$5, {}),
    onClick: onZoomOut,
    disabled: scale === previewScales.minScale
  }, {
    key: "originalSize",
    name: locale.ImagePreview.originalSize,
    content: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$6, {}),
    onClick: onResetScale
  }];
  return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$9, {
    visible,
    forceRender: false,
    getContainer,
    children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index.default, {
      ...__assign({}, globalContext, {
        getPopupContainer: function() {
          return refWrapper.current;
        }
      }),
      children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
        className: classNames$1,
        style: __assign(__assign({}, style || {}), isFixed ? {} : {
          zIndex: "inherit",
          position: "absolute"
        }),
        children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(CSSTransition, {
          in: visible,
          timeout: 400,
          appear: true,
          classNames: "fadeImage",
          mountOnEnter: true,
          unmountOnExit: false,
          onEnter: function(e) {
            e.parentNode.style.display = "block";
            e.style.display = "block";
          },
          onExited: function(e) {
            e.parentNode.style.display = "";
            e.style.display = "none";
          },
          children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
            className: previewPrefixCls + "-mask"
          })
        }), visible && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(resizeObserver, {
          onResize: onWrapperResize,
          children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
            ref: refWrapper,
            className: previewPrefixCls + "-wrapper",
            onClick: onOutsideImgClick,
            children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
              ref: refImageContainer,
              className: previewPrefixCls + "-img-container",
              style: {
                transform: "scale(" + scale + ", " + scale + ")"
              },
              onClick: onOutsideImgClick,
              children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("img", {
                ...__assign({
                  ref: refImage,
                  className: classNames(imgClassName, previewPrefixCls + "-img", (_b = {}, _b[previewPrefixCls + "-img-moving"] = moving, _b)),
                  style: __assign(__assign({}, imgStyle), {
                    transform: "translate(" + translate.x + "px, " + translate.y + "px) rotate(" + rotate + "deg)"
                  })
                }, restImgAttributes, {
                  onLoad: onImgLoaded,
                  onError: onImgLoadError,
                  onMouseDown: onMoveStart,
                  key: previewImgSrc,
                  src: previewImgSrc
                })
              }), isLoading && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
                className: previewPrefixCls + "-loading",
                children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$7, {})
              })]
            }), /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(CSSTransition, {
              in: scaleValueVisible,
              timeout: 400,
              appear: true,
              classNames: "fadeImage",
              unmountOnExit: true,
              children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs("div", {
                className: previewPrefixCls + "-scale-value",
                children: [(scale * 100).toFixed(0), "%"]
              })
            }), isLoaded && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(imagePreviewToolbar, {
              prefixCls,
              previewPrefixCls,
              actions,
              actionsLayout,
              defaultActions,
              simple: toolbarSimple
            }), closable && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
              className: previewPrefixCls + "-close-btn",
              onClick: onCloseClick,
              children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(index$8, {})
            }), previewGroup && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(imagePreviewArrow, {
              previewCount: previewUrlMap.size,
              current: currentIndex,
              infinite,
              onPrev,
              onNext
            })]
          })
        })]
      })
    })
  });
}
var PreviewComponent = React.forwardRef(Preview);
PreviewComponent.displayName = "ImagePreview";
const ImagePreview = PreviewComponent;
module.exports = ImagePreview;
//# sourceMappingURL=image-preview.js.map
