Repository URL to install this package:
|
Version:
8.0.0 ▾
|
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; 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); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactImageFileResizer = _interopRequireDefault(require("react-image-file-resizer"));
var _Button = _interopRequireDefault(require("../../Button/Button"));
var _ButtonLabel = _interopRequireDefault(require("../../Button/ButtonLabel"));
var _LoadingButton = _interopRequireDefault(require("../../Button/LoadingButton"));
var _InputFeedback = _interopRequireDefault(require("../../Input/InputFeedback"));
var _Modal = _interopRequireDefault(require("../../../structure/Modal"));
var _ImageCropper = _interopRequireDefault(require("./ImageCropper"));
var _imageHelper = require("./imageHelper");
var _config = require("./config");
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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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 _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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
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 ImageUpload = /*#__PURE__*/function (_Component) {
_inherits(ImageUpload, _Component);
var _super = _createSuper(ImageUpload);
function ImageUpload(props) {
var _this;
_classCallCheck(this, ImageUpload);
_this = _super.call(this, props);
_this.state = {
imageSrc: '',
fileType: ''
};
_this.handleImageUploadButtonClick = _this.handleImageUploadButtonClick.bind(_assertThisInitialized(_this));
_this.handleChange = _this.handleChange.bind(_assertThisInitialized(_this));
_this.setInputRef = _this.setInputRef.bind(_assertThisInitialized(_this));
_this.handleSaveCroppedImage = _this.handleSaveCroppedImage.bind(_assertThisInitialized(_this));
_this.compressFile = _this.compressFile.bind(_assertThisInitialized(_this));
_this.handleCancelUploadFile = _this.handleCancelUploadFile.bind(_assertThisInitialized(_this));
_this.handleChangeFile = _this.handleChangeFile.bind(_assertThisInitialized(_this));
_this.resetState = _this.resetState.bind(_assertThisInitialized(_this));
_this.handleCropper = _this.handleCropper.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(ImageUpload, [{
key: "setInputRef",
value: function setInputRef(node) {
this.inputFile = node;
}
/**
* Validates file size does not exceed limit in kilobytes
* Call onChange with file if no imageType prop has been provided, else handle the image cropper
*/
}, {
key: "handleChange",
value: function handleChange(event) {
var files = event.target.files;
var imageType = this.props.imageType;
if (files && files.length > 0) {
var file = files[0];
var isBelowFileSize = (0, _imageHelper.validateFileSizeLimit)(file.size, 1000);
if (isBelowFileSize) {
if (!imageType) this.props.onChange(file);
this.handleCropper(file);
} else {
this.props.onError({
errorKey: _config.errorKeys.fileSizeError
});
}
if (this.inputFile) {
this.inputFile.value = '';
}
}
}
/**
* Reads the file to obtain the image source required for the ImageCropper
* imageSrc state triggers the modal with cropper
* @param {File} file - the image file
*/
}, {
key: "handleCropper",
value: function () {
var _handleCropper = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(file) {
var _yield$readImageFile, imageSrc;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return (0, _imageHelper.readImageFile)(file);
case 3:
_yield$readImageFile = _context.sent;
imageSrc = _yield$readImageFile.imageSrc;
this.setState({
imageSrc: imageSrc,
fileType: file.type
});
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
this.props.onError({
errorKey: _config.errorKeys.readImageError
});
case 11:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 8]]);
}));
function handleCropper(_x) {
return _handleCropper.apply(this, arguments);
}
return handleCropper;
}()
/**
* Returns a new blob of the cropped image from getCroppedImg helper.
* A second file size check is performed as in some edge cases the produced cropped image can have a slightly higher size than the original
* (typically this only happens if the file is near 1MB already and the zoom range is below 1)
* If the image is too large (dimensions and size) use react-image-resizer to resize and compress the image
* @param {object} croppedAreaPixels - used in the helper to draw the cropped image on a new canvas
*/
}, {
key: "handleSaveCroppedImage",
value: function () {
var _handleSaveCroppedImage = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(croppedAreaPixels) {
var _this$state, imageSrc, fileType, imageType, croppedImg, isBelowDimensionsLimit, isBelowFileSize;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_this$state = this.state, imageSrc = _this$state.imageSrc, fileType = _this$state.fileType;
imageType = this.props.imageType;
_context2.next = 5;
return (0, _imageHelper.getCroppedImg)(imageSrc, croppedAreaPixels, fileType);
case 5:
croppedImg = _context2.sent;
isBelowDimensionsLimit = (0, _imageHelper.validateImageDimensions)(croppedImg, imageType);
isBelowFileSize = (0, _imageHelper.validateFileSizeLimit)(croppedImg.size, 1000);
if (isBelowDimensionsLimit && isBelowFileSize) {
this.handleChangeFile(croppedImg);
} else {
this.compressFile(croppedImg);
}
_context2.next = 14;
break;
case 11:
_context2.prev = 11;
_context2.t0 = _context2["catch"](0);
this.props.onError({
errorKey: _config.errorKeys.cropImageError
});
case 14:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[0, 11]]);
}));
function handleSaveCroppedImage(_x2) {
return _handleSaveCroppedImage.apply(this, arguments);
}
return handleSaveCroppedImage;
}()
/**
* Calls react-image-resizer to resize and compress the image
* handleChangeFile callback is called with the new image URI as params
* @param {File} file - the new cropped image blob returned
*/
}, {
key: "compressFile",
value: function compressFile(file) {
var _this2 = this;
var imageType = this.props.imageType;
var fileType = this.state.fileType;
var _maxImageDimensions$i = _config.maxImageDimensions[imageType],
maxWidth = _maxImageDimensions$i.maxWidth,
maxHeight = _maxImageDimensions$i.maxHeight;
_reactImageFileResizer["default"].imageFileResizer(file, // e.g event.target.files[0]
maxWidth, // is the maxWidth of the new image
maxHeight, // is the maxHeight of the new image
fileType.match(/[^/]+$/g), // is the compressFormat of the new image
70, // is the quality of the new image - A number between 0 and 100. Used for the JPEG compression.(if no compress is needed, just set it to 100)
0,
/*#__PURE__*/
// is the rotatoion of the new image
function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(uri) {
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", _this2.handleChangeFile(uri));
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x3) {
return _ref.apply(this, arguments);
};
}(), // is the callBack function of the new image URI
'blob' // is the output type of the new image
);
}
}, {
key: "resetState",
value: function resetState() {
this.setState({
imageSrc: '',
fileType: ''
});
}
}, {
key: "handleImageUploadButtonClick",
value: function handleImageUploadButtonClick() {
this.inputFile.click();
}
}, {
key: "handleCancelUploadFile",
value: function handleCancelUploadFile() {
this.resetState();
}
}, {
key: "handleChangeFile",
value: function handleChangeFile(file) {
this.resetState();
this.props.onChange(file);
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
buttonLabel = _this$props.buttonLabel,
name = _this$props.name,
isLoading = _this$props.isLoading,
imageType = _this$props.imageType,
note = _this$props.note,
buttonCancelText = _this$props.buttonCancelText,
buttonApplyText = _this$props.buttonApplyText;
var imageSrc = this.state.imageSrc;
return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
show: Boolean(imageSrc),
title: "Modal for image cropping tool",
variant: "ink"
}, /*#__PURE__*/_react["default"].createElement(_ImageCropper["default"], {
imageSrc: imageSrc,
type: imageType,
onSaveCroppedImage: this.handleSaveCroppedImage,
onCancelCroppedImage: this.handleCancelUploadFile,
buttonCancelText: buttonCancelText,
buttonApplyText: buttonApplyText,
aspect: _config.aspectRatio[imageType]
})), /*#__PURE__*/_react["default"].createElement("div", {
className: "ImageUpload"
}, /*#__PURE__*/_react["default"].createElement("input", {
className: "ImageUpload-input",
name: name,
type: "file",
accept: "image/jpeg,image/png,image/gif",
onChange: this.handleChange,
ref: this.setInputRef
}), /*#__PURE__*/_react["default"].createElement(_Button["default"], {
variant: "whiteWithBorder",
dimension: "compact",
className: "ImageUpload-uploadButton",
type: "button",
onClick: this.handleImageUploadButtonClick,
disabled: isLoading,
inputButtonClass: isLoading ? 'loading' : null
}, /*#__PURE__*/_react["default"].createElement(_LoadingButton["default"], null), /*#__PURE__*/_react["default"].createElement(_ButtonLabel["default"], null, buttonLabel)), note && /*#__PURE__*/_react["default"].createElement("div", {
className: "ImageUpload-note Input--dark"
}, /*#__PURE__*/_react["default"].createElement(_InputFeedback["default"], null, note))));
}
}]);
return ImageUpload;
}(_react.Component);
_defineProperty(ImageUpload, "propTypes", {
buttonLabel: _propTypes["default"].string.isRequired,
name: _propTypes["default"].string.isRequired,
onChange: _propTypes["default"].func,
isLoading: _propTypes["default"].bool.isRequired,
imageType: _propTypes["default"].string,
note: _propTypes["default"].string,
buttonCancelText: _propTypes["default"].string.isRequired,
buttonApplyText: _propTypes["default"].string.isRequired,
onError: _propTypes["default"].func
});
_defineProperty(ImageUpload, "defaultProps", {
onChange: function onChange() {},
note: '',
imageType: '',
onError: function onError() {}
});
var _default = ImageUpload;
exports["default"] = _default;