• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

react-ui-org / react-ui / 14739186620

29 Apr 2025 06:59PM UTC coverage: 90.283%. First build
14739186620

Pull #631

github

web-flow
Merge a666f4fa9 into 4a11a95c7
Pull Request #631: Allow to reset `FileInputField` internal state by calling `resetState` function on its ref (#630)

807 of 897 branches covered (89.97%)

Branch coverage included in aggregate %.

5 of 6 new or added lines in 1 file covered. (83.33%)

754 of 832 relevant lines covered (90.63%)

73.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.49
/src/components/FileInputField/FileInputField.jsx
1
import PropTypes from 'prop-types';
2
import React, {
3
  useCallback,
4
  useEffect,
5
  useContext,
6
  useImperativeHandle,
7
  useRef,
8
  useState,
9
} from 'react';
10
import { withGlobalProps } from '../../providers/globalProps';
11
import { classNames } from '../../helpers/classNames';
12
import { transferProps } from '../../helpers/transferProps';
13
import { TranslationsContext } from '../../providers/translations';
14
import { getRootSizeClassName } from '../_helpers/getRootSizeClassName';
15
import { getRootValidationStateClassName } from '../_helpers/getRootValidationStateClassName';
16
import { resolveContextOrProp } from '../_helpers/resolveContextOrProp';
17
import { InputGroupContext } from '../InputGroup';
18
import { Text } from '../Text';
19
import { FormLayoutContext } from '../FormLayout';
20
import styles from './FileInputField.module.scss';
21

22
export const FileInputField = React.forwardRef((props, ref) => {
4✔
23
  const {
24
    disabled,
25
    fullWidth,
26
    helpText,
27
    id,
28
    isLabelVisible,
29
    label,
30
    layout,
31
    multiple,
32
    onFilesChanged,
33
    required,
34
    size,
35
    validationState,
36
    validationText,
37
    ...restProps
38
  } = props;
52✔
39

40
  const formLayoutContext = useContext(FormLayoutContext);
52✔
41
  const inputGroupContext = useContext(InputGroupContext);
52✔
42
  const translations = useContext(TranslationsContext);
52✔
43

44
  const [selectedFileNames, setSelectedFileNames] = useState([]);
52✔
45
  const [isDragging, setIsDragging] = useState(false);
52✔
46

47
  const internalInputRef = useRef();
52✔
48

49
  // We need to have a reference to the input element to be able to call its methods,
50
  // but at the same time we want to expose this reference to the parent component for
51
  // case someone wants to call input methods from outside the component.
52
  useImperativeHandle(
52✔
53
    ref,
54
    () => {
55
      const inputEl = internalInputRef?.current ?? {};
2!
56
      inputEl.resetState = () => {
2✔
NEW
57
        setSelectedFileNames([]);
×
58
      };
59
      return inputEl;
2✔
60
    },
61
    [setSelectedFileNames],
62
  );
63

64
  const handleFileChange = (files, event) => {
52✔
65
    if (files.length === 0) {
2!
66
      setSelectedFileNames([]);
×
67
      return;
×
68
    }
69

70
    // Mimic the native behavior of the `input` element: if multiple files are selected and the input
71
    // does not accept multiple files, no files are processed.
72
    if (files.length > 1 && !multiple) {
2!
73
      setSelectedFileNames([]);
×
74
      return;
×
75
    }
76

77
    const fileNames = [];
2✔
78

79
    [...files].forEach((file) => {
2✔
80
      fileNames.push(file.name);
2✔
81
    });
82

83
    setSelectedFileNames(fileNames);
2✔
84
    onFilesChanged(files, event);
2✔
85
  };
86

87
  const handleInputChange = (event) => {
52✔
88
    handleFileChange(event.target.files, event);
2✔
89
  };
90

91
  const handleClick = () => {
52✔
92
    internalInputRef?.current.click();
×
93
  };
94

95
  const handleDrop = (event) => {
52✔
96
    event.preventDefault();
×
97
    handleFileChange(event.dataTransfer.files, event);
×
98
    setIsDragging(false);
×
99
  };
100

101
  const handleDragOver = (event) => {
52✔
102
    if (!isDragging) {
×
103
      setIsDragging(true);
×
104
    }
105
    event.preventDefault();
×
106
  };
107

108
  const handleDragLeave = () => {
52✔
109
    if (isDragging) {
×
110
      setIsDragging(false);
×
111
    }
112
  };
113

114
  const handleReset = useCallback((event) => {
52✔
115
    setSelectedFileNames([]);
×
116
    onFilesChanged([], event);
×
117
  }, [onFilesChanged]);
118

119
  useEffect(() => {
52✔
120
    const inputEl = internalInputRef.current;
50✔
121
    if (!inputEl) {
50✔
122
      return;
×
123
    }
124

125
    const { form } = inputEl;
50✔
126
    if (!form) {
50!
127
      return;
50✔
128
    }
129

130
    form.addEventListener('reset', handleReset);
×
131

132
    // eslint-disable-next-line consistent-return
133
    return () => {
×
134
      form.removeEventListener('reset', handleReset);
×
135
    };
136
  }, [handleReset]);
137

138
  return (
52✔
139
    <div
140
      className={classNames(
141
        styles.root,
142
        fullWidth && styles.isRootFullWidth,
27✔
143
        formLayoutContext && styles.isRootInFormLayout,
28✔
144
        resolveContextOrProp(formLayoutContext && formLayoutContext.layout, layout) === 'horizontal'
54✔
145
          ? styles.isRootLayoutHorizontal
146
          : styles.isRootLayoutVertical,
147
        resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled) && styles.isRootDisabled,
53!
148
        inputGroupContext && styles.isRootGrouped,
26!
149
        isDragging && styles.isRootDragging,
26!
150
        required && styles.isRootRequired,
27✔
151
        getRootSizeClassName(
152
          resolveContextOrProp(inputGroupContext && inputGroupContext.size, size),
26!
153
          styles,
154
        ),
155
        getRootValidationStateClassName(validationState, styles),
156
      )}
157
      id={`${id}__root`}
158
      onDragLeave={!disabled ? handleDragLeave : undefined}
26✔
159
      onDragOver={!disabled ? handleDragOver : undefined}
26✔
160
      onDrop={!disabled ? handleDrop : undefined}
26✔
161
    >
162
      <label
163
        className={classNames(
164
          styles.label,
165
          (!isLabelVisible || inputGroupContext) && styles.isLabelHidden,
52✔
166
        )}
167
        htmlFor={id}
168
        id={`${id}__labelText`}
169
      >
170
        {label}
171
      </label>
172
      <div className={styles.field}>
173
        <div className={styles.inputContainer}>
174
          <input
175
            {...transferProps(restProps)}
176
            className={styles.input}
177
            disabled={resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled)}
26!
178
            id={id}
179
            multiple={multiple}
180
            onChange={handleInputChange}
181
            ref={internalInputRef}
182
            required={required}
183
            tabIndex={-1}
184
            type="file"
185
          />
186
          <button
187
            className={styles.dropZone}
188
            disabled={resolveContextOrProp(inputGroupContext && inputGroupContext.disabled, disabled)}
26!
189
            onClick={handleClick}
190
            type="button"
191
          >
192
            <Text lines={1}>
193
              {!selectedFileNames.length && (
51✔
194
                <>
195
                  <span className={styles.dropZoneLink}>{translations.FileInputField.browse}</span>
196
                  {' '}
197
                  {translations.FileInputField.drop}
198
                </>
199
              )}
200
              {selectedFileNames.length === 1 && selectedFileNames[0]}
27✔
201
              {selectedFileNames.length > 1 && (
26!
202
                <>
203
                  {selectedFileNames.length}
204
                  {' '}
205
                  {translations.FileInputField.filesSelected}
206
                </>
207
              )}
208
            </Text>
209
          </button>
210
        </div>
211
        {helpText && (
28✔
212
          <div
213
            className={styles.helpText}
214
            id={`${id}__helpText`}
215
          >
216
            {helpText}
217
          </div>
218
        )}
219
        {validationText && (
28✔
220
          <div
221
            className={styles.validationText}
222
            id={`${id}__validationText`}
223
          >
224
            {validationText}
225
          </div>
226
        )}
227
      </div>
228
    </div>
229
  );
230
});
231

232
FileInputField.defaultProps = {
4✔
233
  disabled: false,
234
  fullWidth: false,
235
  helpText: null,
236
  isLabelVisible: true,
237
  layout: 'vertical',
238
  multiple: false,
239
  required: false,
240
  size: 'medium',
241
  validationState: null,
242
  validationText: null,
243
};
244

245
FileInputField.propTypes = {
4✔
246
  /**
247
   * If `true`, the input will be disabled.
248
   */
249
  disabled: PropTypes.bool,
250
  /**
251
   * If `true`, the field will span the full width of its parent.
252
   */
253
  fullWidth: PropTypes.bool,
254
  /**
255
   * Optional help text.
256
   */
257
  helpText: PropTypes.node,
258
  /**
259
   * ID of the `<input>` HTML element.
260
   *
261
   * Also serves as base for ids of nested elements:
262
   * * `<ID>__label`
263
   * * `<ID>__labelText`
264
   * * `<ID>__helpText`
265
   * * `<ID>__validationText`
266
   */
267
  id: PropTypes.string.isRequired,
268
  /**
269
   * If `false`, the label will be visually hidden (but remains accessible by assistive
270
   * technologies).
271
   */
272
  isLabelVisible: PropTypes.bool,
273
  /**
274
   * File input field label.
275
   */
276
  label: PropTypes.node.isRequired,
277
  /**
278
   * Layout of the field.
279
   *
280
   * Ignored if the component is rendered within `FormLayout` component
281
   * as the value is inherited in such case.
282
   *
283
   */
284
  layout: PropTypes.oneOf(['horizontal', 'vertical']),
285
  /**
286
   * If `true`, the input will accept multiple files.
287
   */
288
  multiple: PropTypes.bool,
289
  /**
290
   * Callback fired when the value of the input changes.
291
   */
292
  onFilesChanged: PropTypes.func.isRequired,
293
  /**
294
   * If `true`, the input will be required.
295
   */
296
  required: PropTypes.bool,
297
  /**
298
   * Size of the field.
299
   *
300
   * Ignored if the component is rendered within `InputGroup` component as the value is inherited in such case.
301
   */
302
  size: PropTypes.oneOf(['small', 'medium', 'large']),
303
  /**
304
   * Alter the field to provide feedback based on validation result.
305
   */
306
  validationState: PropTypes.oneOf(['invalid', 'valid', 'warning']),
307
  /**
308
   * Validation message to be displayed.
309
   */
310
  validationText: PropTypes.node,
311
};
312

313
export const FileInputFieldWithGlobalProps = withGlobalProps(FileInputField, 'FileInputField');
4✔
314

315
export default FileInputFieldWithGlobalProps;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc