"use strict";

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

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

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

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

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

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

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

var _classnames = _interopRequireDefault(require("classnames"));

var _reactIntersectionObserver = _interopRequireDefault(require("react-intersection-observer"));

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

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

var _UnitConvertor = require("../../../lib/_util/UnitConvertor");

var _icon = _interopRequireDefault(require("../icon"));

var _objectFitPolyfill = _interopRequireWildcard(require("../_util/objectFitPolyfill"));

var _PictureContext = _interopRequireWildcard(require("./PictureContext"));

var _preview = _interopRequireDefault(require("../modal/preview"));

var _excluded = ["src", "downloadUrl", "previewUrl", "previewTarget", "lazy", "className", "width", "height", "prefixCls", "style", "sources", "alt", "title", "block", "preview", "modalProps", "objectFit", "objectPosition", "status", "border", "index", "onClick", "children", "onPreview"];

function Picture(props, ref) {
  var _classNames;

  var src = props.src,
      downloadUrl = props.downloadUrl,
      previewUrl = props.previewUrl,
      previewTarget = props.previewTarget,
      lazy = props.lazy,
      className = props.className,
      width = props.width,
      height = props.height,
      prefixCls = props.prefixCls,
      style = props.style,
      sources = props.sources,
      alt = props.alt,
      title = props.title,
      _props$block = props.block,
      block = _props$block === void 0 ? true : _props$block,
      _props$preview = props.preview,
      preview = _props$preview === void 0 ? true : _props$preview,
      modalProps = props.modalProps,
      _props$objectFit = props.objectFit,
      objectFit = _props$objectFit === void 0 ? 'fill' : _props$objectFit,
      _props$objectPosition = props.objectPosition,
      objectPosition = _props$objectPosition === void 0 ? 'center' : _props$objectPosition,
      propStatus = props.status,
      border = props.border,
      index = props.index,
      onClick = props.onClick,
      children = props.children,
      onPreview = props.onPreview,
      rest = (0, _objectWithoutProperties2["default"])(props, _excluded);
  var url = previewUrl || src;
  var pictureRef = (0, _react.useRef)({
    src: url,
    downloadUrl: downloadUrl
  });
  var context = (0, _react.useContext)(_PictureContext["default"]);

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

  var customPrefixCls = getProPrefixCls('picture', prefixCls);
  var imgRef = (0, _react.useRef)(null);

  var _useState = (0, _react.useState)(propStatus || 'empty'),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      status = _useState2[0],
      setStatus = _useState2[1];

  var _useState3 = (0, _react.useState)(!lazy || !!propStatus),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      inView = _useState4[0],
      setInView = _useState4[1];

  var handlePreview = (0, _react.useCallback)(function () {
    if (preview && !previewTarget && status === 'loaded' && url) {
      if (context && (0, _isNumber["default"])(index)) {
        context.preview(index, modalProps);
      } else {
        (0, _preview["default"])({
          list: [{
            src: url,
            downloadUrl: downloadUrl
          }]
        }, modalProps);
      }

      if (onPreview) {
        onPreview();
      }
    }
  }, [context, index, preview, previewTarget, status, url, downloadUrl, onPreview]);
  var handleClick = (0, _react.useCallback)(function (e) {
    handlePreview();

    if (onClick) {
      onClick(e);
    }
  }, [handlePreview, onClick]);
  var wrapperStyle = (0, _objectSpread2["default"])({}, style);
  var elementStyle = {
    objectFit: objectFit,
    objectPosition: objectPosition
  };

  if (typeof width !== 'undefined') {
    var w = (0, _UnitConvertor.pxToRem)(width) || 0;
    elementStyle.width = w;
    wrapperStyle.width = w;
  }

  if (typeof height !== 'undefined') {
    var h = (0, _UnitConvertor.pxToRem)(height) || 0;
    elementStyle.height = h;
    wrapperStyle.height = h;
  }

  (0, _react.useEffect)(function () {
    if (!propStatus && inView && src) {
      var _img = new Image(width, height);

      var onLoad = function onLoad() {
        setStatus('loaded');
      };

      var onError = function onError() {
        setStatus('error');
      };

      _img.addEventListener('load', onLoad, false);

      _img.addEventListener('error', onError, false);

      _img.src = src;
      return function () {
        _img.removeEventListener('load', onLoad, false);

        _img.removeEventListener('error', onError, false);
      };
    }
  }, [inView, src, propStatus]);
  (0, _react.useEffect)(function () {
    if (propStatus) {
      setStatus(propStatus);
    }
  }, [propStatus]);
  (0, _react.useEffect)(function () {
    var current = imgRef.current;

    if (current && !(0, _objectFitPolyfill.isObjectFitSupport)() && objectFit && objectPosition) {
      var onResize = function onResize() {
        return (0, _objectFitPolyfill["default"])(current, objectFit, objectPosition);
      };

      onResize();
      window.addEventListener('resize', onResize, false);
      return function () {
        return window.removeEventListener('resize', onResize, false);
      };
    }
  }, [imgRef, objectFit, objectPosition]);
  (0, _react.useEffect)(function () {
    if (preview && !previewTarget && context && (0, _isNumber["default"])(index) && url) {
      var current = pictureRef.current;
      current.src = url;
      context.registerPicture(index, current);
      return function () {
        return context.unRegisterPicture(index, current);
      };
    }
  }, [index, context, pictureRef, preview, previewTarget, url]);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      preview: handlePreview,
      getImage: function getImage() {
        return imgRef.current;
      }
    };
  }, [handlePreview, imgRef]);

  var renderSources = function renderSources() {
    if (sources) {
      return sources.map(function (source, i) {
        return /*#__PURE__*/_react["default"].createElement("source", (0, _extends2["default"])({
          key: String(i)
        }, source));
      });
    }
  };

  var renderImg = function renderImg() {
    if (children) {
      return children;
    }

    switch (status) {
      case 'loaded':
        {
          return /*#__PURE__*/_react["default"].createElement("img", (0, _extends2["default"])({
            ref: imgRef,
            style: elementStyle,
            className: "".concat(customPrefixCls, "-img"),
            src: src,
            alt: alt || title,
            title: title
          }, rest));
        }

      case 'error':
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(customPrefixCls, "-icon")
        }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "sentiment_dissatisfied"
        }));

      case 'empty':
      default:
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(customPrefixCls, "-icon")
        }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "photo_size_select_actual"
        }));
    }
  };

  var classString = (0, _classnames["default"])(customPrefixCls, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(customPrefixCls, "-border"), border), (0, _defineProperty2["default"])(_classNames, "".concat(customPrefixCls, "-block"), block), (0, _defineProperty2["default"])(_classNames, "".concat(customPrefixCls, "-preview"), preview && status === 'loaded'), _classNames), className);
  var isPictureSupport = typeof HTMLPictureElement !== 'undefined';
  var Cmp = isPictureSupport ? 'picture' : 'div';
  var img = renderImg();

  var picture = /*#__PURE__*/_react["default"].createElement(Cmp, {
    className: classString,
    style: wrapperStyle,
    onClick: handleClick
  }, isPictureSupport && renderSources(), preview && previewTarget ? /*#__PURE__*/_react["default"].createElement("a", {
    target: previewTarget,
    href: url
  }, img) : img);

  if (lazy && !propStatus && status !== 'loaded') {
    return /*#__PURE__*/_react["default"].createElement(_reactIntersectionObserver["default"], {
      onChange: setInView
    }, picture);
  }

  return picture;
}

var ForwardPicture = /*#__PURE__*/(0, _react.forwardRef)(Picture);
ForwardPicture.Provider = _PictureContext.PictureProvider;
ForwardPicture.Context = _PictureContext["default"];
ForwardPicture.displayName = 'Picture';
var _default = ForwardPicture;
exports["default"] = _default;
//# sourceMappingURL=Picture.js.map
