Files
monkey-ai-web/src/components/common/markdown/MarkdownRenderer.jsx
T
zhanjunhao cb9d836227 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

748 lines
22 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import ReactMarkdown from 'react-markdown';
import 'katex/dist/katex.min.css';
import 'highlight.js/styles/github.css';
import './markdown.css';
import RemarkMath from 'remark-math';
import RemarkBreaks from 'remark-breaks';
import RehypeKatex from 'rehype-katex';
import RemarkGfm from 'remark-gfm';
import RehypeHighlight from 'rehype-highlight';
import { useRef, useState, useEffect, useMemo, useId } from 'react';
import React from 'react';
import { useDebouncedCallback } from 'use-debounce';
import clsx from 'clsx';
import { Button, Tooltip, Toast } from '@/components/ui';
import { copy, rehypeSplitWordsIntoSpans } from '../../../helpers';
import { IconCopy } from '@/components/ui/icons';
import { useTranslation } from 'react-i18next';
import ImagePreviewModal from '../../playground/ImagePreviewModal';
// 懒加载 mermaid 库 - 只在需要时才加载这个大型依赖
let mermaidInstance = null;
let mermaidLoading = null;
const loadMermaid = async () => {
if (mermaidInstance) return mermaidInstance;
if (mermaidLoading) return mermaidLoading;
mermaidLoading = import('mermaid').then((module) => {
mermaidInstance = module.default;
mermaidInstance.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'loose',
});
return mermaidInstance;
});
return mermaidLoading;
};
export function Mermaid(props) {
// svgRef 指向一个「React 视角里永远为空」的子节点,我们用 innerHTML 手动塞 SVG。
// 关键:绝不能让 mermaid 去改写 React 正在管理子节点的元素 —— 之前用
// mermaid.run({nodes:[ref.current]}) 直接抹掉了容器里 React 渲染的 loading/文本节点,
// 等 setIsLoading(false) 触发重渲染时,React 找不到那些被 mermaid 删掉的节点,
// 就抛 removeChild "NotFoundError"。改用 mermaid.render() 拿 svg 字符串后写进 svgRef,
// React 始终认为 svgRef 这个 div 是空的,便不会与 mermaid 的 DOM 改动冲突。
const { t } = useTranslation();
const svgRef = useRef(null);
const [hasError, setHasError] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const rawId = useId();
// useId 产出形如 ":r0:",含非法字符;清洗后作为 mermaid.render 的 id 基底(会进 querySelector)
const idBase = `mermaid-${rawId.replace(/[^a-zA-Z0-9_-]/g, '')}`;
// 每次 render 取递增后缀,确保 id 唯一。关键:StrictMode 开发模式下 mount effect 会跑两次,
// 若两次用同一 id 并发调用 mermaid.render,会因其内部临时节点 #d{id} 冲突而报错/画不出图。
const renderSeqRef = useRef(0);
useEffect(() => {
if (!props.code) return;
let cancelled = false;
const renderId = `${idBase}-${renderSeqRef.current++}`;
setIsLoading(true);
setHasError(false);
loadMermaid()
.then((mermaid) => mermaid.render(renderId, props.code))
.then(({ svg, bindFunctions }) => {
if (cancelled || !svgRef.current) return;
svgRef.current.innerHTML = svg;
// 交互式图表(点击/tooltip)需要 mermaid 绑定事件;静态图表则是空操作
if (typeof bindFunctions === 'function') {
bindFunctions(svgRef.current);
}
setIsLoading(false);
})
.catch((e) => {
if (cancelled) return;
setHasError(true);
setIsLoading(false);
console.error('[Mermaid] ', e.message);
});
return () => {
cancelled = true;
};
}, [props.code, idBase]);
function viewSvgInNewWindow() {
const svg = svgRef.current?.querySelector('svg');
if (!svg) return;
const text = new XMLSerializer().serializeToString(svg);
const blob = new Blob([text], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
}
// 解析失败(含流式中途语法不完整)时整体隐藏,不渲染半截图表。
// 调用方是 <Mermaid key={mermaidCode}/>:代码一变即全新实例重挂载并重画,
// 不依赖同实例内重试,所以这里直接卸载是安全的。
if (hasError) {
return null;
}
return (
<div
className={clsx('mermaid-container')}
style={{
cursor: 'pointer',
overflow: 'auto',
padding: '12px',
border: '1px solid var(--ui-color-border)',
borderRadius: '8px',
backgroundColor: 'var(--ui-color-bg-1)',
margin: '12px 0',
position: 'relative',
minHeight: isLoading ? '100px' : 'auto',
}}
onClick={() => viewSvgInNewWindow()}
>
{isLoading && (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
display: 'flex',
alignItems: 'center',
gap: '8px',
color: 'var(--ui-color-text-2)',
fontSize: '12px',
}}
>
<div
style={{
width: '14px',
height: '14px',
border: '2px solid var(--ui-color-border)',
borderTop: '2px solid var(--ui-color-primary)',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
}}
/>
{t('加载图表中...')}
</div>
)}
{/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */}
<div ref={svgRef} />
</div>
);
}
export function PreCode(props) {
const ref = useRef(null);
const [mermaidCode, setMermaidCode] = useState('');
const [htmlCode, setHtmlCode] = useState('');
const { t } = useTranslation();
const renderArtifacts = useDebouncedCallback(() => {
if (!ref.current) return;
const mermaidDom = ref.current.querySelector('code.language-mermaid');
if (mermaidDom) {
setMermaidCode(mermaidDom.innerText);
}
const htmlDom = ref.current.querySelector('code.language-html');
const refText = ref.current.querySelector('code')?.innerText;
if (htmlDom) {
setHtmlCode(htmlDom.innerText);
} else if (
refText?.startsWith('<!DOCTYPE') ||
refText?.startsWith('<svg') ||
refText?.startsWith('<?xml')
) {
setHtmlCode(refText);
}
}, 600);
// 处理代码块的换行
const onMount = useEffectEvent(() => {
if (ref.current) {
const codeElements = ref.current.querySelectorAll('code');
const wrapLanguages = [
'',
'md',
'markdown',
'text',
'txt',
'plaintext',
'tex',
'latex',
];
codeElements.forEach((codeElement) => {
let languageClass = codeElement.className.match(/language-(\w+)/);
let name = languageClass ? languageClass[1] : '';
if (wrapLanguages.includes(name)) {
codeElement.style.whiteSpace = 'pre-wrap';
}
});
setTimeout(renderArtifacts, 1);
}
});
useEffect(() => onMount(), [onMount]);
return (
<>
<pre
ref={ref}
style={{
position: 'relative',
backgroundColor: 'var(--ui-color-fill-0)',
border: '1px solid var(--ui-color-border)',
borderRadius: '6px',
padding: '12px',
margin: '12px 0',
overflow: 'auto',
fontSize: '14px',
lineHeight: '1.4',
}}
>
<div
className='copy-code-button'
style={{
position: 'absolute',
top: '8px',
right: '8px',
display: 'flex',
gap: '4px',
zIndex: 10,
opacity: 0,
transition: 'opacity 0.2s ease',
}}
>
<Tooltip content={t('复制代码')}>
<Button
size='small'
theme='borderless'
icon={<IconCopy />}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
if (ref.current) {
const codeElement = ref.current.querySelector('code');
const code = codeElement?.textContent ?? '';
copy(code).then((success) => {
if (success) {
Toast.success(t('代码已复制到剪贴板'));
} else {
Toast.error(t('复制失败,请手动复制'));
}
});
}
}}
style={{
padding: '4px',
backgroundColor: 'var(--ui-color-bg-2)',
borderRadius: '4px',
cursor: 'pointer',
border: '1px solid var(--ui-color-border)',
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)',
}}
/>
</Tooltip>
</div>
{props.children}
</pre>
{mermaidCode.length > 0 && (
<Mermaid code={mermaidCode} key={mermaidCode} />
)}
{htmlCode.length > 0 && (
<div
style={{
border: '1px solid var(--ui-color-border)',
borderRadius: '8px',
padding: '16px',
margin: '12px 0',
backgroundColor: 'var(--ui-color-bg-1)',
}}
>
<div
style={{
marginBottom: '8px',
fontSize: '12px',
color: 'var(--ui-color-text-2)',
}}
>
{t('HTML预览:')}
</div>
<div dangerouslySetInnerHTML={{ __html: htmlCode }} />
</div>
)}
</>
);
}
function CustomCode(props) {
const ref = useRef(null);
const [collapsed, setCollapsed] = useState(true);
const [showToggle, setShowToggle] = useState(false);
const { t } = useTranslation();
const className = props?.className || '';
// 行内代码 vs 代码块判定:带 language-* 类、或内容含换行 = 代码块;否则按行内代码渲染。
// 关键:行内代码必须渲染成纯 <code>,绝不能套 <div>。行内代码位于 <p> 内,块级 <div>
// 会被浏览器从 <p> 中提升出来、把段落拆开,导致 React 虚拟树与真实 DOM 错位;流式追加
// 文本触发 reconcile 时就会报 removeChild "NotFoundError"。
const isBlock =
/language-(\w+)/.test(className) ||
(typeof props.children === 'string' && props.children.includes('\n')) ||
(Array.isArray(props.children) &&
props.children.some((c) => typeof c === 'string' && c.includes('\n')));
useEffect(() => {
if (ref.current) {
const codeHeight = ref.current.scrollHeight;
setShowToggle(codeHeight > 400);
ref.current.scrollTop = ref.current.scrollHeight;
}
}, [props.children]);
const toggleCollapsed = () => {
setCollapsed((collapsed) => !collapsed);
};
const renderShowMoreButton = () => {
if (showToggle && collapsed) {
return (
<div
style={{
position: 'absolute',
bottom: '8px',
right: '8px',
left: '8px',
display: 'flex',
justifyContent: 'center',
}}
>
<Button size='small' onClick={toggleCollapsed} theme='solid'>
{t('显示更多')}
</Button>
</div>
);
}
return null;
};
// 行内代码:纯 <code>,不包裹任何块级元素,避免 <p> 内嵌 <div> 的非法嵌套
if (!isBlock) {
return <code className={clsx(className)}>{props.children}</code>;
}
return (
<div style={{ position: 'relative' }}>
<code
className={clsx(className)}
ref={ref}
style={{
maxHeight: collapsed ? '400px' : 'none',
overflowY: 'hidden',
display: 'block',
padding: '8px 12px',
backgroundColor: 'var(--ui-color-fill-0)',
borderRadius: '4px',
fontSize: '13px',
lineHeight: '1.4',
}}
>
{props.children}
</code>
{renderShowMoreButton()}
</div>
);
}
function escapeBrackets(text) {
const pattern =
/(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
return text.replace(
pattern,
(match, codeBlock, squareBracket, roundBracket) => {
if (codeBlock) {
return codeBlock;
} else if (squareBracket) {
return `$$${squareBracket}$$`;
} else if (roundBracket) {
return `$${roundBracket}$`;
}
return match;
},
);
}
function tryWrapHtmlCode(text) {
// 尝试包装HTML代码
if (text.includes('```')) {
return text;
}
return text
.replace(
/([`]*?)(\w*?)([\n\r]*?)(<!DOCTYPE html>)/g,
(match, quoteStart, lang, newLine, doctype) => {
return !quoteStart ? '\n```html\n' + doctype : match;
},
)
.replace(
/(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*)([`]*)([\n\r]*?)/g,
(match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => {
return !quoteEnd ? bodyEnd + space + htmlEnd + '\n```\n' : match;
},
);
}
function MarkdownContentImpl(props) {
const {
content,
className,
animated = false,
previousContentLength = 0,
} = props;
const [previewImageUrl, setPreviewImageUrl] = useState(null);
const escapedContent = useMemo(() => {
return tryWrapHtmlCode(escapeBrackets(content));
}, [content]);
// 判断是否为用户消息
const isUserMessage = className && className.includes('user-message');
const rehypePluginsBase = useMemo(() => {
const base = [
RehypeKatex,
[
RehypeHighlight,
{
detect: false,
ignoreMissing: true,
},
],
];
if (animated) {
base.push([rehypeSplitWordsIntoSpans, { previousContentLength }]);
}
return base;
}, [animated, previousContentLength]);
return (
<>
<ReactMarkdown
remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
rehypePlugins={rehypePluginsBase}
components={{
pre: PreCode,
code: CustomCode,
p: (pProps) => (
<p
{...pProps}
dir='auto'
style={{
lineHeight: '1.6',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
a: (aProps) => {
const href = aProps.href || '';
if (/\.(aac|mp3|opus|wav)$/.test(href)) {
return (
<figure style={{ margin: '12px 0' }}>
<audio controls src={href} style={{ width: '100%' }}></audio>
</figure>
);
}
if (/\.(3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href)) {
return (
<video
controls
style={{ width: '100%', maxWidth: '100%', margin: '12px 0' }}
>
<source src={href} />
</video>
);
}
const isInternal = /^\/#/i.test(href);
const target = isInternal ? '_self' : (aProps.target ?? '_blank');
return (
<a
{...aProps}
target={target}
style={{
color: isUserMessage ? '#87CEEB' : 'var(--ui-color-primary)',
textDecoration: 'none',
}}
onMouseEnter={(e) => {
e.target.style.textDecoration = 'underline';
}}
onMouseLeave={(e) => {
e.target.style.textDecoration = 'none';
}}
/>
);
},
h1: (props) => (
<h1
{...props}
style={{
fontSize: '24px',
fontWeight: 'bold',
margin: '20px 0 12px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
h2: (props) => (
<h2
{...props}
style={{
fontSize: '20px',
fontWeight: 'bold',
margin: '18px 0 10px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
h3: (props) => (
<h3
{...props}
style={{
fontSize: '18px',
fontWeight: 'bold',
margin: '16px 0 8px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
h4: (props) => (
<h4
{...props}
style={{
fontSize: '16px',
fontWeight: 'bold',
margin: '14px 0 6px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
h5: (props) => (
<h5
{...props}
style={{
fontSize: '14px',
fontWeight: 'bold',
margin: '12px 0 4px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
h6: (props) => (
<h6
{...props}
style={{
fontSize: '13px',
fontWeight: 'bold',
margin: '10px 0 4px 0',
color: isUserMessage ? 'white' : 'var(--ui-color-text-0)',
}}
/>
),
blockquote: (props) => (
<blockquote
{...props}
style={{
borderLeft: isUserMessage
? '4px solid rgba(255, 255, 255, 0.5)'
: '4px solid var(--ui-color-primary)',
paddingLeft: '16px',
margin: '12px 0',
backgroundColor: isUserMessage
? 'rgba(255, 255, 255, 0.1)'
: 'var(--ui-color-fill-0)',
padding: '8px 16px',
borderRadius: '0 4px 4px 0',
fontStyle: 'italic',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
ul: (props) => (
<ul
{...props}
style={{
margin: '8px 0',
paddingLeft: '20px',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
ol: (props) => (
<ol
{...props}
style={{
margin: '8px 0',
paddingLeft: '20px',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
li: (props) => (
<li
{...props}
style={{
margin: '4px 0',
lineHeight: '1.6',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
table: (props) => (
<div style={{ overflow: 'auto', margin: '12px 0' }}>
<table
{...props}
style={{
width: '100%',
borderCollapse: 'collapse',
border: isUserMessage
? '1px solid rgba(255, 255, 255, 0.3)'
: '1px solid var(--ui-color-border)',
borderRadius: '6px',
overflow: 'hidden',
}}
/>
</div>
),
th: (props) => (
<th
{...props}
style={{
padding: '8px 12px',
backgroundColor: isUserMessage
? 'rgba(255, 255, 255, 0.2)'
: 'var(--ui-color-fill-1)',
border: isUserMessage
? '1px solid rgba(255, 255, 255, 0.3)'
: '1px solid var(--ui-color-border)',
fontWeight: 'bold',
textAlign: 'left',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
td: (props) => (
<td
{...props}
style={{
padding: '8px 12px',
border: isUserMessage
? '1px solid rgba(255, 255, 255, 0.3)'
: '1px solid var(--ui-color-border)',
color: isUserMessage ? 'white' : 'inherit',
}}
/>
),
img: (imgProps) => (
<img
{...imgProps}
className='rounded-lg max-w-full h-auto shadow-sm border border-gray-200/60 dark:border-neutral-700/60 cursor-pointer hover:opacity-90 transition-opacity'
style={{ maxHeight: '400px', margin: '8px 0' }}
onClick={() => setPreviewImageUrl(imgProps.src)}
/>
),
}}
>
{escapedContent}
</ReactMarkdown>
<ImagePreviewModal
visible={!!previewImageUrl}
imageUrl={previewImageUrl}
onClose={() => setPreviewImageUrl(null)}
/>
</>
);
}
export const MarkdownContent = React.memo(MarkdownContentImpl);
export function MarkdownRenderer(props) {
const {
content,
loading,
fontSize = 14,
fontFamily = 'inherit',
className,
style,
animated = false,
previousContentLength = 0,
...otherProps
} = props;
const { t } = useTranslation();
return (
<div
className={clsx('markdown-body', className)}
style={{
fontSize: `${fontSize}px`,
fontFamily: fontFamily,
lineHeight: '1.6',
color: 'var(--ui-color-text-0)',
...style,
}}
dir='auto'
{...otherProps}
>
{loading ? (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '16px',
color: 'var(--ui-color-text-2)',
}}
>
<div
style={{
width: '16px',
height: '16px',
border: '2px solid var(--ui-color-border)',
borderTop: '2px solid var(--ui-color-primary)',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
}}
/>
{t('正在渲染...')}
</div>
) : (
<MarkdownContent
content={content}
className={className}
animated={animated}
previousContentLength={previousContentLength}
/>
)}
</div>
);
}
export default MarkdownRenderer;