import { Control, FieldPath, FieldValues, PathValue, useController, } from 'react-hook-form' import { FormControlLabel, FormControlLabelProps, Switch, SwitchProps, useForkRef, } from '@mui/material' import { ChangeEvent, forwardRef, type ReactElement, Ref, RefAttributes, } from 'react' import {useTransform} from './useTransform' export type SwitchElementProps< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, TValue = unknown, > = Omit & { name: TName control?: Control switchProps?: SwitchProps transform?: { input?: (value: PathValue) => TValue output?: ( event: ChangeEvent, checked: boolean ) => PathValue } } type SwitchElementComponent = < TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, TValue = unknown, >( props: SwitchElementProps & RefAttributes ) => ReactElement const SwitchElement = forwardRef(function SwitchElement< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, TValue = unknown, >( props: SwitchElementProps, ref: Ref ) { const {name, control, switchProps, transform, ...rest} = props const {field} = useController({ name, control, disabled: rest.disabled, }) const {value, onChange} = useTransform({ value: field.value, onChange: field.onChange, transform: { input: transform?.input, output: typeof transform?.output === 'function' ? transform.output : (_event: ChangeEvent, checked: boolean) => { return checked as PathValue }, }, }) const handleSwitchRef = useForkRef(field.ref, switchProps?.ref) return ( { onChange(event, checked) if (typeof switchProps?.onChange === 'function') { switchProps.onChange(event, checked) } }} onBlur={(event) => { field.onBlur() if (typeof switchProps?.onBlur === 'function') { switchProps?.onBlur(event) } }} ref={handleSwitchRef} checked={!!value} /> } {...rest} /> ) }) SwitchElement.displayName = 'SwitchElement' export default SwitchElement as SwitchElementComponent