-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
87 lines (74 loc) · 2.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import React from 'react';
import {SvgFromXml} from 'react-native-svg';
const mathjax = require('./mathjax/es5/js/mathjax.js').mathjax;
const TeX = require('./mathjax/es5/js/input/tex.js').TeX;
const SVG = require('./mathjax/es5/js/output/svg.js').SVG;
const liteAdaptor = require('./mathjax/es5/js/adaptors/liteAdaptor.js').liteAdaptor;
const RegisterHTMLHandler = require('./mathjax/es5/js/handlers/html.js').RegisterHTMLHandler;
const adaptor = liteAdaptor();
RegisterHTMLHandler(adaptor);
const AllPackages =
require("./mathjax/es5/js/input/tex/AllPackages").AllPackages;
const params = {
ex: 8,
em: 16,
width: 80,
inline: true,
packages: AllPackages.sort().join(", "),
fontCache: true
};
const getScale = _svgString => {
const svgString = _svgString.match(/<svg([^\>]+)>/gi).join("");
let [width, height] = (svgString || "")
.replace(
/.* width=\"([\d\.]*)[ep]x\".*height=\"([\d\.]*)[ep]x\".*/gi,
"$1,$2"
)
.split(/\,/gi);
[width, height] = [parseFloat(width), parseFloat(height)];
return [width, height];
};
const applyScale = (svgString, [width, height]) => {
let retSvgString = svgString.replace(
/(<svg[^\>]+height=\")([\d\.]+)([ep]x\"[^\>]+>)/gi,
`$1${height}$3`
);
retSvgString = retSvgString.replace(
/(<svg[^\>]+width=\")([\d\.]+)([ep]x\"[^\>]+>)/gi,
`$1${width}$3`
);
return retSvgString;
};
const applyColor = (svgString, fillColor) => {
return svgString.replace(/currentColor/gim, `${fillColor}`);;
};
const texToSvg = (textext = "", fontSize = 8) => {
if (!textext) {
return "";
}
const tex = new TeX({ packages: params.packages.split(/\s*,\s*/) });
const svg = new SVG({ fontCache: params.fontCache ? "local" : "none" });
const html = mathjax.document("", { InputJax: tex, OutputJax: svg });
const node = html.convert(textext, {
display: true,
em: params.em,
ex: params.ex
});
let svgString = adaptor.outerHTML(node) || "";
svgString = svgString.replace(
/\<mjx-container.*?\>(.*)\<\/mjx-container\>/gi,
"$1"
);
const [width, height] = getScale(svgString);
svgString = applyScale(svgString, [width * fontSize, height * fontSize]);
return `${svgString}`;
};
const MathJax = props => {
const textext = props.children || "";
const fontSize = props.fontSize ? props.fontSize / 2 : undefined;
let svgXml = texToSvg(textext, fontSize);
svgXml = applyColor(svgXml, props.color ? props.color : 'black');
return <SvgFromXml xml={svgXml} {...props} />;
};
export default MathJax;
export {texToSvg};