import { mapValues } from 'lodash' ; import React , { createContext , useCallback , useMemo , useRef , useState , } from 'react' ; import { withRouter } from 'react-router-dom' ; import { UxLocalUIFilterName , uxLocalUIFilterNames , } from '../../../common/ux_ui_filter' ; import { pickKeys } from '../../../common/utils/pick_keys' ; import { UxUIFilters } from '../../../typings/ui_filters' ; import { useDeepObjectIdentity } from '../../hooks/useDeepObjectIdentity' ; import { getDateRange } from './helpers' ; import { resolveUrlParams } from './resolve_url_params' ; import { UrlParams } from './types' ; export interface TimeRange { rangeFrom : string ; rangeTo : string ; } function useUxUiFilters ( params ) { const localUiFilters = mapValues ( pickKeys ( params , ... uxLocalUIFilterNames ) , ( val ) => ( val ? val . split ( ',' ) : [ ] ) ) as Partial < Record < UxLocalUIFilterName , string [ ] > > ; return useDeepObjectIdentity ( { environment : params . environment , ... localUiFilters , } ) ; } const defaultRefresh = ( _time ) => { } ; const UrlParamsContext = createContext ( { rangeId : 0 , refreshTimeRange : defaultRefresh , uxUiFilters : { } as UxUIFilters , urlParams : { } as UrlParams , } ) ; const UrlParamsProvider = withRouter ( ( { location , children } ) => { const refUrlParams = useRef ( resolveUrlParams ( location , { } ) ) ; const { start , end , rangeFrom , rangeTo , exactStart , exactEnd } = refUrlParams . current ; const [ rangeId , setRangeId ] = useState ( 0 ) ; const urlParams = useMemo ( ( ) => resolveUrlParams ( location , { start , end , rangeFrom , rangeTo , exactStart , exactEnd , } ) , [ location , start , end , rangeFrom , rangeTo , exactStart , exactEnd ] ) ; refUrlParams . current = urlParams ; const refreshTimeRange = useCallback ( ( timeRange ) => { refUrlParams . current = { ... refUrlParams . current , ... getDateRange ( { state : { } , ... timeRange } ) , } ; setRangeId ( ( prevRangeId ) => prevRangeId + 1 ) ; } , [ ] ) ; const uxUiFilters = useUxUiFilters ( urlParams ) ; const contextValue = useMemo ( ( ) => { return { rangeId , refreshTimeRange , urlParams , uxUiFilters , } ; } , [ rangeId , refreshTimeRange , uxUiFilters , urlParams ] ) ; return ( < UrlParamsContext . Provider children = { children } value = { contextValue } / > ) ; } ) ; export { UrlParamsContext , UrlParamsProvider , useUxUiFilters } ;