* 处理单个文本节点,将其中的公式替换为渲染后的 HTML
(textNode)
| 246 | * 处理单个文本节点,将其中的公式替换为渲染后的 HTML |
| 247 | */ |
| 248 | function processTextNode(textNode) { |
| 249 | const text = textNode.textContent; |
| 250 | |
| 251 | // 匹配所有公式:$...$ 和 $$...$$ |
| 252 | const formulaRegex = /\$\$([^\$]+?)\$\$|\$([^\$\n]+?)\$/g; |
| 253 | |
| 254 | if (!formulaRegex.test(text)) return; |
| 255 | |
| 256 | // 重置正则 |
| 257 | formulaRegex.lastIndex = 0; |
| 258 | |
| 259 | const fragments = []; |
| 260 | let lastIndex = 0; |
| 261 | let match; |
| 262 | |
| 263 | while ((match = formulaRegex.exec(text)) !== null) { |
| 264 | // 添加公式前的文本 |
| 265 | if (match.index > lastIndex) { |
| 266 | fragments.push(document.createTextNode(text.substring(lastIndex, match.index))); |
| 267 | } |
| 268 | |
| 269 | // 渲染公式 |
| 270 | let formula = match[1] || match[2]; // $$...$$ 或 $...$ |
| 271 | const isDisplay = !!match[1]; |
| 272 | |
| 273 | // 预处理:修复常见的 LaTeX 错误 |
| 274 | formula = fixFormulaErrors(formula, isDisplay); |
| 275 | |
| 276 | try { |
| 277 | // 使用 KaTeX 渲染 |
| 278 | const span = document.createElement('span'); |
| 279 | span.className = isDisplay ? 'katex-block' : 'katex-inline'; |
| 280 | |
| 281 | if (typeof katex !== 'undefined') { |
| 282 | katex.render(formula, span, { |
| 283 | throwOnError: false, |
| 284 | displayMode: isDisplay |
| 285 | }); |
| 286 | fragments.push(span); |
| 287 | processedCount++; |
| 288 | } else { |
| 289 | // KaTeX 不可用,保留原文 |
| 290 | fragments.push(document.createTextNode(match[0])); |
| 291 | } |
| 292 | } catch (error) { |
| 293 | console.warn('[FormulaPostProcessor] 渲染公式失败:', formula, error); |
| 294 | // 渲染失败,保留原文 |
| 295 | fragments.push(document.createTextNode(match[0])); |
| 296 | } |
| 297 | |
| 298 | lastIndex = formulaRegex.lastIndex; |
| 299 | } |
| 300 | |
| 301 | // 添加剩余文本 |
| 302 | if (lastIndex < text.length) { |
| 303 | fragments.push(document.createTextNode(text.substring(lastIndex))); |
| 304 | } |
| 305 |
no test coverage detected