优化markdown渲染

This commit is contained in:
2025-12-29 19:06:45 +08:00
parent 4b6cb726d2
commit d0f133613d
4 changed files with 46 additions and 20 deletions

View File

@@ -599,7 +599,7 @@
await callAIChat(question)
}
// Markdown渲染函数返回富文本节点
// Markdown渲染函数(返回富文本节点)
function renderMarkdown(text : string) : string {
if (!text) return ''
@@ -609,30 +609,31 @@
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// 处理粗体**语法
// 处理粗体(**语法)
html = html.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>')
// 处理斜体*语法但要避免和粗体冲突
// 处理斜体(*语法,但要避免和粗体冲突)
html = html.replace(/(?<!\*)\*([^\*]+)\*(?!\*)/g, '<em>$1</em>')
// 处理行内代码`语法
html = html.replace(/`([^`]+)`/g, '<code style="background-color:#f5f5f5;padding:2px 6px;border-radius:3px;font-family:monospace;color:#e53e3e;">$1</code>')
// 处理行内代码(`语法)
html = html.replace(/`([^`]+)`/g, '<code style="background-color:#f5f5f5;padding:2px 6px;border-radius:3px;font-family:monospace;color:#e53e3e;word-break:break-all;">$1</code>')
// 处理链接[text](url)语法
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:#0055AA;text-decoration:underline;">$1</a>')
// 处理链接([text](url)语法)
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color:#0055AA;text-decoration:underline;word-break:break-all;overflow-wrap:break-word;">$1</a>')
// 处理标题# ## ###等
html = html.replace(/^### (.+)$/gm, '<div style="font-size:16px;font-weight:600;margin:8px 0 4px;">$1</div>')
html = html.replace(/^## (.+)$/gm, '<div style="font-size:18px;font-weight:600;margin:10px 0 6px;">$1</div>')
html = html.replace(/^# (.+)$/gm, '<div style="font-size:20px;font-weight:700;margin:12px 0 8px;">$1</div>')
// 处理标题(# ## ###等)
html = html.replace(/^### (.+)$/gm, '<div style="font-size:16px;font-weight:600;margin:8px 0 4px;word-break:break-word;">$1</div>')
html = html.replace(/^## (.+)$/gm, '<div style="font-size:18px;font-weight:600;margin:10px 0 6px;word-break:break-word;">$1</div>')
html = html.replace(/^# (.+)$/gm, '<div style="font-size:20px;font-weight:700;margin:12px 0 8px;word-break:break-word;">$1</div>')
// 处理无序列表- 或 * 开头
html = html.replace(/^[*-] (.+)$/gm, '<div style="margin-left:16px;">• $1</div>')
// 处理无序列表(- 或 * 开头)
html = html.replace(/^[*-] (.+)$/gm, '<div style="margin-left:16px;word-break:break-word;">• $1</div>')
// 处理换行
html = html.replace(/\n/g, '<br/>')
return html
// 包裹在一个具有换行样式的容器中
return `<div style="word-break:break-word;overflow-wrap:break-word;white-space:normal;max-width:100%;">${html}</div>`
}
// 显示上传选项