/** * 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' ][ 'pageViewTriggers' ]; import type { PageViewTriggersAction } from '../actions/page-view-triggers'; import type { SetupEditor } from '../actions/editor'; type Action = PageViewTriggersAction | SetupEditor; const INIT_STATE = IS.experiment.pageViewTriggers; export function pageViewTriggers( 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_PAGE_VIEW_TRIGGERS': return keyBy( action.actions, 'id' ); case 'SETUP_EDITOR': { if ( 'nab/heatmap' === action.experiment.type ) { return EMPTY_OBJECT; } const newActions = keyBy( action.experiment.pageViewTriggers, 'id' ); if ( isEqual( newActions, state.pageViewTriggers ) ) { return state; } return newActions; } } }