fix: 错题卡片摘要用 KaTeX 渲染公式,不再显示 LaTeX 源码

原先摘要用正则把 LaTeX 转成纯文本,嵌套分数、向量、三角函数等复杂公式会残留源码。
现在先抽出公式片段,文字部分去掉 Markdown 格式,公式用 KaTeX 行内渲染;
截断时公式作为整体,不会被截到一半;无法解析的公式、未闭合的 $ 或缺少定界符的命令仍按纯文本清理。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
margrop
2026-10-31 20:26:53 +08:00
parent eb157dc2ad
commit 2f0c17f4eb
4 changed files with 194 additions and 8 deletions

View File

@@ -0,0 +1,83 @@
/**
* 错题卡片题干摘要:文字去掉 Markdown 格式,公式交给 KaTeX 渲染
*/
import { describe, it, expect, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
vi.mock('@/lib/frontend-logger', () => ({ frontendLogger: { error: vi.fn() } }));
import { QuestionSummary } from '@/components/error-list/question-summary';
import { buildQuestionSummary } from '@/lib/question-summary';
describe('buildQuestionSummary', () => {
it('空内容返回空数组', () => {
expect(buildQuestionSummary('', 80)).toEqual([]);
expect(buildQuestionSummary(null, 80)).toEqual([]);
});
it('拆分文字与公式,并去掉 Markdown 格式', () => {
expect(buildQuestionSummary('**已知** $\\frac{\\sqrt{3}}{2}$,求 $\\sin\\alpha$ 的值', 80)).toEqual([
{ type: 'text', value: '已知 ' },
{ type: 'math', tex: '\\frac{\\sqrt{3}}{2}' },
{ type: 'text', value: ',求 ' },
{ type: 'math', tex: '\\sin\\alpha' },
{ type: 'text', value: ' 的值' },
]);
});
it('统一 \\(…\\)、$$…$$ 定界符,且块公式内的空行不会被当作分段', () => {
expect(buildQuestionSummary('计算 \\(a+b\\):$$x=\n\n1$$\n\n第二段', 80)).toEqual([
{ type: 'text', value: '计算 ' },
{ type: 'math', tex: 'a+b' },
{ type: 'text', value: ':' },
{ type: 'math', tex: 'x=\n\n1' },
]);
});
it('只取第一段', () => {
expect(buildQuestionSummary('第一段\n\n第二段', 80)).toEqual([{ type: 'text', value: '第一段' }]);
});
it('超长时截断文字并加省略号,公式不会被截断到一半', () => {
expect(buildQuestionSummary('一二三四五六', 4)).toEqual([{ type: 'text', value: '一二三四...' }]);
expect(buildQuestionSummary('一二三 $\\frac{1}{2}$ 四五', 4)).toEqual([
{ type: 'text', value: '一二三...' },
]);
expect(buildQuestionSummary('$\\frac{1}{2}$ 一二三四五', 4)).toEqual([
{ type: 'math', tex: '\\frac{1}{2}' },
{ type: 'text', value: '...' },
]);
});
});
/** 渲染摘要,返回 HTML 与去掉标签后的可见文字(不含 KaTeX 隐藏的 MathML 源码) */
function renderSummary(text: string) {
const html = renderToStaticMarkup(<QuestionSummary text={text} maxLength={80} />);
const visible = html
.replace(/<span class="katex-mathml">[\s\S]*?<\/math><\/span>/g, '')
.replace(/<[^>]+>/g, '');
return { html, visible };
}
describe('QuestionSummary', () => {
it('用 KaTeX 渲染公式,不显示 LaTeX 源码', () => {
const { html, visible } = renderSummary('已知 $\\vec{a}=\\frac{1}{2}$');
expect(html).toContain('class="katex"');
expect(visible).toContain('已知');
expect(visible).not.toContain('\\');
});
it('公式无法解析时退回纯文本', () => {
const { html, visible } = renderSummary('错误 $\\frac{1}{2$');
expect(html).not.toContain('class="katex"');
expect(visible).toContain('错误');
expect(visible).not.toContain('$');
});
it('未闭合的 $ 或缺少定界符的 LaTeX 片段按纯文本清理,不残留反斜杠和 $', () => {
for (const text of ['已知 $x \\leq 3', '已知 \\frac{1}{2} \\times 4']) {
const { visible } = renderSummary(text);
expect(visible).not.toMatch(/[\\$]/);
}
});
});

View File

@@ -3,6 +3,7 @@
import { useState } from "react";
import Link from "next/link";
import { DifficultyStars } from "@/components/difficulty-stars";
import { QuestionSummary } from "@/components/error-list/question-summary";
import { MASTERY_STATUS_BORDER, MasteryStatusBadge } from "@/components/mastery-status-badge";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
@@ -11,7 +12,6 @@ import { useLanguage } from "@/contexts/LanguageContext";
import { useTimeZone } from "@/contexts/TimeZoneContext";
import { formatDateTime } from "@/lib/date-time";
import { getItemTags } from "@/lib/item-tags";
import { cleanMarkdown } from "@/lib/markdown-utils";
import { getMistakeStatusLabel } from "@/lib/mistake-status";
import type { ErrorItemSummary } from "@/types/api";
@@ -29,12 +29,6 @@ interface ErrorItemCardProps {
onTagClick: (tag: string) => void;
}
/** 题干第一段去掉 Markdown/LaTeX 格式后的摘要 */
function summarize(questionText: string | null | undefined): string {
const text = cleanMarkdown((questionText || "").split('\n\n')[0]);
return text.length > SUMMARY_LENGTH ? text.substring(0, SUMMARY_LENGTH) + "..." : text;
}
/** 错题列表中的一张卡片:复习状态、摘要、作答状态、星级和知识点 */
export function ErrorItemCard({ item, selectMode, selected, onToggleSelect, selectedTag, onTagClick }: ErrorItemCardProps) {
const { t, language } = useLanguage();
@@ -75,7 +69,7 @@ export function ErrorItemCard({ item, selectMode, selected, onToggleSelect, sele
</div>
</CardHeader>
<CardContent>
<div className="text-sm line-clamp-3">{summarize(item.questionText)}</div>
<QuestionSummary text={item.questionText} maxLength={SUMMARY_LENGTH} className="text-sm line-clamp-3" />
<div className="flex flex-wrap items-center gap-2 mt-3">
<Badge variant="secondary" className="text-xs">
{getMistakeStatusLabel(item.mistakeStatus, language)}

View File

@@ -0,0 +1,40 @@
"use client";
import { useMemo } from "react";
import katex from "katex";
import { cleanMarkdown } from "@/lib/markdown-utils";
import { buildQuestionSummary } from "@/lib/question-summary";
import "katex/dist/katex.min.css";
interface QuestionSummaryProps {
text: string | null | undefined;
maxLength: number;
className?: string;
}
/** 行内渲染公式;KaTeX 无法解析时退回到纯文本 */
function renderMath(tex: string): { html: string } | { text: string } {
try {
return { html: katex.renderToString(tex, { displayMode: false, throwOnError: true, strict: "ignore" }) };
} catch {
return { text: cleanMarkdown(`$${tex}$`) };
}
}
/** 错题卡片的题干摘要:文字去掉 Markdown 格式,公式用 KaTeX 行内渲染 */
export function QuestionSummary({ text, maxLength, className = "" }: QuestionSummaryProps) {
const parts = useMemo(() => buildQuestionSummary(text, maxLength), [text, maxLength]);
return (
<div className={`[&_.katex]:text-[1.05em] ${className}`}>
{parts.map((part, index) => {
if (part.type === "text") return <span key={index}>{part.value}</span>;
const rendered = renderMath(part.tex);
return "html" in rendered
// KaTeX 输出已转义用户内容(默认 trust: false),可直接插入
? <span key={index} dangerouslySetInnerHTML={{ __html: rendered.html }} />
: <span key={index}>{rendered.text}</span>;
})}
</div>
);
}

View File

@@ -0,0 +1,69 @@
/**
* 错题卡片的题干摘要:去掉 Markdown 格式,但保留公式源码,交给 KaTeX 渲染,
* 避免复杂 LaTeX(嵌套分数、向量、三角函数等)被正则转成难以阅读的残留文本。
*/
import { cleanMarkdown } from './markdown-utils';
import { extractMathSegments } from './markdown-math';
/** 摘要片段:普通文字或行内公式 */
export type SummaryPart =
| { type: 'text'; value: string }
| { type: 'math'; tex: string };
const PLACEHOLDER_SPLIT = /@@MATH(\d+)@@/;
/** 公式按源码长度的一半计入摘要长度(渲染后通常比源码短) */
function mathWeight(tex: string): number {
return Math.max(1, Math.ceil(tex.length / 2));
}
/**
* 取题干第一段生成摘要,超过 maxLength 时截断并加省略号;公式不会被截断到一半
*/
export function buildQuestionSummary(questionText: string | null | undefined, maxLength: number): SummaryPart[] {
const { masked, segments } = extractMathSegments(questionText);
// 先抽出公式再分段,避免 $$…$$ 块内的空行把公式拆开
const firstParagraph = masked.trim().split(/\n\s*\n/)[0] ?? '';
const cleaned = cleanMarkdown(firstParagraph);
const pieces = cleaned.split(PLACEHOLDER_SPLIT);
const parts: SummaryPart[] = [];
let used = 0;
let truncated = false;
for (let i = 0; i < pieces.length && !truncated; i++) {
if (i % 2 === 0) {
const text = pieces[i];
if (!text) continue;
const remaining = maxLength - used;
if (text.length > remaining) {
parts.push({ type: 'text', value: text.substring(0, remaining) });
truncated = true;
} else {
parts.push({ type: 'text', value: text });
used += text.length;
}
} else {
const tex = segments[Number(pieces[i])]?.tex.trim();
if (!tex) continue;
const weight = mathWeight(tex);
if (used + weight > maxLength && used > 0) {
truncated = true;
} else {
parts.push({ type: 'math', tex });
used += weight;
}
}
}
if (truncated) {
// 省略号接在最后一段文字后;最后是公式时单独追加
const last = parts[parts.length - 1];
if (last?.type === 'text') {
last.value = `${last.value.trimEnd()}...`;
} else {
parts.push({ type: 'text', value: '...' });
}
}
return parts;
}