import type { ChakraProps } from '@chakra-ui/react'; import { FormControl, Input, InputGroup, InputRightElement, Textarea, chakra, shouldForwardProp } from '@chakra-ui/react'; import React from 'react'; import type { FieldValues, Path } from 'react-hook-form'; import { useController, useFormContext } from 'react-hook-form'; import type { FormFieldPropsBase } from './types'; import FormInputPlaceholder from '../inputs/FormInputPlaceholder'; interface Props< FormFields extends FieldValues, Name extends Path = Path, > extends FormFieldPropsBase { asComponent?: 'Input' | 'Textarea'; } const FormFieldText = < FormFields extends FieldValues, Name extends Path = Path, >({ name, placeholder, isReadOnly, isRequired, rules, onBlur, type = 'text', rightElement, asComponent, max, className, size = 'md', bgColor, minH, maxH, }: Props) => { const { control } = useFormContext(); const { field, fieldState, formState } = useController({ control, name, rules: { ...rules, required: isRequired }, }); const isDisabled = formState.isSubmitting; const handleBlur = React.useCallback(() => { field.onBlur(); onBlur?.(); }, [ field, onBlur ]); const Component = asComponent === 'Textarea' ? Textarea : Input; const input = ( ); const inputPlaceholder = size !== 'xs' && ; return ( { rightElement ? ( { input } { inputPlaceholder } { rightElement({ field }) } ) : ( <> { input } { inputPlaceholder } ) } ); }; const WrappedFormFieldText = chakra(FormFieldText, { shouldForwardProp: (prop) => { const isChakraProp = !shouldForwardProp(prop); if (isChakraProp && ![ 'bgColor', 'size', 'minH', 'maxH' ].includes(prop)) { return false; } return true; }, }); export type WrappedComponent = < FormFields extends FieldValues, Name extends Path = Path, >(props: Props & ChakraProps) => React.JSX.Element; export default React.memo(WrappedFormFieldText) as WrappedComponent;