-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
80 lines (72 loc) 路 1.92 KB
/
utils.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
77
78
79
80
import { ref, watchEffect, watch, toRef, type Ref } from 'vue'
import type { HighlightOptions, ShikiHighlighter } from './types'
import { createHighlighter } from './shiki'
/**
* Lazy-load shiki instance.
*
* You can use this utility both in `server/` and vue app code.
*
* @example
* ```vue
* <script setup>
* const highlighter = await getShikiHighlighter()
* const html = highlighter.highlight(`const hello = 'shiki'`, { lang: 'js' })
* </script>
* ```
*
* @example
* ```ts
* // server/api/highlight.ts
* export default defineEventHandler(async (event) => {
* const highlighter = await getShikiHighlighter()
* return highlighter.highlight(`const hello = 'shiki'`, { lang: 'js' })
* })
* ```
*/
export async function getShikiHighlighter(): Promise<ShikiHighlighter> {
return createHighlighter(
import('shiki-options.mjs').then((m) => m.shikiOptions),
'_internal',
)
}
/**
* Return a lazy highlighted code ref (only usable in Vue)
*
* @example
* ```vue
* <script setup>
* const code = ref(`const hello = 'shiki'`)
* const highlighted = await useShikiHighlighted(code)
* </script>
* ```
*/
export async function useShikiHighlighted(
code: string | undefined | Ref<string | undefined>,
options: HighlightOptions & { highlighted?: string } = {},
) {
const _code = toRef(code)
if ('themes' in options && !options.themes) {
delete options.themes
}
if (import.meta.server) {
const highlighter = await getShikiHighlighter()
return ref(highlighter.highlight(_code.value || '', options))
}
const highlighted = ref(options.highlighted || '')
if (highlighted.value) {
const unwatch = watch(_code, () => {
unwatch()
init()
})
} else {
await init()
}
function init() {
getShikiHighlighter().then((highlighter) => {
watchEffect(() => {
highlighted.value = highlighter.highlight(_code.value || '', options)
})
})
}
return highlighted
}