updux/src/Updux.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-08-25 23:43:07 +00:00
import R from 'remeda';
2022-08-26 19:29:24 +00:00
import { action } from './actions.js';
function isActionGen(action) {
return typeof action === "function" && action.type;
}
2022-08-25 23:43:07 +00:00
export class Updux {
#localInitial = {};
#subduxes = {};
2022-08-26 00:06:52 +00:00
#actions;
2022-08-25 23:43:07 +00:00
#mutations = {};
#config = {};
constructor(config = {}) {
this.#config = config;
this.#localInitial = config.initial ?? {};
this.#subduxes = config.subduxes ?? {};
2022-08-26 00:06:52 +00:00
2022-08-26 19:29:24 +00:00
this.#actions = R.mapValues( config.actions ?? {}, (arg,name) =>
isActionGen(arg) ? arg : action(name,arg)
);
2022-08-26 18:41:22 +00:00
Object.entries(this.#subduxes).forEach( ([slice,sub]) => this.#addSubduxActions(slice,sub) )
}
#addSubduxActions(_slice, subdux) {
if( ! subdux.actions ) return;
// TODO action 'blah' defined multiple times: <where>
Object.entries( subdux.actions ).forEach( ([action,gen]) => {
if( this.#actions[action] ) {
if( this.#actions[action] === gen ) return;
throw new Error(`action '${action}' already defined`);
}
this.#actions[action] = gen;
});
2022-08-25 23:43:07 +00:00
}
get actions() {
return this.#actions;
}
get initial() {
if (Object.keys(this.#subduxes).length === 0) return this.#localInitial;
return Object.assign(
{},
this.#localInitial,
R.mapValues(this.#subduxes, ({ initial }) => initial),
);
}
get reducer() {
2022-08-26 00:06:52 +00:00
return (state, action) => this.upreducer(action)(state);
2022-08-25 23:43:07 +00:00
}
get upreducer() {
2022-08-26 00:06:52 +00:00
return (action) => (state) => {
2022-08-25 23:43:07 +00:00
const mutation = this.#mutations[action.type];
2022-08-26 00:06:52 +00:00
if (mutation) {
state = mutation(action.payload, action)(state);
2022-08-25 23:43:07 +00:00
}
return state;
};
}
2022-08-26 00:06:52 +00:00
setMutation(action, mutation) {
this.#mutations[action.type] = mutation;
2022-08-25 23:43:07 +00:00
}
}