import { Component, ReactElement } from 'react'; import { observer } from 'mobx-react'; import classnames from 'classnames'; import Dropzone from 'react-dropzone'; import { mdiDelete, mdiFileImage } from '@mdi/js'; import prettyBytes from 'pretty-bytes'; import Icon from '../icon'; import { isWindows } from '../../../environment'; interface IProps { field: any; textDelete: string; textUpload: string; textMaxFileSize: string; textMaxFileSizeError: string; className?: string; multiple?: boolean; maxSize?: number; maxFiles?: number; } interface IState { path: string | null; errorState: boolean; errorMessage: { message: string; }; } @observer class ImageUpload extends Component { constructor(props: IProps) { super(props); this.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.replaceAll('\\', '/') : 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, errorMessage: { message: this.props.textMaxFileSizeError, }, }); } } } } render(): ReactElement { const { field, textDelete, textUpload, textMaxFileSize, className = '', multiple = false, maxSize = Number.POSITIVE_INFINITY, maxFiles = 0, } = 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.state.errorMessage.message} )}
); } } export default ImageUpload;