-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
97 lines (85 loc) · 2.9 KB
/
index.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
import "./katex.css";
import { Devs } from "@utils/constants";
import definePlugin, { ReporterTestable } from "@utils/types";
import { makeLazy } from "@utils/lazy";
import { React, useEffect, useMemo, useState } from "@webpack/common";
// @ts-expect-error
export const getKatex = /* #__PURE__*/ makeLazy(async () => (await import("https://unpkg.com/[email protected]/dist/katex.mjs")).default);
export function useKatex() {
const [katex, setKatex] = useState();
useEffect(() => {
if (katex === undefined)
getKatex().then(setKatex);
});
return katex;
}
// @ts-expect-error
export const getDomPurify = /* #__PURE__*/ makeLazy(async () => (await import("https://unpkg.com/[email protected]/dist/purify.es.mjs")).default);
export function useDomPurify() {
const [domPurify, setDomPurify] = useState();
useEffect(() => {
if (domPurify === undefined)
getDomPurify().then(setDomPurify);
});
return domPurify;
}
export interface HighlighterProps {
lang?: string;
content: string;
isPreview: boolean;
tempSettings?: Record<string, any>;
}
export default definePlugin({
name: "KaTeX",
description: "TeX typesetting in discord",
authors: [Devs.skyevg],
reporterTestable: ReporterTestable.Patches,
patches: [
{
find: "codeBlock:{react(",
replacement: {
match: /codeBlock:\{react\((\i),(\i),(\i)\)\{/,
replace: "$&if($1.lang == 'latex' || $1.lang == 'tex') return $self.createBlock($1,$2,$3);"
}
},
{
find: "inlineCode:{react:(",
replacement: {
match: /inlineCode:\{react:\((\i),(\i),(\i)\)=>/,
replace: "$&($1.content.startsWith('$$') && $1.content.endsWith('$$'))?$self.createInline($1,$2,$3):"
}
}
],
start: async () => {
useKatex();
useDomPurify();
},
stop: () => {
},
createBlock: (props: HighlighterProps) => (
<LazyLatex displayMode formula={props.content} />
),
createInline: (props: HighlighterProps) => (
<LazyLatex formula={props.content.substring(1, props.content.length - 1)} />
),
});
function LazyLatex(props) {
const { formula } = props;
const katex = useKatex();
const domPurify = useDomPurify();
return katex && domPurify
? <Latex {...props} katex={katex} domPurify={domPurify} />
: <code>{formula}</code>;
}
function Latex({ katex, formula, displayMode, domPurify }) {
const result = useMemo(() => {
const html = katex.renderToString(formula, {
displayMode,
throwOnError: false
});
return domPurify.sanitize(html);
}, [formula, displayMode]);
return displayMode
? <div className="tex" dangerouslySetInnerHTML={{ __html: result }} />
: <span className="tex" dangerouslySetInnerHTML={{ __html: result }} />;
}