load-mathjax.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import getMeta from '../../utils/meta'
  2. let mathJaxPromise: Promise<typeof window.MathJax>
  3. export const loadMathJax = async () => {
  4. if (!mathJaxPromise) {
  5. mathJaxPromise = new Promise((resolve, reject) => {
  6. // https://docs.mathjax.org/en/v3.2-latest/upgrading/v2.html
  7. window.MathJax = {
  8. // https://docs.mathjax.org/en/latest/options/input/tex.html#the-configuration-block
  9. tex: {
  10. macros: {
  11. // Implements support for the \bm command from the bm package. It bolds the argument in math mode.
  12. // https://github.com/mathjax/MathJax/issues/1219#issuecomment-341059843
  13. bm: ['\\boldsymbol{#1}', 1],
  14. },
  15. inlineMath: [
  16. ['\\(', '\\)'],
  17. ['$', '$'],
  18. ],
  19. displayMath: [
  20. ['\\[', '\\]'],
  21. ['$$', '$$'],
  22. ],
  23. packages: {
  24. '[-]': [
  25. 'html', // avoid creating HTML elements/attributes
  26. 'require', // prevent loading disabled packages
  27. ],
  28. },
  29. processEscapes: true,
  30. processEnvironments: true,
  31. },
  32. loader: {
  33. load: [
  34. 'ui/safe', // https://docs.mathjax.org/en/latest/options/safe.html
  35. ],
  36. },
  37. options: {
  38. enableMenu: false, // https://docs.mathjax.org/en/latest/options/menu.html
  39. },
  40. startup: {
  41. typeset: false,
  42. },
  43. }
  44. const script = document.createElement('script')
  45. const path = getMeta('ol-mathJax3Path')
  46. if (!path) {
  47. reject(new Error('No MathJax path found'))
  48. return
  49. }
  50. script.src = path
  51. script.addEventListener('load', async () => {
  52. await window.MathJax.startup.promise
  53. document.head.appendChild(window.MathJax.svgStylesheet())
  54. resolve(window.MathJax)
  55. })
  56. script.addEventListener('error', reject)
  57. document.head.append(script)
  58. })
  59. }
  60. return mathJaxPromise
  61. }