2021-04-01 19:16:29 +00:00
|
|
|
---
|
|
|
|
import Prism from 'prismjs';
|
2022-03-25 21:13:28 +00:00
|
|
|
import { addAstro } from './internal.mjs';
|
2021-06-22 18:41:04 +00:00
|
|
|
import loadLanguages from 'prismjs/components/index.js';
|
2021-04-01 19:16:29 +00:00
|
|
|
|
2021-09-01 19:49:01 +00:00
|
|
|
export interface Props {
|
|
|
|
class?: string;
|
|
|
|
lang?: string;
|
|
|
|
code: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
const { class: className, lang, code } = Astro.props as Props;
|
|
|
|
|
2021-08-11 21:52:27 +00:00
|
|
|
let classLanguage = `language-${lang}`;
|
2021-04-01 19:16:29 +00:00
|
|
|
|
2021-04-08 19:17:00 +00:00
|
|
|
const languageMap = new Map([['ts', 'typescript']]);
|
|
|
|
|
2021-05-27 14:16:14 +00:00
|
|
|
if (lang == null) {
|
2021-04-08 19:17:00 +00:00
|
|
|
console.warn('Prism.astro: No language provided.');
|
|
|
|
}
|
|
|
|
|
|
|
|
const ensureLoaded = (lang) => {
|
2021-05-27 14:16:14 +00:00
|
|
|
if (lang && !Prism.languages[lang]) {
|
2021-04-08 19:17:00 +00:00
|
|
|
loadLanguages([lang]);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if (languageMap.has(lang)) {
|
|
|
|
ensureLoaded(languageMap.get(lang));
|
|
|
|
} else if (lang === 'astro') {
|
|
|
|
ensureLoaded('typescript');
|
|
|
|
addAstro(Prism);
|
|
|
|
} else {
|
2021-05-17 14:29:16 +00:00
|
|
|
ensureLoaded('markup-templating'); // Prism expects this to exist for a number of other langs
|
2021-04-08 19:17:00 +00:00
|
|
|
ensureLoaded(lang);
|
|
|
|
}
|
|
|
|
|
2021-05-27 14:16:14 +00:00
|
|
|
if (lang && !Prism.languages[lang]) {
|
2021-04-08 19:17:00 +00:00
|
|
|
console.warn(`Unable to load the language: ${lang}`);
|
|
|
|
}
|
|
|
|
|
2021-04-01 19:16:29 +00:00
|
|
|
const grammar = Prism.languages[lang];
|
2021-05-27 14:16:14 +00:00
|
|
|
let html = code;
|
|
|
|
if (grammar) {
|
|
|
|
html = Prism.highlight(code, grammar, lang);
|
|
|
|
}
|
2021-04-01 19:16:29 +00:00
|
|
|
---
|
|
|
|
|
2022-01-31 22:13:22 +00:00
|
|
|
<pre class={[className, classLanguage].join(' ')}><code class={classLanguage}><Fragment set:html={html} /></code></pre>
|