"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _react = _interopRequireWildcard(require("react"));

var _throttle = _interopRequireDefault(require("lodash/throttle"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _ConfigContext = _interopRequireDefault(require("../../../lib/config-provider/ConfigContext"));

var _enum = require("../../../lib/_util/enum");

var _Button = _interopRequireDefault(require("../button/Button"));

var _enum2 = require("../button/enum");

var _Picture = _interopRequireDefault(require("./Picture"));

var _transform = _interopRequireWildcard(require("../_util/transform"));

var _EventManager = _interopRequireDefault(require("../_util/EventManager"));

var _DocumentUtils = require("../_util/DocumentUtils");

var _Toolbar = _interopRequireDefault(require("./Toolbar"));

var _Navbar = _interopRequireDefault(require("./Navbar"));

var scaleSteps = [0.05, 0.06, 0.07, 0.09, 0.11, 0.14, 0.17, 0.21, 0.26, 0.32, 0.39, 0.47, 0.5, 0.57, 0.69, 0.83, 0.92, 1, 1.2, 1.72, 2, 2.4, 2.88, 3.45, 4.14, 4.96, 5.95, 7.14, 8.56, 10];

function getPreviewItem(item) {
  if ((0, _isString["default"])(item)) {
    return {
      src: item
    };
  }

  return item;
}

var PictureViewer = function PictureViewer(props) {
  var list = props.list,
      _props$defaultIndex = props.defaultIndex,
      defaultIndex = _props$defaultIndex === void 0 ? 0 : _props$defaultIndex,
      prefixCls = props.prefixCls,
      modal = props.modal;

  var _useContext = (0, _react.useContext)(_ConfigContext["default"]),
      getProPrefixCls = _useContext.getProPrefixCls;

  var pictureRef = (0, _react.useRef)(null);
  var transformTargetRef = (0, _react.useRef)(null);

  var _useState = (0, _react.useState)(defaultIndex),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      index = _useState2[0],
      setIndex = _useState2[1];

  var _useState3 = (0, _react.useState)(0),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      rotate = _useState4[0],
      setRotate = _useState4[1];

  var _useState5 = (0, _react.useState)([0, 0]),
      _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
      translate = _useState6[0],
      setTranslate = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
      scale = _useState8[0],
      setScale = _useState8[1];

  var _useState9 = (0, _react.useState)(false),
      _useState10 = (0, _slicedToArray2["default"])(_useState9, 2),
      isZoomMode = _useState10[0],
      setIsZoomMode = _useState10[1];

  var handleIndexChange = (0, _react.useCallback)(function (newIndex) {
    if (isZoomMode) setIsZoomMode(false);

    if (newIndex < 0 || newIndex >= list.length) {
      return;
    }

    setIndex(newIndex);
    setTranslate([0, 0]);
    setRotate(0);
    setScale(undefined);
  }, [isZoomMode]);
  var getImageNaturalScale = (0, _react.useCallback)(function () {
    var current = pictureRef.current;

    if (current) {
      var image = current.getImage();

      if (image) {
        var clientWidth = image.clientWidth,
            clientHeight = image.clientHeight,
            naturalHeight = image.naturalHeight,
            naturalWidth = image.naturalWidth;
        var imageScale = Math.min(clientWidth / naturalWidth, clientHeight / naturalHeight);
        return scaleSteps.findIndex(function (step, index, steps) {
          var nextStep = steps[index + 1];
          return step === imageScale || imageScale < step && index === 0 || step < imageScale && nextStep > imageScale || nextStep < imageScale && index === steps.length - 1;
        });
      }
    }

    return scaleSteps.indexOf(1);
  }, [pictureRef]);
  var getCurrentScale = (0, _react.useCallback)(function () {
    if (scale !== undefined) {
      return scale;
    }

    return getImageNaturalScale();
  }, [getImageNaturalScale, scale]);
  var customizedPrefixCls = getProPrefixCls('picture-viewer', prefixCls);
  var handlePrev = (0, _react.useCallback)(function () {
    return handleIndexChange(index - 1);
  }, [index, isZoomMode]);
  var handleNext = (0, _react.useCallback)(function () {
    return handleIndexChange(index + 1);
  }, [index, isZoomMode]);
  var handleClose = (0, _react.useCallback)(function () {
    return modal && modal.close();
  }, []);
  var handleRotateLeft = (0, _react.useCallback)(function () {
    return setRotate((rotate - 90) % 360);
  }, [rotate]);
  var handleRotateRight = (0, _react.useCallback)(function () {
    return setRotate((rotate + 90) % 360);
  }, [rotate]);
  var handleZoomIn = (0, _react.useCallback)(function () {
    if (!isZoomMode) setIsZoomMode(true);
    var currentScale = getCurrentScale();

    if (currentScale < scaleSteps.length - 1) {
      setScale(getCurrentScale() + 1);
    }
  }, [getCurrentScale]);
  var handleZoomOut = (0, _react.useCallback)(function () {
    if (!isZoomMode) setIsZoomMode(true);
    var currentScale = getCurrentScale();

    if (currentScale > 0) {
      setScale(currentScale - 1);
    }
  }, [getCurrentScale]);
  var throttleWheel = (0, _react.useMemo)(function () {
    return (0, _throttle["default"])(function (callback) {
      return callback();
    }, 60);
  }, []);
  var handleWheel = (0, _react.useCallback)(function (e) {
    if (e.deltaX > 0 || e.deltaY > 0) {
      throttleWheel(isZoomMode ? handleZoomOut : handleNext);
    } else {
      throttleWheel(isZoomMode ? handleZoomIn : handlePrev);
    }
  }, [handlePrev, handleNext, handleIndexChange, handleZoomOut, handleZoomIn, isZoomMode]);
  var translateEvent = (0, _react.useMemo)(function () {
    return new _EventManager["default"]();
  }, []);
  var executeTransform = (0, _react.useCallback)(function (target, r, s, t) {
    var transformValue = (0, _transform.toTransformValue)({
      translate: "".concat(t[0], "px,").concat(t[1], "px"),
      rotate: r ? "".concat(r, "deg") : undefined,
      scale: s !== undefined && s > -1 ? scaleSteps[s] / scaleSteps[getImageNaturalScale()] : undefined
    });
    (0, _transform["default"])(transformValue, target.style);
  }, []);
  var handleMouseDown = (0, _react.useCallback)(function (e) {
    var current = transformTargetRef.current;

    if (current) {
      var currentTarget = e.currentTarget;
      var pageX = (0, _DocumentUtils.transformZoomData)(e.pageX);
      var pageY = (0, _DocumentUtils.transformZoomData)(e.pageY);
      currentTarget.style.cursor = 'grabbing';

      var _translate = (0, _slicedToArray2["default"])(translate, 2),
          currentX = _translate[0],
          currentY = _translate[1];

      var startX = currentX - pageX;
      var startY = currentY - pageY;

      var handleMouseMove = function handleMouseMove(me) {
        currentX = startX + (0, _DocumentUtils.transformZoomData)(me.pageX);
        currentY = startY + (0, _DocumentUtils.transformZoomData)(me.pageY);
        executeTransform(current, rotate, scale, [currentX, currentY]);
      };

      var handleMouseUp = function handleMouseUp() {
        currentTarget.style.cursor = '';
        setTranslate([currentX, currentY]);
        translateEvent.removeEventListener('mousemove', handleMouseMove).removeEventListener('mouseup', handleMouseUp);
      };

      translateEvent.setTarget(document).addEventListener('mousemove', handleMouseMove).addEventListener('mouseup', handleMouseUp);
    }
  }, [translate, rotate, scale]);
  (0, _react.useEffect)(function () {
    var current = transformTargetRef.current;

    if (current) {
      executeTransform(current, rotate, scale, translate);
    }
  }, [scale, rotate, translate]);
  (0, _react.useEffect)(function () {
    return function () {
      translateEvent.clear();
    };
  }, []);
  var length = list.length;

  if (length) {
    var _getPreviewItem = getPreviewItem(list[index]),
        src = _getPreviewItem.src,
        downloadUrl = _getPreviewItem.downloadUrl;

    return /*#__PURE__*/_react["default"].createElement("div", {
      className: customizedPrefixCls,
      onWheel: handleWheel
    }, length > 1 && /*#__PURE__*/_react["default"].createElement(_Button["default"], {
      icon: "navigate_before",
      disabled: index === 0,
      funcType: _enum2.FuncType.link,
      onClick: handlePrev,
      className: "".concat(customizedPrefixCls, "-btn ").concat(customizedPrefixCls, "-btn-nav"),
      size: _enum.Size.large
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(customizedPrefixCls, "-picture"),
      onMouseDown: handleMouseDown
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(customizedPrefixCls, "-picture-main"),
      ref: transformTargetRef
    }, /*#__PURE__*/_react["default"].createElement(_Picture["default"], {
      src: src,
      ref: pictureRef,
      objectFit: "scale-down",
      status: "loaded",
      preview: false,
      lazy: false,
      draggable: false
    })), /*#__PURE__*/_react["default"].createElement(_Toolbar["default"], {
      prefixCls: customizedPrefixCls,
      zoomInDisabled: scale === scaleSteps.length - 1,
      zoomOutDisabled: scale === 0,
      onZoomIn: handleZoomIn,
      onZoomOut: handleZoomOut,
      onRotateLeft: handleRotateLeft,
      onRotateRight: handleRotateRight,
      downloadUrl: downloadUrl
    }), length > 1 && /*#__PURE__*/_react["default"].createElement(_Navbar["default"], {
      prefixCls: customizedPrefixCls,
      value: index,
      onChange: handleIndexChange,
      list: list
    })), length > 1 && /*#__PURE__*/_react["default"].createElement(_Button["default"], {
      icon: "navigate_next",
      disabled: index === length - 1,
      funcType: _enum2.FuncType.link,
      onClick: handleNext,
      className: "".concat(customizedPrefixCls, "-btn ").concat(customizedPrefixCls, "-btn-nav"),
      size: _enum.Size.large
    }), /*#__PURE__*/_react["default"].createElement(_Button["default"], {
      icon: "close",
      funcType: _enum2.FuncType.link,
      onClick: handleClose,
      className: "".concat(customizedPrefixCls, "-btn ").concat(customizedPrefixCls, "-btn-close")
    }));
  }

  return null;
};

PictureViewer.displayName = 'PictureViewer';
var _default = PictureViewer;
exports["default"] = _default;
//# sourceMappingURL=PictureViewer.js.map
