import tap from 'tap'; import sinon from 'sinon'; import u from '@yanick/updeep'; import { Updux } from './Updux.js'; import { action } from './actions.js'; tap.test('subscriptions', async () => { const inc = action('inc'); const set_copy = action('set_copy'); const dux = new Updux({ initial: { x: 0, copy: 0, }, actions: { inc, set_copy, }, mutations: { inc: (payload) => u({ x: (x) => x + 1 }), set_copy: (copy) => u({ copy }), }, }); dux.addSubscription((store) => (state, previous, unsubscribe) => { if (state.x > 2) return unsubscribe(); store.dispatch(set_copy(state.x)); }); const store = dux.createStore(); store.dispatch(inc()); tap.same(store.getState(), { x: 1, copy: 1 }); store.dispatch(inc()); store.dispatch(inc()); tap.same(store.getState(), { x: 3, copy: 2 }, 'we unsubscribed'); }); tap.test('subduxes subscriptions', async (t) => { const inc_top = action('inc_top'); const inc_bar = action('inc_bar'); const transform_bar = action('transform_bar'); const bar = new Updux({ initial: 'a', actions: { inc_bar, transform_bar }, mutations: { inc_bar: () => (state) => state + 'a', transform_bar: (outcome) => () => outcome, }, subscriptions: [ (store) => (state, previous, unsubscribe) => { if (state.length <= 2) return; unsubscribe(); store.dispatch(transform_bar('look at ' + state)); }, ], }); const dux = new Updux({ initial: { count: 0, }, subduxes: { bar }, actions: { inc_top, }, mutations: { inc_top: () => u({ count: (count) => count + 1 }), }, effects: { '*': () => (next) => (action) => { next(action); }, }, subscriptions: [ (store) => { return ({ count }, { count: previous } = {}) => { if (count !== previous) { previous = count; store.dispatch.inc_bar(); } }; }, ], }); const store = dux.createStore(); store.dispatch(inc_top()); store.dispatch(inc_top()); t.same(store.getState(), { count: 2, bar: 'look at look at aaa', }); store.dispatch(inc_top()); t.same(store.getState(), { count: 3, bar: 'look at look at aaaa', }); }); tap.test( "subscription within subduxes", {only: true},async(t) => { let innerState = sinon.fake.returns(null); let outerState = sinon.fake.returns(null); const inner = new Updux({ initial: 1, actions: { inc: null }, mutations: { inc: () => state => state + 1, }, subscriptions: [ store => (state, previous, unsub) => { if(!previous) return; store.subscribe( innerState ); unsub(); } ], }) const dux = new Updux({ subduxes: { inner }, subscriptions: [ store => (state, previous, unsub) => { console.log(state,previous); if(!previous) return; store.subscribe( outerState ); unsub(); } ], }); const store = dux.createStore(); store.dispatch({ type: 'noop' }); store.dispatch({ type: 'noop' }); t.notOk( innerState.called ); t.notOk( outerState.called ); store.dispatch.inc(); // still not called, but waiting, now t.notOk( innerState.called ); t.notOk( outerState.called ); store.dispatch.inc(); console.log(outerState.firstCall.args); // console.log(outerState.firstCall) } );