-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
120 lines (98 loc) · 2.49 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const shiki = require('shiki')
const visit = require('unist-util-visit')
const {
commonLangIds,
commonLangAliases,
otherLangIds
} = require('shiki-languages')
const hastToString = require('hast-util-to-string')
const u = require('unist-builder')
const languages = [...commonLangIds, ...commonLangAliases, ...otherLangIds]
module.exports = attacher
function attacher(options) {
var settings = options || {}
var theme = settings.theme || 'nord'
var useBackground =
typeof settings.useBackground === 'undefined'
? true
: Boolean(settings.useBackground)
var shikiTheme
var highlighter
try {
shikiTheme = shiki.getTheme(theme)
} catch (_) {
try {
shikiTheme = shiki.loadTheme(theme)
} catch (_) {
throw new Error('Unable to load theme: ' + theme)
}
}
return transformer
async function transformer(tree) {
highlighter = await shiki.getHighlighter({
theme: shikiTheme,
langs: languages
})
visit(tree, 'element', visitor)
}
function visitor(node, index, parent) {
if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
return
}
if (useBackground) {
addStyle(parent, 'background: ' + shikiTheme.bg)
}
const lang = codeLanguage(node)
if (!lang) {
// Unknown language, fall back to a foreground colour
addStyle(node, 'color: ' + shikiTheme.settings.foreground)
return
}
const tokens = highlighter.codeToThemedTokens(hastToString(node), lang)
const tree = tokensToHast(tokens)
node.children = tree
}
}
function tokensToHast(lines) {
let tree = []
for (const line of lines) {
if (line.length === 0) {
tree.push(u('text', '\n'))
} else {
for (const token of line) {
tree.push(
u(
'element',
{
tagName: 'span',
properties: {style: 'color: ' + token.color}
},
[u('text', token.content)]
)
)
}
tree.push(u('text', '\n'))
}
}
// Remove the last \n
tree.pop()
return tree
}
function addStyle(node, style) {
var props = node.properties || {}
var styles = props.style || []
styles.push(style)
props.style = styles
node.properties = props
}
function codeLanguage(node) {
const className = node.properties.className || []
var value
for (const element of className) {
value = element
if (value.slice(0, 9) === 'language-') {
return value.slice(9)
}
}
return null
}