elk/composables/shiki.ts

64 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2022-11-30 08:45:42 +03:00
import type { Highlighter, Lang } from 'shiki-es'
2022-11-24 06:42:03 +03:00
2022-12-13 16:02:43 +03:00
const shiki = ref<Highlighter>()
2022-11-24 06:42:03 +03:00
const registeredLang = ref(new Map<string, boolean>())
let shikiImport: Promise<void> | undefined
2022-12-13 16:02:43 +03:00
export function useHightlighter(lang: Lang) {
2022-11-24 06:42:03 +03:00
if (!shikiImport) {
2022-11-30 08:45:42 +03:00
shikiImport = import('shiki-es')
2022-11-24 06:42:03 +03:00
.then(async (r) => {
r.setCDN('/shiki/')
shiki.value = await r.getHighlighter({
themes: [
'vitesse-dark',
'vitesse-light',
],
2022-11-30 10:15:26 +03:00
langs: [
'js',
'css',
2022-11-30 10:15:26 +03:00
'html',
],
2022-11-24 06:42:03 +03:00
})
})
}
if (!shiki.value)
2022-12-13 16:02:43 +03:00
return undefined
2022-11-24 06:42:03 +03:00
if (!registeredLang.value.get(lang)) {
shiki.value.loadLanguage(lang)
.then(() => {
registeredLang.value.set(lang, true)
})
2022-11-24 11:57:24 +03:00
.catch((e) => {
console.error(`[shiki] Failed to load language ${lang}`)
console.error(e)
registeredLang.value.set(lang, false)
})
2022-12-13 16:02:43 +03:00
return undefined
2022-11-24 06:42:03 +03:00
}
2022-12-13 16:02:43 +03:00
return shiki.value
}
export function useShikiTheme() {
return isDark.value ? 'vitesse-dark' : 'vitesse-light'
}
export function highlightCode(code: string, lang: Lang) {
const shiki = useHightlighter(lang)
if (!shiki)
return code
return shiki.codeToHtml(code, {
2022-11-24 06:42:03 +03:00
lang,
2022-12-13 16:02:43 +03:00
theme: useShikiTheme(),
2022-11-24 06:42:03 +03:00
})
}
2022-12-13 16:02:43 +03:00
export function useShiki() {
return shiki
}