"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _configProvider = _interopRequireDefault(require("../config-provider"));

var _progress = _interopRequireDefault(require("../progress"));

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

var _button = _interopRequireDefault(require("../button"));

var _util = require("../util");

var _zhCn = _interopRequireDefault(require("../locale/zh-cn.js"));

var _util2 = require("./util");

var _transform = _interopRequireDefault(require("./transform"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var List =
/*#__PURE__*/
function (_Component) {
  _inherits(List, _Component);

  function List() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, List);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(List)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_this), "handleClose", function (file) {
      var _this$props = _this.props,
          onRemove = _this$props.onRemove,
          uploader = _this$props.uploader;
      var remove = onRemove(file);

      _util.func.promiseCall(remove, function () {
        uploader && uploader.removeFile(file);
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleCancel", function (file) {
      var _this$props2 = _this.props,
          onCancel = _this$props2.onCancel,
          uploader = _this$props2.uploader;
      var cancel = onCancel(file);

      _util.func.promiseCall(cancel, function () {
        uploader && uploader.abort(file);
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onImageError", function (file, obj) {
      obj.onerror = null;

      _this.props.onImageError(obj, file);
    });

    _defineProperty(_assertThisInitialized(_this), "onPreview", function (file, e) {
      _this.props.onPreview(file, e);
    });

    return _this;
  }

  _createClass(List, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this2 = this;

      var _this$props3 = this.props,
          listType = _this$props3.listType,
          useDataURL = _this$props3.useDataURL,
          value = _this$props3.value;

      if (listType !== 'image' && listType !== 'card') {
        return;
      }

      useDataURL && value.forEach(function (file) {
        if (typeof document === 'undefined' || typeof window === 'undefined' || !window.FileReader || !window.File || !(file.originFileObj instanceof File) || file.imgURL !== undefined) {
          return;
        }

        file.imgURL = '';
        (0, _util2.previewFile)(file.originFileObj, function (previewDataUrl) {
          file.imgURL = previewDataUrl;

          _this2.forceUpdate();
        });
      });
    }
  }, {
    key: "getInfo",
    value: function getInfo(file) {
      var _classNames;

      var prefixCls = "".concat(this.props.prefix, "upload");
      var downloadURL = file.downloadURL || file.url;
      var imgURL = file.imgURL || file.url;
      var size = this.sizeCaculator(file.size);
      var itemCls = (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-list-item"), true), _defineProperty(_classNames, "".concat(prefixCls, "-list-item-").concat(file.state), file.state), _defineProperty(_classNames, "".concat(prefixCls, "-list-item-error-with-msg"), file.state === 'error' && file.errorMsg), _classNames));
      var alt = file.name || file.alt;
      return {
        prefixCls: prefixCls,
        downloadURL: downloadURL,
        imgURL: imgURL,
        size: size,
        itemCls: itemCls,
        alt: alt
      };
    } // transfer size from number to xx K/ XxxM / xxG

  }, {
    key: "sizeCaculator",
    value: function sizeCaculator(size) {
      var fileSize = parseFloat(size, 10); // fileSize为浮点数 用 < 0.000001 替代 === 0

      if (isNaN(fileSize) || fileSize < 0.0000001) {
        return 0;
      }

      var SIZE_SUFFIX = ['B', 'K', 'M', 'G', 'T', 'P'];
      var suffixIndex = 0; // 在Mac上实验发现 取1024造成显示的大小和实际大小不一致
      // 因为单位制不同 见 https://superuser.com/questions/938234/size-of-files-in-windows-os-its-kb-or-kb

      var BIT_NUMBER_SYSTEM = 1024;

      while (fileSize >= BIT_NUMBER_SYSTEM && suffixIndex < SIZE_SUFFIX.length) {
        suffixIndex++;
        fileSize /= BIT_NUMBER_SYSTEM;
      }

      var suffix = SIZE_SUFFIX[suffixIndex];
      fileSize = fileSize.toFixed(2);
      return "".concat(fileSize).concat(suffix);
    }
  }, {
    key: "getTextList",
    value: function getTextList(file) {
      var _this3 = this;

      var _this$props4 = this.props,
          locale = _this$props4.locale,
          extraRender = _this$props4.extraRender,
          progressProps = _this$props4.progressProps,
          rtl = _this$props4.rtl;

      var _this$getInfo = this.getInfo(file),
          prefixCls = _this$getInfo.prefixCls,
          downloadURL = _this$getInfo.downloadURL,
          size = _this$getInfo.size,
          itemCls = _this$getInfo.itemCls;

      var onClick = function onClick() {
        return file.state === 'uploading' ? _this3.handleCancel(file) : _this3.handleClose(file);
      };

      var onKeyDown = function onKeyDown(e) {
        if (e.keyCode === _util.KEYCODE.ENTER) {
          onClick();
        }
      };

      return _react["default"].createElement("div", {
        className: itemCls,
        key: file.uid || file.name
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-name-wrap")
      }, _react["default"].createElement("a", {
        href: downloadURL,
        target: "_blank",
        rel: "noopener noreferrer",
        style: {
          pointerEvents: downloadURL ? '' : 'none'
        },
        className: "".concat(prefixCls, "-list-item-name")
      }, _react["default"].createElement("span", null, file.name), !!size && _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-list-item-size"),
        dir: rtl ? 'rtl' : undefined
      }, "(", size, ")"), _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-extra")
      }, extraRender(file)))), file.state === 'uploading' ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-progress")
      }, _react["default"].createElement(_progress["default"], _extends({
        size: "medium",
        percent: file.percent,
        textRender: _util.func.noop,
        rtl: rtl
      }, progressProps))) : null, file.state === 'error' && file.errorMsg ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-error-msg")
      }, file.errorMsg) : null, this.props.closable ? _react["default"].createElement(_button["default"].Icon, {
        type: "secondary",
        color: "gray",
        name: "remove",
        size: "medium",
        role: "button",
        "aria-label": locale.upload["delete"],
        tabIndex: "0",
        onClick: onClick,
        onKeyDown: onKeyDown
      }) : null);
    }
  }, {
    key: "getImageList",
    value: function getImageList(file) {
      var _this4 = this;

      var _this$props5 = this.props,
          extraRender = _this$props5.extraRender,
          progressProps = _this$props5.progressProps,
          rtl = _this$props5.rtl;

      var _this$getInfo2 = this.getInfo(file),
          prefixCls = _this$getInfo2.prefixCls,
          downloadURL = _this$getInfo2.downloadURL,
          imgURL = _this$getInfo2.imgURL,
          size = _this$getInfo2.size,
          itemCls = _this$getInfo2.itemCls,
          alt = _this$getInfo2.alt;

      var img = null;

      var onClick = function onClick() {
        return file.state === 'uploading' ? _this4.handleCancel(file) : _this4.handleClose(file);
      };

      var onKeyDown = function onKeyDown(e) {
        if (e.keyCode === _util.KEYCODE.ENTER) {
          onClick();
        }
      };

      if (file.state === 'uploading' || file.state === 'selected' && !imgURL) {
        img = _react["default"].createElement(_icon["default"], {
          type: "picture"
        });
      } else if (file.state === 'error') {
        img = _react["default"].createElement(_icon["default"], {
          type: "emoji-frown"
        });
      } else {
        img = _react["default"].createElement("img", {
          src: imgURL,
          onError: this.onImageError.bind(this, file),
          tabIndex: "0",
          alt: alt,
          onClick: this.onPreview.bind(this, file)
        });
      }

      return _react["default"].createElement("div", {
        className: itemCls,
        key: file.uid || file.name
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-thumbnail")
      }, img), this.props.closable ? _react["default"].createElement(_icon["default"], {
        type: "remove",
        size: "medium",
        tabIndex: "0",
        role: "button",
        onClick: onClick,
        onKeyDown: onKeyDown
      }) : null, _react["default"].createElement("a", {
        href: downloadURL,
        target: "_blank",
        rel: "noopener noreferrer",
        style: {
          pointerEvents: downloadURL ? '' : 'none'
        },
        className: "".concat(prefixCls, "-list-item-name")
      }, _react["default"].createElement("span", null, file.name), !!size && _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-list-item-size"),
        dir: rtl ? 'rtl' : undefined
      }, "(", size, ")"), _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-extra")
      }, extraRender(file))), file.state === 'uploading' ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-progress")
      }, _react["default"].createElement(_progress["default"], _extends({
        size: "medium",
        percent: file.percent,
        textRender: _util.func.noop
      }, progressProps))) : null, file.state === 'error' && file.errorMsg ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-error-msg")
      }, file.errorMsg) : null);
    }
  }, {
    key: "getPictureCardList",
    value: function getPictureCardList(file) {
      var _this5 = this;

      var _this$props6 = this.props,
          locale = _this$props6.locale,
          progressProps = _this$props6.progressProps;

      var _this$getInfo3 = this.getInfo(file),
          prefixCls = _this$getInfo3.prefixCls,
          downloadURL = _this$getInfo3.downloadURL,
          imgURL = _this$getInfo3.imgURL,
          itemCls = _this$getInfo3.itemCls,
          alt = _this$getInfo3.alt;

      var img = null;

      if (file.state === 'uploading' || file.state === 'selected' && !imgURL) {
        img = _react["default"].createElement("div", {
          className: "".concat(prefixCls, "-list-item-handler")
        }, _react["default"].createElement(_icon["default"], {
          type: "picture"
        }), _react["default"].createElement(_button["default"], {
          text: true,
          onClick: function onClick() {
            return _this5.handleCancel(file);
          }
        }, locale.card.cancel));
      } else if (file.state === 'error') {
        img = _react["default"].createElement("div", {
          className: "".concat(prefixCls, "-list-item-handler")
        }, _react["default"].createElement(_icon["default"], {
          type: "emoji-frown"
        }));
      } else {
        img = _react["default"].createElement("img", {
          src: imgURL,
          tabIndex: "0",
          alt: alt,
          onError: this.onImageError.bind(this, file),
          onClick: this.onPreview.bind(this, file)
        });
      }

      var onClose = function onClose() {
        return _this5.handleClose(file);
      };

      var onKeyDownClose = function onKeyDownClose(e) {
        if (e.keyCode === _util.KEYCODE.ENTER) {
          onClose();
        }
      }; // 下载功能受同源策略限制，改为预览图标


      return _react["default"].createElement("div", {
        className: itemCls,
        key: file.uid || file.name
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-wrapper")
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-thumbnail")
      }, img), file.state === 'uploading' ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-item-progress")
      }, _react["default"].createElement(_progress["default"], _extends({
        size: "medium",
        percent: file.percent,
        textRender: _util.func.noop
      }, progressProps))) : null, file.state !== 'uploading' ? _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-tool ").concat(!this.props.closable ? "".concat(prefixCls, "-noclose") : '')
      }, _react["default"].createElement("a", {
        href: downloadURL,
        target: "_blank",
        rel: "noopener noreferrer",
        tabIndex: downloadURL ? '0' : '-1',
        className: "".concat(prefixCls, "-tool-download-link"),
        style: {
          pointerEvents: downloadURL ? '' : 'none'
        }
      }, _react["default"].createElement(_icon["default"], {
        type: downloadURL ? 'eye' : '',
        "aria-label": locale.card.download,
        className: "".concat(prefixCls, "-tool-download-icon")
      })), this.props.closable ? _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-tool-close")
      }, _react["default"].createElement(_icon["default"], {
        type: "trashbin",
        "aria-label": locale.card["delete"],
        tabIndex: "0",
        role: "button",
        onClick: onClose,
        onKeyDown: onKeyDownClose
      })) : null) : ''), _react["default"].createElement("span", {
        className: "".concat(prefixCls, "-list-item-name")
      }, file.name));
    }
  }, {
    key: "render",
    value: function render() {
      var _this6 = this,
          _classNames2;

      var _this$props7 = this.props,
          listType = _this$props7.listType,
          children = _this$props7.children,
          prefix = _this$props7.prefix,
          rtl = _this$props7.rtl,
          className = _this$props7.className;
      var prefixCls = "".concat(prefix, "upload");
      var list = this.props.value.map(function (file) {
        if (listType === 'text') {
          return _this6.getTextList(file);
        } else if (listType === 'image') {
          return _this6.getImageList(file);
        } else if (listType === 'card') {
          return _this6.getPictureCardList(file);
        }

        return null;
      });

      if (rtl && listType === 'card' && Array.isArray(list)) {
        list = list.reverse();
      }

      var listclassNames = (0, _classnames["default"])((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefixCls, "-list"), true), _defineProperty(_classNames2, "".concat(prefixCls, "-list-").concat(this.props.listType), true), _classNames2), className);

      var others = _util.obj.pickAttrsWith(this.props, 'data-');

      return _react["default"].createElement("div", _extends({}, others, {
        className: listclassNames,
        dir: rtl ? 'rtl' : undefined
      }), rtl ? children : list, rtl ? list : children);
    }
  }]);

  return List;
}(_react.Component); // Wrap <List> with <ConfigProvider> to avoid context missing if it is
// referenced by other internal modules.
// https://github.com/alibaba-fusion/next/blob/build/1.13.9/src/upload/upload.jsx#L521


_defineProperty(List, "propTypes", {
  prefix: _propTypes["default"].string,

  /**
   * 多语言
   */
  locale: _propTypes["default"].object,

  /**
   * 文件列表，数据格式请参考 文件对象
   */
  listType: _propTypes["default"].oneOf(['text', 'image', 'card']),

  /**
   * 文件列表
   */
  value: _propTypes["default"].array,
  closable: _propTypes["default"].bool,

  /**
   * 删除文件回调(支持Promise)
   */
  onRemove: _propTypes["default"].func,

  /**
   * 取消上传回调(支持Promise)
   */
  onCancel: _propTypes["default"].func,

  /**
   * 头像加载出错回调
   */
  onImageError: _propTypes["default"].func,

  /**
   * listType=card时点击图片回调
   */
  onPreview: _propTypes["default"].func,

  /**
   * 自定义额外渲染
   */
  extraRender: _propTypes["default"].func,

  /**
   * 透传给Progress props
   */
  progressProps: _propTypes["default"].object,
  children: _propTypes["default"].node,
  uploader: _propTypes["default"].any,

  /**
   * 可选参数，是否本地预览
   */
  useDataURL: _propTypes["default"].bool,
  rtl: _propTypes["default"].bool
});

_defineProperty(List, "defaultProps", {
  prefix: 'next-',
  listType: 'text',
  value: [],
  locale: _zhCn["default"].Upload,
  closable: false,
  onRemove: _util.func.noop,
  onCancel: _util.func.noop,
  extraRender: _util.func.noop,
  onImageError: _util.func.noop,
  onPreview: _util.func.noop,
  progressProps: {}
});

var _default = _configProvider["default"].config(List, {
  componentName: 'Upload',
  transform: _transform["default"]
});

exports["default"] = _default;