summaryrefslogtreecommitdiffstats
path: root/lib/plugins/compatibility.js
blob: 8fddba6e7d67558458ac1ffb9f71188aa4893ef6 (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
var _ = require('lodash');
var error = require('../utils/error');

/*
    Return the context for a plugin.
    It tries to keep compatibilities with GitBook v2
*/
function pluginCtx(plugin) {
    var book = plugin.book;
    var ctx = book;

    return ctx;
}

/*
    Call a function "fn" with a context of page similar to the one in GitBook v2

    @params {Page}
    @returns {String|undefined} new content of the page
*/
function pageHook(page, fn) {
    // Get page context
    var ctx = page.getContext().page;

    // Add other informations
    ctx.type    = page.type;
    ctx.rawPath = page.rawPath;
    ctx.path    = page.path;

    // Deprecate sections
    error.deprecateField(ctx, 'sections', [
        { content: ctx.content, type: 'normal' }
    ], '"sections" property is deprecated, use page.content instead');

    return fn(ctx)
    .then(function(result) {
        // No returned value
        // Existing content will be used
        if (!result) return undefined;

        // GitBook 2 compatibility first
        // Use sections if provided
        if (result.sections) {
            return _.pluck(result.sections, 'content').join('\n');
        }

        // GitBook 3
        // Use returned page.content
        if (result.content) {
            return result.content;
        }
    });
}

module.exports = {
    pluginCtx: pluginCtx,
    pageHook: pageHook
};