From 2f0c17f4eb75f6fee313f67fcee1cc2b87afa2fa Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:26:53 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=94=99=E9=A2=98=E5=8D=A1=E7=89=87?= =?UTF-8?q?=E6=91=98=E8=A6=81=E7=94=A8=20KaTeX=20=E6=B8=B2=E6=9F=93?= =?UTF-8?q?=E5=85=AC=E5=BC=8F=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=20LaTeX=20=E6=BA=90=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原先摘要用正则把 LaTeX 转成纯文本,嵌套分数、向量、三角函数等复杂公式会残留源码。 现在先抽出公式片段,文字部分去掉 Markdown 格式,公式用 KaTeX 行内渲染; 截断时公式作为整体,不会被截到一半;无法解析的公式、未闭合的 $ 或缺少定界符的命令仍按纯文本清理。 Co-Authored-By: Claude Opus 5.5 --- src/__tests__/unit/question-summary.test.tsx | 83 +++++++++++++++++++ src/components/error-list/error-item-card.tsx | 10 +-- .../error-list/question-summary.tsx | 40 +++++++++ src/lib/question-summary.ts | 69 +++++++++++++++ 4 files changed, 194 insertions(+), 8 deletions(-) create mode 100644 src/__tests__/unit/question-summary.test.tsx create mode 100644 src/components/error-list/question-summary.tsx create mode 100644 src/lib/question-summary.ts diff --git a/src/__tests__/unit/question-summary.test.tsx b/src/__tests__/unit/question-summary.test.tsx new file mode 100644 index 00000000..b70c98e4 --- /dev/null +++ b/src/__tests__/unit/question-summary.test.tsx @@ -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(); + const visible = html + .replace(/[\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(/[\\$]/); + } + }); +}); diff --git a/src/components/error-list/error-item-card.tsx b/src/components/error-list/error-item-card.tsx index 1d7f9dc5..383b8bb1 100644 --- a/src/components/error-list/error-item-card.tsx +++ b/src/components/error-list/error-item-card.tsx @@ -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 -
{summarize(item.questionText)}
+
{getMistakeStatusLabel(item.mistakeStatus, language)} diff --git a/src/components/error-list/question-summary.tsx b/src/components/error-list/question-summary.tsx new file mode 100644 index 00000000..ab2144a3 --- /dev/null +++ b/src/components/error-list/question-summary.tsx @@ -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 ( +
+ {parts.map((part, index) => { + if (part.type === "text") return {part.value}; + const rendered = renderMath(part.tex); + return "html" in rendered + // KaTeX 输出已转义用户内容(默认 trust: false),可直接插入 + ? + : {rendered.text}; + })} +
+ ); +} diff --git a/src/lib/question-summary.ts b/src/lib/question-summary.ts new file mode 100644 index 00000000..56cd2ec9 --- /dev/null +++ b/src/lib/question-summary.ts @@ -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; +}