summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/lib/createContext.js
blob: ec240be3a1788a794e67e2cc02d8b15c45c79471 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* eslint-disable no-console */
const Redux = require('redux');
const ReduxThunk = require('redux-thunk').default;

const Plugin = require('../models/Plugin');
const Context = require('../models/Context');
const coreReducers = require('../reducers');
const composeReducer = require('./composeReducer');

const Components = require('../actions/components');
const I18n = require('../actions/i18n');
const Navigation = require('../actions/navigation');

const isBrowser = (typeof window !== 'undefined');

const corePlugin = new Plugin({
    reduce: coreReducers,
    actions: {
        Components, I18n, Navigation
    }
});

/**
 * Create a new context containing redux store from an initial state and a list of plugins.
 * Each plugin entry is the result of {createPlugin}.
 *
 * @param  {Array<Plugin>} plugins
 * @param  {Object} initialState
 * @return {Context} context
 */
function createContext(plugins, initialState) {
    plugins = [corePlugin].concat(plugins);

    // Compose the reducer from core with plugins
    const pluginReducers = plugins.map(plugin => plugin.reduce);
    const reducer = composeReducer(...pluginReducers);

    // Get actions from all plugins
    const actions = plugins.reduce((accu, plugin) => {
        return Object.assign(accu, plugin.actions);
    }, {});

    // Create thunk middleware which include actions
    const thunk = ReduxThunk.withExtraArgument(actions);

    // Create the redux store
    const store = Redux.createStore(
        (state, action) => {
            if (isBrowser) {
                console.log('[store]', action.type);
            }
            return reducer(state, action);
        },
        initialState,
        Redux.compose(Redux.applyMiddleware(thunk))
    );

    // Initialize the plugins
    plugins.forEach(plugin => {
        plugin.init(store.dispatch, store.getState, actions);
    });

    return new Context({
        store,
        actions
    });
}

module.exports = createContext;