/** * External dependencies */ import { keyBy, map, omit, without } from 'lodash'; import type { AnyAction, PostStatus } from '@nelio-content/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 'RESET_STATUSES': return { ...state, statuses: { bySlug: keyBy( action.statuses, 'slug' ), allSlugs: map( action.statuses, 'slug' ), }, }; case 'REORDER_STATUSES': return { ...state, statuses: { bySlug: keyBy( action.slugs.map( ( slug ) => state.statuses.bySlug[ slug ] as PostStatus ), 'slug' ), allSlugs: action.slugs, }, }; case 'MARK_AS_SAVING': return { ...state, saving: action.saving, }; case 'SET_STATUS': { return { ...state, statuses: { bySlug: { ...state.statuses.bySlug, [ action.status.slug ]: { ...action.status, }, }, allSlugs: [ ...( state.statuses.allSlugs.includes( action.status.slug ) ? state.statuses.allSlugs : [ ...state.statuses.allSlugs, action.status.slug, ] ), ], }, }; } case 'REMOVE_STATUS': return { ...state, statuses: { bySlug: omit( state.statuses.bySlug, action.status ), allSlugs: without( state.statuses.allSlugs, action.status ), }, }; case 'OPEN_STATUS_EDITOR': return { ...state, editor: { slug: action.slug, source: action.status, attrs: action.status, isNew: action.isNew, }, }; case 'EDIT_STATUS': { const editor = state.editor; if ( ! editor ) { return state; } return { ...state, editor: { ...editor, attrs: { ...editor.attrs, ...action.status }, }, }; } case 'CLOSE_STATUS_EDITOR': return { ...state, editor: undefined, }; } }