/** * External dependencies */ import { isEqual } from 'lodash'; import type { AnyAction } from '@nab/types'; /** * Internal dependencies */ import { INIT_STATE } from './config'; import type { State } from './types'; import type { Action } from './actions'; export 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_FIELD_VALUE': { const value = state.values[ action.field ]; if ( isEqual( value, action.value ) ) { return state; } return { ...state, values: { ...state.values, [ action.field ]: action.value, }, }; } case 'SET_FIELD_ATTRIBUTES': { const attributes = state.attributes[ action.field ]; const newAttributes = { ...attributes, ...action.attributes, }; if ( isEqual( attributes, newAttributes ) ) { return state; } return { ...state, attributes: { ...state.attributes, [ action.field ]: newAttributes, }, }; } } }