-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathMathJaxProvider.tsx
More file actions
109 lines (94 loc) · 2.58 KB
/
MathJaxProvider.tsx
File metadata and controls
109 lines (94 loc) · 2.58 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import React, { useEffect, useState, ReactNode } from 'react';
declare global {
interface Window {
MathJax: any;
}
}
interface MathJaxConfig {
/** 自定义 MathJax 脚本地址 */
scriptURL?: string;
tex?: {
inlineMath?: string[][];
displayMath?: string[][];
packages?: { [key: string]: string[] };
};
chtml?: {
fontURL?: string;
};
}
const DEFAULT_SCRIPT_URL = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js';
interface MathJaxProviderProps {
children: ReactNode;
config?: MathJaxConfig;
/** 自定义 MathJax 脚本地址,不传则使用默认 CDN */
scriptURL?: string;
loadingComponent?: ReactNode;
className?: string;
}
export default function MathJaxProvider({
children,
config,
scriptURL: scriptURLProp,
loadingComponent,
className = ""
}: MathJaxProviderProps) {
const [isClient, setIsClient] = useState(false);
const [mathJaxLoaded, setMathJaxLoaded] = useState(false);
const defaultConfig: MathJaxConfig = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
packages: {'[+]': ['ams', 'newcommand', 'configmacros']}
},
chtml: {
fontURL: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/output/chtml/fonts/woff-v2'
}
};
const finalConfig = {
...defaultConfig,
...config,
tex: { ...defaultConfig.tex, ...config?.tex },
chtml: { ...defaultConfig.chtml, ...config?.chtml }
};
const scriptURL = scriptURLProp ?? config?.scriptURL ?? DEFAULT_SCRIPT_URL;
useEffect(() => {
setIsClient(true);
window.MathJax = {
...finalConfig,
startup: {
ready: () => {
console.log('MathJax is ready');
window.MathJax.startup.defaultReady();
setMathJaxLoaded(true);
}
}
};
const script = document.createElement('script');
script.src = scriptURL;
script.async = true;
script.onload = () => {
console.log('MathJax script loaded');
};
document.head.appendChild(script);
return () => {
if (document.head.contains(script)) {
document.head.removeChild(script);
}
};
}, []);
useEffect(() => {
if (mathJaxLoaded && window.MathJax) {
window.MathJax.typesetPromise().then(() => {
console.log('MathJax typesetting complete');
});
}
}, [mathJaxLoaded]);
if (!isClient) {
return loadingComponent || <div className={className}>Loading...</div>;
}
return (
<div className={className}>
{mathJaxLoaded ? children : (loadingComponent || <div>Loading MathJax...</div>)}
</div>
);
}