import { Component } from 'react'; import { observer } from 'mobx-react'; import { Field } from 'mobx-react-form'; import classnames from 'classnames'; import Dropzone from 'react-dropzone'; import { mdiDelete, mdiFileImage } from '@mdi/js'; import prettyBytes from 'pretty-bytes'; import { isWindows } from '../../environment'; import Icon from './icon'; type Props = { field: typeof Field; className: string; multiple: boolean; textDelete: string; textUpload: string; textMaxFileSize: string; textMaxFileSizeError: string; maxSize?: number; maxFiles?: number; messages: any; }; // Should this file be converted into the coding style similar to './toggle/index.tsx'? class ImageUpload extends Component { static defaultProps = { multiple: false, maxSize: Number.POSITIVE_INFINITY, maxFiles: 0, }; state = { path: null, errorState: false, }; errorMessage = { message: '', }; onDropAccepted(acceptedFiles) { const { field } = this.props; this.setState({ errorState: false }); for (const file of acceptedFiles) { const imgPath = isWindows ? file.path.replace(/\\/g, '/') : file.path; this.setState({ path: imgPath, }); this.props.field.onDrop(file); } field.set(''); } onDropRejected(rejectedFiles): void { for (const file of rejectedFiles) { for (const error of file.errors) { if (error.code === 'file-too-large') { this.setState({ errorState: true }); this.setState( (this.errorMessage = { message: this.props.textMaxFileSizeError, }), ); } } } } render() { const { field, className, multiple, textDelete, textUpload, textMaxFileSize, maxSize, maxFiles, } = this.props; const cssClasses = classnames({ 'image-upload__dropzone': true, [`${className}`]: className, }); const maxSizeParse: number = maxSize === undefined || maxSize === Number.POSITIVE_INFINITY ? 0 : maxSize; return (
{(field.value && field.value !== 'delete') || this.state.path ? ( <>
) : ( {({ getRootProps, getInputProps }) => (

{textUpload}

)}
)}
{maxSizeParse !== 0 && ( {textMaxFileSize}{' '} {prettyBytes(maxSizeParse, { maximumFractionDigits: 1 })} )} {this.state.errorState && ( {this.errorMessage.message} )}
); } } export default observer(ImageUpload);