import React , { useEffect , useRef , useMemo , useCallback } from 'react' ; import { UseField } from '../../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib' ; import { Phases } from '../../../../../../common/types' ; import { UseFieldProps , FormData } from '../../../../../shared_imports' ; import { useFormErrorsContext } from '../form_errors_context' ; const isXPhaseField = ( phase ) => ( fieldPath ) : boolean => fieldPath . startsWith ( `phases.${ phase }` ) || fieldPath . startsWith ( `_meta.${ phase }` ) ; const isHotPhaseField = isXPhaseField ( 'hot' ) ; const isWarmPhaseField = isXPhaseField ( 'warm' ) ; const isColdPhaseField = isXPhaseField ( 'cold' ) ; const isFrozenPhaseField = isXPhaseField ( 'frozen' ) ; const isDeletePhaseField = isXPhaseField ( 'delete' ) ; const determineFieldPhase = ( fieldPath ) : keyof Phases | 'other' => { if ( isHotPhaseField ( fieldPath ) ) { return 'hot' ; } if ( isWarmPhaseField ( fieldPath ) ) { return 'warm' ; } if ( isColdPhaseField ( fieldPath ) ) { return 'cold' ; } if ( isFrozenPhaseField ( fieldPath ) ) { return 'frozen' ; } if ( isDeletePhaseField ( fieldPath ) ) { return 'delete' ; } return 'other' ; } ; export const EnhancedUseField = < T , F = FormData , I = T > ( props ) : React . ReactElement < any , any > | null => { const { path } = props ; const isMounted = useRef < boolean > ( false ) ; const phase = useMemo ( ( ) => determineFieldPhase ( path ) , [ path ] ) ; const { addError , clearError } = useFormErrorsContext ( ) ; const onError = useCallback ( ( errors ) => { if ( ! isMounted . current ) { return ; } if ( errors ) { addError ( phase , path , errors ) ; } else { clearError ( phase , path ) ; } } , [ phase , path , addError , clearError ] ) ; useEffect ( ( ) => { isMounted . current = true ; return ( ) => { isMounted . current = false ; } ; } , [ ] ) ; useEffect ( ( ) => { return ( ) => { if ( isMounted . current === false ) { clearError ( phase , path ) ; } } ; } , [ phase , path , clearError ] ) ; return < UseField { ... props } onError = { onError } / > ; } ;