course-renderer
Version:
Manages CA School Courses file system storage and HTML conversion
48 lines (47 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const cheerio = require("cheerio");
const MarkdownIt = require("markdown-it");
const escapeHTML = require("escape-html");
const through = require('through2');
const replaceExtension = require('replace-ext');
module.exports = (options) => (through.obj((file, _, callback) => {
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new Error('Streaming not supported'));
return;
}
const md = new MarkdownIt();
const ch = cheerio.load(md.render(file.contents.toString()));
let output = new Array();
traverseSummary(output, ch, ch('ul').first());
file.contents = new Buffer(JSON.stringify(output, null, 4));
file.path = replaceExtension(file.path, '.json');
callback(null, file);
}));
function traverseSummary(output, ch, curEle) {
curEle.children('li').each(function (index, element) {
const childLI = ch(element);
const link = childLI.find('a');
const label = link.text();
const url = link.attr('href').replace(/\.md$/, '.html');
const desc = escapeHTML(childLI.children('blockquote').text().replace(/^\s+|\s+$/g, ''));
const duration = childLI.find('strong').first().text();
const summaryToken = {
content: `[${label}](${url})`,
text: label,
url: url,
description: desc,
duration: duration,
children: []
};
if (childLI.children('ul').length > 0) {
summaryToken.children = traverseSummary([], ch, childLI.children('ul'));
}
output.push(summaryToken);
});
return output;
}