summaryrefslogtreecommitdiffstats
path: root/lib/parse/navigation.js
blob: 9ed82b98e619fdfffcc9ee6da4cbdb48c14fff4d (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
77
78
79
80
81
82
83
84
85
86
87
88
89
var _ = require('lodash');

// Cleans up an article/chapter object
// remove 'articles' and '_path' attributes
function clean(obj) {
    return obj && _.omit(obj, ['articles', '_path']);
}

// Returns a map of
/*
    {
        "file/path.html": {
            prev: ...,
            next: ...,
        },
        ...
    }
*/
function navigation(summary, files) {
    // Support single files as well as list
    files = _.isArray(files) ? files : (_.isString(files) ? [files] : null);

    // Mapping of prev/next for a give path
    var mapping = {};

    // Special README nav
    var README_NAV = {
        path: 'README.html',
        title: 'Introduction',
    };

    // Walk the chapter/article tree and create navigation entires
    _.each(summary.chapters, function(chapter, idx, chapters) {
        // Skip if no path
        if(!chapter.path) return;

        var currentChapter = clean(chapter);
        var prevChapter = (idx-1 < 0) ? README_NAV : chapters[idx-1];
        var nextChapter = (idx+1 >= chapters.length) ? null : chapters[idx+1];

        var prev = (!prevChapter || _.isEmpty(prevChapter.articles)) ?
            prevChapter : _.last(prevChapter.articles);
        var next = (!chapter || _.isEmpty(chapter.articles)) ?
            nextChapter : _.first(chapter.articles);

        // Add chapter mapping
        mapping[chapter.path] = {
            title: chapter.title,
            prev: clean(prev),
            next: clean(next),
            level: (idx+1).toString(),
        };

        // Check a chapter's articles
        _.each(chapter.articles, function(article, _idx, articles) {
            // Skip if no path
            if(!article.path) return;

            var prev = (_idx-1 < 0) ? currentChapter : clean(articles[_idx-1]);
            var next = (_idx+1 >= articles.length) ? nextChapter : clean(articles[_idx+1]);

            mapping[article.path] = {
                title: article.title,
                prev: clean(prev),
                next: clean(next),
                level: [idx+1, _idx+1].join('.'),
            };
        });
    });

    // Hack for README.html
    mapping['README.html'] = {
        title: README_NAV.title,
        prev: null,
        next: clean(summary.chapters[0]),
        level: '0',
    };

    // Filter for only files we want
    if(files) {
        return _.pick(mapping, files);
    }

    return mapping;
}


// Exports
module.exports = navigation;