react-smartui-fileupload
Version:
React fileupload component for smartui project
606 lines (540 loc) • 21 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
var _class, _temp2;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDropzone = require('react-dropzone');
var _reactDropzone2 = _interopRequireDefault(_reactDropzone);
require('../css/style.css');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var initialFile = function initialFile(props) {
return props.fileName && props.fileName !== '' ? { name: props.fileName } : {};
};
var mapExtensionToMimeType = function mapExtensionToMimeType(extension) {
var map = {
a: 'application/octet-stream',
ai: 'application/postscript',
aif: 'audio/x-aiff',
aifc: 'audio/x-aiff',
aiff: 'audio/x-aiff',
au: 'audio/basic',
avi: 'video/x-msvideo',
bat: 'text/plain',
bin: 'application/octet-stream',
bmp: 'image/x-ms-bmp',
c: 'text/plain',
cdf: 'application/x-cdf',
csh: 'application/x-csh',
css: 'text/css',
dll: 'application/octet-stream',
doc: 'application/msword',
dot: 'application/msword',
dvi: 'application/x-dvi',
eml: 'message/rfc822',
eps: 'application/postscript',
etx: 'text/x-setext',
exe: 'application/octet-stream',
gif: 'image/gif',
gtar: 'application/x-gtar',
h: 'text/plain',
hdf: 'application/x-hdf',
htm: 'text/html',
html: 'text/html',
jpe: 'image/jpeg',
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
js: 'application/x-javascript',
ksh: 'text/plain',
latex: 'application/x-latex',
m1v: 'video/mpeg',
man: 'application/x-troff-man',
me: 'application/x-troff-me',
mht: 'message/rfc822',
mhtml: 'message/rfc822',
mif: 'application/x-mif',
mov: 'video/quicktime',
movie: 'video/x-sgi-movie',
mp2: 'audio/mpeg',
mp3: 'audio/mpeg',
mp4: 'video/mp4',
mpa: 'video/mpeg',
mpe: 'video/mpeg',
mpeg: 'video/mpeg',
mpg: 'video/mpeg',
ms: 'application/x-troff-ms',
nc: 'application/x-netcdf',
nws: 'message/rfc822',
o: 'application/octet-stream',
obj: 'application/octet-stream',
oda: 'application/oda',
pbm: 'image/x-portable-bitmap',
pdf: 'application/pdf',
pfx: 'application/x-pkcs12',
pgm: 'image/x-portable-graymap',
png: 'image/png',
pnm: 'image/x-portable-anymap',
pot: 'application/vnd.ms-powerpoint',
ppa: 'application/vnd.ms-powerpoint',
ppm: 'image/x-portable-pixmap',
pps: 'application/vnd.ms-powerpoint',
ppt: 'application/vnd.ms-powerpoint',
pptx: 'application/vnd.ms-powerpoint',
ps: 'application/postscript',
pwz: 'application/vnd.ms-powerpoint',
py: 'text/x-python',
pyc: 'application/x-python-code',
pyo: 'application/x-python-code',
qt: 'video/quicktime',
ra: 'audio/x-pn-realaudio',
ram: 'application/x-pn-realaudio',
ras: 'image/x-cmu-raster',
rdf: 'application/xml',
rgb: 'image/x-rgb',
roff: 'application/x-troff',
rtx: 'text/richtext',
sgm: 'text/x-sgml',
sgml: 'text/x-sgml',
sh: 'application/x-sh',
shar: 'application/x-shar',
snd: 'audio/basic',
so: 'application/octet-stream',
src: 'application/x-wais-source',
swf: 'application/x-shockwave-flash',
t: 'application/x-troff',
tar: 'application/x-tar',
tcl: 'application/x-tcl',
tex: 'application/x-tex',
texi: 'application/x-texinfo',
texinfo: 'application/x-texinfo',
tif: 'image/tiff',
tiff: 'image/tiff',
tr: 'application/x-troff',
tsv: 'text/tab-separated-values',
txt: 'text/plain',
ustar: 'application/x-ustar',
vcf: 'text/x-vcard',
wav: 'audio/x-wav',
wiz: 'application/msword',
wsdl: 'application/xml',
xbm: 'image/x-xbitmap',
xlb: 'application/vnd.ms-excel',
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.ms-excel',
xml: 'text/xml',
xpdl: 'application/xml',
xpm: 'image/x-xpixmap',
xsl: 'application/xml',
xwd: 'image/x-xwindowdump',
zip: 'application/zip'
};
return map[extension] || '';
};
var FileUploadInput = (_temp2 = _class = function (_PureComponent) {
_inherits(FileUploadInput, _PureComponent);
function FileUploadInput() {
var _ref,
_this2 = this;
var _temp, _this, _ret;
_classCallCheck(this, FileUploadInput);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = FileUploadInput.__proto__ || Object.getPrototypeOf(FileUploadInput)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
file: initialFile(_this.props),
errorMessage: '',
isUploading: false,
isDeleting: false
}, _this.calculateFileSizeLabel = function (maxFileSize) {
var fileSize = Math.floor(maxFileSize / 1000000);
var fileSizeLabel = '';
if (fileSize <= 0) fileSizeLabel = 1;else fileSizeLabel = fileSize;
return fileSizeLabel + ' MB';
}, _this.validateDropFile = function (file) {
if (!file) return false;
var _this$props = _this.props,
maxFileSize = _this$props.maxFileSize,
accept = _this$props.accept;
var type = file.type,
size = file.size;
console.log(size, maxFileSize, !size, size > maxFileSize);
if (!size || size > maxFileSize) return 'Error: \u0E02\u0E19\u0E32\u0E14\u0E40\u0E01\u0E34\u0E19 ' + _this.calculateFileSizeLabel(maxFileSize);
var mimeTypes = _this.getMimeTypes(accept);
console.log('mimeTypes', type, mimeTypes);
if (mimeTypes.indexOf(type) < 0) return 'Error: \u0E44\u0E21\u0E48\u0E23\u0E2D\u0E07\u0E23\u0E31\u0E1A\u0E44\u0E1F\u0E25\u0E4C\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17 ' + type;
return '';
}, _this.onDrop = function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(files) {
var _this$props2, name, async, onDrop, onUpload, file, validateDropFile, response;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_this$props2 = _this.props, name = _this$props2.name, async = _this$props2.async, onDrop = _this$props2.onDrop, onUpload = _this$props2.onUpload;
file = files[0];
console.log(file);
validateDropFile = _this.validateDropFile(file);
if (!(validateDropFile === false)) {
_context.next = 6;
break;
}
return _context.abrupt('return');
case 6:
if (!(validateDropFile !== '')) {
_context.next = 9;
break;
}
_this.setState({
errorMessage: validateDropFile
});
return _context.abrupt('return');
case 9:
if (!async) {
_context.next = 24;
break;
}
_this.setState({
isUploading: true,
errorMessage: ''
});
_context.prev = 11;
_context.next = 14;
return onUpload(name, file);
case 14:
response = _context.sent;
if (response) {
_this.setState({
file: file,
isUploading: false
});
}
_context.next = 22;
break;
case 18:
_context.prev = 18;
_context.t0 = _context['catch'](11);
console.error(_context.t0.message);
_this.setState(_extends({}, _this.state, {
file: {},
errorMessage: _context.t0.message,
isUploading: false
}));
case 22:
_context.next = 26;
break;
case 24:
onDrop(name, file);
_this.setState({
file: file
});
case 26:
case 'end':
return _context.stop();
}
}
}, _callee, _this2, [[11, 18]]);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}(), _this.onUpload = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
var _this$props3, name, onUpload, response;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_this$props3 = _this.props, name = _this$props3.name, onUpload = _this$props3.onUpload;
_this.setState({
isUploading: true
});
_context2.prev = 2;
_context2.next = 5;
return onUpload(name, _this.state.file);
case 5:
response = _context2.sent;
if (response) {
_this.setState({
isUploading: false
});
}
_context2.next = 12;
break;
case 9:
_context2.prev = 9;
_context2.t0 = _context2['catch'](2);
_this.setState({
file: {},
errorMessage: _context2.t0.message,
isUploading: false
});
case 12:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this2, [[2, 9]]);
})), _this.onDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
var _this$props4, name, onDelete, response;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_this$props4 = _this.props, name = _this$props4.name, onDelete = _this$props4.onDelete;
_this.setState({
isDeleting: true
});
_context3.prev = 2;
_context3.next = 5;
return onDelete(name, _this.state.file);
case 5:
response = _context3.sent;
if (response) {
_this.setState({
file: {},
isDeleting: false
});
}
_context3.next = 12;
break;
case 9:
_context3.prev = 9;
_context3.t0 = _context3['catch'](2);
_this.setState({
file: {},
errorMessage: _context3.t0.message,
isDeleting: false
});
case 12:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this2, [[2, 9]]);
})), _this.hasFile = function () {
var file = _this.state.file;
return file && file.name && file.name !== '';
}, _this.isLoading = function () {
var _this$state = _this.state,
isUploading = _this$state.isUploading,
isDeleting = _this$state.isDeleting;
return isUploading || isDeleting;
}, _this.disableChooseButton = function () {
return _this.hasFile() || _this.isLoading();
}, _this.disableUploadButton = function () {
var isLoading = _this.state.isLoading;
return !_this.hasFile() || isLoading;
}, _this.disableDeleteButton = function () {
var isLoading = _this.state.isLoading;
return !_this.hasFile() || isLoading;
}, _this.getMimeTypes = function (extensions) {
var extensionArray = extensions.split(',');
var mimeTypes = extensionArray.map(function (mimeType) {
return mapExtensionToMimeType(mimeType);
});
return mimeTypes.join(',');
}, _this.getMimeTypesLabel = function (extensions) {
var extensionArray = extensions.split(',');
var extensionLabelArray = extensionArray.map(function (extension) {
return '.' + extension;
});
return extensionLabelArray.join(', ');
}, _this.renderSmall = function () {
var _this$props5 = _this.props,
accept = _this$props5.accept,
maxFileSize = _this$props5.maxFileSize;
var message = '(';
var acceptMessage = '';
var maxFileSizeMessage = '';
if (accept && accept !== '' && accept !== '*') {
acceptMessage = _this.getMimeTypesLabel(accept);
message = '' + message + acceptMessage;
}
if (maxFileSize && maxFileSize > 0) {
maxFileSizeMessage = '\u0E02\u0E19\u0E32\u0E14\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19 ' + _this.calculateFileSizeLabel(maxFileSize);
if (accept && accept !== '' && accept !== '*') {
message = message + ' \u0E41\u0E25\u0E30 ' + maxFileSizeMessage;
} else {
message = '' + message + maxFileSizeMessage;
}
}
return message + ')';
}, _this.renderMessage = function () {
var _this$state2 = _this.state,
file = _this$state2.file,
errorMessage = _this$state2.errorMessage;
var message = _react2.default.createElement(
'span',
null,
_react2.default.createElement('i', { className: 'fa fa-times-circle fileupload-input-icon' }),
' ',
'\u0E01\u0E23\u0E38\u0E13\u0E32\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E1F\u0E25\u0E4C',
_react2.default.createElement(
'small',
null,
_this.renderSmall()
)
);
if (_this.hasFile()) {
var filename = file.name;
// message = `${filename.substring(0, 25)}${filename.length > 25
// ? '...'
// : ''}`
message = filename;
}
if (errorMessage !== '') {
message = _react2.default.createElement(
'span',
{ className: 'error' },
_react2.default.createElement('i', { className: 'fa fa-times-circle fileupload-input-icon' }),
errorMessage
);
}
return message;
}, _this.render = function () {
var _this$state3 = _this.state,
isUploading = _this$state3.isUploading,
isDeleting = _this$state3.isDeleting;
var _this$props6 = _this.props,
label = _this$props6.label,
required = _this$props6.required,
async = _this$props6.async,
accept = _this$props6.accept;
var hasFile = _this.hasFile();
var isLoading = _this.isLoading();
var hasAccept = accept && accept !== '';
var mimeTypes = _this.getMimeTypes(accept);
console.log('hasAccept', mimeTypes, accept, hasAccept);
return _react2.default.createElement(
'div',
{ className: 'fileupload-input' },
label && label !== '' && _react2.default.createElement(
'div',
{ className: 'fileupload-input-label' },
label,
required && _react2.default.createElement(
'span',
null,
'*'
)
),
_react2.default.createElement(
'div',
{ className: 'fileupload-input-body' },
_react2.default.createElement(
'div',
{ className: 'dropzone' },
_react2.default.createElement(
_reactDropzone2.default,
{
multiple: false,
disabled: hasFile,
accept: hasAccept ? mimeTypes : false,
onDrop: function onDrop(files) {
return _this.onDrop(files);
}
},
_react2.default.createElement(
'div',
{ className: 'dropzone-body ' + (isLoading && 'disable') },
_react2.default.createElement(
'span',
{ className: 'bold' },
'File :'
),
_this.renderMessage(),
isLoading && _react2.default.createElement(
'div',
{ className: 'fileupload-input-loading-pane' },
_react2.default.createElement('div', { className: 'fileupload-input-loading' }),
' ',
isUploading && 'Uploading',
isDeleting && 'Deleting',
'...'
)
),
_react2.default.createElement(
'div',
{ className: 'fileupload-input-button-group' },
_react2.default.createElement(FileUploadInputButton, {
disable: _this.disableChooseButton(),
icon: 'file-o',
label: '\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E1F\u0E25\u0E4C'
})
)
)
),
_react2.default.createElement(
'div',
{ className: 'fileupload-input-button-group' },
!async && _react2.default.createElement(FileUploadInputButton, {
disable: _this.disableUploadButton(),
icon: 'cloud-upload',
label: '\u0E2D\u0E31\u0E1E\u0E42\u0E2B\u0E25\u0E14\u0E44\u0E1F\u0E25\u0E4C',
onClick: _this.onUpload
}),
_react2.default.createElement(FileUploadInputButton, {
disable: _this.disableDeleteButton(),
icon: 'trash-o',
label: '\u0E25\u0E1A\u0E44\u0E1F\u0E25\u0E4C',
onClick: _this.onDelete
})
)
)
);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
return FileUploadInput;
}(_react.PureComponent), _class.propTypes = {
name: _propTypes2.default.string.isRequired,
label: _propTypes2.default.string,
required: _propTypes2.default.bool,
async: _propTypes2.default.bool,
accept: _propTypes2.default.string,
maxFileSize: _propTypes2.default.number,
onDrop: _propTypes2.default.func,
onUpload: _propTypes2.default.func.isRequired,
onDelete: _propTypes2.default.func.isRequired
}, _class.defaultProps = {
name: Date.now(),
label: '',
async: true,
accept: '',
maxFileSize: undefined,
onDrop: function onDrop() {
return 'if you want to get file send prop = onDrop(name, file)';
}
}, _temp2);
exports.default = FileUploadInput;
function FileUploadInputButton(_ref5) {
var disable = _ref5.disable,
icon = _ref5.icon,
label = _ref5.label,
_ref5$onClick = _ref5.onClick,
_onClick = _ref5$onClick === undefined ? function () {
return null;
} : _ref5$onClick;
return _react2.default.createElement(
'button',
{
onClick: function onClick() {
return _onClick();
},
disabled: disable,
className: 'fileupload-input-button ' + (disable && 'disable')
},
_react2.default.createElement('i', { className: 'fa fa-' + icon + ' fileupload-input-icon' }),
_react2.default.createElement(
'span',
null,
label
)
);
}