import { uniqBy } from 'lodash' ; import deepEqual from 'fast-deep-equal' ; import { Observable , pipe , combineLatest } from 'rxjs' ; import { distinctUntilChanged , switchMap , filter , mapTo , map } from 'rxjs/operators' ; import { DashboardContainer } from '..' ; import { isErrorEmbeddable } from '../../services/embeddable' ; import { IndexPattern , IndexPatternsContract } from '../../services/data' ; interface SyncDashboardIndexPatternsProps { dashboardContainer : DashboardContainer ; indexPatterns : IndexPatternsContract ; onUpdateIndexPatterns : ( newIndexPatterns : IndexPattern [ ] ) => void ; } export const syncDashboardIndexPatterns = ( { dashboardContainer , indexPatterns , onUpdateIndexPatterns , } ) => { const updateIndexPatternsOperator = pipe ( filter ( ( container ) => ! ! container && ! isErrorEmbeddable ( container ) ) , map ( ( container ) : IndexPattern [ ] | undefined => { let panelIndexPatterns = [ ] ; Object . values ( container . getChildIds ( ) ) . forEach ( ( id ) => { const embeddableInstance = container . getChild ( id ) ; if ( isErrorEmbeddable ( embeddableInstance ) ) return ; const embeddableIndexPatterns = ( embeddableInstance . getOutput ( ) as any ) . indexPatterns ; if ( ! embeddableIndexPatterns ) return ; panelIndexPatterns . push ( ... embeddableIndexPatterns ) ; } ) ; if ( container . controlGroup ) { panelIndexPatterns . push ( ... ( container . controlGroup . getOutput ( ) . dataViews ?? [ ] ) ) ; } panelIndexPatterns = uniqBy ( panelIndexPatterns , 'id' ) ; /**
         * If no index patterns have been returned yet, and there is at least one embeddable which
         * hasn't yet loaded, defer the loading of the default index pattern by returning undefined.
         */ if ( panelIndexPatterns . length === 0 && Object . keys ( container . getOutput ( ) . embeddableLoaded ) . length > 0 && Object . values ( container . getOutput ( ) . embeddableLoaded ) . some ( ( value ) => value === false ) ) { return ; } return panelIndexPatterns ; } ) , distinctUntilChanged ( ( a , b ) => deepEqual ( a ?. map ( ( ip ) => ip && ip . id ) , b ?. map ( ( ip ) => ip && ip . id ) ) ) , switchMap ( ( panelIndexPatterns ? ) => { return new Observable ( ( observer ) => { if ( ! panelIndexPatterns ) return ; if ( panelIndexPatterns . length > 0 ) { if ( observer . closed ) return ; onUpdateIndexPatterns ( panelIndexPatterns ) ; observer . complete ( ) ; } else { indexPatterns . getDefault ( ) . then ( ( defaultIndexPattern ) => { if ( observer . closed ) return ; onUpdateIndexPatterns ( [ defaultIndexPattern as IndexPattern ] ) ; observer . complete ( ) ; } ) ; } } ) ; } ) ) ; const indexPatternSources = [ dashboardContainer . getOutput$ ( ) ] ; if ( dashboardContainer . controlGroup ) indexPatternSources . push ( dashboardContainer . controlGroup . getOutput$ ( ) ) ; return combineLatest ( indexPatternSources ) . pipe ( mapTo ( dashboardContainer ) , updateIndexPatternsOperator ) . subscribe ( ) ; } ;