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

// Get all the pairs of header + paragraph in a list of nodes
function groups(nodes) {
    // A list of next nodes
    var next = nodes.slice(1).concat(null);

    return _.reduce(nodes, function(accu, node, idx) {
        // Skip
        if(!(
            node.type === 'heading' &&
            (next[idx] && next[idx].type === 'paragraph')
        )) {
            return accu;
        }

        // Add group
        accu.push([
            node,
            next[idx]
        ]);

        return accu;
    }, []);
}

function parseGlossary(src) {
    var nodes = kramed.lexer(src);

    return groups(nodes)
    .map(function(pair) {
        // Simplify each group to a simple object with name/description
        return {
            name: pair[0].text,
            description: pair[1].text,
        };
    });
}

function glossaryToMarkdown(glossary) {
    var bl = "\n";

    var body = _.map(glossary, function(entry) {
        return "## "+entry.name+bl+bl+entry.description;
    }).join(bl+bl);

    return "# Glossary"+bl+bl+body;
}

module.exports = parseGlossary;
module.exports.toText = glossaryToMarkdown;