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 { Switch } from '@luxfi/ui/switch'; import type { SwitchProps } from '@luxfi/ui/switch'; export type FormFieldSwitchProps< FormFields extends FieldValues, Name extends Path, > = Pick< FormFieldPropsBase, 'name' | 'placeholder' | 'rules' | 'controllerProps' > & SwitchProps; const FormFieldSwitchContent = < FormFields extends FieldValues, Name extends Path, >({ name, placeholder, onCheckedChange, rules, controllerProps, disabled, ...rest }: FormFieldSwitchProps) => { const { control } = useFormContext(); const { field, formState } = useController({ control, name, rules, ...controllerProps, }); const handleCheckedChange = React.useCallback(({ checked }: { checked: boolean }) => { field.onChange(checked); onCheckedChange?.({ checked }); }, [ field, onCheckedChange ], ); const switchProps: SwitchProps = { checked: field.value, onCheckedChange: handleCheckedChange, disabled: formState.isSubmitting || disabled, inputProps: { onBlur: field.onBlur, name: field.name }, children: placeholder, ...rest, }; return ; }; export const FormFieldSwitch = React.memo(FormFieldSwitchContent) as typeof FormFieldSwitchContent;