From 702a3e76d4d59fa98ce473a4d33bb15e119f29f8 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Tue, 30 Aug 2022 14:13:59 -0400 Subject: [PATCH 1/4] add reactions to the updux --- src/Updux.js | 68 +++++++++++++++++++++++++++++++++++++++++-- src/reactions.test.js | 50 +++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 src/reactions.test.js diff --git a/src/Updux.js b/src/Updux.js index 1a84745..18bdd7d 100644 --- a/src/Updux.js +++ b/src/Updux.js @@ -4,7 +4,7 @@ import { createStore as reduxCreateStore, applyMiddleware } from 'redux'; import { buildSelectors } from './selectors.js'; import { buildUpreducer } from './upreducer.js'; -import { buildMiddleware } from './middleware.js'; +import { buildMiddleware, augmentMiddlewareApi } from './middleware.js'; import { action, isActionGen } from './actions.js'; /** @@ -21,6 +21,7 @@ export class Updux { #config = {}; #selectors = {}; #effects = []; + #localReactions = []; constructor(config = {}) { this.#config = config; @@ -49,6 +50,8 @@ export class Updux { } else if (R.isObject(config.effects)) { this.#effects = Object.entries(config.effects); } + + this.#localReactions = config.reactions ?? []; } #addSubduxActions(_slice, subdux) { @@ -171,7 +174,7 @@ export class Updux { }; } - //this.subscribeAll(store); + this.subscribeAll(store); return store; } @@ -179,6 +182,67 @@ export class Updux { addEffect(action, effect) { this.#effects = [...this.#effects, [action, effect]]; } + + addReaction( reaction ) { + this.#localReactions = [ ...this.#localReactions, reaction ] + } + + subscribeTo(store, subscription) { + const localStore = augmentMiddlewareApi( + { + ...store, + subscribe: (subscriber) => + this.subscribeTo(store, subscriber), // TODO not sure + }, + this.actions, + this.selectors + ); + + const subscriber = subscription(localStore); + + 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, + subscriberMemoized: memoSub, + subscriber, + }; + } + + subscribeAll(store) { + let results = this.#localReactions.map((sub) => + this.subscribeTo(store, sub) + ); + + for (const subdux in this.#subduxes) { + if (subdux !== '*') { + const localStore = { + ...store, + getState: () => store.getState()[subdux], + }; + results.push(this.#subduxes[subdux].subscribeAll(localStore)); + } + } + + return { + unsub: () => results.forEach(({ unsub }) => unsub()), + subscriberMemoized: () => + results.forEach(({ subscriberMemoized}) => subscriberMemoized()), + subscriber: () => + results.forEach(({ subscriber }) => subscriber() + ), + }; + } } export const dux = (config) => new Updux(config); diff --git a/src/reactions.test.js b/src/reactions.test.js new file mode 100644 index 0000000..225b2c7 --- /dev/null +++ b/src/reactions.test.js @@ -0,0 +1,50 @@ +import { test, expect, vi } from 'vitest'; + +import { Updux } from './Updux.js'; + +test('basic reactions', async () => { + const spyA = vi.fn(); + const spyB = vi.fn(); + const foo = new Updux({ + initial: { i: 0 }, + reactions: [() => spyA], + actions: { inc: null }, + mutations: { + inc: () => (state) => ({ ...state, i: state.i + 1 }), + }, + }); + + foo.addReaction((api) => spyB); + + const store = foo.createStore(); + store.dispatch.inc(); + + expect(spyA).toHaveBeenCalledOnce(); + expect(spyB).toHaveBeenCalledOnce(); +}); + +test('subduxes reactions', async () => { + const spyA = vi.fn(); + const spyB = vi.fn(); + const foo = new Updux({ + subduxes: { + a: new Updux({ + initial: 1, + reactions: [() => state => spyA(state)], + actions: { inc: null }, + mutations: { + inc: () => (state) => state + 1, + }, + }), + b: new Updux({ initial: 10, reactions: [() => spyB] }), + }, + }); + + const store = foo.createStore(); + store.dispatch.inc(); + store.dispatch.inc(); + + expect(spyA).toHaveBeenCalledTimes(2); + expect(spyA).toHaveBeenCalledWith(3) + expect(spyB).toHaveBeenCalledOnce(); // the original inc initialized the state +}); From fbe624a14ccd21bafcfdbeb6e3e2e737dedf7475 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Tue, 30 Aug 2022 14:15:47 -0400 Subject: [PATCH 2/4] add reactions to the tutorial --- docs/tutorial-reactions.test.js | 40 +++++++++++++++++++++++++++ docs/tutorial.md | 48 +++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 docs/tutorial-reactions.test.js diff --git a/docs/tutorial-reactions.test.js b/docs/tutorial-reactions.test.js new file mode 100644 index 0000000..d32f924 --- /dev/null +++ b/docs/tutorial-reactions.test.js @@ -0,0 +1,40 @@ +import { test, expect } from 'vitest'; +import u from 'updeep'; + +import { Updux } from '../src/index.js'; + +const todos = new Updux({ + initial: [], + actions: { + setNbrTodos: null, + addTodo: null, + }, + mutations: { + addTodo: todo => todos => [ ...todos, todo ], + }, + reactions: [ + ({dispatch}) => todos => dispatch.setNbrTodos(todos.length) + ], +}); + +const myDux = new Updux({ + initial: { + nbrTodos: 0 + }, + subduxes: { + todos, + }, + mutations: { + setNbrTodos: nbrTodos => u({ nbrTodos }) + } +}) + +test( "basic tests", async () => { + const store = myDux.createStore(); + + store.dispatch.addTodo('one'); + store.dispatch.addTodo('two'); + + expect(store.getState().nbrTodos).toEqual(2); +}); + diff --git a/docs/tutorial.md b/docs/tutorial.md index 6626941..e3d48e6 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -352,5 +352,53 @@ Note that the `getNextId` selector still gets the right value; when aggregating subduxes selectors Updux auto-wraps them to access the right slice of the top object. ``` +## Reactions + +Reactions -- aka Redux's subscriptions -- can be added to a updux store via the initial config +or the method `addSubscription`. The signature of a reaction is: + +``` +(storeApi) => (state, previousState, unsubscribe) => { + ... +} +``` + +Subscriptions registered for an updux and its subduxes are automatically +subscribed to the store when calling `createStore`. + +The `state` passed to the subscriptions of the subduxes is the local state. + +Also, all subscriptions are wrapped such that they are called only if the +local `state` changed since their last invocation. + +Example: + +``` +const todos = new Updux({ + initial: [], + actions: { + setNbrTodos: null, + } + reactions: [ + ({dispatch}) => todos => dispatch.setNbrTodos(todos.length); + ], +}); + +const myDux = new Updux({ + initial: { + nbr_todos: 0 + }, + subduxes: { + todos, + }, + mutations: { + setNbrTodos: nbrTodos => u({ nbrTodos }) + } +}) +``` + +[immer]: https://www.npmjs.com/package/immer +[lodash]: https://www.npmjs.com/package/lodash +[ts-action]: https://www.npmjs.com/package/ts-action From 16397ce3ee32d5f27417aa6661eb786b01eb3bbb Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Tue, 30 Aug 2022 14:16:29 -0400 Subject: [PATCH 3/4] prettier --- Taskfile.yaml | 6 +++--- src/Updux.js | 24 ++++++++++++------------ src/initial.test.js | 12 +++++++----- src/reactions.test.js | 4 ++-- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index c0dbd7b..e97b9a2 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -24,15 +24,15 @@ tasks: lint:delta: cmds: - - task: 'lint:prettier:delta' - - task: 'lint:eslint:delta' + - task: 'lint:prettier:delta' + - task: 'lint:eslint:delta' lint:prettier:delta: vars: FILES: sh: git diff-ls --diff-filter=d {{.ROOT_BRANCH | default "main"}} | grep -v .vitebook cmds: - - npx prettier --check {{.FILES | catLines }} + - npx prettier --check {{.FILES | catLines }} lint:eslint:delta: vars: diff --git a/src/Updux.js b/src/Updux.js index 18bdd7d..b32af1d 100644 --- a/src/Updux.js +++ b/src/Updux.js @@ -76,10 +76,11 @@ export class Updux { } get initial() { - if (Object.keys(this.#subduxes).length === 0) return this.#localInitial ?? {}; + if (Object.keys(this.#subduxes).length === 0) + return this.#localInitial ?? {}; - if( this.#subduxes['*'] ) { - if( this.#localInitial ) return this.#localInitial; + if (this.#subduxes['*']) { + if (this.#localInitial) return this.#localInitial; return []; } @@ -183,19 +184,18 @@ export class Updux { this.#effects = [...this.#effects, [action, effect]]; } - addReaction( reaction ) { - this.#localReactions = [ ...this.#localReactions, reaction ] + addReaction(reaction) { + this.#localReactions = [...this.#localReactions, reaction]; } subscribeTo(store, subscription) { const localStore = augmentMiddlewareApi( { ...store, - subscribe: (subscriber) => - this.subscribeTo(store, subscriber), // TODO not sure + subscribe: (subscriber) => this.subscribeTo(store, subscriber), // TODO not sure }, this.actions, - this.selectors + this.selectors, ); const subscriber = subscription(localStore); @@ -221,7 +221,7 @@ export class Updux { subscribeAll(store) { let results = this.#localReactions.map((sub) => - this.subscribeTo(store, sub) + this.subscribeTo(store, sub), ); for (const subdux in this.#subduxes) { @@ -237,10 +237,10 @@ export class Updux { return { unsub: () => results.forEach(({ unsub }) => unsub()), subscriberMemoized: () => - results.forEach(({ subscriberMemoized}) => subscriberMemoized()), - subscriber: () => - results.forEach(({ subscriber }) => subscriber() + results.forEach(({ subscriberMemoized }) => + subscriberMemoized(), ), + subscriber: () => results.forEach(({ subscriber }) => subscriber()), }; } } diff --git a/src/initial.test.js b/src/initial.test.js index abbfd50..0aa2a85 100644 --- a/src/initial.test.js +++ b/src/initial.test.js @@ -26,7 +26,7 @@ test('initial value', () => { }); }); -test( "splat initial", async () => { +test('splat initial', async () => { const bar = new Updux({ initial: { id: 0 }, }); @@ -37,8 +37,10 @@ test( "splat initial", async () => { expect(foo.initial).toEqual([]); - expect( new Updux({ - initial: 'overriden', - subduxes: { '*': bar }, - }).initial ).toEqual('overriden'); + expect( + new Updux({ + initial: 'overriden', + subduxes: { '*': bar }, + }).initial, + ).toEqual('overriden'); }); diff --git a/src/reactions.test.js b/src/reactions.test.js index 225b2c7..8b17efb 100644 --- a/src/reactions.test.js +++ b/src/reactions.test.js @@ -30,7 +30,7 @@ test('subduxes reactions', async () => { subduxes: { a: new Updux({ initial: 1, - reactions: [() => state => spyA(state)], + reactions: [() => (state) => spyA(state)], actions: { inc: null }, mutations: { inc: () => (state) => state + 1, @@ -45,6 +45,6 @@ test('subduxes reactions', async () => { store.dispatch.inc(); expect(spyA).toHaveBeenCalledTimes(2); - expect(spyA).toHaveBeenCalledWith(3) + expect(spyA).toHaveBeenCalledWith(3); expect(spyB).toHaveBeenCalledOnce(); // the original inc initialized the state }); From 6b508c9db251cc0639b362f82abcd3fbee7bfc92 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Tue, 30 Aug 2022 14:17:27 -0400 Subject: [PATCH 4/4] remove the original --- src/Updux.original | 457 --------------------------------------------- 1 file changed, 457 deletions(-) delete mode 100644 src/Updux.original diff --git a/src/Updux.original b/src/Updux.original deleted file mode 100644 index 586b803..0000000 --- a/src/Updux.original +++ /dev/null @@ -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 = (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; - - /** - * Local mutations - */ - mutations?: Record; - - /** - * Selectors to apply to the mapped subduxes. Only - * applicable if the dux is a mapping dux. - */ - mappedSelectors?: Record; - - /** - * Local effects. - */ - effects?: Record; - - /** - * 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, - ItemsOf> - > - ) => Upreducer< - AggregateDuxState, - ItemsOf> - >; - - middlewareWrapper?: Function; -} - -export class Updux< - TState extends any = {}, - TActions extends object = {}, - TSelectors = {}, - TSubduxes extends object = {} -> { - /** @type { unknown } */ - #initial = {}; - #subduxes = {}; - - /** @type Record */ - #actions = {}; - #selectors = {}; - #mutations = {}; - #effects = []; - #reactions = []; - #mappedSelectors = undefined; - #mappedReaction = undefined; - #upreducerWrapper = undefined; - - #middlewareWrapper = undefined; - - constructor( - config: UpduxConfig - ) { - 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 { - return this.#memoInitial(this.#initial, this.#subduxes); - } - - get actions(): AggregateDuxActions { - 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, - ItemsOf> - > { - return this.#memoUpreducer( - this.initial, - this.#mutations, - this.#subduxes, - this.#upreducerWrapper - ); - } - - get reducer(): Reducer< - AggregateDuxState, - ItemsOf> - > { - 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>(name: TAction, mutation: Mutation, - ReturnType[TAction]>>) { - if (typeof name === 'function') name = name.type; - - this.#mutations = { - ...this.#mutations, - [name]: mutation, - }; - - return mutation; - } - - addEffect(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; - dispatch: Function & Record; - selectors: Record; - actions: AggregateDuxActions; - } = 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); - } -}