-
Notifications
You must be signed in to change notification settings - Fork 167
/
_shiki_js.tmpl.html
59 lines (50 loc) · 1.59 KB
/
_shiki_js.tmpl.html
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
<script type="module">
// be sure to specify the exact version
import { codeToHtml } from 'https://esm.sh/shiki@1.0.0'
// or
// import { codeToHtml } from 'https://esm.run/shiki@1.0.0'
const htmlEscapes = new Map([
['&', '&'],
['<', '<'],
['>', '>'],
]);
function unescapeHTMLEntities(str) {
for (const [escaped, unescaped] of htmlEscapes) {
str = str.replaceAll(escaped, unescaped)
}
return str
}
await Promise.all(Array.from(document.querySelectorAll('pre code')).map((codeBlock) => {
const classNames = codeBlock.getAttribute("class");
if (classNames == null) {
return
}
let language = null;
for (const className of classNames.split(" ")) {
const [languageToken, ...rest] = className.split("-")
if (languageToken == "language") {
// Some languages may contain their own hyphens like `git-commit`,
// so make sure we handle that case by joining them back together
// before sending out to Shiki.
language = rest.join("-")
break
}
}
if (language == null) {
return
}
return (async () => {
const code = unescapeHTMLEntities(codeBlock.innerHTML)
// Shiki will add its own `<pre><code>`, so go to parent `<pre>` and
// replace the entirety of its HTML.
codeBlock.parentElement.outerHTML =
await codeToHtml(code, {
lang: language,
themes: {
dark: 'nord',
light: 'rose-pine'
}
})
})()
}))
</script>