import { isEmpty , patchData , patchStep , toggleVisualize } from '@app/helpers' ; import { StepType , TraceStep , VisualizationData } from '@app/models' ; import { createEntityAdapter , EntityAdapter , EntityState } from '@ngrx/entity' ; import { Action , createReducer , on } from '@ngrx/store' ; import { CodeMirrorActions , VisualizationActions } from '../actions' ; const noDataError = 'No visualization data found for this cell' ; const defaultEntity = { cellId : 'id' , step : 0 , maxSteps : 0 , visualize : true , } ; export const stateKey = 'visualizationData' ; export interface State extends EntityState < VisualizationData > { } export const adapter = createEntityAdapter < VisualizationData > ( { selectId : ( d ) => d . cellId , } ) ; export const initialState = adapter . getInitialState ( ) ; function setErrorEntity ( state , id ) { return adapter . setOne ( { ... defaultEntity , cellId : id , error : noDataError } , state ) ; } function setData ( state , data ) { return ! ! data ? adapter . setOne ( data , state ) : state ; } function updateData ( state , id , data ) { const entity = state . entities [ id ] ; return ! ! entity ? adapter . upsertOne ( patchData ( entity , data ) , state ) : state ; } function clearData ( state , id ) { return adapter . setOne ( { ... defaultEntity , cellId : id , visualize : false } , state ) ; } function removeData ( state , ids ) { const idsToRemove = ids . filter ( ( id ) => ! ! state . entities [ id ] ) ; return ! isEmpty ( idsToRemove ) ? adapter . removeMany ( ids , state ) : state ; } function updateStep ( state , id , step ) { const entity = state . entities [ id ] ; return ! ! entity ? adapter . upsertOne ( patchStep ( entity , step ) , state ) : state ; } function updateVisualize ( state , id ) { const entity = state . entities [ id ] ; return ! ! entity ? adapter . upsertOne ( toggleVisualize ( entity ) , state ) : setErrorEntity ( state , id ) ; } const visualizationReducer = createReducer ( initialState , on ( VisualizationActions . addData , ( state , { data } ) => setData ( state , data ) ) , on ( VisualizationActions . updateData , ( state , { id , data } ) => updateData ( state , id , data ) ) , on ( VisualizationActions . removeData , ( state , { ids } ) => removeData ( state , ids ) ) , on ( VisualizationActions . updateStep , ( state , { id , step } ) => updateStep ( state , id , step ) ) , on ( VisualizationActions . toggleVisualize , ( state , { id } ) => updateVisualize ( state , id ) ) , on ( CodeMirrorActions . codeChanged , ( state , { id } ) => clearData ( state , id ) ) ) ; export function reducer ( state , action ) { return visualizationReducer ( state , action ) ; }