aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/imageUpload/index.tsx
blob: 3b164ed411d972e28170057deec13ce9ec889d72 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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<IProps, IState> {
  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 (
      <div className="image-upload-wrapper">
        <label className="franz-form__label" htmlFor="iconUpload">
          {field.label}
        </label>
        <div className="image-upload">
          {(field.value && field.value !== 'delete') || this.state.path ? (
            <>
              <div
                className="image-upload__preview"
                style={{
                  backgroundImage: `url("${this.state.path || field.value}")`,
                }}
              />
              <div className="image-upload__action">
                <button
                  type="button"
                  onClick={() => {
                    if (field.value) {
                      field.set('delete');
                    } else {
                      this.setState({
                        path: null,
                      });
                    }
                  }}
                >
                  <Icon icon={mdiDelete} />
                  <p>{textDelete}</p>
                </button>
                <div className="image-upload__action-background" />
              </div>
            </>
          ) : (
            <Dropzone
              onDropAccepted={this.onDropAccepted.bind(this)}
              onDropRejected={this.onDropRejected.bind(this)}
              multiple={multiple}
              accept={{
                'image/jpeg': ['.jpeg', '.jpg'],
                'image/png': ['.png'],
                'image/svg+xml': ['.svg'],
              }}
              minSize={0}
              maxSize={maxSize}
              maxFiles={maxFiles}
            >
              {({ getRootProps, getInputProps }) => (
                <div {...getRootProps()} className={cssClasses}>
                  <Icon icon={mdiFileImage} />
                  <p>{textUpload}</p>
                  <input {...getInputProps()} />
                </div>
              )}
            </Dropzone>
          )}
        </div>
        {maxSizeParse !== 0 && (
          <span className="image-upload-wrapper__file-size">
            {textMaxFileSize}{' '}
            {prettyBytes(maxSizeParse, { maximumFractionDigits: 1 })}
          </span>
        )}
        {this.state.errorState && (
          <span className="image-upload-wrapper__file-size-error">
            {this.state.errorMessage.message}
          </span>
        )}
      </div>
    );
  }
}

export default ImageUpload;