This repository has been archived by the owner on May 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrp-katex.tsx
179 lines (152 loc) · 4.54 KB
/
rp-katex.tsx
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import * as React from "react";
import {forwardRef, useEffect,useImperativeHandle, useMemo, useRef} from "react";
import {usePlayer} from "liqvid";
declare global {
const katex: typeof katex;
}
// option of loading KaTeX asynchronously
const KaTeXLoad = new Promise<typeof katex>((resolve) => {
const script = document.querySelector(`script[src*="katex.js"], script[src*="katex.min.js"]`);
if (!script) return;
if (window.hasOwnProperty("katex")) {
resolve(katex);
} else {
script.addEventListener("load", () => resolve(katex));
}
});
// load macros from <head>
const KaTeXMacros = new Promise<{[key: string]: string;}>((resolve) => {
const macros: {[key: string]: string;} = {};
const scripts: HTMLScriptElement[] = Array.from(document.querySelectorAll("head > script[type='math/tex']"));
return Promise.all(
scripts.map(script =>
fetch(script.src)
.then(res => {
if (res.ok)
return res.text();
throw new Error(`${res.status} ${res.statusText}: ${script.src}`);
})
.then(tex => {
Object.assign(macros, parseMacros(tex));
})
)
).then(() => resolve(macros));
});
// ready Promise
const KaTeXReady = Promise.all([KaTeXLoad, KaTeXMacros]);
interface Props extends React.HTMLAttributes<HTMLSpanElement> {
display?: boolean;
}
export interface Handle {
domElement: HTMLSpanElement;
ready: Promise<void>;
}
// blocking version
const implementation: React.RefForwardingComponent<Handle, Props> = function KTX(props, ref) {
const spanRef = React.useRef<HTMLSpanElement>();
const {children, display, ...attrs} = props;
const resolveRef = useRef<() => void>();
const ready = useMemo(() => {
return new Promise<void>((resolve) => {
resolveRef.current = resolve;
});
}, []);
// handle
useImperativeHandle(ref, () => ({
domElement: spanRef.current,
ready
}));
useEffect(() => {
KaTeXReady.then(([katex, macros]) => {
katex.render(children.toString(), spanRef.current, {
displayMode: !!display,
macros,
strict: "ignore",
throwOnError: false,
trust: true
});
// move katex into placeholder element
const child = spanRef.current.firstElementChild as HTMLSpanElement;
for (let i = 0, len = child.classList.length; i < len; ++i) {
spanRef.current.classList.add(child.classList.item(i));
}
while (child.childNodes.length > 0) {
spanRef.current.appendChild(child.firstChild);
}
child.remove();
// resolve promise
resolveRef.current();
});
}, [children]);
// Google Chrome fails without this
if (display) {
if (!attrs.style)
attrs.style = {};
attrs.style.display = "block";
}
return (
<span {...attrs} ref={spanRef}/>
);
};
const KTXNonBlocking = forwardRef(implementation);
/**
Parse \newcommand macros in a file.
Also supports \ktxnewcommand (for use in conjunction with MathJax).
*/
function parseMacros(file: string) {
const macros = {};
const rgx = /\\(?:ktx)?newcommand\{(.+?)\}(?:\[\d+\])?\{/g;
let match: RegExpExecArray;
while (match = rgx.exec(file)) {
let body = "";
const macro = match[1];
let braceCount = 1;
for (let i = match.index + match[0].length; (braceCount > 0) && (i < file.length); ++i) {
const char = file[i];
if (char === "{") {
braceCount++;
} else if (char === "}") {
braceCount--;
if (braceCount === 0)
break;
} else if (char === "\\") {
body += file.slice(i, i+2);
++i;
continue;
}
body += char;
}
macros[macro] = body;
}
return macros;
}
// blocking version
const KTXBlocking = forwardRef<Handle, Props>(function KTX(props, ref) {
const player = usePlayer();
const innerRef = useRef<React.ElementRef<typeof KTXNonBlocking>>();
if (typeof ref === "function") {
ref(innerRef.current);
} else if (ref) {
ref.current = innerRef.current;
}
/* obstruction nonsense */
const resolve = useRef(null);
useMemo(() => {
const promise = new Promise((res) => {
resolve.current = res;
});
player.obstruct("canplay", promise);
player.obstruct("canplaythrough", promise);
}, []);
useEffect(() => {
if (typeof ref === "function") {
ref(innerRef.current);
} else if (ref) {
ref.current = innerRef.current;
}
innerRef.current.ready.then(() => resolve.current());
}, []);
return (<KTXNonBlocking ref={innerRef} {...props}/>);
});
// exports
export {KTXBlocking as KTX, KTXBlocking, KTXNonBlocking, KaTeXReady};