loadPrismLanguage.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import prismComponents from 'prismjs/components';
  2. /**
  3. * A mapping object containing all Prism languages/aliases that can be loaded using
  4. * `loadPrismLanguage`. Maps language aliases (`js`) to the full language name
  5. * (`javascript`).
  6. */
  7. export const prismLanguageMap: Record<string, string> = Object.fromEntries(
  8. Object.entries(prismComponents.languages)
  9. .map(([lang, value]) => {
  10. if (!value.alias) {
  11. return [[lang, lang]]; // map the full language name to itself
  12. }
  13. return [
  14. [lang, lang], // map the full language name to itself
  15. ...(Array.isArray(value.alias) // map aliases to full language name
  16. ? value.alias.map(alias => [alias, lang])
  17. : [[value.alias, lang]]),
  18. ];
  19. })
  20. .flat(1)
  21. );
  22. /**
  23. * Loads the specified Prism language (aliases like `js` for `javascript` also work).
  24. * Will log a warning if a) the language doesn't exist (unless `suppressExistenceWarning`
  25. * is true) or b) there was a problem downloading the grammar file.
  26. */
  27. export async function loadPrismLanguage(
  28. lang: string,
  29. {
  30. onError,
  31. onLoad,
  32. suppressExistenceWarning,
  33. }: {
  34. onError?: (error) => void;
  35. onLoad?: () => void;
  36. suppressExistenceWarning?: boolean;
  37. }
  38. ) {
  39. try {
  40. const language: string | undefined = prismLanguageMap[lang.toLowerCase()];
  41. // If Prism doesn't have any grammar file available for the language
  42. if (!language) {
  43. if (!suppressExistenceWarning) {
  44. // eslint-disable-next-line no-console
  45. console.warn(
  46. `No Prism grammar file for \`${lang}\` exists. Check the \`lang\` argument passed to \`loadPrismLanguage()\`.`
  47. );
  48. }
  49. return;
  50. }
  51. // Check for dependencies (e.g. `php` requires `markup-templating`) & download them
  52. const deps: string[] | string | undefined =
  53. prismComponents.languages[language].require;
  54. (Array.isArray(deps) ? deps : [deps]).forEach(
  55. async dep => dep && (await import(`prismjs/components/prism-${dep}.min`))
  56. );
  57. // Download language grammar file
  58. await import(`prismjs/components/prism-${language}.min`);
  59. onLoad?.();
  60. } catch (error) {
  61. // eslint-disable-next-line no-console
  62. console.warn(
  63. `Cannot download Prism grammar file for \`${lang}\`. Check the internet connection, and the \`lang\` argument passed to \`loadPrismLanguage()\`.`
  64. );
  65. onError?.(error);
  66. }
  67. }