import React , { FC , useContext , useEffect , useState , useMemo } from 'react' ; import { i18n } from '@kbn/i18n' ; import { SplitFieldSelect } from '../split_field_select' ; import { JobCreatorContext } from '../../../job_creator_context' ; import { Field } from '../../../../../../../../../common/types/fields' ; import { newJobCapsService , filterCategoryFields , } from '../../../../../../../services/new_job_capabilities/new_job_capabilities_service' ; import { PopulationJobCreator } from '../../../../../common/job_creator' ; interface Props { detectorIndex : number ; } export const ByFieldSelector = ( { detectorIndex } ) => { const { jobCreator : jc , jobCreatorUpdate , jobCreatorUpdated } = useContext ( JobCreatorContext ) ; const jobCreator = jc as PopulationJobCreator ; const runtimeCategoryFields = useMemo ( ( ) => filterCategoryFields ( jobCreator . runtimeFields ) , [ ] ) ; const allCategoryFields = useMemo ( ( ) => [ ... newJobCapsService . categoryFields , ... runtimeCategoryFields ] , [ ] ) ; const [ byField , setByField ] = useState ( jobCreator . getByField ( detectorIndex ) ) ; const categoryFields = useFilteredCategoryFields ( allCategoryFields , jobCreator , jobCreatorUpdated ) ; useEffect ( ( ) => { jobCreator . setByField ( byField , detectorIndex ) ; if ( byField !== null && jobCreator . influencers . includes ( byField . name ) === false ) { jobCreator . addInfluencer ( byField . name ) ; } jobCreatorUpdate ( ) ; } , [ byField ] ) ; useEffect ( ( ) => { const bf = jobCreator . getByField ( detectorIndex ) ; setByField ( bf ) ; } , [ jobCreatorUpdated ] ) ; return ( < SplitFieldSelect fields = { categoryFields } changeHandler = { setByField } selectedField = { byField } isClearable = { true } testSubject = "mlByFieldSelect" placeholder = { i18n . translate ( 'xpack.ml.newJob.wizard.pickFieldsStep.populationField.placeholder' , { defaultMessage : 'Split data' , } ) } / > ) ; } ; function useFilteredCategoryFields ( allCategoryFields , jobCreator , jobCreatorUpdated ) { const [ fields , setFields ] = useState ( allCategoryFields ) ; useEffect ( ( ) => { const pf = jobCreator . populationField ; if ( pf !== null ) { setFields ( allCategoryFields . filter ( ( { name } ) => name !== pf . name ) ) ; } else { setFields ( allCategoryFields ) ; } } , [ jobCreatorUpdated ] ) ; return fields ; }