summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-markdown/lib/page.js
blob: 1cd55a872032dc62fd53d9318646f91f21da2337 (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
var _ = require('lodash');
var kramed = require('kramed');

var annotate = require('./annotate');

var RAW_START = "{% raw %}";
var RAW_END = "{% endraw %}";

function escape(str) {
    return RAW_START + str + RAW_END;
}

// Combines annotated nodes
function combine(nodes) {
    return _.pluck(nodes, 'raw').join('');
}

function preparePage(src) {
    var lexed = annotate.blocks(src);
    var levelRaw = 0;

    var escapeCodeElement = function(el) {
        if (el.type == 'code' && levelRaw == 0) {
            el.raw = escape(el.raw);
        } else if (el.type == 'rawStart') {
            levelRaw = levelRaw + 1;
        } else if (el.type == 'rawEnd') {
            levelRaw = 0;
        }
        return el;
    };

    var escaped = lexed

    .map(function(el) {
        // Only escape paragraphs and headings
        if(el.type == 'paragraph' || el.type == 'heading') {
            var line = annotate.inline(el.raw);

            // Escape inline code blocks
            line = line.map(escapeCodeElement);

            // Change raw source code
            el.raw = combine(line);

            return el;
        } else {
            return escapeCodeElement(el);
        }
    });

    return combine(escaped);
}

function parsePage(src) {
    var options = _.extend({}, kramed.defaults, {
        mathjax: false
    });

    return {
        sections: [
            {
                type: "normal",
                content: kramed(src, options)
            }
        ]
    };
}

// Exports
module.exports = parsePage;
module.exports.prepare = preparePage;