import { useRef, useEffect } from 'react' import { useTranslation } from 'react-i18next' import { useFileTreeCreateName } from '../../contexts/file-tree-create-name' import PropTypes from 'prop-types' import { BlockedFilenameError, DuplicateFilenameError, InvalidFilenameError, } from '../../errors' import OLFormGroup from '@/features/ui/components/ol/ol-form-group' import OLFormLabel from '@/features/ui/components/ol/ol-form-label' import OLFormControl from '@/features/ui/components/ol/ol-form-control' import OLNotification from '@/features/ui/components/ol/ol-notification' /** * A form component that renders a text input with label, * plus a validation warning and/or an error message when needed */ export default function FileTreeCreateNameInput({ label, focusName = false, classes = {}, placeholder, error, inFlight, }) { const { t } = useTranslation() // the value is stored in a context provider, so it's available elsewhere in the form const { name, setName, touchedName, validName } = useFileTreeCreateName() // focus the first part of the filename if needed const inputRef = useRef(null) useEffect(() => { if (inputRef.current && focusName) { window.requestAnimationFrame(() => { if (inputRef.current) { inputRef.current.focus() inputRef.current.setSelectionRange( 0, inputRef.current.value.lastIndexOf('.') ) } }) } }, [focusName]) return ( {label || t('file_name')} setName(event.target.value)} ref={inputRef} disabled={inFlight} /> {touchedName && !validName && ( )} {error && } ) } FileTreeCreateNameInput.propTypes = { focusName: PropTypes.bool, label: PropTypes.string, classes: PropTypes.shape({ formGroup: PropTypes.string, }), placeholder: PropTypes.string, error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), inFlight: PropTypes.bool.isRequired, } function ErrorMessage({ error }) { const { t } = useTranslation() // if (typeof error === 'string') { // return error // } switch (error.constructor) { case DuplicateFilenameError: return ( ) case InvalidFilenameError: return ( ) case BlockedFilenameError: return ( ) default: // return return null // other errors are displayed elsewhere } } ErrorMessage.propTypes = { error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired, }