-
Notifications
You must be signed in to change notification settings - Fork 14
/
FileInput.tsx
427 lines (393 loc) · 14.3 KB
/
FileInput.tsx
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// @ts-nocheck
import React, { useState, useEffect } from "react";
import styled, { ThemeProvider } from "styled-components";
import { v4 as uuidv4 } from "uuid";
import { spaces } from "../common/variables.js";
import useTheme from "../useTheme";
import useTranslatedLabels from "../useTranslatedLabels";
import DxcButton from "../button/Button";
import FileItem from "./FileItem";
import FileInputPropsType from "./types";
const audioIcon = (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path fill="none" d="M0 0h24v24H0V0z" />
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z" />
</svg>
);
const videoIcon = (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z" />
<path d="M0 0h24v24H0z" fill="none" />
</svg>
);
const fileIcon = (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path fill="none" d="M0 0h24v24H0V0z" />
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6z" />
</svg>
);
const DxcFileInput = ({
name = "",
mode = "file",
label = "",
buttonLabel,
dropAreaLabel,
helperText = "",
accept,
minSize,
maxSize,
showPreview = false,
multiple = true,
disabled = false,
callbackFile,
value,
margin,
tabIndex = 0,
}: FileInputPropsType): JSX.Element => {
const [isDragging, setIsDragging] = useState(false);
const [files, setFiles] = useState([]);
const [fileInputId] = useState(`file-input-${uuidv4()}`);
const colorsTheme = useTheme();
const translatedLabels = useTranslatedLabels();
useEffect(() => {
const getFiles = async () => {
if (value) {
const valueFiles = await Promise.all(
value.map(async (file) => {
if (file.preview) {
return file;
} else {
const preview = await getFilePreview(file.file);
return { ...file, preview };
}
})
);
setFiles(valueFiles);
}
};
getFiles();
}, [value]);
const handleClick = () => {
document.getElementById(fileInputId).click();
};
const checkFileSize = (file) => {
if (file.size < minSize) {
return translatedLabels.fileInput.fileSizeGreaterThanErrorMessage;
}
if (file.size > maxSize) {
return translatedLabels.fileInput.fileSizeLessThanErrorMessage;
}
};
const getFilePreview = (file) => {
if (file.type.includes("video")) {
return videoIcon;
}
if (file.type.includes("audio")) {
return audioIcon;
}
if (file.type.includes("image")) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
resolve(e.target.result);
};
});
}
return fileIcon;
};
const getFilesToAdd = async (selectedFiles) => {
const filesToAdd = await Promise.all(selectedFiles.map((selectedFile) => getFilePreview(selectedFile))).then(
(previews) => {
return selectedFiles.map((selectedFile, index) => {
const fileInfo = { file: selectedFile, error: checkFileSize(selectedFile), preview: previews[index] };
return fileInfo;
});
}
);
return filesToAdd;
};
const addFile = async (selectedFiles) => {
if (multiple) {
const filesToAdd = await getFilesToAdd(selectedFiles);
const finalFiles = [...files, ...filesToAdd];
if (typeof callbackFile === "function") {
callbackFile(finalFiles);
}
} else {
const fileToAdd =
selectedFiles.length === 1 ? await getFilesToAdd(selectedFiles) : await getFilesToAdd([selectedFiles[0]]);
if (typeof callbackFile === "function") {
callbackFile(fileToAdd);
}
}
};
const selectFiles = (e) => {
const selectedFiles = e.target.files;
const filesArray = Object.keys(selectedFiles).map((key) => selectedFiles[key]);
addFile(filesArray);
};
const onDelete = (fileName) => {
const filesCopy = [...files];
const fileToRemove = filesCopy.find((file) => {
return file.file.name === fileName;
});
const fileIndex = filesCopy.indexOf(fileToRemove);
filesCopy.splice(fileIndex, 1);
if (typeof callbackFile === "function") {
callbackFile(filesCopy);
}
};
const handleDrag = (e) => {
e.preventDefault();
e.stopPropagation();
};
const handleDragIn = (e) => {
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) setIsDragging(true);
};
const handleDragOut = (e) => {
// only if dragged items leave container (outside, not to childs)
if (!e.currentTarget.contains(e.relatedTarget)) setIsDragging(false);
};
const handleDrop = (e) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const filesObject = e.dataTransfer.files;
if (filesObject && filesObject.length > 0) {
const filesArray = Object.keys(filesObject).map((key) => filesObject[key]);
addFile(filesArray);
}
};
return (
<ThemeProvider theme={colorsTheme.fileInput}>
<FileInputContainer margin={margin} name={name}>
<Label htmlFor={fileInputId} disabled={disabled}>
{label}
</Label>
<HelperText disabled={disabled}>{helperText}</HelperText>
{mode === "file" ? (
<FileContainer multiple={multiple} files={files}>
<ValueInput
id={fileInputId}
type="file"
accept={accept}
multiple={multiple}
onChange={selectFiles}
name={name}
disabled={disabled}
readOnly
aria-hidden="true"
/>
<DxcButton
mode="secondary"
label={
buttonLabel ??
(multiple
? translatedLabels.fileInput.multipleButtonLabelDefault
: translatedLabels.fileInput.singleButtonLabelDefault)
}
onClick={handleClick}
disabled={disabled}
size="medium"
tabIndex={tabIndex}
/>
{files.map((file) => {
return (
<>
<FileItemContainer mode={mode} multiple={multiple} files={files}>
<FileItem
mode={mode}
multiple={multiple}
name={file.file.name}
error={file.error}
showPreview={mode === "file" && !multiple ? false : showPreview}
numFiles={files.length}
preview={file.preview}
type={file.file.type}
onDelete={onDelete}
tabIndex={tabIndex}
/>
</FileItemContainer>
</>
);
})}
</FileContainer>
) : (
<Container>
<ValueInput
id={fileInputId}
type="file"
accept={accept}
multiple={multiple}
onChange={selectFiles}
name={name}
disabled={disabled}
readOnly
aria-hidden="true"
/>
<DragDropArea
isDragging={isDragging}
disabled={disabled}
mode={mode}
onDrop={handleDrop}
onDragEnter={handleDragIn}
onDragOver={handleDrag}
onDragLeave={handleDragOut}
>
<ButtonContainer mode={mode}>
<DxcButton
mode="secondary"
label={buttonLabel ?? translatedLabels.fileInput.dropAreaButtonLabelDefault}
onClick={handleClick}
disabled={disabled}
size="fitContent"
/>
</ButtonContainer>
{mode === "dropzone" ? (
<DropzoneLabel disabled={disabled}>
{dropAreaLabel ??
(multiple
? translatedLabels.fileInput.multipleDropAreaLabelDefault
: translatedLabels.fileInput.singleDropAreaLabelDefault)}
</DropzoneLabel>
) : (
<FiledropLabel disabled={disabled}>
{dropAreaLabel ??
(multiple
? translatedLabels.fileInput.multipleDropAreaLabelDefault
: translatedLabels.fileInput.singleDropAreaLabelDefault)}
</FiledropLabel>
)}
</DragDropArea>
{files.map((file) => {
return (
<FileItemContainer mode={mode} multiple={multiple} files={files}>
<FileItem
mode={mode}
multiple={multiple}
name={file.file.name}
error={file.error}
showPreview={showPreview}
numFiles={files.length}
preview={file.preview}
type={file.file.type}
onDelete={onDelete}
tabIndex={tabIndex}
/>
</FileItemContainer>
);
})}
</Container>
)}
{files.length === 1 &&
files.map((file) => {
return file.error && mode === "file" && !multiple && <ErrorMessage>{file.error}</ErrorMessage>;
})}
</FileInputContainer>
</ThemeProvider>
);
};
const FileInputContainer = styled.div`
display: flex;
flex-direction: column;
margin: ${(props) => (props.margin && typeof props.margin !== "object" ? spaces[props.margin] : "0px")};
margin-top: ${(props) =>
props.margin && typeof props.margin === "object" && props.margin.top ? spaces[props.margin.top] : ""};
margin-right: ${(props) =>
props.margin && typeof props.margin === "object" && props.margin.right ? spaces[props.margin.right] : ""};
margin-bottom: ${(props) =>
props.margin && typeof props.margin === "object" && props.margin.bottom ? spaces[props.margin.bottom] : ""};
margin-left: ${(props) =>
props.margin && typeof props.margin === "object" && props.margin.left ? spaces[props.margin.left] : ""};
width: fit-content;
`;
const Label = styled.label`
color: ${(props) => (props.disabled ? props.theme.disabledLabelFontColor : props.theme.labelFontColor)};
font-family: ${(props) => props.theme.labelFontFamily};
font-size: ${(props) => props.theme.labelFontSize};
font-weight: ${(props) => props.theme.labelFontWeight};
line-height: ${(props) => props.theme.labelLineHeight};
`;
const HelperText = styled.span`
color: ${(props) => (props.disabled ? props.theme.disabledHelperTextFontcolor : props.theme.helperTextFontColor)};
font-family: ${(props) => props.theme.helperTextFontFamily};
font-size: ${(props) => props.theme.helperTextFontSize};
font-weight: ${(props) => props.theme.helperTextFontWeight};
line-height: ${(props) => props.theme.helperTextLineHeight};
`;
const DragDropArea = styled.div`
display: flex;
overflow: hidden;
box-sizing: border-box;
flex-direction: ${(props) => (props.mode === "filedrop" ? "row" : "column")};
${(props) => props.mode === "dropzone" && "justify-content: center; padding: 1rem;"};
align-items: center;
height: ${(props) => (props.mode === "filedrop" ? "48px" : "160px")};
width: 320px;
box-shadow: 0 0 0 2px transparent;
border-radius: ${(props) => props.theme.dropBorderRadius};
border-width: ${(props) => props.theme.dropBorderThickness};
border-style: ${(props) => props.theme.dropBorderStyle};
border-color: ${(props) => (props.disabled ? props.theme.disabledDropBorderColor : props.theme.dropBorderColor)};
${(props) =>
props.isDragging &&
`
background-color: ${props.theme.dragoverDropBackgroundColor};
border-color: transparent;
box-shadow: 0 0 0 2px ${props.theme.focusDropBorderColor};
`}
cursor: ${(props) => props.disabled && "not-allowed"};
`;
const FileContainer = styled.div`
display: flex;
flex-direction: ${(props) => (props.multiple || props.files.length > 1 ? "column" : "row")};
margin-top: 0.25rem;
`;
const ValueInput = styled.input`
display: none;
`;
const ButtonContainer = styled.div`
${(props) => props.mode === "filedrop" && "padding: 2px 12px 2px 3px"};
`;
const DropzoneLabel = styled.div`
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 3;
text-align: center;
margin-top: 0.5rem;
color: ${(props) => (props.disabled ? props.theme.disabledDropLabelFontColor : props.theme.dropLabelFontColor)};
font-family: ${(props) => props.theme.dropLabelFontFamily};
font-size: ${(props) => props.theme.dropLabelFontSize};
font-weight: ${(props) => props.theme.dropLabelFontWeight};
`;
const FiledropLabel = styled.span`
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: ${(props) => (props.disabled ? props.theme.disabledDropLabelFontColor : props.theme.dropLabelFontColor)};
font-family: ${(props) => props.theme.dropLabelFontFamily};
font-size: ${(props) => props.theme.dropLabelFontSize};
font-weight: ${(props) => props.theme.dropLabelFontWeight};
margin-right: 1rem;
`;
const Container = styled.div`
display: flex;
flex-direction: column;
margin-top: 0.25rem;
`;
const FileItemContainer = styled.div`
margin-top: ${(props) => (props.multiple || props.files.length > 1 || props.mode !== "file") && "4px"};
margin-left: ${(props) => props.mode === "file" && props.files.length === 1 && !props.multiple && "4px"};
`;
const ErrorMessage = styled.div`
color: ${(props) => props.theme.errorMessageFontColor};
font-family: ${(props) => props.theme.errorMessageFontFamily};
font-size: ${(props) => props.theme.errorMessageFontSize};
font-weight: ${(props) => props.theme.errorMessageFontWeight};
line-height: ${(props) => props.theme.errorMessageLineHeight};
margin-top: 0.25rem;
`;
export default DxcFileInput;