summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/models/Context.js
blob: f4b0d4c95d3b923c59601c93e17a5d387d90f330 (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
const { Record, List } = require('immutable');

const DEFAULTS = {
    store: null,
    actions: {},
    plugins: List()
};

class Context extends Record(DEFAULTS) {
    constructor(...args) {
        super(...args);

        this.dispatch = this.dispatch.bind(this);
        this.getState = this.getState.bind(this);
    }

    /**
     * Return current state
     * @return {Object}
     */
    getState() {
        const { store } = this;
        return store.getState();
    }

    /**
     * Dispatch an action
     * @param {Action} action
     */
    dispatch(action) {
        const { store } = this;
        return store.dispatch(action);
    }

    /**
     * Deactivate the context, cleanup resources from plugins.
     */
    deactivate() {
        const { plugins, actions } = this;

        plugins.forEach(plugin => {
            plugin.deactivate(this.dispatch, this.getState, actions);
        });
    }

    /**
     * Activate the context and the plugins.
     */
    activate() {
        const { plugins, actions } = this;

        plugins.forEach(plugin => {
            plugin.activate(this.dispatch, this.getState, actions);
        });
    }
}

module.exports = Context;