summaryrefslogtreecommitdiffstats
path: root/webapp/plugins/index.js
blob: 2e8240cecbc9d6e1a3b37f5b88ff8f26376d956c (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
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

// EXPERIMENTAL - SUBJECT TO CHANGE

import store from 'stores/redux_store.jsx';
import {ActionTypes} from 'utils/constants.jsx';
import {getSiteURL} from 'utils/url.jsx';

window.plugins = {};

export function registerComponents(components) {
    store.dispatch({
        type: ActionTypes.RECEIVED_PLUGIN_COMPONENTS,
        data: components || {}
    });
}

export function initializePlugins() {
    const pluginJson = window.mm_config.Plugins || '[]';

    let pluginManifests;
    try {
        pluginManifests = JSON.parse(pluginJson);
    } catch (error) {
        console.error('Invalid plugins JSON: ' + error); //eslint-disable-line no-console
        return;
    }

    pluginManifests.forEach((m) => {
        function onLoad() {
            // Add the plugin's js to the page
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.text = this.responseText;
            document.getElementsByTagName('head')[0].appendChild(script);

            // Initialize the plugin
            console.log('Registering ' + m.id + ' plugin...'); //eslint-disable-line no-console
            const plugin = window.plugins[m.id];
            plugin.initialize(registerComponents, store);
            console.log('...done'); //eslint-disable-line no-console
        }

        // Fetch the plugin's bundled js
        const xhrObj = new XMLHttpRequest();
        xhrObj.open('GET', getSiteURL() + m.bundle_path, true);
        xhrObj.addEventListener('load', onLoad);
        xhrObj.send('');
    });
}