git ssb

2+

cel / scuttlebot.io



Tree: b8ae20f0192e52a26783f66104a4f5c98f6aa48d

Files: b8ae20f0192e52a26783f66104a4f5c98f6aa48d / markdown.js

2651 bytesRaw
1var fs = require('fs')
2var remark = require('remark')
3var html = require('remark-html')
4var slug = require('remark-slug')
5var autolinkHeadings = require('remark-autolink-headings')
6var com = require('./tmpl/com.part')
7
8const linkSvg = '<svg aria-hidden="true" class="octicon octicon-link" height="16" role="img" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1h-1c-1.5 0-3-1.69-3-3.5s1.55-3.5 3-3.5h4c1.45 0 3 1.69 3 3.5 0 1.41-0.91 2.72-2 3.25v-1.16c0.58-0.45 1-1.27 1-2.09 0-1.28-1.02-2.5-2-2.5H4c-0.98 0-2 1.22-2 2.5s1 2.5 2 2.5z m9-3h-1v1h1c1 0 2 1.22 2 2.5s-1.02 2.5-2 2.5H9c-0.98 0-2-1.22-2-2.5 0-0.83 0.42-1.64 1-2.09v-1.16c-1.09 0.53-2 1.84-2 3.25 0 1.81 1.55 3.5 3 3.5h4c1.45 0 3-1.69 3-3.5s-1.5-3.5-3-3.5z"></path></svg>'
9
10module.exports.doc = function (path) {
11 var text = fs.readFileSync(path, 'utf-8')
12 return remark()
13 .use(slug)
14 .use(autolinkHeadings, {
15 attributes: { class: 'anchor' },
16 template: linkSvg
17 })
18 .use(html)
19 .use(transformCodeExamples)
20 .process(text)
21}
22
23// find any <code> sections and group them together into our code-examples component
24function transformCodeExamples (remark, options) {
25 remark.Compiler.prototype.visitors.codeExamples = renderCodeExamples
26 return ast => {
27 var groups = findCodeGroupings(ast)
28 createCodeExamples(ast, groups)
29 return ast
30 }
31}
32
33// locate the contiguous <code> groupings
34function findCodeGroupings (ast) {
35 var groups = [], groupStart = false
36 ast.children.forEach((node, i) => {
37 if (groupStart) {
38 // in a grouping, look for a non-code item
39 if (node.type !== 'code' || !node.lang) {
40 groups.push([groupStart, i])
41 groupStart = false
42 }
43 } else {
44 // not in a grouping, look for a code item
45 if (node.type === 'code' && node.lang) {
46 groupStart = i
47 }
48 }
49 })
50 if (groupStart)
51 groups.push([groupStart, groupStart+1])
52 return groups
53}
54
55// replace <code> groupings with code-example nodes
56function createCodeExamples (ast, groups) {
57 var offset = 0 // offset to counter the changes introduced by splices
58 groups.forEach(group => {
59 var start = group[0], end = group[1]
60 var len = end - start
61 ast.children.splice(start-offset, len, {
62 type: 'codeExamples',
63 children: ast.children.slice(start-offset, start-offset+len),
64 position: false // TODO - what is this?
65 })
66 offset += len - 1
67 })
68}
69
70// convert from AST to html
71function renderCodeExamples (node, ast) {
72 var codes = {}
73 node.children.forEach(node => {
74 if (node.type == 'code' && !!node.lang)
75 codes[node.lang] = node.value
76 })
77
78 return com.code(codes)
79}
80

Built with git-ssb-web