| 1 |
import {FileProps} from '@givewp/forms/propTypes'; |
| 2 |
import {__, sprintf} from '@wordpress/i18n'; |
| 3 |
import {useEffect, useRef} from "react"; |
| 4 |
|
| 5 |
/** |
| 6 |
* @since 4.3.2 manually focus the visible input when error is present. |
| 7 |
* @since 4.3.0 Add aria-required attribute and file size and type validations. |
| 8 |
*/ |
| 9 |
|
| 10 |
export default function File({Label, allowedMimeTypes, maxUploadSize, ErrorMessage, fieldError, description, inputProps}: FileProps) { |
| 11 |
const FieldDescription = window.givewp.form.templates.layouts.fieldDescription; |
| 12 |
const {setValue, setError} = window.givewp.form.hooks.useFormContext(); |
| 13 |
const {name} = inputProps; |
| 14 |
const ref = useRef<HTMLInputElement>(null); |
| 15 |
|
| 16 |
useEffect(() => { |
| 17 |
if (fieldError && ref.current) { |
| 18 |
ref.current.focus(); |
| 19 |
} |
| 20 |
}, [fieldError]); |
| 21 |
|
| 22 |
return ( |
| 23 |
<> |
| 24 |
<label htmlFor={`${name}-field`}> |
| 25 |
<Label /> |
| 26 |
</label> |
| 27 |
{description && <FieldDescription description={description} />} |
| 28 |
|
| 29 |
<input |
| 30 |
ref={ref} |
| 31 |
id={`${name}-field`} |
| 32 |
type="file" |
| 33 |
aria-invalid={fieldError ? 'true' : 'false'} |
| 34 |
accept={allowedMimeTypes.join(',')} |
| 35 |
onChange={(e) => { |
| 36 |
const file = e.target.files[0]; |
| 37 |
|
| 38 |
if (!file) { |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
if (!allowedMimeTypes.includes(file.type)) { |
| 43 |
setError(name, {message: __('The selected file must be a valid file type.', 'give')}); |
| 44 |
return; |
| 45 |
} |
| 46 |
|
| 47 |
if (file.size > maxUploadSize) { |
| 48 |
setError(name, {message: sprintf(__('The selected file must be less than or equal to %d bytes.', 'give'), maxUploadSize)}); |
| 49 |
return; |
| 50 |
} |
| 51 |
|
| 52 |
setError(name, undefined); |
| 53 |
setValue(name, file); |
| 54 |
}} |
| 55 |
aria-required={inputProps['aria-required']} |
| 56 |
/> |
| 57 |
|
| 58 |
<input type="hidden" {...inputProps} /> |
| 59 |
|
| 60 |
<ErrorMessage /> |
| 61 |
</> |
| 62 |
); |
| 63 |
} |
| 64 |
|