File size: 1,312 Bytes
aea470f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { memo, useEffect, useRef } from "react";

interface MathBlockProps { content: string; inline?: boolean }

const MathBlock = memo(function MathBlock({ content, inline = false }: MathBlockProps) {
  const ref = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    if (!ref.current) return;
    let cancelled = false;
    import("katex").then(katex => {
      if (cancelled || !ref.current) return;
      try {
        katex.default.render(content.trim(), ref.current, {
          displayMode: !inline,
          throwOnError: false,
          output: "html",
          trust: false,
        });
      } catch (e) {
        if (ref.current) ref.current.textContent = content;
      }
    }).catch(() => {
      if (ref.current) ref.current.textContent = content;
    });
    return () => { cancelled = true; };
  }, [content, inline]);

  if (inline) {
    return <span ref={ref} style={{ fontFamily: "KaTeX_Main, serif" }} />;
  }

  return (
    <div style={{
      background: "#0d0d18", border: "1px solid #1e1e2e", borderRadius: 10,
      padding: "0.75rem 1rem", marginBottom: "0.6em",
      display: "flex", justifyContent: "center", overflowX: "auto",
    }}>
      <span ref={ref} style={{ fontFamily: "KaTeX_Main, serif", fontSize: "1.05em" }} />
    </div>
  );
}
);
export default MathBlock;