import React , { ComponentClass , createElement , FunctionComponent , SyntheticEvent } from 'react' ; import { fieldSelector , FormBaseState } from 'stapp-formbase' ; import { Stapp } from 'stapp' ; import { renderComponent } from '../helpers/renderComponent' ; import { ConsumerProps , FieldProps } from '../models/Props' ; /**
 * Creates react form helper.
 * See examples in the examples folder.
 */ export const createField = < State extends FormBaseState , Api > ( Consumer , appName = 'Stapp' ) : FunctionComponent < FieldProps < State > > => { const Field = ( props ) => { const selector = fieldSelector ( props . name , props . extraSelector ) ; const handleChange = ( api ) => ( event ) => { api . formBase . setValue ( { [ props . name ] : event . currentTarget . value } ) ; } ; const handleBlur = ( api , active ) => ( ) => { active && api . formBase . setActive ( null ) ; api . formBase . setTouched ( { [ props . name ] : true } ) ; } ; const handleFocus = ( api ) => ( ) => { api . formBase . setActive ( props . name ) ; } ; return createElement ( Consumer , { map : selector , children : ( fieldState , api , app ) => { const result = { input : { name : props . name , value : fieldState . value || '' , onChange : handleChange ( api ) , onBlur : handleBlur ( api , fieldState . active ) , onFocus : handleFocus ( api ) } , meta : { error : fieldState . error , touched : fieldState . touched , active : fieldState . active , dirty : fieldState . dirty } , extra : fieldState . extra } ; return renderComponent ( { name : 'Field' , renderProps : props , renderArgs : [ result , api , app ] , componentProps : Object . assign ( { api , app } , result ) } ) ; } } ) ; } ; ( Field as FunctionComponent ) . displayName = `${ appName }.Field` ; return Field ; } ;