astro/packages/astro-prism/Prism.astro

50 lines
1.1 KiB
Text
Raw Normal View History

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