|
1 | 1 | import { useEffect } from 'react'; |
| 2 | +import { useShadowRootElements } from '@backstage/plugin-techdocs-react'; |
| 3 | +import { init } from 'mathjax'; |
2 | 4 |
|
3 | | -function runTypeSet(){ |
4 | | - if (typeof (<any>window)?.MathJax !== "undefined"){ |
5 | | - console.log("MathJax was found and typeset is called!"); |
6 | | - (<any>window).MathJax.typeset(); |
7 | | - return true; |
8 | | - } |
9 | | - return false; |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +const mathjaxConfig = { |
| 9 | + loader: { |
| 10 | + load: ['input/tex', 'output/svg'], |
| 11 | + }, |
| 12 | + tex: { |
| 13 | + inlineMath: [["\\(", "\\)"]], |
| 14 | + displayMath: [["\\[", "\\]"]], |
| 15 | + processEscapes: true, |
| 16 | + processEnvironments: true |
| 17 | + }, |
| 18 | + options: { |
| 19 | + ignoreHtmlClass: ".*|", |
| 20 | + processHtmlClass: "arithmatex" |
| 21 | + } |
10 | 22 | }; |
11 | 23 |
|
12 | 24 |
|
13 | | -export const MathjaxAddon = () => { |
| 25 | +let mathjax: any; |
| 26 | +let mathjaxPromise = init(mathjaxConfig); |
| 27 | + |
| 28 | + |
| 29 | +async function processMathjax(preBlock: any){ |
| 30 | + if (!mathjax){ |
| 31 | + mathjax = await mathjaxPromise; |
| 32 | + } |
| 33 | + |
| 34 | + const blockText = preBlock.innerText; |
| 35 | + const svg = mathjax.tex2svg( blockText ); |
| 36 | + const svgHTML = mathjax.startup.adaptor.outerHTML(svg); |
| 37 | + preBlock.innerHTML = svgHTML; |
| 38 | + |
| 39 | +}; |
| 40 | + |
| 41 | + |
| 42 | +export const MathjaxAddon = () => { |
| 43 | + |
| 44 | + const mathjaxPreBlocks = useShadowRootElements<HTMLSpanElement>(['.arithmatex']); |
| 45 | + |
14 | 46 | useEffect(()=>{ |
15 | 47 |
|
16 | | - if (!runTypeSet()){ |
17 | | - console.log("No MathJax was found, now loading!"); |
18 | | - const script = document.createElement('script'); |
19 | | - script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'; |
20 | | - script.async = true; |
21 | | - document.body.appendChild(script); |
22 | | - setTimeout(()=>{ |
23 | | - runTypeSet(); |
24 | | - }, 500); |
25 | | - }; |
26 | | - |
27 | | - }, []); |
| 48 | + mathjaxPreBlocks.forEach(preBlock =>{ |
| 49 | + processMathjax(preBlock); |
| 50 | + }); |
| 51 | + |
| 52 | + }, [mathjaxPreBlocks]); |
28 | 53 |
|
29 | 54 | return null; |
30 | 55 | }; |
0 commit comments