291 lines
12 KiB
TypeScript
291 lines
12 KiB
TypeScript
/**
|
|
* features/chat/page/useChatPageMarkdown.ts
|
|
* 用途:统一处理聊天页 Markdown 渲染、内嵌文件块提取、消息可见性判断与特殊链接点击。
|
|
* 依赖:Vue computed、marked、ChatMessageBubble handlers、聊天消息类型。
|
|
* 逻辑:由 useChatPage 组装上下文后创建页面级 Markdown API,再分发给 ChatMessageBubble 做消息渲染和交互。
|
|
*/
|
|
import { computed } from 'vue';
|
|
import { marked } from 'marked';
|
|
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
|
|
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
|
|
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
|
import type { Ref } from 'vue';
|
|
|
|
marked.setOptions({ gfm: true, breaks: true });
|
|
|
|
const INLINE_FILE_BLOCK_REGEX = /\[FILE_START\]([\s\S]*?)\[FILE_END\]/g;
|
|
const INLINE_ATTACHMENT_HINT_REGEX = /^.*(?:如果您需要查看全部数据,请下载附件。?|请下载附件。?).*$/gim;
|
|
|
|
interface InlineFileExtractResult {
|
|
cleanedText: string;
|
|
files: InlineDownloadFile[];
|
|
}
|
|
|
|
const INLINE_DOWNLOAD_LINK_LINE_REGEX = /^[ \t>*-]*\[[^\]]*下载(?:全部|全量)?数据[^\]]*\]\([^)]+\)\s*$/gim;
|
|
|
|
/**
|
|
* 在 JSON.parse 失败时兜底提取文件字段,兼容 Dify 偶发返回的近似 JSON 文本。
|
|
* 核心逻辑:优先抽取 name/data/mime_type 三个字段;若缺失关键字段则返回 null,避免伪造按钮。
|
|
* @param rawPayload - FILE_START/FILE_END 包裹的原始文本。
|
|
* @returns 尽力恢复后的文件对象;恢复失败时返回 null。
|
|
*/
|
|
function decodeLooseJsonString(rawValue: string): string {
|
|
return String(rawValue || '')
|
|
.replace(/\\u([0-9a-fA-F]{4})/g, (_match, code: string) => String.fromCharCode(Number.parseInt(code, 16)))
|
|
.replace(/\\r/g, '\r')
|
|
.replace(/\\n/g, '\n')
|
|
.replace(/\\t/g, '\t')
|
|
.replace(/\\f/g, '\f')
|
|
.replace(/\\b/g, '\b')
|
|
.replace(/\\"/g, '"')
|
|
.replace(/\\\\/g, '\\');
|
|
}
|
|
|
|
function tryParseInlineFileFallback(rawPayload: string): InlineDownloadFile | null {
|
|
const raw = String(rawPayload || '').trim();
|
|
const nameMatch = raw.match(/"name"\s*:\s*"((?:\\.|[^"\\])*)"/i);
|
|
const dataMatch = raw.match(/"data"\s*:\s*"([\s\S]*?)"\s*(?:,\s*"mime_type"|\s*}$)/i);
|
|
const mimeMatch = raw.match(/"mime_type"\s*:\s*"((?:\\.|[^"\\])*)"/i);
|
|
const name = nameMatch?.[1] ? decodeLooseJsonString(nameMatch[1]).trim() : '';
|
|
const data = dataMatch?.[1] ? decodeLooseJsonString(dataMatch[1]) : '';
|
|
const mimeType = mimeMatch?.[1] ? decodeLooseJsonString(mimeMatch[1]).trim() : '';
|
|
if (!name || !data) return null;
|
|
return {
|
|
name,
|
|
data,
|
|
mime_type: mimeType || 'application/octet-stream',
|
|
};
|
|
}
|
|
|
|
export interface ChatPageMarkdownContext {
|
|
messages: Ref<ChatMessage[]>;
|
|
isThinking: Ref<boolean>;
|
|
prepareMarkdownDisplayText: (text: string) => string;
|
|
handleLeaveMarkdownClick: (event: MouseEvent) => void;
|
|
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
|
|
openPreview: (file: SourceFileLink) => Promise<void>;
|
|
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
|
|
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
|
|
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
|
|
shouldExpandSourceDetails: (msgItem: Record<string, unknown>) => boolean;
|
|
getSourceTitle: ChatMessageBubbleHandlers['getSourceTitle'];
|
|
getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta'];
|
|
getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief'];
|
|
getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload'];
|
|
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
|
|
canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview'];
|
|
getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary'];
|
|
openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog'];
|
|
shippingActionButtonClass: ChatMessageBubbleHandlers['shippingActionButtonClass'];
|
|
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
|
|
}
|
|
|
|
/**
|
|
* 提取 Dify 返回文本中的内嵌文件块,并把原始 JSON 从聊天正文里剥离。
|
|
* 核心逻辑:使用 FILE_START/FILE_END 正则定位片段,逐个 JSON.parse 成可下载文件;解析失败时保留原文避免误伤正常消息。
|
|
* @param text - 助手原始 answer 文本,可能混有 Markdown 与文件 JSON。
|
|
* @returns 清理后的展示文本与可下载文件列表。
|
|
*/
|
|
function extractInlineDownloadFiles(text: string): InlineFileExtractResult {
|
|
if (!text) {
|
|
return { cleanedText: '', files: [] };
|
|
}
|
|
|
|
const files: InlineDownloadFile[] = [];
|
|
const seenKeys = new Set<string>();
|
|
|
|
let cleanedText = text.replace(INLINE_FILE_BLOCK_REGEX, (_match, rawPayload: string) => {
|
|
try {
|
|
const parsed = JSON.parse(String(rawPayload || '').trim()) as Partial<InlineDownloadFile>;
|
|
const name = String(parsed.name || '').trim();
|
|
const data = typeof parsed.data === 'string' ? parsed.data : '';
|
|
const mimeType = String(parsed.mime_type || '').trim() || 'application/octet-stream';
|
|
|
|
if (!name || !data) {
|
|
return '';
|
|
}
|
|
|
|
const dedupeKey = `${name}::${mimeType}::${data}`;
|
|
if (!seenKeys.has(dedupeKey)) {
|
|
seenKeys.add(dedupeKey);
|
|
files.push({
|
|
name,
|
|
data,
|
|
mime_type: mimeType,
|
|
});
|
|
}
|
|
return '';
|
|
} catch {
|
|
const fallbackFile = tryParseInlineFileFallback(rawPayload);
|
|
if (fallbackFile) {
|
|
const dedupeKey = `${fallbackFile.name}::${fallbackFile.mime_type || ''}::${fallbackFile.data}`;
|
|
if (!seenKeys.has(dedupeKey)) {
|
|
seenKeys.add(dedupeKey);
|
|
files.push(fallbackFile);
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
});
|
|
|
|
// [STEP 1] 流式消息可能先到 FILE_START、后到 FILE_END,这一阶段先把未闭合块整体隐藏,避免原始 CSV/JSON 外露。
|
|
const danglingStartIndex = cleanedText.indexOf('[FILE_START]');
|
|
if (danglingStartIndex >= 0) {
|
|
cleanedText = cleanedText.slice(0, danglingStartIndex);
|
|
}
|
|
|
|
// [STEP 2] 如果消息正文已经内置了 Markdown 下载链接,保留说明文案但移除直接下载入口,统一交给预览卡片处理。
|
|
if (files.length > 0) {
|
|
cleanedText = cleanedText.replace(INLINE_DOWNLOAD_LINK_LINE_REGEX, '');
|
|
}
|
|
|
|
// [STEP 3] 无论是否存在附件按钮,都移除“请下载附件”类兜底文案,避免 <=5 条时误导用户,也避免 >5 条时重复提示。
|
|
cleanedText = cleanedText.replace(INLINE_ATTACHMENT_HINT_REGEX, '');
|
|
|
|
return {
|
|
cleanedText: cleanedText.trim(),
|
|
files,
|
|
};
|
|
}
|
|
|
|
function safeExtractInlineDownloadFiles(text: string): InlineFileExtractResult {
|
|
try {
|
|
return extractInlineDownloadFiles(text);
|
|
} catch {
|
|
return {
|
|
cleanedText: String(text || '').replace(/\[FILE_START\][\s\S]*$/g, '').trim(),
|
|
files: [],
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 将内嵌文件内容转成浏览器本地下载。
|
|
* 核心逻辑:按 mime/type 生成 Blob 与 object URL,触发隐藏 a 标签点击后立即回收 URL,避免把大段 CSV 暴露在 DOM 中。
|
|
* @param file - 已从消息中解析出的单个可下载文件,要求 name/data 均非空。
|
|
*/
|
|
function downloadInlineFile(file: InlineDownloadFile): void {
|
|
if (!file.name || !file.data) return;
|
|
const blob = new Blob([file.data], { type: file.mime_type || 'application/octet-stream;charset=utf-8' });
|
|
const objectUrl = URL.createObjectURL(blob);
|
|
const anchor = document.createElement('a');
|
|
anchor.href = objectUrl;
|
|
anchor.download = file.name;
|
|
anchor.style.display = 'none';
|
|
document.body.appendChild(anchor);
|
|
anchor.click();
|
|
document.body.removeChild(anchor);
|
|
URL.revokeObjectURL(objectUrl);
|
|
}
|
|
|
|
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
|
if (msgItem?.role === 'user') return true;
|
|
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
|
const content = (msgItem?.content || '').trim();
|
|
if (content) return true;
|
|
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
|
if (ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
|
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
|
|
};
|
|
|
|
/**
|
|
* 判断某条 assistant 消息是否已经具备“正文已出现”的特征。
|
|
* 核心逻辑:仅把真正可读的正文或结构化子消息视为已开始回复;
|
|
* 单纯的引用源、空内容或中间元数据不应压掉“思考中”提示。
|
|
*/
|
|
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
|
|
if (msgItem?.role !== 'assistant') return false;
|
|
if (msgItem?.type === 'leave-form'
|
|
|| msgItem?.type === 'leave-confirmation'
|
|
|| msgItem?.type === 'leave-result'
|
|
|| msgItem?.type === 'shipping-inventory-mapping'
|
|
|| msgItem?.type === 'shipping-parse-review'
|
|
|| msgItem?.type === 'shipping-match-result') {
|
|
return true;
|
|
}
|
|
return Boolean(String(msgItem?.content || '').trim());
|
|
};
|
|
|
|
const shouldShowThinkingBubble = computed(() => {
|
|
if (!ctx.isThinking.value) return false;
|
|
let lastUserIndex = -1;
|
|
for (let i = ctx.messages.value.length - 1; i >= 0; i--) {
|
|
if (ctx.messages.value[i]?.role === 'user') {
|
|
lastUserIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
if (lastUserIndex < 0) return true;
|
|
return !ctx.messages.value
|
|
.slice(lastUserIndex + 1)
|
|
.some((msgItem) => hasMeaningfulAssistantReply(msgItem));
|
|
});
|
|
|
|
const handleChatMarkdownClick = (event: MouseEvent) => {
|
|
const target = event.target as HTMLElement | null;
|
|
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
|
const preview = ctx.parsePlmPreviewLink(anchor?.getAttribute('href') || '');
|
|
if (preview) {
|
|
event.preventDefault();
|
|
void ctx.openPreview(preview);
|
|
return;
|
|
}
|
|
ctx.handleLeaveMarkdownClick(event);
|
|
};
|
|
|
|
/**
|
|
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
|
|
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
|
|
* @param text - 原始聊天文本。
|
|
* @returns 供 v-html 使用的安全展示字符串。
|
|
*/
|
|
const renderMarkdown = (text: string) => {
|
|
if (!text) return '';
|
|
const extracted = safeExtractInlineDownloadFiles(text);
|
|
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
|
|
try {
|
|
const rendered = marked.parse(displayText);
|
|
const html = typeof rendered === 'string' ? rendered : displayText;
|
|
return html
|
|
.replace(/<(td|th)\b([^>]*)>(?:\s| |<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
|
|
`<${tagName}${attrs}>无</${tagName}>`
|
|
))
|
|
.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
|
|
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
|
|
));
|
|
} catch {
|
|
return displayText;
|
|
}
|
|
};
|
|
|
|
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
|
|
renderMarkdown,
|
|
onMarkdownClick: handleChatMarkdownClick,
|
|
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
|
|
downloadInlineFile,
|
|
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
|
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
|
|
canOpenQueryPreview: ctx.canOpenQueryPreview,
|
|
getQueryPreviewSummary: ctx.getQueryPreviewSummary,
|
|
openQueryPreviewDialog: ctx.openQueryPreviewDialog,
|
|
shippingActionButtonClass: ctx.shippingActionButtonClass,
|
|
onShippingActionClick: ctx.onShippingActionClick,
|
|
getDisplayRetrieverResources: (msgItem) => ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>),
|
|
getSourceLinks: (resources) => ctx.getSourceLinks(resources),
|
|
shouldExpandSourceDetails: (msgItem) => ctx.shouldExpandSourceDetails(msgItem as unknown as Record<string, unknown>),
|
|
getSourceTitle: ctx.getSourceTitle,
|
|
getSourceMeta: ctx.getSourceMeta,
|
|
getSourceBrief: ctx.getSourceBrief,
|
|
openPreview: ctx.openPreview,
|
|
};
|
|
|
|
return {
|
|
shouldRenderMessage,
|
|
shouldShowThinkingBubble,
|
|
messageBubbleHandlers,
|
|
renderMarkdown,
|
|
handleChatMarkdownClick,
|
|
};
|
|
}
|