-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
63 lines (53 loc) · 2.19 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
55
56
57
58
59
60
61
62
63
var extend = require('util')._extend;
var fs = require('fs');
var handlebars = require('handlebars');
var hljs = require('highlight.js');
var marked = require('marked');
var path = require('path');
var renderer = require('./lib/marked');
module.exports = function(input, options, cb) {
options = extend({
template: path.join(__dirname, 'template.html')
}, options);
// Read input file
var inputFile = fs.readFileSync(path.join(process.cwd(), input));
// The divider for pages is four newlines
var pages = inputFile.toString().replace(/(?:\r\n)/mg, "\n").split('\n\n\n\n');
// Process each page
pages = pages.map(function(page, i) {
// Convert Markdown to HTML
var body = marked(page, { renderer: renderer });
// Find the title of the page by identifying the <h1>
// The second match is the inner group
var foundHeadings = body.match('<h1.*>(.*)</h1>');
var title = foundHeadings && foundHeadings[1] || 'Page ' + (i + 1);
var anchor = title.toLowerCase().replace(/[^\w]+/g, '-');
var subheadings = null;
if(options.includeSubheadings) {
var subheadRe = /(<h2.*?>(.*?)<\/h2>)/g;
var foundSubheadings = [];
var match;
var i = 0;
while((match = subheadRe.exec(body)) !== null) {
i = i + 1;
var subTitle = match[2];
var subAnchor = anchor + '-sub-' + i;
foundSubheadings.push({title: subTitle, anchor: subAnchor, content: match[1]});
}
if(foundSubheadings.length) {
subheadings = foundSubheadings.map(function(subheading) {
body = body.replace(subheading.content, '<section id="' + subheading.anchor +'"></section>' + subheading.content);
return {title: subheading.title, anchor: subheading.anchor};
});
}
}
var results = { title: title, anchor: anchor, body: body};
if(subheadings) {results.subheadings = subheadings};
return results;
});
// Write file to disk
var templateFile = fs.readFileSync(path.join(process.cwd(), options.template));
var template = handlebars.compile(templateFile.toString(), { noEscape: true });
var outputPath = path.join(process.cwd(), options.output);
fs.writeFile(outputPath, template({ pages: pages }), cb);
}