-
Notifications
You must be signed in to change notification settings - Fork 12
/
rehype-prism.ts
69 lines (57 loc) · 1.49 KB
/
rehype-prism.ts
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
69
/**
* Copyright (c) 2017 Mapbox
* MIT License
*/
import visit from 'unist-util-visit'
import nodeToString from 'hast-util-to-string'
import nodeToHTML from 'hast-util-to-html'
import refractor from 'refractor'
const aliases = {
js: 'jsx',
html: 'markup',
}
export default function rehypePrism(options: any) {
options = options || {}
return (tree: any) => {
visit(tree, 'element', visitor)
}
function visitor(node: any, index: any, parent: any) {
if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
return
}
const lang = getLanguage(node, options.aliases || aliases)
if (lang === null) {
return
}
let result = node
try {
parent.properties.className = (parent.properties.className || []).concat(
'language-' + lang,
)
result = refractor.highlight(nodeToString(node), lang)
} catch (err) {
if (/Unknown language/.test(err.message)) {
return
}
throw err
}
node.children = []
node.properties.dangerouslySetInnerHTML = {
__html: nodeToHTML({
type: 'root',
children: result,
}),
}
}
}
function getLanguage(node: any, aliases: any) {
const className = node.properties.className || []
for (const classListItem of className) {
if (classListItem.slice(0, 9) === 'language-') {
let language = classListItem.slice(9).replace(/{.*/, '')
let alias = aliases[language]
return alias || language
}
}
return null
}