summaryrefslogtreecommitdiffstats
path: root/packages/gitbook/src/browser/render.js
blob: e97676557317f9458b7ec2676207598014b20899 (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
70
71
72
73
74
75
76
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const GitBook = require('gitbook-core');

const loadPlugins = require('./loadPlugins');

const BOOTSTRAP_CODE = '(function() { require("gitbook-core").bootstrap() })()';

function HTML({head, innerHTML, payload, scripts}) {
    const attrs = head.htmlAttributes.toComponent();

    return (
        <html {...attrs}>
            <head>
                {head.title.toComponent()}
                {head.meta.toComponent()}
                {head.link.toComponent()}
                {head.style.toComponent()}
            </head>
            <body>
                <div id="content" dangerouslySetInnerHTML={{__html: innerHTML}} />
                {scripts.map(script => {
                    return <script key={script} src={script} />;
                })}
                <script type="application/payload+json" dangerouslySetInnerHTML={{__html: payload}} />
                <script type="application/javascript" dangerouslySetInnerHTML={{__html: BOOTSTRAP_CODE}} />
                {head.script.toComponent()}
            </body>
        </html>
    );
}
HTML.propTypes = {
    head:      React.PropTypes.object,
    innerHTML: React.PropTypes.string,
    payload:   React.PropTypes.string,
    scripts:   React.PropTypes.arrayOf(React.PropTypes.string)
};

/**
 * Render a page
 * @param  {OrderedMap<String:Plugin>} plugin
 * @param  {Object} initialState
 * @return {String} html
 */
function render(plugins, initialState) {
    // Load the plugins
    const browserPlugins = loadPlugins(plugins);
    const payload = JSON.stringify(initialState);
    const context = GitBook.createContext(browserPlugins, initialState);

    const scripts = plugins.toList()
        .filter(plugin => plugin.getPackage().has('browser'))
        .map(plugin => 'gitbook/plugins/' + plugin.getName() + '.js')
        .toArray();

    const el = GitBook.renderWithContext(context);

    // Render inner body
    const innerHTML = ReactDOMServer.renderToString(el);

    // Get headers
    const head = GitBook.Head.rewind();

    // Render whole HTML page
    const htmlEl = <HTML
        head={head}
        innerHTML={innerHTML}
        payload={payload}
        scripts={['gitbook/core.js'].concat(scripts)}
    />;

    const html = ReactDOMServer.renderToStaticMarkup(htmlEl);
    return html;
}

module.exports = render;