1
0
mirror of https://github.com/elk-zone/elk synced 2024-11-23 22:56:09 +09:00
elk/composables/shikiji.ts

72 lines
1.6 KiB
TypeScript
Raw Normal View History

import { type Highlighter, type BuiltinLanguage as Lang } from 'shikiji'
2022-11-24 12:42:03 +09:00
const highlighter = ref<Highlighter>()
2022-11-24 12:42:03 +09:00
const registeredLang = ref(new Map<string, boolean>())
let shikijiImport: Promise<void> | undefined
2022-11-24 12:42:03 +09:00
export function useHighlighter(lang: Lang) {
if (!shikijiImport) {
shikijiImport = import('shikiji')
.then(async ({ getHighlighter }) => {
highlighter.value = await getHighlighter({
2022-11-24 12:42:03 +09:00
themes: [
'vitesse-dark',
'vitesse-light',
],
2022-11-30 16:15:26 +09:00
langs: [
'js',
'css',
2022-11-30 16:15:26 +09:00
'html',
],
2022-11-24 12:42:03 +09:00
})
})
}
if (!highlighter.value)
2022-12-13 22:02:43 +09:00
return undefined
2022-11-24 12:42:03 +09:00
if (!registeredLang.value.get(lang)) {
highlighter.value.loadLanguage(lang)
2022-11-24 12:42:03 +09:00
.then(() => {
registeredLang.value.set(lang, true)
})
2023-01-14 00:08:08 +09:00
.catch(() => {
const fallbackLang = 'md'
highlighter.value?.loadLanguage(fallbackLang).then(() => {
2023-01-14 00:08:08 +09:00
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
}
return highlighter.value
2022-12-13 22:02:43 +09:00
}
function useShikijiTheme() {
return useColorMode().value === 'dark' ? 'vitesse-dark' : 'vitesse-light'
2022-12-13 22:02:43 +09: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 22:02:43 +09:00
export function highlightCode(code: string, lang: Lang) {
const highlighter = useHighlighter(lang)
if (!highlighter)
return escapeHtml(code)
2022-12-13 22:02:43 +09:00
return highlighter.codeToHtml(code, {
2022-11-24 12:42:03 +09:00
lang,
theme: useShikijiTheme(),
2022-11-24 12:42:03 +09:00
})
}