File size: 2,358 Bytes
114f6bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d24ee3
114f6bd
 
 
 
 
 
3d24ee3
114f6bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const fs = require('fs');
const path = require('path');

const scriptDir = __dirname;
const katexJsPath = path.join(scriptDir, 'assets', 'katex.min.js');
const katexCssPath = path.join(scriptDir, 'assets', 'katex.min.css');

const code = fs.readFileSync(katexJsPath, 'utf8');
const katexCss = fs.readFileSync(katexCssPath, 'utf8');

const m = { exports: {} };
const fn = new Function('module', 'exports', code);
fn(m, m.exports);
const katex = m.exports;

let eqCounter = 0;

function renderMath(text) {
    eqCounter = 0;

    // First replace block math $$ ... $$
    let output = text.replace(/\$\$([\s\S]+?)\$\$/g, (match, eq) => {
        eqCounter++;
        const rawEq = eq.trim();
        try {
            const mathHtml = katex.renderToString(rawEq, {
                displayMode: true,
                output: 'htmlAndMathml',
                throwOnError: false,
                strict: false
            });
            return `<table class="eq-table"><tr><td class="eq-cell-math">${mathHtml}</td><td class="eq-cell-num">(${eqCounter})</td></tr></table>`;
        } catch (e) {
            console.error('KaTeX block error on:', rawEq, e);
            return match;
        }
    });

    // Next replace inline math $ ... $ (excluding escaped \$)
    output = output.replace(/(?<!\\)\$([^\$\n]+?)(?<!\\)\$/g, (match, eq) => {
        const rawEq = eq.trim();
        try {
            return katex.renderToString(rawEq, {
                displayMode: false,
                output: 'htmlAndMathml',
                throwOnError: false,
                strict: false
            });
        } catch (e) {
            console.error('KaTeX inline error on:', rawEq, e);
            return match;
        }
    });

    // Also replace KaTeX CSS placeholder if present
    if (output.includes('/* __KATEX_CSS__ */')) {
        output = output.replace('/* __KATEX_CSS__ */', katexCss);
    }

    return output;
}

module.exports = { renderMath, katexCss };

if (require.main === module) {
    const inputFile = process.argv[2];
    const outputFile = process.argv[3] || inputFile;
    if (inputFile) {
        const raw = fs.readFileSync(inputFile, 'utf8');
        const rendered = renderMath(raw);
        fs.writeFileSync(outputFile, rendered, 'utf8');
        console.log(`Pre-rendered KaTeX math from ${inputFile} -> ${outputFile}`);
    }
}