summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-asciidoc/lib/summary.js
blob: 17c98348964c61982a5466ada9978a628e380f3b (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
var _ = require('lodash');
var cheerio = require('cheerio');

var convert = require('./utils/convert');


// parse a ul list and return list of chapters recursvely
function parseList($ul, $) {
	var articles = [];

	$ul.children("li").each(function() {
		var article = {};

		var $li = $(this);
		var $p = $li.children("p");

		article.title = $p.text();

		// Parse link
		var $a = $p.children("a");
		if ($a.length > 0) {
			article.title = $a.first().text();
			article.path = $a.attr("href").replace(/\\/g, '/').replace(/^\/+/, '')
		}

		// Sub articles
		var $sub = $li.children(".olist").children("ol");
		article.articles = parseList($sub, $);

		articles.push(article);
	});

	return articles;
}

function defaultChapterList(chapterList, entryPoint) {
    var first = _.first(chapterList);

    // Check if introduction node was specified in SUMMARY.md
    if (first && first.path == entryPoint) {
        return chapterList;
    }

    // It wasn't specified, so add in default
    return [
        {
        	path: entryPoint,
        	title: 'Introduction'
        }
    ].concat(chapterList);
}

function parseChaptersLevel(chapterList, level, base) {
	var i = base || 0;
	return _.map(chapterList, function(chapter) {
		chapter.level = (level? [level || "", i] : [i]).join(".");
		chapter.article = parseChaptersLevel(chapter.articles || [], chapter.level, 1);

		i = i + 1;
		return chapter;
	});
};

function parseSummary(src, entryPoint) {
	entryPoint = entryPoint || "README.adoc";

    var html = convert(src);
    $ = cheerio.load(html);

    var chapters = parseList($("ol").first(), $);
    chapters = defaultChapterList(chapters, entryPoint);
    chapters = parseChaptersLevel(chapters);

    return {
    	chapters: chapters
    };
}

function parseEntries (src) {
    return [];
}


// Exports
module.exports = parseSummary;
module.exports.entries = parseEntries;