summaryrefslogtreecommitdiffstats
path: root/lib/parse/page.js
blob: 047f3e4de3ced26f95bf19f4453ac1f33b3e5c63 (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
var _ = require('lodash');
var marked = require('marked');


// Split a page up into sections (lesson, exercises, ...)
function splitSections(nodes) {
    var section = [];

    return _.reduce(nodes, function(sections, el) {
        if(el.type === 'hr') {
            sections.push(section);
            section = [];
        } else {
            section.push(el);
        }

        return sections;
    }, []).concat([section]); // Add remaining nodes
}

// What is the type of this section
function sectionType(nodes) {
    if(_.filter(nodes, {
        type: 'code'
    }).length === 3) {
        return 'exercise';
    }

    return 'normal';
}

function parsePage(src) {
    var nodes = marked.lexer(src);

    return _.chain(splitSections(nodes))
    .map(function(section) {
        // Detect section type
        section.type = sectionType(section);
        return section;
    })
    .map(function(section, idx) {
        // Transform given type
        if(section.type === 'exercise' && (idx % 2) == 1) {
            return {
                type: section.type,
            };
        }

        // marked's Render expects this, we don't use it yet
        section.links = {};

        // Render normal pages
        return {
            type: section.type,
            content: marked.parser(section)
        };
    })
    .value();
}

// Exports
module.exports = parsePage;