-
Notifications
You must be signed in to change notification settings - Fork 30
/
Upload.js
292 lines (270 loc) · 7.56 KB
/
Upload.js
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import React, { useRef, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import UploadCore from '@availity/upload-core';
import { avFilesDeliveryApi } from '@availity/api-axios';
import { Input, InputGroup } from 'reactstrap';
import { FormGroup, Feedback } from '@availity/form';
import Dropzone from 'react-dropzone';
import Icon from '@availity/icon';
import { useField, useFormikContext } from 'formik';
import classNames from 'classnames';
import uuid from 'uuid/v4';
import FilePickerBtn from './FilePickerBtn';
import FileList from './FileList';
import './styles.scss';
const Upload = ({
allowedFileNameCharacters,
allowedFileTypes,
btnText,
bucketId,
children,
className,
clientId,
customerId,
deliverFileOnSubmit = false,
deliveryChannel,
disabled = false,
feedbackClass,
fileDeliveryMetadata,
getDropRejectionMessage,
max,
maxSize,
multiple = true,
name,
onFileRemove,
onFileUpload,
showFileDrop = false,
}) => {
const input = useRef(null);
const [field, metadata] = useField(name);
const {
errors,
isSubmitting,
isValidating,
setFieldError,
setFieldValue,
} = useFormikContext();
const classes = classNames(
className,
metadata.touched ? 'is-touched' : 'is-untouched',
metadata.touched && metadata.error && 'is-invalid'
);
const fieldValue = Array.isArray(field.value) ? field.value : [];
const callFileDelivery = useCallback(
async (upload) => {
if (!Array.isArray(upload)) upload = [upload];
const uploadResults = [];
try {
for (const u of upload) {
const data = {
deliveries: [
{
deliveryChannel,
fileURI: u.references[0],
metadata:
typeof fileDeliveryMetadata === 'function'
? fileDeliveryMetadata(u)
: fileDeliveryMetadata,
},
],
};
uploadResults.push(
avFilesDeliveryApi.uploadFilesDelivery(data, {
clientId,
customerId,
})
);
}
await Promise.all(uploadResults);
} catch {
setFieldError(name, 'An error occurred while uploading files.');
}
},
[
clientId,
customerId,
deliveryChannel,
fileDeliveryMetadata,
name,
setFieldError,
]
);
useEffect(() => {
// eslint-disable-next-line unicorn/consistent-function-scoping
async function checkValidFormAndCallFileDelivery() {
if (Object.keys(errors).length === 0) {
await callFileDelivery(fieldValue);
}
}
if (
!onFileUpload &&
isSubmitting === true &&
isValidating === false &&
deliverFileOnSubmit &&
deliveryChannel &&
fileDeliveryMetadata
) {
checkValidFormAndCallFileDelivery();
}
}, [
callFileDelivery,
deliverFileOnSubmit,
deliveryChannel,
errors,
fieldValue,
fileDeliveryMetadata,
isSubmitting,
isValidating,
onFileUpload,
]);
const removeFile = (fileId) => {
const newFiles = fieldValue.filter((file) => file.id !== fileId);
if (newFiles.length !== fieldValue.length) {
setFieldValue(name, newFiles, true);
if (onFileRemove) onFileRemove(newFiles, fileId);
}
};
const setFiles = (files) => {
let selectedFiles = [];
for (let i = 0; i < files.length; i++) {
selectedFiles[i] = files[i];
}
if (max && selectedFiles.length + fieldValue.length > max) {
selectedFiles = selectedFiles.slice(
0,
Math.max(0, max - fieldValue.length)
);
}
const newFiles = fieldValue.concat(
selectedFiles.map((file) => {
const upload = new UploadCore(file, {
bucketId,
customerId,
clientId,
fileTypes: allowedFileTypes,
maxSize,
allowedFileNameCharacters,
});
upload.id = `${upload.id}-${uuid()}`;
if (file.dropRejectionMessage) {
upload.errorMessage = file.dropRejectionMessage;
} else {
upload.start();
}
if (onFileUpload) {
onFileUpload(upload);
} else if (
!deliverFileOnSubmit &&
deliveryChannel &&
fileDeliveryMetadata
) {
upload.onSuccess.push(() => {
callFileDelivery(upload);
});
}
return upload;
})
);
setFieldValue(name, newFiles, true);
};
const handleFileInputChange = (event) => {
setFiles(event.target.files);
};
const onDrop = (acceptedFiles, fileRejections) => {
const rejectedFilesToDrop = fileRejections.map(({ file, errors }) => {
const dropRejectionMessage = getDropRejectionMessage
? getDropRejectionMessage(errors, file)
: errors.map((error) => error.message).join(', ');
file.dropRejectionMessage = dropRejectionMessage;
return file;
});
setFiles([...acceptedFiles, ...rejectedFilesToDrop]);
};
let fileAddArea;
const text = btnText || (
<>
<Icon name="plus-circle" title="Add File Icon" />
{fieldValue.length === 0 ? 'Add File' : 'Add Another File Attachment'}
</>
);
if (!max || fieldValue.length < max) {
fileAddArea = showFileDrop ? (
<FormGroup for={name}>
<Input name={name} style={{ display: 'none' }} />
<InputGroup disabled={disabled} className={classes}>
<Dropzone
onDrop={onDrop}
multiple={multiple}
maxSize={maxSize}
accept={allowedFileTypes}
>
{({ getRootProps, getInputProps, isDragActive }) => (
<section>
<div
{...getRootProps({
className: isDragActive ? 'file-drop-active' : 'file-drop',
})}
>
<input data-testid="file-picker" {...getInputProps()} />
<p>
<strong>Drag and Drop</strong>
</p>
{text}
</div>
</section>
)}
</Dropzone>
</InputGroup>
<Feedback
className={classNames('d-block', feedbackClass)}
name={name}
/>
</FormGroup>
) : (
<FilePickerBtn
data-testid="file-picker"
onChange={handleFileInputChange}
color={fieldValue.length === 0 ? 'light' : 'link'}
multiple={multiple}
allowedFileTypes={allowedFileTypes}
maxSize={maxSize}
name={name}
disabled={disabled}
>
{text}
</FilePickerBtn>
);
}
return (
<>
<FileList files={fieldValue} onRemoveFile={removeFile}>
{children}
</FileList>
{fileAddArea}
</>
);
};
Upload.propTypes = {
allowedFileNameCharacters: PropTypes.string,
allowedFileTypes: PropTypes.arrayOf(PropTypes.string),
btnText: PropTypes.node,
bucketId: PropTypes.string.isRequired,
children: PropTypes.func,
className: PropTypes.string,
clientId: PropTypes.string.isRequired,
customerId: PropTypes.string.isRequired,
deliverFileOnSubmit: PropTypes.bool,
deliveryChannel: PropTypes.string,
disabled: PropTypes.bool,
feedbackClass: PropTypes.string,
fileDeliveryMetadata: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
getDropRejectionMessage: PropTypes.func,
max: PropTypes.number,
maxSize: PropTypes.number,
multiple: PropTypes.bool,
name: PropTypes.string.isRequired,
onFileRemove: PropTypes.func,
onFileUpload: PropTypes.func,
showFileDrop: PropTypes.bool,
};
export default Upload;