-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathindex.ts
More file actions
82 lines (71 loc) · 2.08 KB
/
index.ts
File metadata and controls
82 lines (71 loc) · 2.08 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
/** 默认 MathJax 脚本地址,可由用户通过 config.scriptURL 覆盖 */
export const DEFAULT_SCRIPT_URL = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js';
export const DEFAULT_CONFIG = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true,
processEnvironments: true,
packages: ['base', 'ams', 'newcommand', 'configmacros']
},
chtml: {
linebreaks: { automatic: true, width: 'container' }
},
startup: {
ready: () => {
console.log('MathJax v3 startup ready');
}
}
};
/** 扩展配置:可传入 scriptURL 自定义加载地址 */
export interface LoadMathJaxConfig extends Record<string, unknown> {
scriptURL?: string;
}
let mathJaxInstance: any = null;
export const getMathJax = () => mathJaxInstance || (globalThis as any).MathJax;
export const loadMathJax = async (
callback = () => { },
config: typeof DEFAULT_CONFIG & LoadMathJaxConfig = DEFAULT_CONFIG
) => {
if (typeof window === 'undefined') {
callback();
return;
}
if ((globalThis as any).MathJax) {
mathJaxInstance = (globalThis as any).MathJax;
callback();
return;
}
const scriptURL = config.scriptURL ?? DEFAULT_SCRIPT_URL;
try {
(globalThis as any).MathJax = {
...config,
startup: {
...config.startup,
ready: () => {
(globalThis as any).MathJax.startup.defaultReady();
mathJaxInstance = (globalThis as any).MathJax;
if (config.startup?.ready) {
config.startup.ready();
}
callback();
}
}
};
const script = document.createElement('script');
script.src = scriptURL;
script.async = true;
script.id = 'MathJax-script';
script.onload = () => {
console.log('MathJax v3 script loaded from CDN');
};
script.onerror = () => {
console.error('Failed to load MathJax v3 from CDN');
callback();
};
document.head.appendChild(script);
} catch (error) {
console.error('Failed to load MathJax v3:', error);
callback();
}
};