course-renderer
Version:
Manages CA School Courses file system storage and HTML conversion
59 lines (45 loc) • 1.93 kB
text/typescript
import * as cheerio from 'cheerio'
import * as MarkdownIt from 'markdown-it'
import * as escapeHTML from 'escape-html'
const through = require('through2')
const replaceExtension = require('replace-ext')
module.exports = (options: any) => (through.obj((file: any, _: any, callback: any) => {
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: Array<{}> = 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: Array<{}>, ch: CheerioStatic, curEle: Cheerio): Array<{}> {
curEle.children('li').each( function( index: number, element: CheerioElement ) {
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: any = {
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
}