test(frontend): extract Markdown renderer to utils/markdown.ts + add vitest regression tests
CI / gate (push) Has been cancelled
CI / gate (push) Has been cancelled
This commit is contained in:
1 parent
11b80b90f4
commit
7674729804
3 files changed
+294
-184
No files matched your search
@@ -6,9 +6,7 @@ import type { Conversation, Message } from '@/types';
|
||||
import './ChatPage.css';
|
||||
|
||||
// ===== 增强渲染依赖 =====
|
||||
import hljs from 'highlight.js';
|
||||
import 'highlight.js/styles/github.css';
|
||||
import katex from 'katex';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import mermaid from 'mermaid';
|
||||
|
||||
@@ -16,7 +14,7 @@ mermaid.initialize({ startOnLoad: false, theme: 'default' });
|
||||
|
||||
// ===== Enhanced Markdown Renderer =====
|
||||
// 媒体(图片/视频)以受限缩略图呈现,并提供下载(格式+尺寸)选项
|
||||
interface MediaInfo { type: 'img' | 'video'; src: string; alt?: string; }
|
||||
import { renderMarkdownToHtml, MediaInfo } from '@/utils/markdown';
|
||||
|
||||
// 全屏灯箱预览
|
||||
const ChatLightbox: React.FC<{ src: string; type: 'img' | 'video'; onClose: () => void }> = ({ src, type, onClose }) => {
|
||||
@@ -154,182 +152,17 @@ const ChatMedia: React.FC<{ info: MediaInfo }> = ({ info }) => {
|
||||
};
|
||||
|
||||
const MarkdownContent: React.FC<{ content: string }> = ({ content }) => {
|
||||
// 渲染管线(代码块/加粗/表格/换行/媒体占位符等)已抽到 src/utils/markdown.ts,
|
||||
// 组件只负责把返回的 html 切分为「文本片段 + 媒体组件」。
|
||||
const { html, media } = useMemo(() => renderMarkdownToHtml(content), [content]);
|
||||
|
||||
const nodes = useMemo(() => {
|
||||
let text = content;
|
||||
|
||||
// 1. Extract code blocks first (protect from other replacements)
|
||||
const codeBlocks: string[] = [];
|
||||
const mermaidBlocks: string[] = [];
|
||||
text = text.replace(/```(\w*)\n?([\s\S]*?)```/g, (_m: string, _lang: string, code: string) => {
|
||||
if (_lang === 'mermaid') {
|
||||
const idx = mermaidBlocks.length;
|
||||
mermaidBlocks.push('<div class="md-mermaid" data-code="' + escapeHtml(code.trim()) + '"></div>');
|
||||
return '\x00MERMAID' + idx + '\x00';
|
||||
}
|
||||
const idx = codeBlocks.length;
|
||||
codeBlocks.push('<pre class="md-code-block"><code class="md-code">' + escapeHtml(code.trim()) + '</code></pre>');
|
||||
return '\x00CODEBLOCK' + idx + '\x00';
|
||||
});
|
||||
|
||||
// 2. Extract inline code
|
||||
const inlineCodes: string[] = [];
|
||||
text = text.replace(/`([^`]+)`/g, (_m: string, code: string) => {
|
||||
const idx = inlineCodes.length;
|
||||
inlineCodes.push('<code class="md-inline-code">' + escapeHtml(code) + '</code>');
|
||||
return '\x00INLINE' + idx + '\x00';
|
||||
});
|
||||
|
||||
// 2.5 Extract media blocks (<img>/<video>) → 结构化,后续渲染为 React 组件
|
||||
const mediaBlocks: MediaInfo[] = [];
|
||||
text = text.replace(/<(img|video)([^>]*?)\/?>/gi, (_m: string, tag: string, attrs: string) => {
|
||||
const type = tag.toLowerCase() === 'img' ? 'img' : 'video';
|
||||
const srcM = attrs.match(/src=["']([^"']+)["']/i);
|
||||
const altM = attrs.match(/alt=["']([^"']*)["']/i);
|
||||
mediaBlocks.push({ type, src: srcM ? srcM[1] : '', alt: altM ? altM[1] : '' });
|
||||
return '\x00MEDIA' + (mediaBlocks.length - 1) + '\x00';
|
||||
});
|
||||
|
||||
// 2.6 Normalize excessive blank lines in prose (code blocks already extracted)
|
||||
text = text.replace(/\n{3,}/g, '\n\n').trim();
|
||||
|
||||
// 2.8 LaTeX 数学公式:$$...$$(块级)和 $...$(行内)
|
||||
// 提取为占位符,渲染后用 KaTeX 处理
|
||||
const mathBlocks: string[] = [];
|
||||
text = text.replace(/\$\$([\s\S]+?)\$\$/g, (_m: string, formula: string) => {
|
||||
try {
|
||||
const rendered = katex.renderToString(formula.trim(), { displayMode: true, throwOnError: false });
|
||||
const idx = mathBlocks.length;
|
||||
mathBlocks.push(`<div class="md-math-block">${rendered}</div>`);
|
||||
return '\x00MATHBLOCK' + idx + '\x00';
|
||||
} catch { return _m; }
|
||||
});
|
||||
text = text.replace(/\$([^\s$][^$]*[^\s$])\$/g, (_m: string, formula: string) => {
|
||||
try {
|
||||
const rendered = katex.renderToString(formula.trim(), { displayMode: false, throwOnError: false });
|
||||
const idx = mathBlocks.length;
|
||||
mathBlocks.push(`<span class="md-math-inline">${rendered}</span>`);
|
||||
return '\x00MATHBLOCK' + idx + '\x00';
|
||||
} catch { return _m; }
|
||||
});
|
||||
|
||||
// 2.9 Strikethrough: ~~text~~ → <del>text</del>
|
||||
text = text.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||||
|
||||
// 2.10 Auto-link bare URLs: http(s)://... → <a>
|
||||
text = text.replace(/(?<![="'>])https?:\/\/[^\s<>[\]()]+/g, (url: string) =>
|
||||
`<a class="md-link" href="${url}" target="_blank" rel="noopener">${url}</a>`
|
||||
);
|
||||
|
||||
// 3. Headers
|
||||
text = text.replace(/^#### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||
text = text.replace(/^### (.+)$/gm, '<h4 class="md-h4">$1</h4>');
|
||||
text = text.replace(/^## (.+)$/gm, '<h3 class="md-h3">$1</h3>');
|
||||
text = text.replace(/^# (.+)$/gm, '<h2 class="md-h2">$1</h2>');
|
||||
|
||||
// 4. Horizontal rule
|
||||
text = text.replace(/^---+$/gm, '<hr class="md-hr">');
|
||||
|
||||
// 5. Blockquotes
|
||||
text = text.replace(/^> (.+)$/gm, '<blockquote class="md-blockquote">$1</blockquote>');
|
||||
|
||||
// 6. Links [text](url)
|
||||
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a class="md-link" href="$2" target="_blank" rel="noopener">$1</a>');
|
||||
|
||||
// 7. Bold and italic
|
||||
text = text.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||
text = text.replace(/(?<!\w)\*(?!\*)(.+?)(?<!\*)\*(?!\w)/g, '<em>$1</em>');
|
||||
|
||||
// 7.5 Extract Markdown tables after inline formatting so cells support bold/italic/links.
|
||||
// 表格提取放在加粗/链接之后,避免单元格内 **xxx** 原样显示;同时压缩单元格内多余 <br>。
|
||||
const tableBlocks: string[] = [];
|
||||
text = text.replace(
|
||||
/((?:^\|.+\|\r?\n)+^\|[\s\-:|]+\|\r?\n(?:^\|.+\|\r?\n?)+)/gm,
|
||||
(_m: string, block: string) => {
|
||||
const lines = block.trim().split(/\r?\n/).filter((l: string) => l.trim());
|
||||
if (lines.length < 2) return block;
|
||||
const headerCells = lines[0].split('|').slice(1, -1).map((c: string) => c.trim());
|
||||
const alignCells = lines[1].split('|').slice(1, -1).map((c: string) => {
|
||||
const t = c.trim();
|
||||
const left = t.startsWith(':');
|
||||
const right = t.endsWith(':');
|
||||
if (left && right) return 'center';
|
||||
if (right) return 'right';
|
||||
if (left) return 'left';
|
||||
return 'left';
|
||||
});
|
||||
const normalizeCell = (cell: string) => {
|
||||
return cell
|
||||
.replace(/<br\s*\/?>\s*/gi, '<br/>')
|
||||
.replace(/\n/g, '<br/>')
|
||||
.replace(/(<br\/>){2,}/g, '<br/>')
|
||||
.replace(/^(<br\/>)+|(<br\/>)+$/g, '');
|
||||
};
|
||||
const bodyRows = lines.slice(2).map((row: string) =>
|
||||
row.split('|').slice(1, -1).map((c: string) => normalizeCell(c.trim()))
|
||||
);
|
||||
const thead = headerCells.map((c: string, i: number) =>
|
||||
`<th style="text-align:${alignCells[i] || 'left'}">${normalizeCell(c)}</th>`
|
||||
).join('');
|
||||
const tbody = bodyRows.map((r: string[]) =>
|
||||
'<tr>' + r.map((c: string, i: number) =>
|
||||
`<td style="text-align:${alignCells[i] || 'left'}">${c}</td>`
|
||||
).join('') + '</tr>'
|
||||
).join('');
|
||||
const html = `<table class="md-table"><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table>`;
|
||||
const idx = tableBlocks.length;
|
||||
tableBlocks.push(html);
|
||||
return '\x00TABLE' + idx + '\x00';
|
||||
}
|
||||
);
|
||||
|
||||
// 8. Lists
|
||||
text = text.replace(/^\s*[-*] (.+)$/gm, '<li class="md-li">$1</li>');
|
||||
text = text.replace(/^\s*\d+\. (.+)$/gm, '<li class="md-li">$1</li>');
|
||||
// Wrap consecutive <li> in <ul>
|
||||
text = text.replace(/((?:<li class="md-li">[\s\S]*?<\/li>\n?)+)/g, '<ul class="md-ul">$1</ul>');
|
||||
|
||||
// 9. Convert double newlines to paragraph breaks, single newlines to spaces
|
||||
text = text.replace(/\n\n/g, '</p><p class="md-p">');
|
||||
text = text.replace(/\n/g, ' ');
|
||||
|
||||
// 10. Restore code blocks and inline codes
|
||||
text = text.replace(/\x00CODEBLOCK(\d+)\x00/g, (_m: string, idx: string) => codeBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00MERMAID(\d+)\x00/g, (_m: string, idx: string) => mermaidBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00INLINE(\d+)\x00/g, (_m: string, idx: string) => inlineCodes[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00TABLE(\d+)\x00/g, (_m: string, idx: string) => tableBlocks[parseInt(idx)] || '');
|
||||
text = text.replace(/\x00MATHBLOCK(\d+)\x00/g, (_m: string, idx: string) => mathBlocks[parseInt(idx)] || '');
|
||||
|
||||
// 10.5 Apply syntax highlighting to code blocks + add copy button
|
||||
text = text.replace(
|
||||
/<pre class="md-code-block"><code class="md-code">([\s\S]*?)<\/code><\/pre>/g,
|
||||
(_m: string, code: string) => {
|
||||
const decoded = code.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
let highlighted: string;
|
||||
try { highlighted = hljs.highlightAuto(decoded).value; } catch { highlighted = code; }
|
||||
return `<div class="md-code-wrapper">
|
||||
<button class="md-code-copy" onclick="navigator.clipboard.writeText(this.parentElement.querySelector('code').textContent);this.textContent='已复制';setTimeout(()=>this.textContent='复制',2000)">复制</button>
|
||||
<pre class="md-code-block"><code class="md-code hljs">${highlighted}</code></pre>
|
||||
</div>`;
|
||||
}
|
||||
);
|
||||
|
||||
// 11. Wrap in paragraph and clean up
|
||||
text = '<p class="md-p">' + text + '</p>';
|
||||
text = text.replace(/<p class="md-p"><\/p>/g, '');
|
||||
text = text.replace(/<p class="md-p">(<h[234][\s\S]*?<\/h[234]>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<pre[\s\S]*?<\/pre>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<ul[\s\S]*?<\/ul>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<hr[\s\S]*?)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<blockquote[\s\S]*?<\/blockquote>)<\/p>/g, '$1');
|
||||
text = text.replace(/<p class="md-p">(<table[\s\S]*?<\/table>)<\/p>/g, '$1');
|
||||
|
||||
// 12. 拆分为文本片段与媒体组件
|
||||
const parts = text.split(/(\x00MEDIA\d+\x00)/g);
|
||||
// 12. 拆分为文本片段与媒体组件(媒体以 \x00MEDIA<n>\x00 占位符保留在 html 中)
|
||||
const parts = html.split(/(\x00MEDIA\d+\x00)/g);
|
||||
return parts.map((part: string, i: number) => {
|
||||
const m = part.match(/^\x00MEDIA(\d+)\x00$/);
|
||||
if (m) {
|
||||
const info = mediaBlocks[parseInt(m[1])];
|
||||
const info = media[parseInt(m[1])];
|
||||
if (info && info.src) return <ChatMedia key={'m' + i} info={info} />;
|
||||
return null;
|
||||
}
|
||||
@@ -339,7 +172,7 @@ const MarkdownContent: React.FC<{ content: string }> = ({ content }) => {
|
||||
if (!s.trim()) return null;
|
||||
return <div key={'t' + i} className="md-text-seg" dangerouslySetInnerHTML={{ __html: s }} />;
|
||||
});
|
||||
}, [content]);
|
||||
}, [html, media]);
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
@@ -397,14 +230,6 @@ const ClarifyCard: React.FC<{ data: { prompt: string; options: any[] }; onChoose
|
||||
};
|
||||
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
// ===== Time Formatting =====
|
||||
function formatTime(iso: string): string {
|
||||
return formatChatTime(iso);
|
||||
|
||||
Reference in new issue
Block a user