import { isFunction , omitBy , union } from 'lodash' ; import { migrateAppState } from './migrate_app_state' ; import { createStateContainer , syncState , IOsdUrlStateStorage , } from '../../../../opensearch_dashboards_utils/public' ; import { PureVisState , VisualizeAppState , VisualizeAppStateTransitions } from '../types' ; const STATE_STORAGE_KEY = '_a' ; interface Arguments { osdUrlStateStorage : IOsdUrlStateStorage ; stateDefaults : VisualizeAppState ; byValue ? : boolean ; } function toObject ( state ) { return omitBy ( state , ( value , key ) => { return key . charAt ( 0 ) === '$' || key . charAt ( 0 ) === '_' || isFunction ( value ) ; } ) as PureVisState ; } const pureTransitions = { set : ( state ) => ( prop , value ) => ( { ... state , [ prop ] : value } ) , setVis : ( state ) => ( vis ) => ( { ... state , vis : { ... state . vis , ... vis , } , } ) , unlinkSavedSearch : ( state ) => ( { query , parentFilters = [ ] } ) => ( { ... state , query : query || state . query , filters : union ( state . filters , parentFilters ) , linked : false , } ) , updateVisState : ( state ) => ( newVisState ) => ( { ... state , vis : toObject ( newVisState ) } ) , updateSavedQuery : ( state ) => ( savedQueryId ) => { const updatedState = { ... state , savedQuery : savedQueryId , } ; if ( ! savedQueryId ) { delete updatedState . savedQuery ; } return updatedState ; } , } as VisualizeAppStateTransitions ; function createVisualizeByValueAppState ( stateDefaults ) { const initialState = migrateAppState ( { ... stateDefaults , ... stateDefaults , } ) ; const stateContainer = createStateContainer < VisualizeAppState , VisualizeAppStateTransitions > ( initialState , pureTransitions ) ; const stopStateSync = ( ) => { } ; return { stateContainer , stopStateSync } ; } function createDefaultVisualizeAppState ( { stateDefaults , osdUrlStateStorage } ) { const urlState = osdUrlStateStorage . get < VisualizeAppState > ( STATE_STORAGE_KEY ) ; const initialState = migrateAppState ( { ... stateDefaults , ... urlState , } ) ; osdUrlStateStorage . set ( STATE_STORAGE_KEY , initialState , { replace : true } ) ; const stateContainer = createStateContainer < VisualizeAppState , VisualizeAppStateTransitions > ( initialState , pureTransitions ) ; const { start : startStateSync , stop : stopStateSync } = syncState ( { storageKey : STATE_STORAGE_KEY , stateContainer : { ... stateContainer , set : ( state ) => { if ( state ) { stateContainer . set ( state ) ; } } , } , stateStorage : osdUrlStateStorage , } ) ; startStateSync ( ) ; return { stateContainer , stopStateSync } ; } export function createVisualizeAppState ( { stateDefaults , osdUrlStateStorage , byValue } ) { if ( byValue ) { return createVisualizeByValueAppState ( stateDefaults ) ; } return createDefaultVisualizeAppState ( { stateDefaults , osdUrlStateStorage } ) ; }