import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import { Button, Split, SplitItem, Spinner, FormGroup, } from '@patternfly/react-core'; import { TimesIcon, CheckIcon, PencilAltIcon, ExclamationCircleIcon, } from '@patternfly/react-icons'; import './EditableInput.scss'; const EditableInput = props => { const [editing, setEditing] = useState(false); const [submitting, setSubmitting] = useState(false); const [inputValue, setInputValue] = useState(props.value); const [error, setError] = useState(''); const [touched, setTouched] = useState(false); const stopSubmitting = () => setSubmitting(false); const handleSubmit = event => { event.preventDefault(); onSubmit(); }; const onFinish = () => { setSubmitting(false); setEditing(false); }; const onSubmit = () => { setSubmitting(true); props.onConfirm(inputValue, onFinish, stopSubmitting, onError); }; const onError = err => { setTouched(false); setError(err); }; const onCancel = () => { setInputValue(props.value); setEditing(false); setError(''); }; const onChange = value => { if (!touched) { setTouched(true); } setInputValue(value); }; const editBtn = ( ); if (!editing) { return ( {props.value || {__('None provided')}} {props.allowed && editBtn} ); } const Component = props.component; const shouldValidate = (isTouched, err) => { if (!isTouched) { return err ? 'error' : 'success'; } return 'noval'; }; const valid = shouldValidate(touched, error); return (
} validated={valid} >
{submitting && ( )}
); }; EditableInput.propTypes = { allowed: PropTypes.bool.isRequired, value: PropTypes.string, onConfirm: PropTypes.func.isRequired, attrName: PropTypes.string.isRequired, component: PropTypes.object.isRequired, inputProps: PropTypes.object, }; EditableInput.defaultProps = { inputProps: {}, value: '', }; export default EditableInput;