|
| 1 | +import { FieldValues, useController } from 'react-hook-form'; |
| 2 | +import { useFieldControllerLabels, useOnErrorMessage } from '../hooks'; |
| 3 | +import { DistributiveOmit, FieldControllerProps } from '../types'; |
| 4 | +import { MuiTelInput, type MuiTelInputProps } from 'mui-tel-input'; |
| 5 | + |
| 6 | +export type PhoneInputControllerProps<FV extends FieldValues> = FieldControllerProps<FV> & |
| 7 | + DistributiveOmit< |
| 8 | + MuiTelInputProps, |
| 9 | + 'onChange' | 'error' | 'helperText' | 'label' | 'name' | 'disabled' | 'value' | 'onBlur' |
| 10 | + >; |
| 11 | + |
| 12 | +export const PhoneInputController = <FV extends FieldValues>({ |
| 13 | + control, |
| 14 | + label, |
| 15 | + name, |
| 16 | + optional = false, |
| 17 | + requiredLabel, |
| 18 | + onErrorMessage, |
| 19 | + disabled = false, |
| 20 | + ...muiTelInputProps |
| 21 | +}: PhoneInputControllerProps<FV>) => { |
| 22 | + const { fieldControllerLabel } = useFieldControllerLabels({ label, optional, requiredLabel }); |
| 23 | + const { fieldOnErrorMessage } = useOnErrorMessage({ onErrorMessage }); |
| 24 | + |
| 25 | + const { |
| 26 | + field: { onChange, ref, ...restField }, |
| 27 | + fieldState: { invalid, error }, |
| 28 | + } = useController({ |
| 29 | + control, |
| 30 | + disabled, |
| 31 | + name, |
| 32 | + }); |
| 33 | + |
| 34 | + return ( |
| 35 | + <MuiTelInput |
| 36 | + {...restField} |
| 37 | + defaultCountry='PT' |
| 38 | + aria-required={optional ? 'false' : 'true'} |
| 39 | + error={invalid} |
| 40 | + helperText={error?.message ? fieldOnErrorMessage(error?.message) : null} |
| 41 | + inputRef={ref} |
| 42 | + ref={ref} |
| 43 | + label={fieldControllerLabel} |
| 44 | + onChange={(_, info) => { |
| 45 | + onChange(info.numberValue); |
| 46 | + }} |
| 47 | + sx={{ |
| 48 | + ...muiTelInputProps?.sx, |
| 49 | + '.MuiTelInput-FlagImg': { |
| 50 | + borderRadius: (theme) => theme.shape.borderRadius / 4, |
| 51 | + }, |
| 52 | + }} |
| 53 | + {...muiTelInputProps} |
| 54 | + /> |
| 55 | + ); |
| 56 | +}; |
0 commit comments