UNPKG

awv3

Version:
42 lines (36 loc) 1.49 kB
import omitBy from 'lodash/omitBy'; import isObject from 'lodash/isObject'; import { mixin } from '../lifecycle'; const scope = 'elements'; export const base = mixin(scope, element); export const types = { ...base.types, addChild: `${scope}/addChild`, removeChild: `${scope}/removeChild`, removeAllChilds: `${scope}/removeAllChilds`, event: `${scope}/event` }; export const actions = { ...base.actions, addChild: (id, child) => ({ type: types.addChild, id, child }), removeChild: (id, child) => ({ type: types.removeChild, id, child }), removeAllChilds: id => ({ type: types.removeAllChilds, id }), event: (id, event) => ({ type: types.event, id, event: omitBy(event, isObject) }) }; function element(state, { type, ...payload }) { switch (type) { case types.addChild: return { ...state, children: [...state.children, payload.child] }; case types.removeChild: return { ...state, children: state.children.filter(item => item !== payload.child) }; case types.removeAllChilds: // It's worth optimizing the already-empty case to preserve referential equality // because removeAllChilds is often called idempotently return state.children.length === 0 ? state : { ...state, children: [] }; case types.event: return { ...state, lastEvent: payload.event }; default: return state; } } export const reducer = base.reducer;