import { observer } from 'mobx-react-lite' ; import { useCallback , useMemo , useState , useContext } from 'react' ; import { FormContext } from './FormContext' ; import { RadioGroupContext , IRadioGroupContext } from './RadioGroupContext' ; type BaseProps = React . PropsWithChildren < { name : string ; } > ; type ControlledProps < T > = BaseProps & { value ? : T ; onChange ? : ( value : T , name : string ) => any ; state ? : never ; } ; type ObjectProps < TKey extends keyof TState , TState > = BaseProps & { name : TKey ; state : TState ; onChange ? : ( value : TState [ TKey ] , name : TKey ) => any ; value ? : never ; } ; interface RadioGroupType { < T > ( props ) : JSX . Element ; < TKey extends keyof TState , TState > ( props ) : JSX . Element ; } export const RadioGroup = observer ( function RadioGroup ( { name , value : controlledValue , state , onChange , children , } ) { const formContext = useContext ( FormContext ) ; const [ selfValue , setValue ] = useState < string | number > ( ) ; const handleChange = useCallback ( ( value ) => { if ( state ) { state [ name ] = value ; } else { setValue ( value ) ; } if ( onChange ) { onChange ( value , name ) ; } if ( formContext ) { formContext . change ( value , name ) ; } } , [ name , state , formContext , onChange ] ) ; const value = state ? state [ name ] : controlledValue ?? selfValue ; const context = useMemo ( ( ) => ( { name , value , onChange : handleChange , } ) , [ value , value , handleChange ] ) ; return ( < RadioGroupContext . Provider value = { context } > { children } < /RadioGroupContext.Provider>); } ) ;