2022-11-30 14:45:42 +09:00
|
|
|
import type { Highlighter, Lang } from 'shiki-es'
|
2022-11-24 12:42:03 +09:00
|
|
|
|
2022-12-13 22:02:43 +09:00
|
|
|
const shiki = ref<Highlighter>()
|
2022-11-24 12:42:03 +09:00
|
|
|
|
|
|
|
const registeredLang = ref(new Map<string, boolean>())
|
|
|
|
let shikiImport: Promise<void> | undefined
|
|
|
|
|
2023-01-17 15:47:46 +09:00
|
|
|
export function useHighlighter(lang: Lang) {
|
2022-11-24 12:42:03 +09:00
|
|
|
if (!shikiImport) {
|
2022-11-30 14:45:42 +09:00
|
|
|
shikiImport = import('shiki-es')
|
2022-11-24 12:42:03 +09:00
|
|
|
.then(async (r) => {
|
|
|
|
r.setCDN('/shiki/')
|
|
|
|
shiki.value = await r.getHighlighter({
|
|
|
|
themes: [
|
|
|
|
'vitesse-dark',
|
|
|
|
'vitesse-light',
|
|
|
|
],
|
2022-11-30 16:15:26 +09:00
|
|
|
langs: [
|
2022-12-03 02:40:02 +09:00
|
|
|
'js',
|
|
|
|
'css',
|
2022-11-30 16:15:26 +09:00
|
|
|
'html',
|
|
|
|
],
|
2022-11-24 12:42:03 +09:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!shiki.value)
|
2022-12-13 22:02:43 +09:00
|
|
|
return undefined
|
2022-11-24 12:42:03 +09:00
|
|
|
|
|
|
|
if (!registeredLang.value.get(lang)) {
|
|
|
|
shiki.value.loadLanguage(lang)
|
|
|
|
.then(() => {
|
|
|
|
registeredLang.value.set(lang, true)
|
|
|
|
})
|
2023-01-14 00:08:08 +09:00
|
|
|
.catch(() => {
|
|
|
|
const fallbackLang = 'md'
|
|
|
|
shiki.value?.loadLanguage(fallbackLang).then(() => {
|
|
|
|
registeredLang.value.set(fallbackLang, true)
|
|
|
|
})
|
2022-11-24 17:57:24 +09:00
|
|
|
})
|
2022-12-13 22:02:43 +09:00
|
|
|
return undefined
|
2022-11-24 12:42:03 +09:00
|
|
|
}
|
|
|
|
|
2022-12-13 22:02:43 +09:00
|
|
|
return shiki.value
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useShikiTheme() {
|
2022-12-29 21:26:08 +09:00
|
|
|
return useColorMode().value === 'dark' ? 'vitesse-dark' : 'vitesse-light'
|
2022-12-13 22:02:43 +09:00
|
|
|
}
|
|
|
|
|
2023-01-15 19:48:22 +09:00
|
|
|
const HTML_ENTITIES = {
|
|
|
|
'<': '<',
|
|
|
|
'>': '>',
|
|
|
|
'&': '&',
|
|
|
|
'\'': ''',
|
|
|
|
'"': '"',
|
|
|
|
} as Record<string, string>
|
|
|
|
|
|
|
|
function escapeHtml(text: string) {
|
|
|
|
return text.replace(/[<>&'"]/g, ch => HTML_ENTITIES[ch])
|
|
|
|
}
|
|
|
|
|
2022-12-13 22:02:43 +09:00
|
|
|
export function highlightCode(code: string, lang: Lang) {
|
2023-01-17 15:25:57 +09:00
|
|
|
const shiki = useHighlighter(lang)
|
2022-12-13 22:02:43 +09:00
|
|
|
if (!shiki)
|
2023-01-15 19:48:22 +09:00
|
|
|
return escapeHtml(code)
|
2022-12-13 22:02:43 +09:00
|
|
|
|
|
|
|
return shiki.codeToHtml(code, {
|
2022-11-24 12:42:03 +09:00
|
|
|
lang,
|
2022-12-13 22:02:43 +09:00
|
|
|
theme: useShikiTheme(),
|
2022-11-24 12:42:03 +09:00
|
|
|
})
|
|
|
|
}
|
2022-12-13 22:02:43 +09:00
|
|
|
|
|
|
|
export function useShiki() {
|
|
|
|
return shiki
|
|
|
|
}
|