/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ 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 '@douyinfe/semi-ui'; import { copy, rehypeSplitWordsIntoSpans } from '../../../helpers'; import { IconCopy } from '@douyinfe/semi-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 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'); } // 解析失败(含流式中途语法不完整)时整体隐藏,不渲染半截图表。 // 调用方是 :代码一变即全新实例重挂载并重画, // 不依赖同实例内重试,所以这里直接卸载是安全的。 if (hasError) { return null; } return (
viewSvgInNewWindow()} > {isLoading && (
加载图表中...
)} {/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */}
); } 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(' { 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); } }, []); return ( <>
        
{props.children}
{mermaidCode.length > 0 && ( )} {htmlCode.length > 0 && (
HTML预览:
)} ); } 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-* 类、或内容含换行 = 代码块;否则按行内代码渲染。 // 关键:行内代码必须渲染成纯 ,绝不能套
。行内代码位于

内,块级

// 会被浏览器从

中提升出来、把段落拆开,导致 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 (

); } return null; }; // 行内代码:纯 ,不包裹任何块级元素,避免

内嵌

的非法嵌套 if (!isBlock) { return {props.children}; } return (
{props.children} {renderShowMoreButton()}
); } 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]*?)()/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 ( <> (

), a: (aProps) => { const href = aProps.href || ''; if (/\.(aac|mp3|opus|wav)$/.test(href)) { return (

); } if (/\.(3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href)) { return ( ); } const isInternal = /^\/#/i.test(href); const target = isInternal ? '_self' : (aProps.target ?? '_blank'); return ( { e.target.style.textDecoration = 'underline'; }} onMouseLeave={(e) => { e.target.style.textDecoration = 'none'; }} /> ); }, h1: (props) => (

), h2: (props) => (

), h3: (props) => (

), h4: (props) => (

), h5: (props) => (

), h6: (props) => (
), blockquote: (props) => (
), ul: (props) => (
    ), ol: (props) => (
      ), li: (props) => (
    1. ), table: (props) => (
      ), th: (props) => (
      ), td: (props) => ( ), img: (imgProps) => ( setPreviewImageUrl(imgProps.src)} /> ), }} > {escapedContent} 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; return (
      {loading ? (
      正在渲染...
      ) : ( )}
      ); } export default MarkdownRenderer;