feat: add shared utilities for chat message handling and mermaid rendering
- Introduced new utility functions in `chatMessageShared.ts` for handling incomplete image placeholders, formatting titles, building markdown, and copying text to clipboard. - Added `mermaidShared.ts` to manage Mermaid initialization and rendering, including functions for creating code renderers and binding fullscreen events. - Updated `AgentStreamDisplay.vue` and `botmsg.vue` components to utilize the new utilities, improving code organization and reusability. - Removed redundant Mermaid initialization and image handling logic from components, streamlining the codebase. These changes enhance the functionality and maintainability of chat message rendering and Mermaid diagram integration.
This commit is contained in:
@@ -219,7 +219,6 @@ 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';
|
||||
@@ -228,42 +227,24 @@ import { useUIStore } from '@/stores/ui';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
|
||||
import { hydrateProtectedFileImages } from '@/utils/security';
|
||||
import {
|
||||
buildManualMarkdown,
|
||||
copyTextToClipboard,
|
||||
formatManualTitle,
|
||||
replaceIncompleteImageWithPlaceholder,
|
||||
} from '@/utils/chatMessageShared';
|
||||
import {
|
||||
bindMermaidFullscreenEvents,
|
||||
createMermaidCodeRenderer,
|
||||
ensureMermaidInitialized,
|
||||
renderMermaidInContainer,
|
||||
} from '@/utils/mermaidShared';
|
||||
|
||||
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
|
||||
}
|
||||
});
|
||||
ensureMermaidInitialized();
|
||||
|
||||
// DOMPurify 配置 - 支持 Mermaid SVG 标签
|
||||
const DOMPurifyConfig = {
|
||||
@@ -1217,26 +1198,6 @@ const preprocessMarkdown = (contentStr: string): string => {
|
||||
);
|
||||
};
|
||||
|
||||
const replaceIncompleteImageWithPlaceholder = (content: string): string => {
|
||||
const lastImgStart = content.lastIndexOf('![');
|
||||
if (lastImgStart < 0) return content;
|
||||
|
||||
const tail = content.slice(lastImgStart);
|
||||
const hasImageOpen = tail.startsWith('![');
|
||||
const hasBracketClose = tail.includes(']');
|
||||
const hasParenOpen = tail.includes('(');
|
||||
const hasParenClose = tail.includes(')');
|
||||
if (!hasImageOpen) return content;
|
||||
|
||||
// Incomplete image syntax at stream tail, e.g. ) {
|
||||
const placeholder = `<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>`;
|
||||
return content.slice(0, lastImgStart) + placeholder;
|
||||
}
|
||||
|
||||
return content;
|
||||
};
|
||||
|
||||
// Get tokens from markdown content
|
||||
const getTokens = (content: any) => {
|
||||
const contentStr = typeof content === 'string' ? content : String(content || '');
|
||||
@@ -1248,20 +1209,7 @@ const getTokens = (content: any) => {
|
||||
|
||||
// 自定义渲染器 - 支持 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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
return `<pre><code class="language-${displayLang}">${escapedCode}</code></pre>`;
|
||||
};
|
||||
agentRenderer.code = createMermaidCodeRenderer('mermaid-agent');
|
||||
|
||||
// Render HTML from a single token
|
||||
const getTokenHTML = (token: any): string => {
|
||||
@@ -1311,64 +1259,21 @@ const renderedMermaidIds = new Set<string>();
|
||||
// 渲染 Mermaid 图表的函数
|
||||
const renderMermaidDiagrams = async () => {
|
||||
try {
|
||||
if (rootElement.value) {
|
||||
const mermaidElements = rootElement.value.querySelectorAll<HTMLElement>('.mermaid');
|
||||
console.log('[Mermaid] Found mermaid elements:', mermaidElements?.length);
|
||||
|
||||
// 过滤出未渲染的元素
|
||||
const unrenderedElements: HTMLElement[] = [];
|
||||
mermaidElements.forEach((el) => {
|
||||
const id = el.id || `mermaid-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
if (!el.id) {
|
||||
el.id = id;
|
||||
}
|
||||
if (!renderedMermaidIds.has(el.id) && !el.querySelector('svg')) {
|
||||
renderedMermaidIds.add(el.id);
|
||||
unrenderedElements.push(el);
|
||||
}
|
||||
const renderedCount = await renderMermaidInContainer(rootElement.value, renderedMermaidIds);
|
||||
if (renderedCount > 0) {
|
||||
nextTick(() => {
|
||||
bindMermaidClickEvents();
|
||||
});
|
||||
|
||||
if (unrenderedElements.length > 0) {
|
||||
await mermaid.run({
|
||||
nodes: unrenderedElements
|
||||
});
|
||||
console.log('[Mermaid] Rendering complete for', unrenderedElements.length, 'elements');
|
||||
// 渲染完成后绑定点击事件
|
||||
nextTick(() => {
|
||||
bindMermaidClickEvents();
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Mermaid rendering error:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Mermaid 点击处理函数 - 必须在 bindMermaidClickEvents 之前定义
|
||||
const handleMermaidClick = (e: Event) => {
|
||||
e.stopPropagation();
|
||||
const target = e.currentTarget as HTMLElement;
|
||||
const svg = target.querySelector('svg');
|
||||
if (svg) {
|
||||
openMermaidFullscreen(svg.outerHTML);
|
||||
}
|
||||
};
|
||||
|
||||
// 为 Mermaid 容器绑定点击全屏事件(绑定在 div 上,不是 SVG 上)
|
||||
const bindMermaidClickEvents = () => {
|
||||
if (!rootElement.value) {
|
||||
console.log('[Mermaid] rootElement is null');
|
||||
return;
|
||||
}
|
||||
// 绑定在 .mermaid div 上,而不是 SVG 上
|
||||
const mermaidDivs = rootElement.value.querySelectorAll<HTMLElement>('.mermaid');
|
||||
console.log('[Mermaid] Found mermaid divs:', mermaidDivs.length);
|
||||
mermaidDivs.forEach((div, index) => {
|
||||
div.style.cursor = 'pointer';
|
||||
// 移除旧的事件监听器(避免重复绑定)
|
||||
div.removeEventListener('click', handleMermaidClick);
|
||||
div.addEventListener('click', handleMermaidClick);
|
||||
console.log(`[Mermaid] Bound click event to div ${index}`);
|
||||
bindMermaidFullscreenEvents(rootElement.value, (svgOuterHTML: string) => {
|
||||
openMermaidFullscreen(svgOuterHTML);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1729,23 +1634,6 @@ const formatJSON = (obj: any): string => {
|
||||
}
|
||||
};
|
||||
|
||||
const buildManualMarkdown = (question: string, answer: string): string => {
|
||||
const safeQuestion = question?.trim() || '(无提问内容)';
|
||||
const safeAnswer = answer?.trim() || '(无回答内容)';
|
||||
return `${safeAnswer}`;
|
||||
};
|
||||
|
||||
const formatManualTitle = (question: string): string => {
|
||||
if (!question) {
|
||||
return '会话摘录';
|
||||
}
|
||||
const condensed = question.replace(/\s+/g, ' ').trim();
|
||||
if (!condensed) {
|
||||
return '会话摘录';
|
||||
}
|
||||
return condensed.length > 40 ? `${condensed.slice(0, 40)}...` : condensed;
|
||||
};
|
||||
|
||||
// Helper function to get actual content (from answer or last thinking)
|
||||
const getActualContent = (answerEvent: any): string => {
|
||||
// First try to get content from answer event
|
||||
@@ -1775,22 +1663,8 @@ const handleCopyAnswer = async (answerEvent: any) => {
|
||||
}
|
||||
|
||||
try {
|
||||
// 尝试使用现代 Clipboard API
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
await navigator.clipboard.writeText(content);
|
||||
MessagePlugin.success('已复制到剪贴板');
|
||||
} else {
|
||||
// 降级到传统方式
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = content;
|
||||
textArea.style.position = 'fixed';
|
||||
textArea.style.opacity = '0';
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
MessagePlugin.success('已复制到剪贴板');
|
||||
}
|
||||
await copyTextToClipboard(content);
|
||||
MessagePlugin.success('已复制到剪贴板');
|
||||
} catch (err) {
|
||||
console.error('复制失败:', err);
|
||||
MessagePlugin.error('复制失败,请手动复制');
|
||||
@@ -1821,6 +1695,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
||||
|
||||
<style lang="less" scoped>
|
||||
@import '../../../components/css/markdown.less';
|
||||
@import '../../../components/css/chat-message-shared.less';
|
||||
|
||||
.agent-stream-display {
|
||||
display: flex;
|
||||
@@ -2296,84 +2171,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
||||
}
|
||||
|
||||
.answer-toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
gap: 6px;
|
||||
margin-top: 4px;
|
||||
min-height: 32px;
|
||||
|
||||
:deep(.t-button) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: auto;
|
||||
width: auto;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: #666;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
// 确保按钮内容区域正确显示
|
||||
.t-button__content {
|
||||
display: inline-flex !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
// t-button__text 包含图标,需要显示但只显示图标
|
||||
.t-button__text {
|
||||
display: inline-flex !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
// 确保图标显示
|
||||
.t-icon {
|
||||
display: inline-flex !important;
|
||||
visibility: visible !important;
|
||||
opacity: 1 !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex-shrink: 0;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
// 确保 SVG 图标也显示
|
||||
.t-icon svg {
|
||||
display: block !important;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
// 隐藏文字节点(但不是图标)
|
||||
.t-button__text > :not(.t-icon) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Hover 效果
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(7, 192, 95, 0.08);
|
||||
border-color: rgba(7, 192, 95, 0.3);
|
||||
color: #07c05f;
|
||||
|
||||
.t-icon {
|
||||
color: #07c05f;
|
||||
}
|
||||
}
|
||||
|
||||
// Active 效果
|
||||
&:active:not(:disabled) {
|
||||
background: rgba(7, 192, 95, 0.12);
|
||||
border-color: rgba(7, 192, 95, 0.4);
|
||||
transform: translateY(0.5px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3247,103 +3045,10 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.streaming-image-loading) {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
width: clamp(150px, 30vw, 260px);
|
||||
max-width: 100%;
|
||||
aspect-ratio: 4 / 3;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(175, 190, 210, 0.55);
|
||||
background: linear-gradient(
|
||||
145deg,
|
||||
rgba(245, 249, 255, 0.72) 0%,
|
||||
rgba(228, 236, 248, 0.62) 45%,
|
||||
rgba(214, 225, 242, 0.58) 100%
|
||||
);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.75),
|
||||
inset 0 -1px 0 rgba(168, 182, 206, 0.28),
|
||||
0 8px 20px rgba(100, 121, 152, 0.12);
|
||||
backdrop-filter: blur(3px) saturate(115%);
|
||||
-webkit-backdrop-filter: blur(3px) saturate(115%);
|
||||
overflow: hidden;
|
||||
vertical-align: middle;
|
||||
animation: streamingImageBreath 2.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
:deep(.streaming-image-loading__skeleton) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
110deg,
|
||||
rgba(234, 239, 246, 0.95) 8%,
|
||||
rgba(248, 250, 252, 0.98) 18%,
|
||||
rgba(234, 239, 246, 0.95) 33%
|
||||
);
|
||||
background-size: 220% 100%;
|
||||
animation: streamingImageShimmer 1.4s linear infinite;
|
||||
}
|
||||
|
||||
:deep(.streaming-image-loading)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
border: 1px solid rgba(255, 255, 255, 0.45);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
:deep(.streaming-image-loading)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -35%;
|
||||
top: -55%;
|
||||
width: 62%;
|
||||
height: 210%;
|
||||
background: linear-gradient(
|
||||
120deg,
|
||||
rgba(255, 255, 255, 0) 0%,
|
||||
rgba(255, 255, 255, 0.38) 46%,
|
||||
rgba(255, 255, 255, 0) 100%
|
||||
);
|
||||
transform: rotate(16deg);
|
||||
animation: streamingImageMirror 2.8s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes streamingImageShimmer {
|
||||
to {
|
||||
background-position-x: -220%;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes streamingImageMirror {
|
||||
0%, 100% {
|
||||
left: -38%;
|
||||
opacity: 0.35;
|
||||
}
|
||||
50% {
|
||||
left: 110%;
|
||||
opacity: 0.75;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes streamingImageBreath {
|
||||
0%, 100% {
|
||||
transform: translateY(0) scale(1);
|
||||
filter: saturate(1);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-0.5px) scale(1.01);
|
||||
filter: saturate(1.06);
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user