2020-11-29 18:26:42 -07:00
|
|
|
import { Flex, FormControl, FormLabel, FormErrorMessage } from '@chakra-ui/react';
|
2020-12-20 01:21:24 -07:00
|
|
|
import { useFormContext } from 'react-hook-form';
|
2020-11-29 18:26:42 -07:00
|
|
|
import { If } from '~/components';
|
|
|
|
import { useColorValue } from '~/context';
|
|
|
|
import { useBooleanValue } from '~/hooks';
|
|
|
|
|
2020-12-20 01:21:24 -07:00
|
|
|
import { TField, TFormError } from './types';
|
2020-11-29 18:26:42 -07:00
|
|
|
|
|
|
|
export const FormField = (props: TField) => {
|
2020-12-20 01:21:24 -07:00
|
|
|
const { name, label, children, labelAddOn, fieldAddOn, hiddenLabels = false, ...rest } = props;
|
2020-11-29 18:26:42 -07:00
|
|
|
const labelColor = useColorValue('blackAlpha.700', 'whiteAlpha.700');
|
2020-12-20 01:21:24 -07:00
|
|
|
const errorColor = useColorValue('red.500', 'red.300');
|
2020-11-29 18:26:42 -07:00
|
|
|
const opacity = useBooleanValue(hiddenLabels, 0, undefined);
|
2020-12-11 09:55:21 -07:00
|
|
|
|
2020-12-20 01:21:24 -07:00
|
|
|
const { errors } = useFormContext();
|
|
|
|
|
|
|
|
const error = name in errors && (errors[name] as TFormError);
|
|
|
|
|
|
|
|
if (error !== false) {
|
|
|
|
console.warn(`${label} Error: ${error.message}`);
|
|
|
|
}
|
2020-12-11 09:55:21 -07:00
|
|
|
|
2020-11-29 18:26:42 -07:00
|
|
|
return (
|
|
|
|
<FormControl
|
|
|
|
mx={2}
|
|
|
|
d="flex"
|
|
|
|
w="100%"
|
|
|
|
maxW="100%"
|
|
|
|
flexDir="column"
|
|
|
|
my={{ base: 2, lg: 4 }}
|
2020-12-20 01:21:24 -07:00
|
|
|
isInvalid={error !== false}
|
2020-11-29 18:26:42 -07:00
|
|
|
flex={{ base: '1 0 100%', lg: '1 0 33.33%' }}
|
|
|
|
{...rest}>
|
|
|
|
<FormLabel
|
|
|
|
pl={1}
|
|
|
|
pr={0}
|
|
|
|
htmlFor={name}
|
|
|
|
display="flex"
|
|
|
|
opacity={opacity}
|
|
|
|
alignItems="center"
|
2020-12-29 02:08:45 -07:00
|
|
|
justifyContent="space-between"
|
|
|
|
color={error !== false ? errorColor : labelColor}>
|
2020-11-29 18:26:42 -07:00
|
|
|
{label}
|
|
|
|
<If c={typeof labelAddOn !== 'undefined'}>{labelAddOn}</If>
|
|
|
|
</FormLabel>
|
|
|
|
{children}
|
|
|
|
<If c={typeof fieldAddOn !== 'undefined'}>
|
|
|
|
<Flex justify="flex-end" pt={3}>
|
|
|
|
{fieldAddOn}
|
|
|
|
</Flex>
|
|
|
|
</If>
|
2020-12-20 01:21:24 -07:00
|
|
|
<FormErrorMessage opacity={opacity}>{error && error.message}</FormErrorMessage>
|
2020-11-29 18:26:42 -07:00
|
|
|
</FormControl>
|
|
|
|
);
|
|
|
|
};
|