letting go of typescript... again
This commit is contained in:
parent
325ad47731
commit
7494fe553e
@ -1,5 +1,4 @@
|
||||
module.exports = {
|
||||
parser: "@typescript-eslint/parser",
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
@ -8,7 +7,7 @@ module.exports = {
|
||||
es6: true,
|
||||
browser: true,
|
||||
},
|
||||
plugins: ['@typescript-eslint','todo-plz', 'no-only-tests'],
|
||||
plugins: ['todo-plz', 'no-only-tests'],
|
||||
overrides: [
|
||||
],
|
||||
rules: {
|
||||
|
@ -2,7 +2,10 @@
|
||||
"type": "module",
|
||||
"types": "./dist/index.d.ts",
|
||||
"dependencies": {
|
||||
"remeda": "^1.0.1"
|
||||
"immer": "^9.0.15",
|
||||
"json-schema-shorthand": "^2.0.0",
|
||||
"remeda": "^1.0.1",
|
||||
"updeep": "^1.2.1"
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
@ -30,14 +33,10 @@
|
||||
},
|
||||
"homepage": "https://github.com/yanick/updux#readme",
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "^5.35.1",
|
||||
"@typescript-eslint/parser": "^5.35.1",
|
||||
"eslint": "^8.22.0",
|
||||
"eslint-plugin-no-only-tests": "^3.0.0",
|
||||
"eslint-plugin-todo-plz": "^1.2.1",
|
||||
"prettier": "^2.7.1",
|
||||
"tsd": "^0.22.0",
|
||||
"typescript": "^4.7.4",
|
||||
"vitest": "^0.22.1"
|
||||
}
|
||||
}
|
||||
|
@ -6,14 +6,20 @@ specifiers:
|
||||
eslint: ^8.22.0
|
||||
eslint-plugin-no-only-tests: ^3.0.0
|
||||
eslint-plugin-todo-plz: ^1.2.1
|
||||
immer: ^9.0.15
|
||||
json-schema-shorthand: ^2.0.0
|
||||
prettier: ^2.7.1
|
||||
remeda: ^1.0.1
|
||||
tsd: ^0.22.0
|
||||
typescript: ^4.7.4
|
||||
updeep: ^1.2.1
|
||||
vitest: ^0.22.1
|
||||
|
||||
dependencies:
|
||||
immer: 9.0.15
|
||||
json-schema-shorthand: 2.0.0
|
||||
remeda: 1.0.1
|
||||
updeep: 1.2.1
|
||||
|
||||
devDependencies:
|
||||
'@typescript-eslint/eslint-plugin': 5.35.1_ktjxjibzrfqejavile4bhmzhjq
|
||||
@ -1069,6 +1075,10 @@ packages:
|
||||
engines: {node: '>= 4'}
|
||||
dev: true
|
||||
|
||||
/immer/9.0.15:
|
||||
resolution: {integrity: sha512-2eB/sswms9AEUSkOm4SbV5Y7Vmt/bKRwByd52jfLkW4OLYeaTP3EEiJ9agqU0O/tq6Dk62Zfj+TJSqfm1rLVGQ==}
|
||||
dev: false
|
||||
|
||||
/import-fresh/3.3.0:
|
||||
resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==}
|
||||
engines: {node: '>=6'}
|
||||
@ -1164,6 +1174,13 @@ packages:
|
||||
resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}
|
||||
dev: true
|
||||
|
||||
/json-schema-shorthand/2.0.0:
|
||||
resolution: {integrity: sha512-tA1EoSDLDdQEv396fLdlzU3WPSVdN2MVMivfNX0Fdm6woEH4mNX3nRGj//wi/VvWDDOpLiN5w9TSlKIXbItiHg==}
|
||||
dependencies:
|
||||
lodash: 4.17.21
|
||||
updeep: 1.2.1
|
||||
dev: false
|
||||
|
||||
/json-schema-traverse/0.4.1:
|
||||
resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}
|
||||
dev: true
|
||||
@ -1212,6 +1229,10 @@ packages:
|
||||
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
|
||||
dev: true
|
||||
|
||||
/lodash/4.17.21:
|
||||
resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
|
||||
dev: false
|
||||
|
||||
/log-symbols/4.1.0:
|
||||
resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==}
|
||||
engines: {node: '>=10'}
|
||||
@ -1757,6 +1778,12 @@ packages:
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/updeep/1.2.1:
|
||||
resolution: {integrity: sha512-cqWsgE1DVNkUeKW+1OfnftBNtSXnxep4aj8GS5oI0dkSfOIU1T6N3vADLhp9EtFPpmmCBHKMQAtsr2b2KY9Lyg==}
|
||||
dependencies:
|
||||
lodash: 4.17.21
|
||||
dev: false
|
||||
|
||||
/uri-js/4.4.1:
|
||||
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
|
||||
dependencies:
|
||||
|
52
src/Updux.js
Normal file
52
src/Updux.js
Normal file
@ -0,0 +1,52 @@
|
||||
import R from 'remeda';
|
||||
|
||||
import { Action, ActionGenerator } from './actions.js';
|
||||
|
||||
export class Updux {
|
||||
#localInitial = {};
|
||||
#subduxes = {};
|
||||
#actions ;
|
||||
#mutations = {};
|
||||
#config = {};
|
||||
|
||||
constructor(config = {}) {
|
||||
this.#config = config;
|
||||
this.#localInitial = config.initial ?? {};
|
||||
this.#subduxes = config.subduxes ?? {};
|
||||
this.#actions = config.actions ?? {};
|
||||
}
|
||||
|
||||
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() {
|
||||
return (state,action) => this.upreducer(action)(state);
|
||||
}
|
||||
|
||||
get upreducer() {
|
||||
return (action) => state => {
|
||||
const mutation = this.#mutations[action.type];
|
||||
|
||||
if( mutation ) {
|
||||
state = mutation(action.payload,action)(state);
|
||||
}
|
||||
|
||||
return state;
|
||||
};
|
||||
}
|
||||
|
||||
setMutation( action, mutation ) {
|
||||
this.#mutations[ action.type ] = mutation;
|
||||
}
|
||||
}
|
@ -1,457 +0,0 @@
|
||||
/* TODO change * for leftovers to +, change subscriptions to reactions */
|
||||
import moize from 'moize';
|
||||
import u from 'updeep';
|
||||
import { createStore as reduxCreateStore, applyMiddleware } from 'redux';
|
||||
import { get, map, mapValues, merge, difference } from 'lodash-es';
|
||||
|
||||
import { buildInitial } from './buildInitial/index.js';
|
||||
import { buildActions } from './buildActions/index.js';
|
||||
import { buildSelectors } from './buildSelectors/index.js';
|
||||
import { action } from './actions.js';
|
||||
import { buildUpreducer } from './buildUpreducer.js';
|
||||
import {
|
||||
buildMiddleware,
|
||||
augmentMiddlewareApi,
|
||||
effectToMiddleware,
|
||||
} from './buildMiddleware/index.js';
|
||||
|
||||
import {
|
||||
AggregateDuxActions,
|
||||
AggregateDuxState,
|
||||
Dict,
|
||||
ItemsOf,
|
||||
Reducer,
|
||||
Upreducer,
|
||||
} from './types.js';
|
||||
|
||||
type Mutation<TState,TAction extends { payload?: any }> = (payload:TAction['payload'], action:TAction) => (state: TState) => TState;
|
||||
|
||||
/**
|
||||
* Configuration object typically passed to the constructor of the class Updux.
|
||||
*/
|
||||
export interface UpduxConfig<
|
||||
TState = any,
|
||||
TActions = {},
|
||||
TSelectors = {},
|
||||
TSubduxes = {}
|
||||
> {
|
||||
/**
|
||||
* Local initial state.
|
||||
* @default {}
|
||||
*/
|
||||
initial?: TState;
|
||||
|
||||
/**
|
||||
* Subduxes to be merged to this dux.
|
||||
*/
|
||||
subduxes?: TSubduxes;
|
||||
|
||||
/**
|
||||
* Local actions.
|
||||
*/
|
||||
actions?: TActions;
|
||||
|
||||
/**
|
||||
* Local selectors.
|
||||
*/
|
||||
selectors?: Record<string, Function>;
|
||||
|
||||
/**
|
||||
* Local mutations
|
||||
*/
|
||||
mutations?: Record<string, Function>;
|
||||
|
||||
/**
|
||||
* Selectors to apply to the mapped subduxes. Only
|
||||
* applicable if the dux is a mapping dux.
|
||||
*/
|
||||
mappedSelectors?: Record<string, Function>;
|
||||
|
||||
/**
|
||||
* Local effects.
|
||||
*/
|
||||
effects?: Record<string, Function>;
|
||||
|
||||
/**
|
||||
* Local reactions.
|
||||
*/
|
||||
reactions?: Function[];
|
||||
|
||||
/**
|
||||
* If true, enables mapped reactions. Additionally, it can be
|
||||
* a reaction function, which will treated as a regular
|
||||
* reaction for the mapped dux.
|
||||
*/
|
||||
mappedReaction?: Function | boolean;
|
||||
|
||||
/**
|
||||
* Wrapping function for the upreducer to provides full customization.
|
||||
* @example
|
||||
* // if an action has the 'dontDoIt' meta flag, don't do anything
|
||||
* const dux = new Updux({
|
||||
* ...,
|
||||
* upreducerWrapper: (upreducer) => action => {
|
||||
* if( action?.meta?.dontDoIt ) return state => state;
|
||||
* return upreducer(action);
|
||||
* }
|
||||
* })
|
||||
*/
|
||||
upreducerWrapper?: (
|
||||
upreducer: Upreducer<
|
||||
AggregateDuxState<TState, TSubduxes>,
|
||||
ItemsOf<AggregateDuxActions<TActions, TSubduxes>>
|
||||
>
|
||||
) => Upreducer<
|
||||
AggregateDuxState<TState, TSubduxes>,
|
||||
ItemsOf<AggregateDuxActions<TActions, TSubduxes>>
|
||||
>;
|
||||
|
||||
middlewareWrapper?: Function;
|
||||
}
|
||||
|
||||
export class Updux<
|
||||
TState extends any = {},
|
||||
TActions extends object = {},
|
||||
TSelectors = {},
|
||||
TSubduxes extends object = {}
|
||||
> {
|
||||
/** @type { unknown } */
|
||||
#initial = {};
|
||||
#subduxes = {};
|
||||
|
||||
/** @type Record<string,Function> */
|
||||
#actions = {};
|
||||
#selectors = {};
|
||||
#mutations = {};
|
||||
#effects = [];
|
||||
#reactions = [];
|
||||
#mappedSelectors = undefined;
|
||||
#mappedReaction = undefined;
|
||||
#upreducerWrapper = undefined;
|
||||
|
||||
#middlewareWrapper = undefined;
|
||||
|
||||
constructor(
|
||||
config: UpduxConfig<TState, TActions, TSelectors, TSubduxes>
|
||||
) {
|
||||
this.#initial = config.initial ?? {};
|
||||
this.#subduxes = config.subduxes ?? {};
|
||||
|
||||
if (config.subduxes) {
|
||||
this.#subduxes = mapValues(config.subduxes, (sub) =>
|
||||
sub instanceof Updux ? sub : new Updux(sub)
|
||||
);
|
||||
}
|
||||
|
||||
if (config.actions) {
|
||||
for (const [type, actionArg] of Object.entries(config.actions)) {
|
||||
if (typeof actionArg === 'function' && actionArg.type) {
|
||||
this.#actions[type] = actionArg;
|
||||
} else {
|
||||
const args = Array.isArray(actionArg)
|
||||
? actionArg
|
||||
: [actionArg];
|
||||
this.#actions[type] = action(type, ...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.#selectors = config.selectors ?? {};
|
||||
this.#mappedSelectors = config.mappedSelectors;
|
||||
|
||||
this.#mutations = config.mutations ?? {};
|
||||
|
||||
Object.keys(this.#mutations)
|
||||
.filter((action) => action !== '+')
|
||||
.filter((action) => !this.actions.hasOwnProperty(action))
|
||||
.forEach((action) => {
|
||||
throw new Error(`action '${action}' is not defined`);
|
||||
});
|
||||
|
||||
if (config.effects) {
|
||||
this.#effects = Object.entries(config.effects);
|
||||
}
|
||||
|
||||
this.#reactions = config.reactions ?? [];
|
||||
|
||||
this.#mappedReaction = config.mappedReaction;
|
||||
|
||||
this.#upreducerWrapper = config.upreducerWrapper;
|
||||
|
||||
this.#middlewareWrapper = config.middlewareWrapper;
|
||||
}
|
||||
|
||||
#memoInitial = moize(buildInitial);
|
||||
#memoActions = moize(buildActions);
|
||||
#memoSelectors = moize(buildSelectors);
|
||||
#memoUpreducer = moize(buildUpreducer);
|
||||
#memoMiddleware = moize(buildMiddleware);
|
||||
|
||||
setMappedSelector(name, f) {
|
||||
this.#mappedSelectors = {
|
||||
...this.#mappedSelectors,
|
||||
[name]: f,
|
||||
};
|
||||
}
|
||||
|
||||
get middleware() {
|
||||
return this.#memoMiddleware(
|
||||
this.#effects,
|
||||
this.actions,
|
||||
this.selectors,
|
||||
this.#subduxes,
|
||||
this.#middlewareWrapper,
|
||||
this
|
||||
);
|
||||
}
|
||||
|
||||
setMiddlewareWrapper(wrapper: Function) {
|
||||
this.#middlewareWrapper = wrapper;
|
||||
}
|
||||
|
||||
/** @member { unknown } */
|
||||
get initial(): AggregateDuxState<TState, TSubduxes> {
|
||||
return this.#memoInitial(this.#initial, this.#subduxes);
|
||||
}
|
||||
|
||||
get actions(): AggregateDuxActions<TActions, TSubduxes> {
|
||||
return this.#memoActions(this.#actions, this.#subduxes) as any;
|
||||
}
|
||||
|
||||
get selectors() {
|
||||
return this.#memoSelectors(
|
||||
this.#selectors,
|
||||
this.#mappedSelectors,
|
||||
this.#subduxes
|
||||
);
|
||||
}
|
||||
|
||||
get subduxes() { return this.#subduxes }
|
||||
|
||||
get upreducer(): Upreducer<
|
||||
AggregateDuxState<TState, TSubduxes>,
|
||||
ItemsOf<AggregateDuxActions<TActions, TSubduxes>>
|
||||
> {
|
||||
return this.#memoUpreducer(
|
||||
this.initial,
|
||||
this.#mutations,
|
||||
this.#subduxes,
|
||||
this.#upreducerWrapper
|
||||
);
|
||||
}
|
||||
|
||||
get reducer(): Reducer<
|
||||
AggregateDuxState<TState, TSubduxes>,
|
||||
ItemsOf<AggregateDuxActions<TActions, TSubduxes>>
|
||||
> {
|
||||
return (state, action) => this.upreducer(action)(state);
|
||||
}
|
||||
|
||||
addSubscription(subscription) {
|
||||
this.#reactions = [...this.#reactions, subscription];
|
||||
}
|
||||
|
||||
addReaction(reaction) {
|
||||
this.#reactions = [...this.#reactions, reaction];
|
||||
}
|
||||
|
||||
|
||||
setAction(type, payloadFunc?: (...args: any) => any) {
|
||||
const theAction = action(type, payloadFunc);
|
||||
|
||||
this.#actions = { ...this.#actions, [type]: theAction };
|
||||
|
||||
return theAction;
|
||||
}
|
||||
|
||||
setSelector(name, func) {
|
||||
// TODO selector already exists? Complain!
|
||||
this.#selectors = {
|
||||
...this.#selectors,
|
||||
[name]: func,
|
||||
};
|
||||
return func;
|
||||
}
|
||||
|
||||
setMutation<TAction extends keyof AggregateDuxActions<TActions,TSubduxes>>(name: TAction, mutation: Mutation<AggregateDuxState<TState, TSubduxes>,
|
||||
ReturnType<AggregateDuxActions<TActions,TSubduxes>[TAction]>>) {
|
||||
if (typeof name === 'function') name = name.type;
|
||||
|
||||
this.#mutations = {
|
||||
...this.#mutations,
|
||||
[name]: mutation,
|
||||
};
|
||||
|
||||
return mutation;
|
||||
}
|
||||
|
||||
addEffect<TType, E>(action: TType, effect: E): E {
|
||||
this.#effects = [...this.#effects, [action, effect]];
|
||||
return effect;
|
||||
}
|
||||
|
||||
augmentMiddlewareApi(api) {
|
||||
return augmentMiddlewareApi(api, this.actions, this.selectors);
|
||||
}
|
||||
|
||||
splatSubscriber(store, inner, splatReaction) {
|
||||
const cache = {};
|
||||
|
||||
return () => (state, previous, unsub) => {
|
||||
const cacheKeys = Object.keys(cache);
|
||||
|
||||
const newKeys = difference(Object.keys(state), cacheKeys);
|
||||
|
||||
for (const slice of newKeys) {
|
||||
let localStore = {
|
||||
...store,
|
||||
getState: () => store.getState()[slice],
|
||||
};
|
||||
|
||||
cache[slice] = [];
|
||||
|
||||
if (typeof splatReaction === 'function') {
|
||||
localStore = {
|
||||
...localStore,
|
||||
...splatReaction(localStore, slice),
|
||||
};
|
||||
}
|
||||
|
||||
const { unsub, subscriber, subscriberRaw } =
|
||||
inner.subscribeAll(localStore);
|
||||
|
||||
cache[slice].push({ unsub, subscriber, subscriberRaw });
|
||||
subscriber();
|
||||
}
|
||||
|
||||
const deletedKeys = difference(cacheKeys, Object.keys(state));
|
||||
|
||||
for (const deleted of deletedKeys) {
|
||||
for (const inner of cache[deleted]) {
|
||||
inner.subscriber();
|
||||
inner.unsub();
|
||||
}
|
||||
delete cache[deleted];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
subscribeTo(store, subscription, setupArgs = []) {
|
||||
const localStore = augmentMiddlewareApi(
|
||||
{
|
||||
...store,
|
||||
subscribe: (subscriber) =>
|
||||
this.subscribeTo(store, () => subscriber),
|
||||
},
|
||||
this.actions,
|
||||
this.selectors
|
||||
);
|
||||
|
||||
const subscriber = subscription(localStore, ...setupArgs);
|
||||
|
||||
let previous;
|
||||
|
||||
const memoSub = () => {
|
||||
const state = store.getState();
|
||||
if (state === previous) return;
|
||||
let p = previous;
|
||||
previous = state;
|
||||
subscriber(state, p, unsub);
|
||||
};
|
||||
|
||||
let ret = store.subscribe(memoSub);
|
||||
const unsub = typeof ret === 'function' ? ret : ret.unsub;
|
||||
return {
|
||||
unsub,
|
||||
subscriber: memoSub,
|
||||
subscriberRaw: subscriber,
|
||||
};
|
||||
}
|
||||
|
||||
subscribeAll(store) {
|
||||
let results = this.#reactions.map((sub) =>
|
||||
this.subscribeTo(store, sub)
|
||||
);
|
||||
|
||||
for (const subdux in this.#subduxes) {
|
||||
if (subdux !== '*') {
|
||||
const localStore = {
|
||||
...store,
|
||||
getState: () => get(store.getState(), subdux),
|
||||
};
|
||||
results.push(this.#subduxes[subdux].subscribeAll(localStore));
|
||||
}
|
||||
}
|
||||
|
||||
if (this.#mappedReaction) {
|
||||
results.push(
|
||||
this.subscribeTo(
|
||||
store,
|
||||
this.splatSubscriber(
|
||||
store,
|
||||
this.#subduxes['*'],
|
||||
this.#mappedReaction
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
unsub: () => results.forEach(({ unsub }) => unsub()),
|
||||
subscriber: () =>
|
||||
results.forEach(({ subscriber }) => subscriber()),
|
||||
subscriberRaw: (...args) =>
|
||||
results.forEach(({ subscriberRaw }) =>
|
||||
subscriberRaw(...args)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
createStore(initial?: unknown, enhancerGenerator?: Function) {
|
||||
const enhancer = (enhancerGenerator ?? applyMiddleware)(
|
||||
this.middleware
|
||||
);
|
||||
|
||||
const store: {
|
||||
getState: Function & Record<string, Function>;
|
||||
dispatch: Function & Record<string, Function>;
|
||||
selectors: Record<string, Function>;
|
||||
actions: AggregateDuxActions<TActions, TSubduxes>;
|
||||
} = reduxCreateStore(
|
||||
this.reducer as any,
|
||||
initial ?? this.initial,
|
||||
enhancer
|
||||
) as any;
|
||||
|
||||
store.actions = this.actions;
|
||||
|
||||
store.selectors = this.selectors;
|
||||
|
||||
merge(
|
||||
store.getState,
|
||||
mapValues(this.selectors, (selector) => {
|
||||
return (...args) => {
|
||||
let result = selector(store.getState());
|
||||
|
||||
if (typeof result === 'function') return result(...args);
|
||||
|
||||
return result;
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
for (const action in this.actions) {
|
||||
store.dispatch[action] = (...args) => {
|
||||
return store.dispatch(this.actions[action](...(args as any)));
|
||||
};
|
||||
}
|
||||
|
||||
this.subscribeAll(store);
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
effectToMiddleware(effect) {
|
||||
return effectToMiddleware(effect, this.actions, this.selectors);
|
||||
}
|
||||
}
|
43
src/Updux.ts
43
src/Updux.ts
@ -1,43 +0,0 @@
|
||||
import R from 'remeda';
|
||||
|
||||
import { DuxAggregateState, UpduxConfig } from './types';
|
||||
import { Action, ActionGenerator } from './actions.js';
|
||||
|
||||
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(): ( state: DuxAggregateState<TState,TSubduxes>, action: Action ) => DuxAggregateState<TState,TSubduxes> {
|
||||
return (state,action) => this.upreducer(action)(state);
|
||||
}
|
||||
|
||||
get upreducer(): (action: Action) => (state: DuxAggregateState<TState,TSubduxes>) => DuxAggregateState<TState,TSubduxes> {
|
||||
return (action) => state => state;
|
||||
}
|
||||
}
|
26
src/actions.js
Normal file
26
src/actions.js
Normal file
@ -0,0 +1,26 @@
|
||||
export function action(
|
||||
type,
|
||||
payloadFunction,
|
||||
transformer,
|
||||
) {
|
||||
let generator = function (...payloadArg) {
|
||||
const result = { type };
|
||||
|
||||
if (payloadFunction) {
|
||||
result.payload = payloadFunction(...payloadArg);
|
||||
} else {
|
||||
if (payloadArg[0] !== undefined) result.payload = payloadArg[0];
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
if (transformer) {
|
||||
const orig = generator;
|
||||
generator = (...args) => transformer(orig(...args), args);
|
||||
}
|
||||
|
||||
generator.type = type;
|
||||
|
||||
return generator;
|
||||
}
|
@ -5,7 +5,7 @@ import { action } from './actions.js';
|
||||
import { Updux } from './Updux.js';
|
||||
|
||||
test('basic action', () => {
|
||||
const foo = action('foo', (thing: string) => ({ thing }));
|
||||
const foo = action('foo', (thing) => ({ thing }));
|
||||
|
||||
expect(foo('bar')).toEqual({
|
||||
type: 'foo',
|
||||
@ -18,7 +18,7 @@ test('basic action', () => {
|
||||
test( "Updux config accepts actions", () => {
|
||||
const foo = new Updux({
|
||||
actions: {
|
||||
one: action('one', (x: string) => ({x})),
|
||||
one: action('one', (x) => ({x})),
|
||||
two: action('two', x => x),
|
||||
}
|
||||
});
|
@ -1,51 +0,0 @@
|
||||
export type Action<T extends string = string, TPayload = any> = {
|
||||
type: T;
|
||||
meta?: Record<string, unknown>;
|
||||
payload?: TPayload;
|
||||
};
|
||||
|
||||
export type ActionGenerator<
|
||||
TType extends string = string,
|
||||
TPayloadGen = (...args: any[]) => any,
|
||||
> = {
|
||||
type: TType;
|
||||
} & (TPayloadGen extends (...args: any) => any
|
||||
? ReturnType<TPayloadGen> extends void
|
||||
? (...args: Parameters<TPayloadGen>) => {
|
||||
type: TType;
|
||||
}
|
||||
: (...args: Parameters<TPayloadGen>) => {
|
||||
type: TType;
|
||||
payload: ReturnType<TPayloadGen>;
|
||||
}
|
||||
: (...args: any[]) => { type: TType; payload?: unknown });
|
||||
|
||||
export function action<
|
||||
TType extends string,
|
||||
TPayload extends (...args: any) => any,
|
||||
>(
|
||||
type: TType,
|
||||
payloadFunction?: TPayload,
|
||||
transformer?: Function,
|
||||
): ActionGenerator<TType, TPayload> {
|
||||
let generator: any = function (...payloadArg:any[]) {
|
||||
const result: Action = { type };
|
||||
|
||||
if (payloadFunction) {
|
||||
result.payload = payloadFunction(...payloadArg);
|
||||
} else {
|
||||
if (payloadArg[0] !== undefined) result.payload = payloadArg[0];
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
if (transformer) {
|
||||
const orig = generator;
|
||||
generator = (...args: any) => transformer(orig(...args), args);
|
||||
}
|
||||
|
||||
generator.type = type;
|
||||
|
||||
return generator;
|
||||
}
|
30
src/mutations.test.js
Normal file
30
src/mutations.test.js
Normal file
@ -0,0 +1,30 @@
|
||||
import { test, expect } from 'vitest';
|
||||
import schema from 'json-schema-shorthand';
|
||||
import u from 'updeep';
|
||||
|
||||
import { action } from './actions.js';
|
||||
|
||||
import { Updux } from './Updux.js';
|
||||
|
||||
test('set a mutation', () => {
|
||||
const dux = new Updux({
|
||||
initial: {
|
||||
x: "potato",
|
||||
},
|
||||
actions: {
|
||||
foo: action('foo', (x) => ({x})),
|
||||
bar: action('bar'),
|
||||
}
|
||||
});
|
||||
|
||||
dux.setMutation( dux.actions.foo, (payload,action) => u({
|
||||
x: payload.x + action.type
|
||||
}) );
|
||||
|
||||
const result = dux.reducer(undefined,dux.actions.foo("hello "));
|
||||
expect( result ).toEqual({
|
||||
x: "hello foo"
|
||||
})
|
||||
|
||||
|
||||
});
|
28
src/types.ts
28
src/types.ts
@ -1,28 +0,0 @@
|
||||
import { ActionGenerator } from "./actions.js";
|
||||
|
||||
/**
|
||||
* 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]> };
|
||||
|
||||
export type DuxAggregateState<TState,TSubduxes> = TState & DuxStateSubduxes<TSubduxes> ;
|
||||
|
105
tsconfig.json
105
tsconfig.json
@ -1,105 +0,0 @@
|
||||
{
|
||||
"include": ["./src"],
|
||||
"exclude": ["./docs", "./dist"],
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs" /* Specify what module code is generated. */,
|
||||
// "rootDir": "./src", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */,
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true /* Enable all strict type-checking options. */,
|
||||
"noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user