fix(guide): fix KaTeX math rendering in Guided Learning pages

- Configure $...$ and $$...$$ delimiters in auto-render (KaTeX default
  only recognizes $$..$$ and \(\..\))
- Remove broken SRI integrity hashes from CDN links (hash mismatch blocks
  resource loading)
- Add parent-window fallback rendering: detects bare LaTeX text nodes
  (e.g. \underbrace, \mathbb without $ wrapping), auto-wraps them,
  then calls renderMathInElement — handles cases where inline init script
  gets corrupted by page content containing </script> strings
- Increase guide agent max_tokens 8192->16384 to prevent HTML truncation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
kevin
2026-04-08 09:17:59 +08:00
parent 5c048a9609
commit 055c467a40
2 changed files with 131 additions and 40 deletions

View File

@@ -12,6 +12,13 @@ interface HTMLViewerProps {
onOpenDebugModal: () => void;
}
/**
* Regex that matches common LaTeX patterns NOT already wrapped in $..$ or $$..$$.
* Used to detect bare LaTeX commands in text nodes.
*/
const BARE_LATEX_RE =
/(?<![\\$])(?:\\(?:underbrace|mathbb|frac|text|sqrt|subseteq|supseteq|notsubset|mid|pmod|leq|geq|Rightarrow|Leftarrow|Rightarrow|neq|approx|infty|partial|nabla|forall|exists|emptyset|varnothing|in|notin|alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega|vec|hat|bar|dot|tilde|overline|overbrace|boldsymbol|mathrm|mathit|mathbf|mathcal|mathfrak|mathscr|mathsf|mathtt|quad|qquad|ldots|cdots|vdots|ddots|prime|limits|sum|int|prod|oint|bigcup|bigcap|bigvee|bigwedge|bigoplus|bigotimes|binom|choose)[\s{])|\{[^}]*\\(?:underbrace|mathbb|frac|text|sqrt)/;
export default function HTMLViewer({
html,
currentIndex,
@@ -53,12 +60,100 @@ export default function HTMLViewer({
const timer = setTimeout(() => {
if (htmlFrameRef.current) {
const iframe = htmlFrameRef.current;
// Set srcdoc
iframe.srcdoc = htmlWithKaTeX;
lastWrittenRef.current = htmlWithKaTeX;
/**
* Fallback rendering strategy:
* 1. Wait for CDN scripts to load
* 2. Find text nodes with bare LaTeX (no $ wrapping)
* 3. Wrap them in $...$ delimiters
* 4. Call renderMathInElement to render everything
*/
const fallbackDelays = [1500, 3000];
const fallbackTimers = fallbackDelays.map((delay) =>
setTimeout(() => {
try {
const doc = iframe.contentDocument;
if (!doc || !doc.body) return;
const win = doc.defaultView as Window & {
renderMathInElement?: (el: HTMLElement, opts: Record<string, unknown>) => void;
};
if (typeof win?.renderMathInElement !== "function") return;
let wrappedCount = 0;
// Step 1: Find text nodes with bare LaTeX and fix them
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);
const nodesToProcess: Text[] = [];
let node: Text | null;
while ((node = walker.nextNode() as Text | null)) {
// Skip if inside a .katex element (already rendered)
const parent = node.parentElement;
if (parent && parent.closest(".katex")) continue;
const text = node.textContent || "";
// Check for bare LaTeX patterns not already delimited
if (BARE_LATEX_RE.test(text) && !/^\$.*\$$/.test(text.trim())) {
nodesToProcess.push(node);
}
}
// Process each bare LaTeX text node
for (const textNode of nodesToProcess) {
const originalText = textNode.textContent || "";
const trimmed = originalText.trim();
// Skip already-delimited content
if (
trimmed.startsWith("$") ||
trimmed.endsWith("$") ||
trimmed.startsWith("\\(") ||
trimmed.startsWith("\\[")
)
continue;
// Wrap the entire text node content in $...$
// KaTeX handles non-math parts gracefully (renders them as \text{})
const span = doc.createElement("span");
span.textContent = `$${originalText}$`;
textNode.parentNode?.replaceChild(span, textNode);
wrappedCount++;
}
// Step 2: Render all math (including newly wrapped)
win.renderMathInElement(doc.body, {
delimiters: [
{ left: "$$", right: "$$", display: true },
{ left: "$", right: "$", display: false },
{ left: "\\(", right: "\\)", display: false },
{ left: "\\[", right: "\\]", display: true },
],
throwOnError: false,
});
if (wrappedCount > 0) {
console.log(`[KaTeX] Auto-wrapped ${wrappedCount} bare LaTeX nodes`);
}
} catch (_e) {
// Silently ignore fallback errors
}
}, delay),
);
// Store cleanup refs
(iframe as unknown as Record<string, unknown>).__fallbackTimers = fallbackTimers;
}
}, 100);
return () => clearTimeout(timer);
return () => {
clearTimeout(timer);
// Clear any pending fallback timers from previous render
const prev = htmlFrameRef.current as unknown as Record<string, unknown> | null;
if (prev?.__fallbackTimers) {
(prev.__fallbackTimers as ReturnType<typeof setTimeout>[]).forEach(clearTimeout);
}
};
}, [html, currentIndex, injectKaTeX]);
if (!html) {

View File

@@ -1,12 +1,13 @@
/**
* Hook for injecting KaTeX support into HTML content
* Hook for injecting KaTeX resources + render script into HTML content.
*
* Strategy: inject CDN resources into <head> + a small inline init script
* that polls for renderMathInElement availability. HTMLViewer also has
* a parent-window fallback in case the inline script gets corrupted by
* page content containing "</script>" strings.
*/
export function useKaTeXInjection() {
/**
* Inject KaTeX CSS and JS into HTML if not already present
*/
const injectKaTeX = (html: string): string => {
// Check if KaTeX is already included (case-insensitive)
const htmlLower = html.toLowerCase();
const hasKaTeX =
htmlLower.includes("katex.min.css") ||
@@ -16,55 +17,50 @@ export function useKaTeXInjection() {
htmlLower.includes("unpkg.com/katex");
if (hasKaTeX) {
console.log("KaTeX already included in HTML, skipping injection");
console.log("[KaTeX] Already included, skipping injection");
return html;
}
// KaTeX CDN links (using version 0.16.9 for compatibility)
const katexCSS =
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">';
const katexJS =
'<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>';
const katexAutoRender =
'<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>';
// CDN resources (no SRI hash to avoid mismatch)
const katexResources = [
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" crossorigin="anonymous">',
'<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js" crossorigin="anonymous"><' + "/script>",
'<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js" crossorigin="anonymous"><' + "/script>",
].join("\n ");
const katexInjection = ` ${katexCSS}\n ${katexJS}\n ${katexAutoRender}`;
// Inline render script — placed in <head> with DOMContentLoaded listener.
// Uses data-katex-init attr so sanitizer preserves it (contains "katex").
// Polls every 100ms up to 5s for auto-render to load via defer.
// eslint-disable-next-line no-template-curly-in-string
const katexInit =
'<script data-katex-init>' +
'document.addEventListener("DOMContentLoaded",function(){var t=0,i=setInterval(function(){if(typeof renderMathInElement==="function"){clearInterval(i);try{renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:true},{left:"$",right:"$",display:false},{left:"\\\\(",right:"\\\\)",display:false},{left:"\\\\[",right:"\\\\]",display:true}],throwOnError:false});console.log("[KaTeX] Rendered "+document.querySelectorAll(".katex").length+" formulas")}catch(e){console.error("[KaTeX] Error:",e)}}else if(++t>50){clearInterval(i);console.warn("[KaTeX] Timeout")}},100)});' +
"<" + "/script>";
// Try to inject into </head> section (most common case)
const headContent = katexResources + "\n " + katexInit;
// Inject into <head>
if (html.includes("</head>")) {
console.log("Injecting KaTeX before </head> tag");
return html.replace("</head>", `${katexInjection}\n</head>`);
return html.replace("</head>", headContent + "\n</head>");
}
// If no </head> tag, try to inject after <head> tag
if (html.includes("<head>")) {
console.log("Injecting KaTeX after <head> tag");
// Use regex to handle <head> with attributes
return html.replace(/<head([^>]*)>/i, `<head$1>\n${katexInjection}`);
return html.replace(/<head([^>]*)>/i, "<head$1>\n" + headContent);
}
// If HTML structure exists but no <head>, add it
if (html.includes("<html")) {
console.log("Adding <head> section with KaTeX");
return html.replace(
/(<html[^>]*>)/i,
`$1\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n${katexInjection}\n</head>`,
"$1\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + headContent + "\n</head>",
);
}
// If no HTML structure, wrap it with full HTML document
console.log("Wrapping content with full HTML document including KaTeX");
return `<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
${katexInjection}
</head>
<body>
${html}
</body>
</html>`;
// Wrap bare content
return (
"<!DOCTYPE html>\n<html lang=\"zh\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
headContent +
"\n</head>\n<body>\n" +
html +
"\n</body>\n</html>"
);
};
return { injectKaTeX };