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

react-ui-org / react-ui / 15460179879

01 May 2025 07:44AM CUT coverage: 90.283%. Remained the same
15460179879

push

github

bedrich-schindler
Bump version to v0.59.2

807 of 897 branches covered (89.97%)

Branch coverage included in aggregate %.

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
  const handleReset = useCallback((event) => {
52✔
50
    setSelectedFileNames([]);
×
51
    onFilesChanged([], event);
×
52
  }, [onFilesChanged]);
53

54
  // We need to have a reference to the input element to be able to call its methods,
55
  // but at the same time we want to expose this reference to the parent component in
56
  // case someone wants to call input methods from outside the component.
57
  useImperativeHandle(
52✔
58
    ref,
59
    () => {
60
      // The reason of extending object instead of using spread operator is that
61
      // if it is transformed to the object, it changes the reference of the object
62
      // and its prototype chain.
63
      const inputEl = internalInputRef?.current ?? {};
2!
64
      inputEl.resetState = () => {
2✔
65
        handleReset(null);
×
66
      };
67
      return inputEl;
2✔
68
    },
69
    [handleReset],
70
  );
71

72
  const handleFileChange = (files, event) => {
52✔
73
    if (files.length === 0) {
2!
74
      setSelectedFileNames([]);
×
75
      return;
×
76
    }
77

78
    // Mimic the native behavior of the `input` element: if multiple files are selected and the input
79
    // does not accept multiple files, no files are processed.
80
    if (files.length > 1 && !multiple) {
2!
81
      setSelectedFileNames([]);
×
82
      return;
×
83
    }
84

85
    const fileNames = [];
2✔
86

87
    [...files].forEach((file) => {
2✔
88
      fileNames.push(file.name);
2✔
89
    });
90

91
    setSelectedFileNames(fileNames);
2✔
92
    onFilesChanged(files, event);
2✔
93
  };
94

95
  const handleInputChange = (event) => {
52✔
96
    handleFileChange(event.target.files, event);
2✔
97
  };
98

99
  const handleClick = () => {
52✔
100
    internalInputRef?.current.click();
×
101
  };
102

103
  const handleDrop = (event) => {
52✔
104
    event.preventDefault();
×
105
    handleFileChange(event.dataTransfer.files, event);
×
106
    setIsDragging(false);
×
107
  };
108

109
  const handleDragOver = (event) => {
52✔
110
    if (!isDragging) {
×
111
      setIsDragging(true);
×
112
    }
113
    event.preventDefault();
×
114
  };
115

116
  const handleDragLeave = () => {
52✔
117
    if (isDragging) {
×
118
      setIsDragging(false);
×
119
    }
120
  };
121

122
  useEffect(() => {
52✔
123
    const inputEl = internalInputRef.current;
50✔
124
    if (!inputEl) {
50✔
125
      return () => {};
×
126
    }
127

128
    const { form } = inputEl;
50✔
129
    if (!form) {
50!
130
      return () => {};
50✔
131
    }
132

133
    form.addEventListener('reset', handleReset);
×
134

135
    return () => {
×
136
      form.removeEventListener('reset', handleReset);
×
137
    };
138
  }, [handleReset]);
139

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

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

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

315
export const FileInputFieldWithGlobalProps = withGlobalProps(FileInputField, 'FileInputField');
4✔
316

317
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

© 2025 Coveralls, Inc