-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFileInputField.jsx
More file actions
330 lines (303 loc) · 9.13 KB
/
Copy pathFileInputField.jsx
File metadata and controls
330 lines (303 loc) · 9.13 KB
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
import PropTypes from 'prop-types';
import React, {
useCallback,
useEffect,
useContext,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { withGlobalProps } from '../../providers/globalProps';
import { classNames } from '../../helpers/classNames';
import { transferProps } from '../../helpers/transferProps';
import { TranslationsContext } from '../../providers/translations';
import { getRootSizeClassName } from '../_helpers/getRootSizeClassName';
import { getRootValidationStateClassName } from '../_helpers/getRootValidationStateClassName';
import { resolveContextOrProp } from '../_helpers/resolveContextOrProp';
import { InputGroupContext } from '../InputGroup';
import { Text } from '../Text';
import { FormLayoutContext } from '../FormLayout';
import styles from './FileInputField.module.scss';
/* istanbul ignore file */
export const FileInputField = React.forwardRef((props, ref) => {
const {
disabled,
fullWidth,
helpText,
id,
isLabelVisible,
label,
layout,
multiple,
onFilesChanged,
required,
size,
validationState,
validationText,
...restProps
} = props;
const formLayoutContext = useContext(FormLayoutContext);
const inputGroupContext = useContext(InputGroupContext);
const translations = useContext(TranslationsContext);
const [selectedFileNames, setSelectedFileNames] = useState([]);
const [isDragging, setIsDragging] = useState(false);
const internalInputRef = useRef();
const handleReset = useCallback((event) => {
if (internalInputRef.current) {
internalInputRef.current.value = '';
}
setSelectedFileNames([]);
onFilesChanged([], event);
}, [onFilesChanged]);
// We need to have a reference to the input element to be able to call its methods,
// but at the same time we want to expose this reference to the parent component in
// case someone wants to call input methods from outside the component.
useImperativeHandle(
ref,
() => {
// The reason of extending object instead of using spread operator is that
// if it is transformed to the object, it changes the reference of the object
// and its prototype chain.
const inputEl = internalInputRef?.current ?? {};
inputEl.resetState = () => {
handleReset(null);
};
return inputEl;
},
[handleReset],
);
const handleFileChange = (files, event) => {
if (files.length === 0) {
setSelectedFileNames([]);
onFilesChanged([], event);
return;
}
// Mimic the native behavior of the `input` element: if multiple files are selected and the input
// does not accept multiple files, no files are processed.
if (files.length > 1 && !multiple) {
setSelectedFileNames([]);
onFilesChanged([], event);
return;
}
const fileNames = [];
[...files].forEach((file) => {
fileNames.push(file.name);
});
setSelectedFileNames(fileNames);
onFilesChanged(files, event);
};
const handleInputChange = (event) => {
handleFileChange(event.target.files, event);
};
const handleClick = () => {
internalInputRef?.current.click();
};
const handleDrop = (event) => {
event.preventDefault();
handleFileChange(event.dataTransfer.files, event);
setIsDragging(false);
};
const handleDragOver = (event) => {
if (!isDragging) {
setIsDragging(true);
}
event.preventDefault();
};
const handleDragLeave = () => {
if (isDragging) {
setIsDragging(false);
}
};
useEffect(() => {
const inputEl = internalInputRef.current;
if (!inputEl) {
return () => {};
}
const { form } = inputEl;
if (!form) {
return () => {};
}
form.addEventListener('reset', handleReset);
return () => {
form.removeEventListener('reset', handleReset);
};
}, [handleReset]);
return (
<div
className={classNames(
styles.root,
fullWidth && styles.isRootFullWidth,
formLayoutContext && styles.isRootInFormLayout,
resolveContextOrProp(formLayoutContext && formLayoutContext.layout, layout) === 'horizontal'
? styles.isRootLayoutHorizontal
: styles.isRootLayoutVertical,
resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled) && styles.isRootDisabled,
inputGroupContext && styles.isRootGrouped,
isDragging && styles.isRootDragging,
required && styles.isRootRequired,
getRootSizeClassName(
resolveContextOrProp(inputGroupContext && inputGroupContext.size, size),
styles,
),
getRootValidationStateClassName(validationState, styles),
)}
id={`${id}__root`}
onDragLeave={!disabled ? handleDragLeave : undefined}
onDragOver={!disabled ? handleDragOver : undefined}
onDrop={!disabled ? handleDrop : undefined}
>
<label
className={classNames(
styles.label,
(!isLabelVisible || inputGroupContext) && styles.isLabelHidden,
)}
htmlFor={id}
id={`${id}__labelText`}
>
{label}
</label>
<div className={styles.field}>
<div className={styles.inputContainer}>
<input
{...transferProps(restProps)}
className={styles.input}
disabled={resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled)}
id={id}
multiple={multiple}
onChange={handleInputChange}
ref={internalInputRef}
required={required}
tabIndex={-1}
type="file"
/>
<button
className={styles.dropZone}
disabled={resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled)}
onClick={handleClick}
type="button"
>
<Text lines={1}>
{isDragging && (
<span className={styles.dropFileHereText}>
{translations.FileInputField.dropFileHere}
</span>
)}
{!isDragging && !selectedFileNames.length && (
<>
<span className={styles.dropZoneLink}>{translations.FileInputField.browse}</span>
{' '}
{translations.FileInputField.drop}
</>
)}
{!isDragging && selectedFileNames.length === 1 && selectedFileNames[0]}
{!isDragging && selectedFileNames.length > 1 && (
<>
{selectedFileNames.length}
{' '}
{translations.FileInputField.filesSelected}
</>
)}
</Text>
</button>
</div>
{helpText && (
<div
className={styles.helpText}
id={`${id}__helpText`}
>
{helpText}
</div>
)}
{validationText && (
<div
className={styles.validationText}
id={`${id}__validationText`}
>
{validationText}
</div>
)}
</div>
</div>
);
});
FileInputField.defaultProps = {
disabled: false,
fullWidth: false,
helpText: undefined,
isLabelVisible: true,
layout: 'vertical',
multiple: false,
required: false,
size: 'medium',
validationState: undefined,
validationText: undefined,
};
FileInputField.propTypes = {
/**
* If `true`, the input will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the field will span the full width of its parent.
*/
fullWidth: PropTypes.bool,
/**
* Optional help text.
*/
helpText: PropTypes.node,
/**
* ID of the `<input>` HTML element.
*
* Also serves as base for ids of nested elements:
* * `<ID>__label`
* * `<ID>__labelText`
* * `<ID>__helpText`
* * `<ID>__validationText`
*/
id: PropTypes.string.isRequired,
/**
* If `false`, the label will be visually hidden (but remains accessible by assistive
* technologies).
*/
isLabelVisible: PropTypes.bool,
/**
* File input field label.
*/
label: PropTypes.node.isRequired,
/**
* Layout of the field.
*
* Ignored if the component is rendered within `FormLayout` component
* as the value is inherited in such case.
*
*/
layout: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* If `true`, the input will accept multiple files.
*/
multiple: PropTypes.bool,
/**
* Callback fired when the value of the input changes.
*/
onFilesChanged: PropTypes.func.isRequired,
/**
* If `true`, the input will be required.
*/
required: PropTypes.bool,
/**
* Size of the field.
*
* Ignored if the component is rendered within `InputGroup` component as the value is inherited in such case.
*/
size: PropTypes.oneOf(['small', 'medium', 'large']),
/**
* Alter the field to provide feedback based on validation result.
*/
validationState: PropTypes.oneOf(['invalid', 'valid', 'warning']),
/**
* Validation message to be displayed.
*/
validationText: PropTypes.node,
};
export const FileInputFieldWithGlobalProps = withGlobalProps(FileInputField, 'FileInputField');
export default FileInputFieldWithGlobalProps;