okami.mom/strata

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

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

main
4.9 KiB130 linesraw
1/**
2 * Finding the math in an answer (#3268). Pure text work, no rendering: the pieces are drawn by components/MathView.tsx.
3 *
4 * Recognised, as models write them:
5 *   $$ ... $$ and \[ ... \]   display math (may span lines)
6 *   $ ... $  and \( ... \)    inline math (one line)
7 * A dollar sign that is money stays text: "costs $5 and $10" has no math, because an opening $ must be followed by a non-space,
8 * a closing $ must follow a non-space and must not be followed by a digit. `\$` is a literal dollar sign.
9 * Code (backtick spans, fenced blocks) is never searched: the caller splits it off first.
10 */
11export type MathPart = { kind: 'text'; text: string } | { kind: 'math'; tex: string; display: boolean };
12
13const isSpace = (c: string | undefined) => c === undefined || /\s/.test(c);
14const isDigit = (c: string | undefined) => c !== undefined && c >= '0' && c <= '9';
15
16/** Where the unescaped `close` starts at or after `from`, or -1. `\\` and `\$` style escapes are skipped. */
17function findClose(text: string, from: number, close: string, oneLine: boolean): number {
18    for (let i = from; i < text.length; i++) {
19        const c = text[i];
20        if (oneLine && c === '\n')
21            return -1;
22        if (c === '\\' && close !== '\\)' && close !== '\\]') {
23            i++;
24            continue;
25        }
26        if (text.startsWith(close, i))
27            return i;
28    }
29    return -1;
30}
31
32export function splitMath(text: string): MathPart[] {
33    const parts: MathPart[] = [];
34    let plain = '';
35    const flush = () => {
36        if (plain) {
37            parts.push({ kind: 'text', text: plain });
38            plain = '';
39        }
40    };
41    const push = (tex: string, display: boolean) => {
42        if (!tex.trim())
43            return false;
44        flush();
45        parts.push({ kind: 'math', tex: tex.trim(), display });
46        return true;
47    };
48    for (let i = 0; i < text.length;) {
49        const c = text[i];
50        if (c === '\\') {
51            const next = text[i + 1];
52            if (next === '$') {                       // \$ is a dollar sign
53                plain += '$';
54                i += 2;
55                continue;
56            }
57            if (next === '(' || next === '[') {
58                const close = next === '(' ? '\\)' : '\\]';
59                const end = findClose(text, i + 2, close, next === '(');
60                if (end > 0 && push(text.slice(i + 2, end), next === '[')) {
61                    i = end + 2;
62                    continue;
63                }
64            }
65            plain += c + (next ?? '');
66            i += 2;
67            continue;
68        }
69        if (c === '$') {
70            if (text[i + 1] === '$') {
71                const end = findClose(text, i + 2, '$$', false);
72                if (end > 0 && push(text.slice(i + 2, end), true)) {
73                    i = end + 2;
74                    continue;
75                }
76                plain += '$$';
77                i += 2;
78                continue;
79            }
80            if (!isSpace(text[i + 1])) {
81                const end = findClose(text, i + 1, '$', true);
82                if (end > i + 1 && !isSpace(text[end - 1]) && !isDigit(text[end + 1]) && push(text.slice(i + 1, end), false)) {
83                    i = end + 1;
84                    continue;
85                }
86            }
87        }
88        plain += c;
89        i++;
90    }
91    flush();
92    return parts;
93}
94
95/** True when the text holds any math, so a plain answer costs nothing. */
96export function hasMath(text: string): boolean {
97    return text.includes('$') || text.includes('\\(') || text.includes('\\[');
98}
99
100/**
101 * A block of display math that starts a line: `$$ ... $$` on one line, or `$$` / `\[` on its own line up to the line with the closing
102 * delimiter. Returns the formula and the number of lines used, or null (an unclosed block, e.g. while the answer is still streaming,
103 * stays text).
104 */
105export function displayBlock(lines: string[], at: number): { tex: string; used: number } | null {
106    const first = lines[at].trim();
107    const opens = first.startsWith('$$') ? '$$' : first.startsWith('\\[') ? '\\[' : '';
108    if (!opens)
109        return null;
110    const closes = opens === '$$' ? '$$' : '\\]';
111    const rest = first.slice(2);
112    const sameLine = rest.indexOf(closes);
113    if (sameLine >= 0) {
114        // "$$ x $$" alone on the line; text after the closing delimiter makes it an inline display in a paragraph instead
115        return rest.slice(sameLine + closes.length).trim() ? null : { tex: rest.slice(0, sameLine), used: 1 };
116    }
117    const body = [rest];
118    for (let j = at + 1; j < lines.length && j < at + 60; j++) {
119        const t = lines[j].trim();
120        const end = t.indexOf(closes);
121        if (end >= 0) {
122            if (t.slice(end + closes.length).trim())
123                return null;
124            body.push(t.slice(0, end));
125            return { tex: body.join('\n'), used: j - at + 1 };
126        }
127        body.push(lines[j]);
128    }
129    return null;
130}