This repository has been archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (49 loc) · 1.6 KB
/
index.js
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
const fs = require('fs');
const showdown = require('showdown');
const converter = new showdown.Converter({ smartIndentationFix: true, disableForced4SpacesIndentedSublists: true });
const cheerio = require('cheerio')
const randomstring = require("randomstring");
let tree = [];
const parseOutline = (outlinePath) => {
const md = fs.readFileSync(outlinePath, 'utf8');
const html = converter.makeHtml(md);
const $ = cheerio.load(html);
// add uuids to each item that doesn't have one.
const uuidsAdded = addUuids($);
const title = $('#summary').text();
const firstUl = $('ul').first();
let treeAssembled = assembleTree($, firstUl);
let outline = Object.assign({}, { title: title, tree: tree });
return outline;
}
assembleTree = ($, parent) => {
$(parent).children('li').each((index, el) => {
const parentID = $(el).parent('ul').parent('li').find('a').attr('id') || null;
const a = $(el).children().closest('a');
const title = $(a).text();
const href = $(a).attr('href');
const id = $(a).attr('id');
const item = Object.assign({}, { id: id, location: href, title: title, parent: parentID, order: index });
tree.push(item);
// recursively find more ul's and keep building tree
const ul = $(el).children('ul').each((i, childUl) => {
assembleTree($, childUl);
});
});
return;
}
/**
* Add UUID's to anchors in html
* @return void
*/
addUuids = ($) => {
$('a').each((i, el) => {
const id = $(el).attr('id');
if (id === undefined) {
const uuid = randomstring.generate();
$(el).attr('id', uuid);
}
})
return;
}
module.exports = parseOutline;