forked from elk-zone/elk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshiki.ts
76 lines (64 loc) · 1.74 KB
/
shiki.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
70
71
72
73
74
75
76
import type { Highlighter, BuiltinLanguage as Lang } from 'shiki'
const highlighter = ref<Highlighter>()
const registeredLang = ref(new Map<string, boolean>())
let shikiImport: Promise<void> | undefined
export function useHighlighter(lang: Lang): {
promise?: Promise<void>
highlighter?: Highlighter
} {
if (!shikiImport) {
shikiImport = import('shiki')
.then(async ({ getHighlighter }) => {
highlighter.value = await getHighlighter({
themes: [
'vitesse-dark',
'vitesse-light',
],
langs: [
'js',
'css',
'html',
],
})
})
return { promise: shikiImport }
}
if (!highlighter.value)
return { promise: shikiImport }
if (!registeredLang.value.get(lang)) {
const promise = highlighter.value.loadLanguage(lang)
.then(() => {
registeredLang.value.set(lang, true)
})
.catch(() => {
const fallbackLang = 'md'
highlighter.value?.loadLanguage(fallbackLang).then(() => {
registeredLang.value.set(fallbackLang, true)
})
})
return { promise }
}
return { highlighter: highlighter.value }
}
function useShikiTheme() {
return useColorMode().value === 'dark' ? 'vitesse-dark' : 'vitesse-light'
}
const HTML_ENTITIES = {
'<': '<',
'>': '>',
'&': '&',
'\'': ''',
'"': '"',
} as Record<string, string>
function escapeHtml(text: string) {
return text.replace(/[<>&'"]/g, ch => HTML_ENTITIES[ch])
}
export function highlightCode(code: string, lang: Lang) {
const { highlighter } = useHighlighter(lang)
if (!highlighter)
return escapeHtml(code)
return highlighter.codeToHtml(code, {
lang,
theme: useShikiTheme(),
})
}