awv3
Version:
⚡ AWV3 embedded CAD
42 lines (36 loc) • 1.6 kB
JavaScript
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, from = 'children') => ({ type: types.addChild, id, child, from }),
removeChild: (id, child, from = 'children') => ({ type: types.removeChild, id, child, from }),
removeAllChilds: (id, from = 'children') => ({ type: types.removeAllChilds, id, from }),
event: (id, event) => ({ type: types.event, id, event: omitBy(event, isObject) })
};
function element(state, { type, ...payload }) {
switch (type) {
case types.addChild:
return { ...state, [payload.from]: [...state[payload.from], payload.child] };
case types.removeChild:
return { ...state, [payload.from]: state[payload.from].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[payload.from].length === 0 ? state : { ...state, [payload.from]: [] };
case types.event:
return { ...state, lastEvent: payload.event };
default:
return state;
}
}
export const reducer = base.reducer;