/** * External dependencies */ import { isEqual, keyBy } from 'lodash'; import { EMPTY_OBJECT } from '@nab/utils'; import type { AnyAction } from '@nab/types'; /** * Internal dependencies */ import { INIT_STATE as IS } from '../config'; import type { State as FullState } from '../types'; type State = FullState[ 'experiment' ][ 'scope' ]; import type { ScopeAction } from '../actions/scope'; import type { SetupEditor } from '../actions/editor'; type Action = ScopeAction | SetupEditor; const INIT_STATE = IS.experiment.scope; export function scope( state = INIT_STATE, action: AnyAction ): State { return actualReducer( state, action as Action ) ?? state; } function actualReducer( state: State, action: Action ): State { switch ( action.type ) { case 'SET_SCOPE_RULES': { const newRules = action.rules.map( ( rule ) => state[ rule.id ] && isEqual( state[ rule.id ], rule ) ? state[ rule.id ] : rule ); return keyBy( newRules, 'id' ); } case 'SETUP_EDITOR': { if ( 'nab/heatmap' === action.experiment.type ) { return EMPTY_OBJECT; } const newState = keyBy( action.experiment.scope, 'id' ); return isEqual( newState, state ) ? state : newState; } } }