feat(渲染): 支持 LaTeX 数学公式,KaTeX 本地化

聊天消息与 md 文件预览都支持 $...$ 行内与 $$...$$ 块级。

实现:占位符往返,不用 marked 扩展
- 解析前把公式抠成 @@MATHn@@(跳过围栏代码与行内代码)
- marked 正常解析后把占位换回 KaTeX 输出
- 这样公式里的 * _ \ { } 不会被 marked 当成强调/转义

行内 $ 的边界判断:前后紧邻字母/数字时不识别,避免「花了 $5 和 $6」被当公式。

KaTeX 0.16.11 本地 vendor(592KB,含 20 个 woff2 字体),不走 CDN。
md 预览的新窗口用根绝对路径引入 CSS,blob 文档的相对路径找不到字体。
This commit is contained in:
2026-11-17 22:42:48 +08:00
parent 85984e1ee2
commit 488734641d
27 changed files with 141 additions and 3 deletions
+7 -1
View File
@@ -48,7 +48,13 @@
if (typeof marked !== 'undefined') marked.setOptions({ breaks: true, gfm: true });
function mdHtml(text) {
if (typeof marked === 'undefined') return { html: esc(text), fmt: false };
try { return { html: marked.parse(text || ''), fmt: true }; }
try {
// 公式先抠成占位、marked 解析完再填回 KaTeX 输出(见 math.js)
const html = typeof mdParseWithMath === 'function'
? mdParseWithMath(text || '', marked)
: marked.parse(text || '');
return { html: html, fmt: true };
}
catch (_) { return { html: esc(text), fmt: false }; }
}
function fmtTime(ts) {
+116
View File
@@ -0,0 +1,116 @@
// 数学公式渲染(KaTeX 本地化,vendor/katex/)。
// 所有 markdown 入口(聊天气泡 / md 文件预览 / 流式增量)都走 core.js 的 mdHtml(),
// 公式处理收在这一个文件里,不散落到各处。
//
// 支持:
// $$...$$ 块级(可换行)
// $...$ 行内($ 后不能是空白、前不能是数字/字母,避免「$5 ... $6」被当公式)
//
// 实现方式:占位符往返,而不是 marked 扩展。
// 1) markdown 解析前,把公式抠成 @@MATHn@@ 占位(跳过围栏代码与行内代码)
// 2) 交给 marked 正常解析
// 3) 输出 HTML 里把占位换回 KaTeX 渲染结果
// 这样公式里的 * _ \ { } 不会被 marked 当成强调/转义吃掉。
const MATH_PH = /@@MATH(\d+)@@/g;
// 从 markdown 源里抠出公式,返回 { md, store }
function mathExtract(src) {
const text = String(src || '');
const store = [];
let out = '';
let i = 0;
while (i < text.length) {
// 围栏代码块整段跳过(三个反引号)
if (text.startsWith('```', i)) {
const end = text.indexOf('```', i + 3);
const stop = end < 0 ? text.length : end + 3;
out += text.slice(i, stop);
i = stop;
continue;
}
// 行内代码跳过
if (text[i] === '`') {
const end = text.indexOf('`', i + 1);
if (end > i) {
out += text.slice(i, end + 1);
i = end + 1;
continue;
}
}
// 块级 $$...$$
if (text.startsWith('$$', i)) {
const end = text.indexOf('$$', i + 2);
if (end > i + 2) {
const latex = text.slice(i + 2, end).trim();
if (latex) {
store.push({ latex: latex, display: true });
out += '@@MATH' + (store.length - 1) + '@@';
i = end + 2;
continue;
}
}
}
// 行内 $...$
if (text[i] === '$') {
const m = /^\$(?!\s)((?:\\.|[^$\\\n])+?)(?<!\s)\$/.exec(text.slice(i));
if (m) {
const before = i > 0 ? text[i - 1] : '';
const after = text[i + m[0].length] || '';
// 前后紧邻字母/数字时不当公式:$5 和 $6、a$b$c 之类
if (!/[0-9A-Za-z]/.test(before) && !/[0-9A-Za-z]/.test(after)) {
store.push({ latex: m[1], display: false });
out += '@@MATH' + (store.length - 1) + '@@';
i += m[0].length;
continue;
}
}
}
out += text[i];
i++;
}
return { md: out, store: store };
}
function mathEsc(s) {
return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) {
return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c];
});
}
// 单个公式 → HTML。KaTeX 不存在或 LaTeX 有错时原样吐回,用户能看见哪里写错了。
function mathRenderOne(latex, display) {
const wrap = display ? '$$' : '$';
if (typeof katex === 'undefined') {
return '<span class="math-fallback">' + wrap + mathEsc(latex) + wrap + '</span>';
}
try {
const html = katex.renderToString(latex, {
displayMode: display,
throwOnError: false,
output: 'html',
strict: false,
});
// 块级公式自己占一行;行内公式保持内联
return display ? '<span class="math-block">' + html + '</span>' : '<span class="math-inline">' + html + '</span>';
} catch (e) {
return '<span class="math-error" title="' + mathEsc(String((e && e.message) || e)) + '">' +
wrap + mathEsc(latex) + wrap + '</span>';
}
}
// 把 HTML 里的占位换回渲染结果
function mathExpand(html, store) {
if (!store || !store.length) return html;
return String(html || '').replace(MATH_PH, function (all, idx) {
const item = store[Number(idx)];
return item ? mathRenderOne(item.latex, item.display) : all;
});
}
// 一步到位:markdown → 含公式的 HTML。markedRef 由调用方传入(core.js 里的全局 marked)
function mdParseWithMath(text, markedRef) {
const r = mathExtract(text);
const html = markedRef.parse(r.md);
return mathExpand(html, r.store);
}
+7 -2
View File
@@ -497,17 +497,22 @@ function pvCloseOverlayQuiet() { const fs = document.getElementById('fs-viewer')
// 其余按 text/plain 原样打开——服务端文件响应一律 attachment,直接导航只会触发下载。
// md 里原样透传的 <script> 在面板(innerHTML)本就不执行,但 blob 文档会执行,故先剔除以保持一致。
function pvMdDoc(html, name) {
// KaTeX 样式表用根绝对路径引入:blob 文档的 base 是 blob:,相对路径找不到字体
const css =
'body{margin:0;padding:24px 32px 48px;max-width:900px;font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#1f2328;background:#fff}' +
'img{max-width:100%;height:auto}pre{background:#f6f8fa;padding:12px 14px;border-radius:8px;overflow:auto}' +
'code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}' +
'table{border-collapse:collapse}th,td{border:1px solid #d8dee4;padding:6px 10px}' +
'blockquote{margin:0;padding:0 14px;color:#57606a;border-left:3px solid #d8dee4}' +
'a{color:#0969da}';
'a{color:#0969da}' +
'.math-block{display:block;text-align:center;margin:14px 0;overflow-x:auto;overflow-y:hidden}';
const title = esc(String(name || '').split('/').pop() || '预览');
const origin = (typeof location !== 'undefined' && location.origin) ? location.origin : '';
return '<!DOCTYPE html><html><head><meta charset="utf-8">' +
'<meta name="viewport" content="width=device-width,initial-scale=1">' +
'<title>' + title + '</title><style>' + css + '</style></head><body>' +
'<title>' + title + '</title>' +
'<link rel="stylesheet" href="' + origin + '/vendor/katex/katex.min.css">' +
'<style>' + css + '</style></head><body>' +
html.replace(/<script\b[\s\S]*?(?:<\/script\s*>|$)/gi, '') + '</body></html>';
}
function pvTextUrl(text) { return URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); }