| 1 | import flourite from "flourite" |
| 2 | import { decode } from "html-entities" |
| 3 | import { codeThemes, getHighlighter } from "@/utils/highlighter" |
| 4 | |
| 5 | const vShiki = { |
| 6 | created: async ( |
| 7 | el: HTMLElement, |
| 8 | binding: { value: { lang?: string; fallbackLang?: string; decode?: boolean } } |
| 9 | ) => { |
| 10 | const children = el.children[0] |
| 11 | |
| 12 | if (!children) return |
| 13 | |
| 14 | const code = binding?.value?.decode ? decode(children.innerHTML) : children.innerHTML |
| 15 | |
| 16 | let flouriteDetect = null |
| 17 | if (!binding?.value?.lang) { |
| 18 | const fl = flourite(code, { shiki: true }).language |
| 19 | if (fl !== "unknown") { |
| 20 | flouriteDetect = fl |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | const language = binding?.value?.lang || flouriteDetect || binding?.value?.fallbackLang || "text" |
| 25 | |
| 26 | const formattedCode = (val: string) => { |
| 27 | try { |
| 28 | return JSON.stringify(JSON.parse(val), null, 4) |
| 29 | } catch { |
| 30 | return val |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | const html = (await getHighlighter()).codeToHtml(formattedCode(code), { |
| 35 | lang: language, |
| 36 | themes: codeThemes |
| 37 | }) |
| 38 | el.innerHTML = html |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | export default vShiki |