fraudTech commited on
Commit
e261d6d
·
1 Parent(s): 2b736fa
Files changed (1) hide show
  1. web/src/math-preprocessing.ts +0 -296
web/src/math-preprocessing.ts DELETED
@@ -1,296 +0,0 @@
1
- /**
2
- * Math Preprocessing for KaTeX Rendering
3
- *
4
- * This file contains utilities to preprocess mathematical content before
5
- * KaTeX rendering. It handles common LaTeX formatting issues, delimiter
6
- * normalization, and edge cases that would otherwise break rendering.
7
- */
8
-
9
- // Math environments that should be treated as display math
10
- const DISPLAY_MATH_ENVS = [
11
- 'aligned', 'align', 'align\\*', 'equation', 'equation\\*',
12
- 'gather', 'gather\\*', 'multline', 'multline\\*',
13
- 'array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix', 'Vmatrix',
14
- 'cases', 'split', 'eqnarray', 'eqnarray\\*',
15
- ];
16
-
17
- /**
18
- * Preprocesses content to make it KaTeX-compatible.
19
- * Comprehensive preprocessing to handle user input edge cases.
20
- * Backend prompt reduces LLM errors, but this handles ALL input.
21
- */
22
- export function preprocessMathContent(content: string): string {
23
- if (!content) return content;
24
-
25
- let processed = content;
26
-
27
- // Step -3: Strip LaTeX vertical spacing from line-break commands: \\[Nunit] → \\\\
28
- // This MUST run before Step 1 (/\\\\[/g conversion) because \\\\[4pt] contains \\[
29
- // which Step 1 would incorrectly convert to a display-math delimiter.
30
- processed = processed.replace(/\\\\(\[\s*[\d.]+\s*(?:mm|pt|em|ex|cm|in|pc|bp|sp|dd|cc|nd|nc)\s*\])/g, '\\\\');
31
-
32
- // Step -2: Convert ```math / ```latex / ```tex fenced code blocks to $$ display math.
33
- // The LLM sometimes wraps math in these fences. remark-gfm captures them as code nodes
34
- // BEFORE remark-math sees the content, so they never reach KaTeX. Converting them here
35
- // (before ReactMarkdown) ensures proper LaTeX rendering.
36
- processed = processed.replace(
37
- /^```[ \t]*(?:math|latex|tex)[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm,
38
- (_match: string, inner: string) => `\n$$\n${inner.trim()}\n$$\n`
39
- );
40
-
41
- // Step -2b: Convert plain (no-language) code fences whose content is a LaTeX display
42
- // math environment to $$ blocks. The LLM sometimes wraps \begin{aligned} / \begin{equation}
43
- // etc. in bare ``` fences (no language tag), which remark-gfm renders as <code> — bypassing
44
- // all math rendering. Only ``` fences with nothing (or only whitespace) after the opening
45
- // backticks are matched here; language-tagged fences are left untouched so that legitimate
46
- // code examples are preserved.
47
- processed = processed.replace(
48
- /^```[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm,
49
- (_match: string, inner: string) => {
50
- const trimmed = inner.trim();
51
- const hasMathEnv = DISPLAY_MATH_ENVS.some(env => {
52
- const envName = env.replace(/\\\*/g, '*');
53
- return trimmed.includes(`\\begin{${envName}}`);
54
- });
55
- if (hasMathEnv) {
56
- return `\n$$\n${trimmed}\n$$\n`;
57
- }
58
- return _match;
59
- }
60
- );
61
-
62
- // Step -1: Convert lone-$-on-its-own-line delimiters to $$ display math.
63
- // remark-math cannot parse multiline inline $...$. This pattern arises when the
64
- // AI writes inline math split across lines, or when \(...\) is later converted to $...$
65
- // and the expression spans multiple lines.
66
- // Pattern: newline + lone-$ (not $$) on its own line + content + lone-$ (not $$)
67
- //
68
- // Run twice to handle consecutive blocks.
69
- for (let _pass = 0; _pass < 2; _pass++) {
70
- processed = processed.replace(
71
- /\n[ \t]*(?<!\$)\$(?!\$)[ \t]*\n([\s\S]*?)\n[ \t]*(?<!\$)\$(?!\$)[ \t]*(?=\n|$)/g,
72
- (_match: string, inner: string) => `\n$$\n${inner.trim()}\n$$`
73
- );
74
- }
75
- // Also handle the edge case where the content starts at the very beginning of the string
76
- // (no leading newline before the opening $)
77
- processed = processed.replace(
78
- /^[ \t]*(?<!\$)\$(?!\$)[ \t]*\n([\s\S]*?)\n[ \t]*(?<!\$)\$(?!\$)[ \t]*(?=\n|$)/,
79
- (_match: string, inner: string) => `$$\n${inner.trim()}\n$$`
80
- );
81
-
82
- // Step 1: Normalize delimiters OUTSIDE existing $$ blocks only.
83
- // Convert \(...\) to $...$ and \[...\] to $$...$$
84
- // MUST run BEFORE Step 0 so that \[ \begin{aligned}...\end{aligned} \] is converted
85
- // to $$...$$ first — otherwise Step 0 would wrap the inner \begin{env} in $$, then
86
- // Step 1 would convert the outer \[ and \] into extra $$ markers, creating empty blocks
87
- // and leaving the \begin{aligned} as raw text outside any $$ wrapper.
88
- {
89
- const parts1 = processed.split(/(\$\$[\s\S]*?\$\$)/g);
90
- processed = parts1.map((part) => {
91
- if (part.startsWith('$$') && part.endsWith('$$')) return part;
92
- return part
93
- .replace(/\\\(/g, '$')
94
- .replace(/\\\)/g, '$')
95
- .replace(/\\\[/g, '\n$$\n')
96
- .replace(/\\\]/g, '\n$$\n');
97
- }).join('');
98
- }
99
-
100
- // Step 0a: Promote inline $\begin{display-env}...\end{display-env}$ to $$...$$
101
- // When the LLM wraps a display-only environment in single-$ delimiters, KaTeX renders
102
- // it in inline mode and shows a red error (bmatrix, aligned, etc. require display mode).
103
- // This step converts those to $$ display blocks BEFORE Step 0 handles bare environments.
104
- {
105
- const inlineDisplayPattern = new RegExp(
106
- `(?<!\\$)\\$(\\\\begin\\{(${DISPLAY_MATH_ENVS.join('|')})\\}[\\s\\S]*?\\\\end\\{\\2\\})\\$(?!\\$)`,
107
- 'g'
108
- );
109
- processed = processed.replace(inlineDisplayPattern, (_match, inner) => `$$\n${inner.trim()}\n$$`);
110
- }
111
-
112
- // Step 0: Wrap undelimited \begin{env}...\end{env} blocks in $$ delimiters.
113
- // Only wraps blocks that are NOT already inside existing $$ delimiters.
114
- // Runs AFTER Step 1 so that \[ \begin{aligned}...\end{aligned} \] is already $$-wrapped
115
- // and won't be double-wrapped here.
116
- {
117
- const envPattern = new RegExp(
118
- `\\\\begin\\{(${DISPLAY_MATH_ENVS.join('|')})\\}([\\s\\S]*?)\\\\end\\{\\1\\}`,
119
- 'g'
120
- );
121
- const parts = processed.split(/(\$\$[\s\S]*?\$\$)/g);
122
- processed = parts.map((part) => {
123
- // Odd-indexed parts are existing $$ blocks — leave them untouched
124
- if (part.startsWith('$$') && part.endsWith('$$')) return part;
125
- // Even-indexed parts are plain text — wrap any bare \begin{env}..\end{env}
126
- return part.replace(envPattern, (match) => `$$\n${match}\n$$`);
127
- }).join('');
128
- }
129
-
130
- // Step 0.5: Merge adjacent $$ blocks that are only separated by optional whitespace.
131
- // This occurs when the LLM writes $$expr =$$\begin{cases}...\end{cases} — Step 0 wraps
132
- // the \begin block, producing $$expr =$$\n$$\n\begin{cases}...\n$$. Those two consecutive
133
- // $$ blocks should be one combined display math expression.
134
- // NOTE: uses [ \t]*\n?[ \t]* (at most ONE newline with surrounding horizontal whitespace)
135
- // because Step 0 inserts exactly \n before the second $$. Using \s* would incorrectly merge
136
- // separate equations that happen to be on adjacent lines ($$a=b$$\n\n$$c=d$$).
137
- // Run twice to collapse 3+ consecutive $$ blocks (e.g. $$a=$$\n$$b=$$\n$$c$$).
138
- for (let _mergePass = 0; _mergePass < 2; _mergePass++) {
139
- processed = processed.replace(/\$\$([\s\S]*?)\$\$[ \t]*\n?[ \t]*\$\$([\s\S]*?)\$\$/g, (_match, a, b) => {
140
- return `$$\n${a.trim()} ${b.trim()}\n$$`;
141
- });
142
- }
143
-
144
- // Step 1.5: Re-run the lone-$-on-its-own-line fix AFTER delimiter normalization.
145
- // \(\ncontent\n\) becomes $\ncontent\n$ after Step 1, so we need another pass.
146
- for (let _pass2 = 0; _pass2 < 2; _pass2++) {
147
- processed = processed.replace(
148
- /\n[ \t]*(?<!\$)\$(?!\$)[ \t]*\n([\s\S]*?)\n[ \t]*(?<!\$)\$(?!\$)[ \t]*(?=\n|$)/g,
149
- (_match: string, inner: string) => `\n$$\n${inner.trim()}\n$$`
150
- );
151
- }
152
- processed = processed.replace(
153
- /^[ \t]*(?<!\$)\$(?!\$)[ \t]*\n([\s\S]*?)\n[ \t]*(?<!\$)\$(?!\$)[ \t]*(?=\n|$)/,
154
- (_match: string, inner: string) => `$$\n${inner.trim()}\n$$`
155
- );
156
-
157
- // Step 2: Fix content inside display math blocks.
158
- processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, inner) => {
159
- let cleaned = inner;
160
- // 2a: Remove lone $ that aren't escaped (i.e. not \$) and aren't part of $$
161
- cleaned = cleaned.replace(/(?<!\\)(?<!\$)\$(?!\$)/g, '');
162
- // 2b: Normalize \ <space> & → \\\ & inside aligned/matrix environments.
163
- // The LLM sometimes uses a single backslash-space as a line-break in aligned
164
- // instead of the correct \\\ (double backslash). This causes a KaTeX parse
165
- // error that shows the raw LaTeX source as plain text.
166
- // Negative lookbehind (?<!\\) avoids double-processing already-correct \\\ &.
167
- cleaned = cleaned.replace(/(?<!\\)\\ &/g, '\\\\ &');
168
- return `$$${cleaned}$$`;
169
- });
170
-
171
- // Step 3: Clean up delimiter stacking ($$$$, $$$, etc.)
172
- processed = processed.replace(/\${3,}/g, '$$');
173
-
174
- // Step 3.5: Remove empty display math blocks ($$\s*$$).
175
- // These are created when \[ \] (empty) is converted to $$…$$ or when delimiter
176
- // normalization produces adjacent $$ markers with only whitespace between them.
177
- processed = processed.replace(/\$\$\s*\$\$/g, '');
178
-
179
- // Step 4: Fix malformed \left and \right (only strip when completely invalid)
180
- // Only remove \left/\right when followed by another backslash-command (chained incorrectly)
181
- processed = processed.replace(/\\left\\frac/g, '\\frac');
182
- processed = processed.replace(/\\right\\frac/g, '\\frac');
183
- // Only strip bare \left/\right not followed by any bracket/delimiter character OR a letter.
184
- // Letters indicate it is part of a longer command: \leftarrow, \rightarrow,
185
- // \rightharpoonup, \leftrightarrow, etc. — those must NEVER be stripped.
186
- processed = processed.replace(/\\left(?![([{|.\\a-zA-Z])/g, '');
187
- processed = processed.replace(/\\right(?![)\]|}|.\\a-zA-Z])/g, '');
188
-
189
- // Step 5: Fix list markers contaminating delimiters (outside math blocks only)
190
- const displayMathSplit = processed.split(/(\$\$[\s\S]*?\$\$)/g);
191
- processed = displayMathSplit.map(segment => {
192
- if (segment.startsWith('$$') && segment.endsWith('$$')) {
193
- return segment;
194
- }
195
- let cleaned = segment;
196
- cleaned = cleaned.replace(/(\d+)\$\$/g, '$1. $$');
197
- cleaned = cleaned.replace(/\$\$(\d+)\$/g, '$$ $1.');
198
- // Only fix isolated $number$ patterns (likely stray list markers)
199
- cleaned = cleaned.replace(/(?<!\$)\$(\d+)\$(?!\$)/g, '$1.');
200
- return cleaned;
201
- }).join('');
202
-
203
- // Step 6: Ensure display math is on its own lines with blank-line separation.
204
- // Using \n\n before and after $$ ensures remark-math (micromark) parses them as
205
- // block-level math nodes rather than inline continuations inside a paragraph.
206
- processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, math) => {
207
- const trimmed = math.trim();
208
- return `\n\n$$\n${trimmed}\n$$\n\n`;
209
- });
210
-
211
- // Step 6.5: Remove empty display math blocks that Step 6 may have normalised to \n$$\n\n$$\n
212
- processed = processed.replace(/\n\$\$\n\s*\n\$\$\n/g, '\n');
213
-
214
- // Step 7: Fix spacing commands used outside math: \,2mm] → remove
215
- // This cleans up stray \2mm] artifacts from malformed \\[2mm] line spacing
216
- processed = processed.replace(/\\,?\d+(?:mm|pt|em|ex|cm)\]/g, '');
217
-
218
- // Step 8: Clean up multiple newlines
219
- processed = processed.replace(/\n{3,}/g, '\n\n');
220
-
221
- return processed;
222
- }
223
-
224
- /**
225
- * Extract math expressions from content for validation/preview
226
- */
227
- export function extractMathExpressions(content: string): Array<{
228
- type: 'inline' | 'display';
229
- content: string;
230
- raw: string;
231
- }> {
232
- const expressions: Array<{ type: 'inline' | 'display'; content: string; raw: string }> = [];
233
-
234
- // Extract display math $$...$$
235
- const displayRegex = /\$\$([\s\S]*?)\$\$/g;
236
- let match;
237
- while ((match = displayRegex.exec(content)) !== null) {
238
- expressions.push({
239
- type: 'display',
240
- content: match[1].trim(),
241
- raw: match[0]
242
- });
243
- }
244
-
245
- // Extract inline math $...$ (but not $$...$$)
246
- const inlineRegex = /(?<!\$)\$([^$\n]+?)\$(?!\$)/g;
247
- while ((match = inlineRegex.exec(content)) !== null) {
248
- expressions.push({
249
- type: 'inline',
250
- content: match[1].trim(),
251
- raw: match[0]
252
- });
253
- }
254
-
255
- return expressions;
256
- }
257
-
258
- /**
259
- * Check if content contains valid-looking math
260
- */
261
- export function hasMathContent(content: string): boolean {
262
- if (!content) return false;
263
-
264
- // Check for common math patterns
265
- const patterns = [
266
- /\$[^$]+\$/, // Inline math
267
- /\$\$[\s\S]*?\$\$/, // Display math
268
- /\\\([\s\S]*?\\\)/, // \(...\)
269
- /\\\[[\s\S]*?\\\]/, // \[...\]
270
- /\\begin\{(align|aligned|equation|gather|multline|math|displaymath)/, // Environments
271
- /\\(frac|sum|prod|int|lim|sqrt|alpha|beta|gamma|delta|epsilon|pi|theta|phi|lambda)/, // Common commands
272
- /_[a-zA-Z0-9]/, // Subscripts
273
- /\^[a-zA-Z0-9]/, // Superscripts
274
- ];
275
-
276
- return patterns.some(pattern => pattern.test(content));
277
- }
278
-
279
- /**
280
- * Sanitize math content to prevent XSS while preserving LaTeX
281
- * MathJax's safe extension handles most of this, but we add extra protection
282
- */
283
- export function sanitizeMathContent(content: string): string {
284
- if (!content) return content;
285
-
286
- // Remove script tags (though MathJax shouldn't execute them anyway)
287
- let sanitized = content.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
288
-
289
- // Remove event handlers
290
- sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
291
-
292
- // Allow only safe HTML tags that don't interfere with math
293
- // (MathJax handles the rest)
294
-
295
- return sanitized;
296
- }