From 055c467a402f31902b9debdfc60168e8bfc57785 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 8 Apr 2026 09:17:59 +0800 Subject: [PATCH] fix(guide): fix KaTeX math rendering in Guided Learning pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 strings - Increase guide agent max_tokens 8192->16384 to prevent HTML truncation Co-Authored-By: Claude Sonnet 4.6 --- .../guide/components/HTMLViewer.tsx | 97 ++++++++++++++++++- .../guide/hooks/useKaTeXInjection.ts | 74 +++++++------- 2 files changed, 131 insertions(+), 40 deletions(-) diff --git a/web/app/(workspace)/guide/components/HTMLViewer.tsx b/web/app/(workspace)/guide/components/HTMLViewer.tsx index 1be4b3d3a..9e05cae09 100644 --- a/web/app/(workspace)/guide/components/HTMLViewer.tsx +++ b/web/app/(workspace)/guide/components/HTMLViewer.tsx @@ -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 = + /(? { 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) => 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).__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 | null; + if (prev?.__fallbackTimers) { + (prev.__fallbackTimers as ReturnType[]).forEach(clearTimeout); + } + }; }, [html, currentIndex, injectKaTeX]); if (!html) { diff --git a/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts b/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts index 840f8cdf4..e90cd63ca 100644 --- a/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts +++ b/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts @@ -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 + 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 "" 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 = - ''; - const katexJS = - ''; - const katexAutoRender = - ''; + // CDN resources (no SRI hash to avoid mismatch) + const katexResources = [ + '', + '