60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
import R from 'remeda';
|
|
import { Action, ActionGenerator } from './actions';
|
|
|
|
/**
|
|
* Configuration object typically passed to the constructor of the class Updux.
|
|
*/
|
|
export interface UpduxConfig<TState = any, TActions extends Record<string,ActionGenerator> = Record<string,ActionGenerator>, TSubduxes = {}> {
|
|
/**
|
|
* Local initial state.
|
|
* @default {}
|
|
*/
|
|
initial?: TState;
|
|
|
|
actions?: TActions;
|
|
|
|
/**
|
|
* Subduxes to be merged to this dux.
|
|
*/
|
|
subduxes?: TSubduxes;
|
|
}
|
|
|
|
type StateOf<D> = D extends { initial: infer I } ? I : unknown;
|
|
|
|
export type DuxStateSubduxes<C extends {}> = keyof C extends never
|
|
? unknown
|
|
: { [K in keyof C]: StateOf<C[K]> };
|
|
|
|
type DuxAggregateState<TState,TSubduxes> = TState & DuxStateSubduxes<TSubduxes> ;
|
|
|
|
export class Updux<TState extends any = {}, TActions extends { [key: string]: ActionGenerator } = {}, TSubduxes = {}> {
|
|
#localInitial: any = {};
|
|
#subduxes;
|
|
#actions : TActions;
|
|
|
|
constructor(config: UpduxConfig<TState, TActions, TSubduxes>) {
|
|
this.#localInitial = config.initial ?? {};
|
|
this.#subduxes = config.subduxes ?? {};
|
|
|
|
this.#actions = config.actions ?? ([] as any);
|
|
}
|
|
|
|
get actions() {
|
|
return this.#actions;
|
|
}
|
|
|
|
get initial(): DuxAggregateState<TState,TSubduxes>{
|
|
if (Object.keys(this.#subduxes).length === 0) return this.#localInitial;
|
|
|
|
return Object.assign(
|
|
{},
|
|
this.#localInitial,
|
|
R.mapValues(this.#subduxes, ({ initial }) => initial),
|
|
);
|
|
}
|
|
|
|
get reducer() {
|
|
return (state : DuxAggregateState<TState,TSubduxes>, _action : any) => state;
|
|
}
|
|
}
|