import { getClassNames } from '@websolutespa/bom-core'; import { FormState, FormValidationError } from '@websolutespa/bom-mixer-forms'; import { useLabel } from '@websolutespa/bom-mixer-hooks'; import styled from 'styled-components'; import { UIStyledComponentProps } from '../components/types'; import { getCssResponsive } from '../components/utils'; import { getVariant, useVariants } from '../variants'; import { IFieldErrorVariants, fieldErrorVariants } from './field-error.variants'; type Props = { state: FormState; label?: string; className?: string; variant?: keyof typeof fieldErrorVariants | (string & {}); variants?: IFieldErrorVariants; }; export type FieldErrorProps = UIStyledComponentProps; const StyledFieldError = styled.div>` ${props => getVariant(props.variant, props.variants)} ${props => getCssResponsive(props)} `; export function FieldError({ state, label, className, variant = 'default', variants, ...props }: FieldErrorProps) { const errorLabel = useLabel(); const getErrorLabel = (error: FormValidationError) => { const keyLabel = `error.${error.key}.label`; const key = `error.${error.key}`; const errorKeyLabel = label && errorLabel(keyLabel, { label }); const errorKey = label ? (errorKeyLabel !== keyLabel ? errorKeyLabel : errorLabel(key, { label })) : errorLabel(key); return errorKey; }; const classNames = getClassNames('field-error', className, variant); const globalVariants = useVariants('fieldError', fieldErrorVariants); variants = variants || globalVariants; return ( <> {state.flags.touched && state.errors.map(error => ( {getErrorLabel(error)} ))} ); }