import { i18n } from '@osd/i18n' ; import { toMountPoint } from '../../../opensearch_dashboards_react/public' ; import { ActionByType , createAction , IncompatibleActionError } from '../../../ui_actions/public' ; import { getOverlays , getIndexPatterns } from '../services' ; import { applyFiltersPopover } from '../ui/apply_filters' ; import type { IEmbeddable } from '../../../embeddable/public' ; import { Filter , FilterManager , TimefilterContract , opensearchFilters } from '..' ; export const ACTION_GLOBAL_APPLY_FILTER = 'ACTION_GLOBAL_APPLY_FILTER' ; export interface ApplyGlobalFilterActionContext { filters : Filter [ ] ; timeFieldName ? : string ; embeddable ? : IEmbeddable ; } async function isCompatible ( context ) { return context . filters !== undefined ; } export function createFilterAction ( filterManager , timeFilter ) { return createAction < typeof ACTION_GLOBAL_APPLY_FILTER > ( { type : ACTION_GLOBAL_APPLY_FILTER , id : ACTION_GLOBAL_APPLY_FILTER , order : 100 , getIconType : ( ) => 'filter' , getDisplayName : ( ) => { return i18n . translate ( 'data.filter.applyFilterActionTitle' , { defaultMessage : 'Apply filter to current view' , } ) ; } , isCompatible , execute : async ( { filters , timeFieldName } ) => { if ( ! filters ) { throw new Error ( 'Applying a filter requires a filter' ) ; } if ( ! ( await isCompatible ( { filters } ) ) ) { throw new IncompatibleActionError ( ) ; } let selectedFilters = filters ; if ( selectedFilters . length > 1 ) { const indexPatterns = await Promise . all ( filters . map ( ( filter ) => { return getIndexPatterns ( ) . get ( filter . meta . index ! ) ; } ) ) ; const filterSelectionPromise = new Promise ( ( resolve ) => { const overlay = getOverlays ( ) . openModal ( toMountPoint ( applyFiltersPopover ( filters , indexPatterns , ( ) => { overlay . close ( ) ; resolve ( [ ] ) ; } , ( filterSelection ) => { overlay . close ( ) ; resolve ( filterSelection ) ; } ) ) , { 'data-test-subj' : 'test' , } ) ; } ) ; selectedFilters = await filterSelectionPromise ; } if ( timeFieldName ) { const { timeRangeFilter , restOfFilters } = opensearchFilters . extractTimeFilter ( timeFieldName , selectedFilters ) ; filterManager . addFilters ( restOfFilters ) ; if ( timeRangeFilter ) { opensearchFilters . changeTimeFilter ( timeFilter , timeRangeFilter ) ; } } else { filterManager . addFilters ( selectedFilters ) ; } } , } ) ; }