Skip to content

Commit 2ce857c

Browse files
author
Hamada Gasmallah
committed
feat: Implemented mathjax rendering as part of the react hook
1 parent 31e1a6e commit 2ce857c

File tree

2 files changed

+46
-21
lines changed

2 files changed

+46
-21
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "backstage-plugin-techdocs-addon-mathjax",
3-
"version": "0.0.2",
3+
"version": "0.0.3",
44
"main": "src/index.ts",
55
"types": "src/index.ts",
66
"license": "MIT",

src/Mathjax/Mathjax.ts

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,55 @@
11
import { useEffect } from 'react';
2+
import { useShadowRootElements } from '@backstage/plugin-techdocs-react';
3+
import { init } from 'mathjax';
24

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+
}
1022
};
1123

1224

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+
1446
useEffect(()=>{
1547

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]);
2853

2954
return null;
3055
};

0 commit comments

Comments
 (0)