/*
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 (