git ssb

2+

cel / scuttlebot.io



Tree: 88cc22ff535622f9d4c218ca12f0d920febd8429

Files: 88cc22ff535622f9d4c218ca12f0d920febd8429 / markdown.js

1916 bytesRaw
1var fs = require('fs')
2var remark = require('remark')
3var html = require('remark-html')
4var com = require('./tmpl/com.part')
5
6module.exports.doc = function (path) {
7 var text = fs.readFileSync(path, 'utf-8')
8 return remark()
9 .use(html)
10 .use(transformCodeExamples)
11 .process(text)
12}
13
14// find any <code> sections and group them together into our code-examples component
15function transformCodeExamples (remark, options) {
16 remark.Compiler.prototype.visitors.codeExamples = renderCodeExamples
17 return ast => {
18 var groups = findCodeGroupings(ast)
19 createCodeExamples(ast, groups)
20 return ast
21 }
22}
23
24// locate the contiguous <code> groupings
25function findCodeGroupings (ast) {
26 var groups = [], groupStart = false
27 ast.children.forEach((node, i) => {
28 if (groupStart) {
29 // in a grouping, look for a non-code item
30 if (node.type !== 'code' || !node.lang) {
31 groups.push([groupStart, i])
32 groupStart = false
33 }
34 } else {
35 // not in a grouping, look for a code item
36 if (node.type === 'code' && node.lang) {
37 groupStart = i
38 }
39 }
40 })
41 if (groupStart)
42 groups.push([groupStart, groupStart+1])
43 return groups
44}
45
46// replace <code> groupings with code-example nodes
47function createCodeExamples (ast, groups) {
48 var offset = 0 // offset to counter the changes introduced by splices
49 groups.forEach(group => {
50 var start = group[0], end = group[1]
51 var len = end - start
52 ast.children.splice(start-offset, len, {
53 type: 'codeExamples',
54 children: ast.children.slice(start-offset, start-offset+len),
55 position: false // TODO - what is this?
56 })
57 offset += len - 1
58 })
59}
60
61// convert from AST to html
62function renderCodeExamples (node, ast) {
63 var codes = {}
64 node.children.forEach(node => {
65 if (node.type == 'code' && !!node.lang)
66 codes[node.lang] = node.value
67 })
68
69 return com.code(codes)
70}
71

Built with git-ssb-web