feat: support mermaid display

This commit is contained in:
Li Xianggang
2026-03-02 11:25:02 +08:00
committed by lyingbug
parent 92e95b19ed
commit db21694dd5
7 changed files with 1514 additions and 32 deletions
+1198 -12
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -19,6 +19,7 @@
"dompurify": "^3.2.6",
"highlight.js": "^11.11.1",
"marked": "^5.1.2",
"mermaid": "^11.4.1",
"pagefind": "^1.1.1",
"papaparse": "^5.5.3",
"pinia": "^3.0.1",
+15
View File
@@ -6,6 +6,21 @@
cursor: pointer;
}
// Mermaid 图表样式
.mermaid {
margin: 16px 0;
padding: 16px;
background: #f8f9fa;
border-radius: 8px;
overflow-x: auto;
text-align: center;
svg {
max-width: 100%;
height: auto;
}
}
h1,
h2,
h3,
+58
View File
@@ -3,6 +3,7 @@
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import mermaid from "mermaid";
import { onMounted, ref, nextTick, onUnmounted, onUpdated, watch } from "vue";
import { downKnowledgeDetails, deleteGeneratedQuestion } from "@/api/knowledge-base/index";
import { MessagePlugin, DialogPlugin } from "tdesign-vue-next";
@@ -11,6 +12,38 @@ import { useI18n } from 'vue-i18n';
const { t } = useI18n();
// Mermaid 初始化计数器,用于生成唯一ID
let mermaidRenderCount = 0;
// 初始化 Mermaid
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'strict',
fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
curve: 'basis'
},
sequence: {
useMaxWidth: true,
diagramMarginX: 8,
diagramMarginY: 8,
actorMargin: 50,
width: 150,
height: 65
},
gantt: {
useMaxWidth: true,
leftPadding: 75,
gridLineStartPadding: 35,
barHeight: 20,
barGap: 4,
topPadding: 50
}
});
marked.use({
mangle: false,
headerIds: false,
@@ -133,6 +166,15 @@ renderer.image = function (href, title, text) {
// 自定义代码块渲染器,只显示语言标签
renderer.code = function (code, infostring) {
const lang = (infostring || '').trim();
// Mermaid 图表处理
if (lang === 'mermaid') {
// 生成唯一ID
const id = `mermaid-${++mermaidRenderCount}`;
// 返回带有 mermaid 类的 div,后续由 mermaid.run() 处理
return `<div class="mermaid" id="${id}">${code}</div>`;
}
let detectedLang = lang;
let highlighted = '';
if (lang && hljs.getLanguage(lang)) {
@@ -209,9 +251,25 @@ watch(() => props.details.md, (newVal) => {
}
})
}
// 渲染 Mermaid 图表
await renderMermaidDiagrams();
})
}, { immediate: true, deep: true })
// 渲染 Mermaid 图表的函数
const renderMermaidDiagrams = async () => {
try {
const mermaidElements = mdContentWrap.value?.querySelectorAll('.mermaid');
if (mermaidElements && mermaidElements.length > 0) {
await mermaid.run({
nodes: mermaidElements
});
}
} catch (error) {
console.error('Mermaid rendering error:', error);
}
};
// 安全地处理 Markdown 内容(使用 marked)
const processMarkdown = (markdownText) => {
if (!markdownText || typeof markdownText !== 'string') return '';
+21 -2
View File
@@ -12,12 +12,31 @@ const DOMPurifyConfig = {
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li', 'blockquote', 'pre', 'code',
'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td',
'div', 'span', 'figure', 'figcaption', 'think'
'div', 'span', 'figure', 'figcaption', 'think',
// Mermaid SVG 支持的标签
'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polygon',
'polyline', 'text', 'tspan', 'defs', 'marker', 'filter', 'use',
'clippath', 'lineargradient', 'radialgradient', 'stop', 'pattern',
'image', 'foreignobject', 'desc', 'title', 'switch', 'symbol', 'mask'
],
// 允许的属性
ALLOWED_ATTR: [
'href', 'title', 'alt', 'src', 'class', 'id', 'style',
'target', 'rel', 'width', 'height'
'target', 'rel', 'width', 'height',
// Mermaid SVG 支持的属性
'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity',
'fill-opacity', 'opacity', 'transform', 'viewbox', 'preserveaspectratio',
'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'rx', 'ry', 'r',
'dx', 'dy', 'text-anchor', 'dominant-baseline', 'font-family', 'font-size',
'font-weight', 'font-style', 'letter-spacing', 'word-spacing',
'marker-start', 'marker-mid', 'marker-end', 'markerunits', 'markerwidth',
'markerheight', 'refx', 'refy', 'orient', 'points', 'offset',
'gradientunits', 'gradienttransform', 'spreadmethod', 'stop-color', 'stop-opacity',
'patternunits', 'patterntransform', 'clippathunits', 'maskunits',
'filterunits', 'primitiveunits', 'xmlns', 'xmlns:xlink', 'xlink:href',
'version', 'baseprofile', 'enable-background', 'overflow', 'visibility',
'display', 'pointer-events', 'cursor', 'data-emit', 'direction'
],
// 允许的协议
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
@@ -219,6 +219,7 @@ import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import mermaid from 'mermaid';
import ToolResultRenderer from './ToolResultRenderer.vue';
import picturePreview from '@/components/picture-preview.vue';
import { getChunkByIdOnly } from '@/api/knowledge-base';
@@ -230,6 +231,71 @@ const router = useRouter();
const uiStore = useUIStore();
const { t } = useI18n();
// Mermaid 初始化计数器
let agentMermaidCount = 0;
// 初始化 Mermaid
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'strict',
fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
curve: 'basis'
},
sequence: {
useMaxWidth: true,
diagramMarginX: 8,
diagramMarginY: 8,
actorMargin: 50,
width: 150,
height: 65
},
gantt: {
useMaxWidth: true,
leftPadding: 75,
gridLineStartPadding: 35,
barHeight: 20,
barGap: 4,
topPadding: 50
}
});
// DOMPurify 配置 - 支持 Mermaid SVG 标签
const DOMPurifyConfig = {
ALLOWED_TAGS: [
'p', 'br', 'strong', 'em', 'u', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'span', 'table', 'thead', 'tbody',
'tr', 'th', 'td', 'img', 'figure', 'figcaption', 'div',
// Mermaid SVG 支持的标签
'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polygon',
'polyline', 'text', 'tspan', 'defs', 'marker', 'filter', 'use',
'clippath', 'lineargradient', 'radialgradient', 'stop', 'pattern',
'image', 'foreignobject', 'desc', 'title', 'switch', 'symbol', 'mask'
],
ALLOWED_ATTR: [
'href', 'title', 'target', 'rel', 'data-tooltip', 'data-url', 'data-kb-id',
'data-chunk-id', 'data-doc', 'class', 'role', 'tabindex', 'src', 'alt',
'width', 'height', 'style', 'id',
// Mermaid SVG 支持的属性
'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity',
'fill-opacity', 'opacity', 'transform', 'viewbox', 'preserveaspectratio',
'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'rx', 'ry', 'r',
'dx', 'dy', 'text-anchor', 'dominant-baseline', 'font-family', 'font-size',
'font-weight', 'font-style', 'letter-spacing', 'word-spacing',
'marker-start', 'marker-mid', 'marker-end', 'markerunits', 'markerwidth',
'markerheight', 'refx', 'refy', 'orient', 'points', 'offset',
'gradientunits', 'gradienttransform', 'spreadmethod', 'stop-color', 'stop-opacity',
'patternunits', 'patterntransform', 'clippathunits', 'maskunits',
'filterunits', 'primitiveunits', 'xmlns', 'xmlns:xlink', 'xlink:href',
'version', 'baseprofile', 'enable-background', 'overflow', 'visibility',
'display', 'pointer-events', 'cursor', 'data-emit', 'direction'
]
};
const TOOL_NAME_I18N: Record<string, string> = {
search_knowledge: '知识库检索',
knowledge_search: '知识库检索',
@@ -386,12 +452,17 @@ const expandedEvents = ref<Set<string>>(new Set());
// Watch event stream to auto-expand thinking tools
watch(eventStream, (stream) => {
if (!stream || !Array.isArray(stream)) return;
stream.forEach((event: any) => {
if (event?.type === 'tool_call' && event?.tool_name === 'thinking' && event?.tool_call_id) {
expandedEvents.value.add(event.tool_call_id);
}
});
// 渲染 Mermaid 图表
nextTick(() => {
renderMermaidDiagrams();
});
}, { immediate: true, deep: true });
// State for intermediate steps collapse
@@ -1150,19 +1221,33 @@ const preprocessMarkdown = (contentStr: string): string => {
const getTokens = (content: any) => {
const contentStr = typeof content === 'string' ? content : String(content || '');
if (!contentStr.trim()) return [];
const processed = preprocessMarkdown(contentStr);
return marked.lexer(processed);
};
// 自定义渲染器 - 支持 Mermaid
const agentRenderer = new marked.Renderer();
agentRenderer.code = function(code, infostring) {
const lang = (infostring || '').trim();
// Mermaid 图表处理
if (lang === 'mermaid') {
const id = `mermaid-agent-${++agentMermaidCount}`;
return `<div class="mermaid" id="${id}">${code}</div>`;
}
// 普通代码块
const displayLang = lang || 'Code';
const escapedCode = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return `<pre><code class="language-${displayLang}">${escapedCode}</code></pre>`;
};
// Render HTML from a single token
const getTokenHTML = (token: any): string => {
try {
const html = marked.parser([token]);
return DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'span', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'img', 'figure', 'figcaption'],
ALLOWED_ATTR: ['href', 'title', 'target', 'rel', 'data-tooltip', 'data-url', 'data-kb-id', 'data-chunk-id', 'data-doc', 'class', 'role', 'tabindex', 'src', 'alt', 'width', 'height', 'style']
});
const html = marked.parser([token], { renderer: agentRenderer });
return DOMPurify.sanitize(html, DOMPurifyConfig);
} catch (e) {
console.error('Token rendering error:', e);
return '';
@@ -1173,22 +1258,35 @@ const getTokenHTML = (token: any): string => {
const renderMarkdown = (content: any): string => {
const contentStr = typeof content === 'string' ? content : String(content || '');
if (!contentStr.trim()) return '';
try {
const processed = preprocessMarkdown(contentStr);
const html = marked.parse(processed) as string;
const html = marked.parse(processed, { renderer: agentRenderer }) as string;
if (!html) return '';
return DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'span', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'img', 'figure', 'figcaption'],
ALLOWED_ATTR: ['href', 'title', 'target', 'rel', 'data-tooltip', 'data-url', 'data-kb-id', 'data-chunk-id', 'data-doc', 'class', 'role', 'tabindex', 'src', 'alt', 'width', 'height', 'style']
});
return DOMPurify.sanitize(html, DOMPurifyConfig);
} catch (e) {
console.error('Markdown rendering error:', e, 'Content:', contentStr.substring(0, 100));
return contentStr.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
};
// 渲染 Mermaid 图表的函数
const renderMermaidDiagrams = async () => {
try {
if (rootElement.value) {
const mermaidElements = rootElement.value.querySelectorAll<HTMLElement>('.mermaid');
if (mermaidElements && mermaidElements.length > 0) {
await mermaid.run({
nodes: mermaidElements
});
}
}
} catch (error) {
console.error('Mermaid rendering error:', error);
}
};
// Tool summary - extract key info to display externally
const getToolSummary = (event: any): string => {
if (!event || event.pending || !event.success) return '';
@@ -2063,18 +2161,18 @@ const handleAddToKnowledge = (answerEvent: any) => {
border-collapse: collapse;
margin: 6px 0;
font-size: 11px;
th, td {
border: 1px solid #e5e7eb;
padding: 5px 8px;
}
th {
background: #f9fafb;
font-weight: 600;
}
}
:deep(img) {
max-width: 80%;
max-height: 300px;
@@ -2089,11 +2187,26 @@ const handleAddToKnowledge = (answerEvent: any) => {
cursor: pointer;
transition: transform 0.2s ease;
background-color: #f9fafb; /* 加载时的占位背景色 */
&:hover {
transform: scale(1.02);
}
}
// Mermaid 图表样式
:deep(.mermaid) {
margin: 16px 0;
padding: 16px;
background: #f8f9fa;
border-radius: 8px;
overflow-x: auto;
text-align: center;
svg {
max-width: 100%;
height: auto;
}
}
}
}
@@ -48,6 +48,7 @@
<script setup>
import { onMounted, onBeforeUnmount, watch, computed, ref, reactive, defineProps, nextTick } from 'vue';
import { marked } from 'marked';
import mermaid from 'mermaid';
import docInfo from './docInfo.vue';
import deepThink from './deepThink.vue';
import AgentStreamDisplay from './AgentStreamDisplay.vue';
@@ -62,6 +63,39 @@ marked.use({
headerIds: false,
breaks: true, // 全局启用单个换行支持
});
// Mermaid 初始化计数器
let botmsgMermaidCount = 0;
// 初始化 Mermaid
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'strict',
fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
curve: 'basis'
},
sequence: {
useMaxWidth: true,
diagramMarginX: 8,
diagramMarginY: 8,
actorMargin: 50,
width: 150,
height: 65
},
gantt: {
useMaxWidth: true,
leftPadding: 75,
gridLineStartPadding: 35,
barHeight: 20,
barGap: 4,
topPadding: 50
}
});
const emit = defineEmits(['scroll-bottom'])
const { t } = useI18n()
const uiStore = useUIStore();
@@ -115,6 +149,22 @@ customRenderer.image = function(href, title, text) {
return createSafeImage(href, text || '', title || '');
};
// 覆盖代码块渲染方法,支持 Mermaid
customRenderer.code = function(code, infostring) {
const lang = (infostring || '').trim();
// Mermaid 图表处理
if (lang === 'mermaid') {
const id = `mermaid-botmsg-${++botmsgMermaidCount}`;
return `<div class="mermaid" id="${id}">${code}</div>`;
}
// 普通代码块
const displayLang = lang || 'Code';
const escapedCode = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return `<pre><code class="language-${displayLang}">${escapedCode}</code></pre>`;
};
// 计算属性:将 Markdown 文本转换为 tokens
const markdownTokens = computed(() => {
const text = props.content || props.session?.content || '';
@@ -247,12 +297,37 @@ const handleMarkdownImageClick = (e) => {
}
};
// 渲染 Mermaid 图表的函数
const renderMermaidDiagrams = async () => {
try {
if (parentMd.value) {
const mermaidElements = parentMd.value.querySelectorAll('.mermaid');
if (mermaidElements && mermaidElements.length > 0) {
await mermaid.run({
nodes: mermaidElements
});
}
}
} catch (error) {
console.error('Mermaid rendering error:', error);
}
};
// 监听内容变化并渲染 Mermaid
watch(() => [props.content, props.session?.content], () => {
nextTick(() => {
renderMermaidDiagrams();
});
}, { immediate: true });
onMounted(async () => {
// 为 markdown-content 中的图片添加点击事件
nextTick(() => {
if (parentMd.value) {
parentMd.value.addEventListener('click', handleMarkdownImageClick, true);
}
// 初始渲染 Mermaid 图表
renderMermaidDiagrams();
});
});
@@ -389,6 +464,21 @@ onBeforeUnmount(() => {
transform: scale(1.02);
}
}
// Mermaid 图表样式
:deep(.mermaid) {
margin: 16px 0;
padding: 16px;
background: #f8f9fa;
border-radius: 8px;
overflow-x: auto;
text-align: center;
svg {
max-width: 100%;
height: auto;
}
}
}
.ai-markdown-img {