-
Notifications
You must be signed in to change notification settings - Fork 1
/
useKaTeX.ts
45 lines (40 loc) · 1.08 KB
/
useKaTeX.ts
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
import { type RefCallback, useCallback, useState } from "./deps/preact.tsx";
import { importKaTeX, KatexOptions } from "./katex.ts";
export interface ParseError {
name: string;
message: string;
position: number;
}
export interface UseKaTeXResult<T extends HTMLElement> {
ref: RefCallback<T>;
error: string;
}
export const useKaTeX = <T extends HTMLElement>(
formula: string,
options?: KatexOptions,
): UseKaTeXResult<T> => {
const [error, setError] = useState<string>("");
const ref: RefCallback<T> = useCallback(
(element) => {
if (!element) {
setError("");
return;
}
importKaTeX().then((katex) => {
try {
katex.render(formula, element, options);
setError("");
} catch (e) {
if (e instanceof Error && e.name === "ParseError") {
// remove an unnecessary token
setError(e.message.slice("KaTeX parse error: ".length));
} else {
throw e;
}
}
});
},
[formula, ...Object.values(options ?? {})],
);
return { ref, error };
};