saagie-ui
Version:
Saagie UI from Saagie Design System
107 lines (94 loc) • 2.39 kB
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
import { withFormsy, propTypes as formsyPropTypes } from 'formsy-react';
import { FormPassword } from '../../core/atoms/formPassword/FormPassword';
import { FormGroup } from '../../core/molecules/formGroup/FormGroup';
const propTypes = {
...formsyPropTypes,
children: PropTypes.node,
disabled: PropTypes.bool,
/**
* Object of props passed to the <FormGroup> component
*/
groupProps: PropTypes.object,
helper: PropTypes.node,
/**
* Object of props passed to the <input> element
*/
inputProps: PropTypes.object,
label: PropTypes.node,
onChange: PropTypes.func,
placeholder: PropTypes.string,
};
const defaultProps = {
children: null,
disabled: false,
groupProps: {},
helper: null,
inputProps: {},
label: null,
onChange: () => {},
placeholder: null,
};
export const FieldPasswordUI = ({
// Formsy props
errorMessage,
value,
isFormSubmitted,
isPristine,
isRequired,
isValid,
setValue,
// Global props
children,
disabled,
groupProps,
helper,
label,
onChange,
placeholder,
// Custom props
inputProps,
}) => {
const [isTouched, setIsTouched] = React.useState(false);
const [isFocused, setIsFocused] = React.useState(false);
const isFeedbackVisible = (isTouched && !isPristine) || isFormSubmitted;
const isError = !isValid && isFeedbackVisible;
const handleChange = (event) => {
const val = event.currentTarget.value.trim();
setValue(val);
onChange(val);
};
const handleFocus = () => {
setIsFocused(true);
setIsTouched(true);
};
const handleBlur = () => {
setIsFocused(false);
};
return (
<FormGroup
label={label}
helper={helper}
isOptional={!isRequired}
validationState={!isFocused && isError ? 'danger' : null}
feedbackMessage={isFeedbackVisible && errorMessage}
{...groupProps}
>
<FormPassword
className="sui-a-form-control"
disabled={disabled}
placeholder={placeholder}
defaultValue={value || ''}
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
{...inputProps}
/>
{children}
</FormGroup>
);
};
FieldPasswordUI.propTypes = propTypes;
FieldPasswordUI.defaultProps = defaultProps;
export const FieldPassword = withFormsy(FieldPasswordUI);