From 69670dbc24089eb566fa18cb5e20694def6454e5 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 3 Mar 2026 21:54:08 +0800 Subject: [PATCH] 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. --- .../components/css/chat-message-shared.less | 166 +++++++++ frontend/src/utils/chatMessageShared.ts | 54 +++ frontend/src/utils/mermaidShared.ts | 108 ++++++ .../chat/components/AgentStreamDisplay.vue | 341 ++---------------- frontend/src/views/chat/components/botmsg.vue | 326 ++--------------- 5 files changed, 375 insertions(+), 620 deletions(-) create mode 100644 frontend/src/components/css/chat-message-shared.less create mode 100644 frontend/src/utils/chatMessageShared.ts create mode 100644 frontend/src/utils/mermaidShared.ts diff --git a/frontend/src/components/css/chat-message-shared.less b/frontend/src/components/css/chat-message-shared.less new file mode 100644 index 00000000..7e46b26b --- /dev/null +++ b/frontend/src/components/css/chat-message-shared.less @@ -0,0 +1,166 @@ +.answer-toolbar { + display: flex; + justify-content: flex-start; + gap: 6px; + margin-top: 8px; + 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 { + 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; + } + + .t-icon svg { + display: block !important; + width: 16px; + height: 16px; + } + + .t-button__text > :not(.t-icon) { + display: none; + } + + &: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:not(:disabled) { + background: rgba(7, 192, 95, 0.12); + border-color: rgba(7, 192, 95, 0.4); + transform: translateY(0.5px); + } + } +} + +: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 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); + } +} diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts new file mode 100644 index 00000000..ff6539ef --- /dev/null +++ b/frontend/src/utils/chatMessageShared.ts @@ -0,0 +1,54 @@ +const STREAMING_IMAGE_PLACEHOLDER = ''; + +export const replaceIncompleteImageWithPlaceholder = (content: string): string => { + if (!content) return ''; + + 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. ![alt](local://... + if (!hasBracketClose || (hasParenOpen && !hasParenClose)) { + return content.slice(0, lastImgStart) + STREAMING_IMAGE_PLACEHOLDER; + } + + return content; +}; + +export 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; +}; + +export const buildManualMarkdown = (_question: string, answer: string): string => { + const safeAnswer = answer?.trim() || '(无回答内容)'; + return `${safeAnswer}`; +}; + +export const copyTextToClipboard = async (content: string): Promise => { + if (navigator.clipboard && navigator.clipboard.writeText) { + await navigator.clipboard.writeText(content); + return; + } + + 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); +}; diff --git a/frontend/src/utils/mermaidShared.ts b/frontend/src/utils/mermaidShared.ts new file mode 100644 index 00000000..9a88ed92 --- /dev/null +++ b/frontend/src/utils/mermaidShared.ts @@ -0,0 +1,108 @@ +import mermaid from 'mermaid'; + +let mermaidInitialized = false; + +const MERMAID_CONFIG = { + 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, + }, +}; + +export const ensureMermaidInitialized = () => { + if (mermaidInitialized) return; + mermaid.initialize(MERMAID_CONFIG as any); + mermaidInitialized = true; +}; + +export const createMermaidCodeRenderer = (idPrefix: string) => { + let mermaidCount = 0; + + return (code: string, infostring?: string) => { + const lang = (infostring || '').trim(); + if (lang === 'mermaid') { + const id = `${idPrefix}-${++mermaidCount}`; + return `
${code}
`; + } + + const displayLang = lang || 'Code'; + const escapedCode = code + .replace(/&/g, '&') + .replace(//g, '>'); + return `
${escapedCode}
`; + }; +}; + +export const renderMermaidInContainer = async ( + rootElement: HTMLElement | null | undefined, + renderedMermaidIds: Set, +) => { + if (!rootElement) return 0; + + const mermaidElements = rootElement.querySelectorAll('.mermaid'); + 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); + } + }); + + if (unrenderedElements.length === 0) return 0; + + await mermaid.run({ nodes: unrenderedElements }); + return unrenderedElements.length; +}; + +export const bindMermaidFullscreenEvents = ( + rootElement: HTMLElement | null | undefined, + onOpenFullscreen: (svgOuterHTML: string) => void, +) => { + if (!rootElement) return; + + const mermaidDivs = rootElement.querySelectorAll('.mermaid'); + mermaidDivs.forEach((div) => { + div.style.cursor = 'pointer'; + const oldHandler = (div as any).__mermaidClickHandler as EventListener | undefined; + if (oldHandler) { + div.removeEventListener('click', oldHandler); + } + const handler: EventListener = (e: Event) => { + e.stopPropagation(); + const target = e.currentTarget as HTMLElement; + const svg = target.querySelector('svg'); + if (svg) { + onOpenFullscreen(svg.outerHTML); + } + }; + (div as any).__mermaidClickHandler = handler; + div.addEventListener('click', handler); + }); +}; diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index a130ca29..1f86876f 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -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. ![alt](local://... - if (!hasBracketClose || (hasParenOpen && !hasParenClose)) { - const placeholder = ``; - 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 `
${code}
`; - } - - // 普通代码块 - const displayLang = lang || 'Code'; - const escapedCode = code.replace(/&/g, '&').replace(//g, '>'); - return `
${escapedCode}
`; -}; +agentRenderer.code = createMermaidCodeRenderer('mermaid-agent'); // Render HTML from a single token const getTokenHTML = (token: any): string => { @@ -1311,64 +1259,21 @@ const renderedMermaidIds = new Set(); // 渲染 Mermaid 图表的函数 const renderMermaidDiagrams = async () => { try { - if (rootElement.value) { - const mermaidElements = rootElement.value.querySelectorAll('.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('.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) => { diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index d7763ef5..f26eb74c 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -48,7 +48,6 @@