elk/composables/shiki.ts

74 lines
1.7 KiB
TypeScript
Raw Normal View History

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