/** * External dependencies */ import type { AnyAction } from '@nab/types'; /** * Internal dependencies */ import { INIT_STATE } from './config'; import { EMPTY_ARRAY } from '../constants'; import type { State } from './types'; import type { Action } from './actions'; export default function reducer( 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_POSITION': return { ...state, position: action.position, }; case 'SET_TAB': return { ...state, tab: action.tab, }; case 'SET_STATUS': return { ...state, status: action.status, }; case 'SET_CLOUD_CONNECTION': return { ...state, cloudStatus: action.connected ? 'reachable' : 'unreachable', }; case 'SET_GDPR_STATUS': return { ...state, gdprStatus: action.status, }; case 'ADD_NEW_PAGE': return { ...state, navigation: [ { name: '', url: action.url, date: new Date().toISOString(), events: EMPTY_ARRAY, heatmapClicks: EMPTY_ARRAY, }, ...state.navigation, ], }; case 'SET_PAGE_NAME': { const [ page, ...navigation ] = state.navigation; if ( ! page ) { return state; } return { ...state, navigation: [ { ...page, name: action.name }, ...navigation ], }; } case 'SET_SETTINGS': return { ...state, settings: { ...state.settings, ...action.settings, }, }; case 'SET_ALTERNATIVE': return { ...state, cookies: { ...state.cookies, alternative: action.value, }, newCookies: { ...state.newCookies, alternative: action.value, }, }; case 'SET_SEGMENTATION': return { ...state, cookies: { ...state.cookies, segmentation: action.value, }, newCookies: { ...state.newCookies, segmentation: action.value, }, }; case 'SET_NEW_ALTERNATIVE': return { ...state, newCookies: { ...state.newCookies, alternative: action.value, }, }; case 'SET_NEW_ACTIVE_SEGMENTS': return { ...state, newCookies: { ...state.newCookies, segmentation: { ...state.newCookies.segmentation, activeSegments: { ...state.newCookies.segmentation.activeSegments, [ action.experimentId ]: action.segments, }, }, }, }; case 'SET_VIEWS': return { ...state, cookies: { ...state.cookies, views: action.value, }, }; case 'ADD_VIEW_EVENT': case 'ADD_CONVERSION_EVENT': { const [ page, ...navigation ] = state.navigation; if ( ! page ) { return state; } return { ...state, navigation: [ { ...page, events: [ action.event, ...page.events ] }, ...navigation, ], }; } case 'ADD_CLICK_EVENT': { const [ page, ...navigation ] = state.navigation; if ( ! page ) { return state; } return { ...state, navigation: [ { ...page, heatmapClicks: [ action.event, ...page.heatmapClicks ], }, ...navigation, ], }; } case 'SET_HIGHLIGHTED_CLICK': return { ...state, highlightedClick: action.selector, }; } }