okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-021-iE' into f-021-int3616148bb

main
2.0 KiB43 linesraw
1/**
2 * One formula of an answer (#3268), drawn by KaTeX. KaTeX and its fonts are bundled with the app (no network) and load as a separate
3 * chunk the first time an answer holds math, so a chat without math pays nothing. Until the chunk is there, and if it cannot load,
4 * the formula shows as its source text, as before.
5 */
6import { useEffect, useState } from 'react';
7
8type Katex = typeof import('katex').default;
9let loading: Promise<Katex> | null = null;
10const drawn = new Map<string, string>();
11
12function loadKatex(): Promise<Katex> {
13    loading ??= Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([module]) => module.default);
14    return loading;
15}
16
17function draw(katex: Katex, tex: string, display: boolean): string {
18    const key = (display ? 'D' : 'I') + tex;
19    const known = drawn.get(key);
20    if (known !== undefined)
21        return known;
22    // trust stays off (no \href, \url, \includegraphics); a broken formula is shown as its source, not as an error page
23    const html = katex.renderToString(tex, { displayMode: display, throwOnError: false, strict: 'ignore', trust: false, maxSize: 30, maxExpand: 500 });
24    if (drawn.size > 400)
25        drawn.clear();
26    drawn.set(key, html);
27    return html;
28}
29
30const source = (tex: string, display: boolean) => (display ? `$$${tex}$$` : `$${tex}$`);
31
32export function MathView({ tex, display }: { tex: string; display: boolean }) {
33    const [html, setHtml] = useState<string | null>(() => drawn.get((display ? 'D' : 'I') + tex) ?? null);
34    useEffect(() => {
35        let live = true;
36        loadKatex().then(katex => { if (live) setHtml(draw(katex, tex, display)); }).catch(() => { /* stays as source text */ });
37        return () => { live = false; };
38    }, [tex, display]);
39    const cls = display ? 'md-math md-math--display' : 'md-math';
40    if (html === null)
41        return <code className={cls + ' md-math--source'}>{source(tex, display)}</code>;
42    return <span className={cls} dangerouslySetInnerHTML={{ __html: html }}/>;
43}