forked from ryanflorence/render-markdown-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (60 loc) · 1.55 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
64
65
66
67
68
const fs = require("fs")
const MarkdownIt = require("markdown-it")
const Prism = require("prismjs")
const HeaderLinks = require("markdown-it-anchor")
const aliases = {
js: "jsx",
render: "jsx",
"render-babel": "jsx",
html: "markup",
sh: "bash"
}
const supportedTypes = {
render: true,
"render-babel": true
}
const highlight = (str, lang) => {
if (lang) {
highlightLang = aliases[lang] || lang
require(`prismjs/components/prism-${highlightLang}.js`)
if (Prism.languages[highlightLang]) {
const highlighted = Prism.highlight(str, Prism.languages[highlightLang])
return supportedTypes[lang]
? appendScript(lang, str, highlighted)
: highlighted
} else {
return str
}
} else {
return str
}
}
const appendScript = (lang, js, html) => {
const type = lang === "render-babel" ? "babel" : "javascript"
const id = `render-${Math.random()
.toString(32)
.substring(2)}`
const script =
lang === "render-babel"
? `
(function() { var DOM_NODE = document.getElementById("${id}");
${js}
})()`
: `
document.addEventListener("DOMContentLoaded", function(event) { var DOM_NODE = document.getElementById("${id}");
${js}
})`
return `<pre class="render-js-code"><code class="jsx">${html}</code></pre>
<div id="${id}" class="render-js"></div>
<script type="text/${type}">${script}</script>
`
}
const md = new MarkdownIt({
html: true,
highlight: highlight
}).use(HeaderLinks, {
permalink: true,
permalinkBefore: true,
permalinkSymbol: "#"
})
module.exports = source => md.render(source)