summaryrefslogtreecommitdiffstats
path: root/lib/api/encodeProgress.js
blob: afa0341143ecad5bea9f7fbd8ba2f0a0ab6941d1 (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
var Immutable = require('immutable');
var encodeNavigation = require('./encodeNavigation');

/**
    page.progress is a deprecated property from GitBook v2

    @param {Output}
    @param {Page}
    @return {Object}
*/
function encodeProgress(output, page) {
    var current = page.getPath();
    var navigation = encodeNavigation(output);
    navigation = Immutable.Map(navigation);

    var n = navigation.size;
    var percent = 0, prevPercent = 0, currentChapter = null;
    var done = true;

    var chapters = navigation
        .map(function(nav, chapterPath) {
            nav.path = chapterPath;
            return nav;
        })
        .valueSeq()
        .sortBy(function(nav) {
            return nav.index;
        })
        .map(function(nav, i) {
            // Calcul percent
            nav.percent = (i * 100) / Math.max((n - 1), 1);

            // Is it done
            nav.done = done;
            if (nav.path == current) {
                currentChapter = nav;
                percent = nav.percent;
                done = false;
            } else if (done) {
                prevPercent = nav.percent;
            }

            return nav;
        })
        .toJS();

    return {
        // Previous percent
        prevPercent: prevPercent,

        // Current percent
        percent: percent,

        // List of chapter with progress
        chapters: chapters,

        // Current chapter
        current: currentChapter
    };
}

module.exports = encodeProgress;