mirror of
https://example.com
synced 2024-11-22 15:26:38 +09:00
feat: auto load MkCode syntax highlight
This commit is contained in:
parent
030e31f3c5
commit
cb9ea0708a
2 changed files with 45 additions and 4 deletions
|
@ -7,8 +7,8 @@
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed } from "vue";
|
import { computed, ref } from "vue";
|
||||||
import Prism from "prismjs";
|
import Prism, { loadLanguage } from "@/scripts/prism";
|
||||||
import "prismjs/themes/prism-okaidia.css";
|
import "prismjs/themes/prism-okaidia.css";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
|
@ -17,9 +17,24 @@ const props = defineProps<{
|
||||||
inline?: boolean;
|
inline?: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const prismLang = computed(() =>
|
// fallback to "plaintext" if language not loaded
|
||||||
Prism.languages[props.lang] ? props.lang : "plaintext",
|
const prismLang = ref(
|
||||||
|
props.lang != null && props.lang in Prism.languages
|
||||||
|
? props.lang
|
||||||
|
: "plaintext",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// try to load language asynchronously
|
||||||
|
if (props.lang != null && !(props.lang in Prism.languages)) {
|
||||||
|
const { lang } = props;
|
||||||
|
loadLanguage(props.lang).then(
|
||||||
|
// onLoaded
|
||||||
|
() => (prismLang.value = lang),
|
||||||
|
// onError
|
||||||
|
() => {},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const html = computed(() =>
|
const html = computed(() =>
|
||||||
Prism.highlight(
|
Prism.highlight(
|
||||||
props.code,
|
props.code,
|
||||||
|
|
26
packages/client/src/scripts/prism.ts
Normal file
26
packages/client/src/scripts/prism.ts
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
import Prism from "prismjs";
|
||||||
|
import "prismjs/plugins/autoloader/prism-autoloader.js";
|
||||||
|
|
||||||
|
// TODO
|
||||||
|
Prism.plugins.autoloader.languages_path =
|
||||||
|
"https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/";
|
||||||
|
|
||||||
|
const nonExistingLanguagesCache = new Set<string>();
|
||||||
|
export const loadLanguage = (lang: string) =>
|
||||||
|
new Promise<void>((resolve, reject) => {
|
||||||
|
// cached non-existing language
|
||||||
|
if (nonExistingLanguagesCache.has(lang)) return reject();
|
||||||
|
// load language with autoloader
|
||||||
|
Prism.plugins.autoloader.loadLanguages(
|
||||||
|
lang,
|
||||||
|
// loaded
|
||||||
|
() => resolve(),
|
||||||
|
// failed
|
||||||
|
() => {
|
||||||
|
nonExistingLanguagesCache.add(lang);
|
||||||
|
reject();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Prism;
|
Loading…
Reference in a new issue