feat(chat): add shared markdown rendering pipeline

Extract chat markdown styles, renderer, DOMPurify config, syntax
highlighting, and mermaid support into reusable utilities with tests.
This commit is contained in:
wizardchen
2026-06-16 00:49:12 +08:00
committed by lyingbug
parent efe8b6f41d
commit ee1c3c732c
14 changed files with 1806 additions and 219 deletions
@@ -0,0 +1,75 @@
// Dark-theme highlight token colors only. Chat Markdown layout/chrome styles
// belong to chat-markdown.less.
html[theme-mode='dark'] {
.markdown-content .chat-code-block__pre,
.answer-content .chat-code-block__pre,
.ai-markdown-template .chat-code-block__pre,
.agent-stream-display .chat-code-block__pre {
.hljs {
color: #c9d1d9;
}
.hljs-doctag,
.hljs-keyword,
.hljs-meta .hljs-keyword,
.hljs-template-tag,
.hljs-template-variable,
.hljs-type,
.hljs-variable.language_ {
color: #ff7b72;
}
.hljs-title,
.hljs-title.class_,
.hljs-title.class_.inherited__,
.hljs-title.function_ {
color: #d2a8ff;
}
.hljs-attr,
.hljs-attribute,
.hljs-literal,
.hljs-meta,
.hljs-number,
.hljs-operator,
.hljs-variable,
.hljs-selector-attr,
.hljs-selector-class,
.hljs-selector-id {
color: #79c0ff;
}
.hljs-regexp,
.hljs-string,
.hljs-meta .hljs-string {
color: #a5d6ff;
}
.hljs-built_in,
.hljs-symbol {
color: #ffa657;
}
.hljs-comment,
.hljs-code,
.hljs-formula {
color: #8b949e;
}
.hljs-name,
.hljs-quote,
.hljs-selector-tag,
.hljs-selector-pseudo {
color: #7ee787;
}
.hljs-subst {
color: #c9d1d9;
}
.hljs-section {
color: #1f6feb;
font-weight: 700;
}
}
}
@@ -0,0 +1,72 @@
// Syntax highlighting tokens for chat code blocks.
.chat-markdown-hljs() {
:deep(.chat-code-block__pre) {
.hljs {
color: #24292e;
background: transparent;
}
.hljs-doctag,
.hljs-keyword,
.hljs-meta .hljs-keyword,
.hljs-template-tag,
.hljs-template-variable,
.hljs-type,
.hljs-variable.language_ {
color: #d73a49;
}
.hljs-title,
.hljs-title.class_,
.hljs-title.class_.inherited__,
.hljs-title.function_ {
color: #6f42c1;
}
.hljs-attr,
.hljs-attribute,
.hljs-literal,
.hljs-meta,
.hljs-number,
.hljs-operator,
.hljs-variable,
.hljs-selector-attr,
.hljs-selector-class,
.hljs-selector-id {
color: #005cc5;
}
.hljs-regexp,
.hljs-string,
.hljs-meta .hljs-string {
color: #032f62;
}
.hljs-built_in,
.hljs-symbol {
color: #e36209;
}
.hljs-comment,
.hljs-code,
.hljs-formula {
color: #6a737d;
}
.hljs-name,
.hljs-quote,
.hljs-selector-tag,
.hljs-selector-pseudo {
color: #22863a;
}
.hljs-subst {
color: #24292e;
}
.hljs-section {
color: #005cc5;
font-weight: 700;
}
}
}
@@ -0,0 +1,587 @@
@import './chat-hljs.less';
// Single source of truth for chat answer Markdown typography and block styles.
// Used by botmsg, AgentStreamDisplay, embed chat, and the dev Markdown test page.
// Future chat Markdown visual changes should be made here instead of in
// individual Vue components. Non-chat document/wiki preview styles intentionally
// live outside this file.
//
// Shared typography for chat answer markdown (botmsg, AgentStreamDisplay, embed).
// Tuned against ChatGPT markdown test doc: 16px body, 24px line-height on paragraphs,
// stepped headings, dotted links, light tables, pill inline code, kbd chips.
.chat-markdown-typography() {
font-size: 16px;
color: var(--td-text-color-primary);
line-height: 1.625;
letter-spacing: normal;
-webkit-font-smoothing: antialiased;
:deep(p) {
margin: 0 0 0.25em;
line-height: 1.625;
+ p {
margin-top: 0.75em;
}
&:last-child {
margin-bottom: 0;
}
}
// Citation-only paragraphs from marked (tag on its own line) — keep compact.
:deep(p:has(> .citation:only-child)) {
margin: 0.125em 0 0.375em;
line-height: 1.625;
}
// Inline citations share the paragraph line box with body text.
:deep(p:has(.citation)) {
line-height: 1.625;
}
:deep(p:has(.citation) + p:has(> img:only-child)),
:deep(p:has(> .citation:only-child) + p:has(> img:only-child)) {
margin-top: 0.5em;
}
// Models often emit standalone **小节标题:** paragraphs instead of headings.
:deep(p:has(> strong:only-child)) {
margin-top: 1.25em;
margin-bottom: 0.5em;
line-height: 1.5;
&:first-child {
margin-top: 0;
}
}
:deep(p + ul),
:deep(p + ol),
:deep(ul + p),
:deep(ol + p),
:deep(blockquote + p),
:deep(p + blockquote) {
margin-top: 0.75em;
}
:deep(strong) {
font-weight: 600;
}
:deep(em) {
font-style: italic;
}
:deep(del) {
text-decoration: line-through;
opacity: 0.72;
}
:deep(kbd) {
display: inline-block;
padding: 0.15em 0.45em;
font-family: var(--app-font-family-mono);
font-size: 0.8125em;
font-weight: 500;
line-height: 1.4;
color: var(--td-text-color-primary);
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
border-radius: 5px;
box-shadow: 0 1px 0 color-mix(in srgb, var(--td-text-color-primary) 8%, transparent);
}
:deep(code):not(pre code) {
background: color-mix(in srgb, var(--td-text-color-primary) 8%, transparent);
padding: 0.15em 0.3em;
border-radius: 4px;
font-family: var(--app-font-family-mono);
font-size: 0.875em;
font-weight: 500;
}
:deep(pre:not(.chat-code-block__pre):not(.chat-mermaid-block__canvas)) {
background: var(--td-bg-color-secondarycontainer);
padding: 14px 16px;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
overflow-x: auto;
margin: 0.75em 0;
line-height: 1.55;
font-size: 13px;
code {
background: none;
padding: 0;
font-size: inherit;
font-weight: 400;
}
}
:deep(.chat-code-block) {
margin: 0.75em 0;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
overflow: hidden;
background: var(--td-bg-color-container);
box-shadow: 0 1px 2px color-mix(in srgb, var(--td-text-color-primary) 6%, transparent);
}
:deep(.chat-code-block__header) {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 36px;
padding: 6px 10px 6px 12px;
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
:deep(.chat-code-block__lang) {
font-size: 12px;
font-weight: 600;
line-height: 1.2;
color: var(--td-text-color-secondary);
letter-spacing: 0.02em;
text-transform: none;
}
:deep(.chat-code-block__copy) {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0;
padding: 4px 8px;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-secondary);
font-size: 12px;
font-weight: 500;
line-height: 1;
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
&:hover {
background: color-mix(in srgb, var(--td-text-color-primary) 6%, var(--td-bg-color-secondarycontainer));
border-color: var(--td-component-border);
color: var(--td-text-color-primary);
}
&.is-copied {
color: var(--td-text-color-primary);
}
&.is-error {
color: var(--td-error-color);
}
}
:deep(.chat-code-block__copy-icon) {
flex-shrink: 0;
}
:deep(.chat-code-block__pre) {
margin: 0;
padding: 14px 16px;
border-radius: 0;
background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 88%, var(--td-bg-color-container));
overflow-x: auto;
font-size: 13px;
line-height: 1.55;
code {
background: transparent;
padding: 0;
border-radius: 0;
font-size: inherit;
font-weight: 400;
white-space: pre;
display: block;
}
}
:deep(.chat-mermaid-block) {
margin: 0.75em 0;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
overflow: hidden;
background: var(--td-bg-color-container);
box-shadow: 0 1px 3px color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
}
:deep(.chat-mermaid-block__header) {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 36px;
padding: 6px 10px 6px 12px;
background: var(--td-bg-color-secondarycontainer);
border-bottom: 1px solid var(--td-component-stroke);
}
:deep(.chat-mermaid-block__badge) {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--td-text-color-secondary);
}
:deep(.chat-mermaid-block__expand) {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
margin: 0;
padding: 0;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-secondary);
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
&:hover:not(:disabled) {
background: color-mix(in srgb, var(--td-text-color-primary) 6%, var(--td-bg-color-secondarycontainer));
border-color: var(--td-component-border);
color: var(--td-text-color-primary);
}
&:disabled,
&.is-disabled {
opacity: 0.35;
cursor: not-allowed;
}
}
:deep(.chat-mermaid-block__canvas) {
margin: 0;
padding: 20px 16px 18px;
border: 0;
border-radius: 0;
background: var(--td-bg-color-container);
overflow-x: auto;
text-align: center;
cursor: zoom-in;
svg {
max-width: 100%;
height: auto;
}
.node rect,
.node circle,
.node ellipse,
.node polygon,
.node path {
stroke-width: 1.5px;
}
.edgePath path,
.flowchart-link {
stroke-width: 1.6px;
}
.label,
.nodeLabel,
.edgeLabel {
font-family: var(--app-font-family);
}
}
:deep(.chat-mermaid-block--loading .streaming-mermaid-loading) {
margin: 0;
max-width: none;
min-height: 200px;
border: 0;
border-radius: 0;
}
:deep(pre.mermaid:not(.chat-mermaid-block__canvas)) {
margin: 0.75em 0;
padding: 20px 16px;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
background: var(--td-bg-color-secondarycontainer);
overflow-x: auto;
text-align: center;
cursor: zoom-in;
svg {
max-width: 100%;
height: auto;
}
}
:deep(ul) {
margin: 0.35em 0 0.75em;
padding-left: 1.625em;
list-style-type: disc;
list-style-position: outside;
ul {
list-style-type: disc;
margin: 0.25em 0 0;
padding-left: 1.25em;
}
}
:deep(ol) {
margin: 0.35em 0 0.75em;
padding-left: 1.625em;
list-style-type: decimal;
list-style-position: outside;
ol {
list-style-type: decimal;
margin: 0.25em 0 0;
padding-left: 1.25em;
}
}
:deep(li) {
margin: 0;
line-height: 1.625;
padding-left: 0.375em;
+ li {
margin-top: 0.375em;
}
&::marker {
font-weight: 700;
color: var(--td-text-color-primary);
}
> p {
margin: 0;
+ p {
margin-top: 0.25em;
}
}
}
:deep(ol > li)::marker {
font-variant-numeric: tabular-nums;
}
:deep(li > ul),
:deep(li > ol) {
margin-top: 0.25em;
margin-bottom: 0;
}
:deep(li:has(> input[type='checkbox'])) {
list-style: none;
margin-left: -1.625em;
padding-left: 0;
&::marker {
content: none;
}
input[type='checkbox'] {
margin: 0 0.5em 0 0;
vertical-align: middle;
accent-color: var(--td-brand-color);
}
}
:deep(blockquote) {
border-left: 2px solid var(--td-component-stroke);
padding: 0.5em 0 0.5em 1.25em;
margin: 0.5em 0 0.75em;
color: var(--td-text-color-secondary);
font-weight: 400;
font-style: normal;
blockquote {
margin-top: 0.35em;
margin-bottom: 0;
}
}
:deep(blockquote),
:deep(blockquote p) {
line-height: 1.5;
}
:deep(hr) {
margin: 1.75em 0;
border: none;
border-top: 1px solid var(--td-component-stroke);
}
:deep(h1) {
font-size: 1.5em;
font-weight: 600;
margin: 0 0 0.375em;
line-height: 1.333;
}
:deep(h2) {
font-size: 1.25em;
font-weight: 600;
margin: 1em 0 0.25em;
line-height: 1.4;
&:first-child {
margin-top: 0;
}
}
:deep(h3) {
font-size: 1.125em;
font-weight: 600;
margin: 0.875em 0 0.25em;
line-height: 1.556;
}
:deep(h4),
:deep(h5),
:deep(h6) {
font-weight: 600;
margin: 1em 0 0;
line-height: 1.5;
}
:deep(h4) {
font-size: 1em;
}
:deep(h5) {
font-size: 0.9375em;
}
:deep(h6) {
font-size: 0.875em;
font-weight: 600;
color: var(--td-text-color-secondary);
}
:deep(h1:first-child),
:deep(h2:first-child),
:deep(h3:first-child),
:deep(h4:first-child),
:deep(h5:first-child),
:deep(h6:first-child) {
margin-top: 0;
}
:deep(a) {
color: var(--td-brand-color);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--td-brand-color) 45%, transparent);
text-underline-offset: 0.18em;
&:hover {
color: var(--td-brand-color-hover);
text-decoration-color: var(--td-brand-color);
}
}
:deep(.chat-markdown-table) {
width: fit-content;
max-width: 100%;
margin: 0.875em 0 1em;
overflow-x: auto;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
-webkit-overflow-scrolling: touch;
}
:deep(table) {
word-break: initial;
border-collapse: separate;
border-spacing: 0;
display: table;
font-size: 14px;
line-height: 1.55;
width: max-content;
min-width: 0;
}
:deep(table thead) {
background-color: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 75%, var(--td-bg-color-container));
}
:deep(table tbody tr:nth-child(2n)) {
background-color: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 45%, transparent);
}
:deep(table tr th) {
font-weight: 600;
border: 0;
border-right: 1px solid var(--td-component-stroke);
border-bottom: 1px solid var(--td-component-stroke);
background-color: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 75%, var(--td-bg-color-container));
text-align: left;
margin: 0;
padding: 8px 12px;
white-space: nowrap;
}
:deep(table tr td) {
border: 0;
border-right: 1px solid var(--td-component-stroke);
border-bottom: 1px solid var(--td-component-stroke);
text-align: left;
margin: 0;
padding: 8px 12px;
vertical-align: top;
}
:deep(table tr th:last-child),
:deep(table tr td:last-child) {
border-right: 0;
}
:deep(table tbody tr:last-child td) {
border-bottom: 0;
}
:deep(table th[align='center']),
:deep(table td[align='center']) {
text-align: center;
}
:deep(table th[align='right']),
:deep(table td[align='right']) {
text-align: right;
}
:deep(img) {
max-width: 80%;
max-height: 300px;
width: auto;
height: auto;
border-radius: 8px;
display: block;
margin: 1.25em 0;
border: 0.5px solid var(--td-component-stroke);
object-fit: contain;
cursor: pointer;
transition: transform 0.2s ease;
}
:deep(p:has(> img:only-child)) {
margin: 1.25em 0;
line-height: 0;
}
:deep(.mermaid) {
margin: 0;
}
.chat-markdown-hljs();
}
+3 -1
View File
@@ -1,3 +1,5 @@
// Legacy Markdown styles for non-chat document/editor surfaces that render
// `.md-content`. Chat answer Markdown must use `chat-markdown.less` only.
:deep(.md-content) { :deep(.md-content) {
box-sizing: border-box !important; box-sizing: border-box !important;
@@ -440,4 +442,4 @@
.outline-label { .outline-label {
font-family: var(--app-font-family); font-family: var(--app-font-family);
} }
} }
+1
View File
@@ -8,6 +8,7 @@ import TDesign from "tdesign-vue-next";
import "tdesign-vue-next/es/style/index.css"; import "tdesign-vue-next/es/style/index.css";
import "@/assets/theme/theme.css"; import "@/assets/theme/theme.css";
import "@/assets/dropdown-menu.less"; import "@/assets/dropdown-menu.less";
import "@/components/css/chat-hljs-dark.less";
// vue-virtual-scroller ships its own tiny stylesheet — required for // vue-virtual-scroller ships its own tiny stylesheet — required for
// RecycleScroller/DynamicScroller to size their viewport correctly. // RecycleScroller/DynamicScroller to size their viewport correctly.
// Without it the scroller computes 0 height and renders no items. // Without it the scroller computes 0 height and renders no items.
@@ -0,0 +1,181 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
createChatMarkdownRenderer,
preprocessMathDelimiters,
renderChatMarkdown,
replaceIncompleteImageWithPlaceholder,
} from './chatMarkdownRenderer.ts'
import { resolveCitationChunkId, joinCitationTagsToPreviousLine, collapseStandaloneCitationParagraphs } from './citationMarkdown.ts'
const SAMPLE_DOC = 'example-report.docx'
const SAMPLE_CHUNK_A = '00000001-0000-4000-8000-000000000001'
const SAMPLE_CHUNK_B = '00000002-0000-4000-8000-000000000002'
const SAMPLE_CHUNK_C = '00000003-0000-4000-8000-000000000003'
const SAMPLE_CHUNK_PRESERVE = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
test('preprocessMathDelimiters converts escaped math delimiters for marked-katex', () => {
assert.equal(
preprocessMathDelimiters('inline \\(a+b\\) and block \\[x^2\\]'),
'inline $a+b$ and block $$x^2$$',
)
})
test('replaceIncompleteImageWithPlaceholder hides an unfinished streaming image', () => {
assert.equal(
replaceIncompleteImageWithPlaceholder('before ![chart](local://bucket/path'),
'before <span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>',
)
})
test('renderChatMarkdown preserves citations, math, and sanitized output through one shared pipeline', () => {
const renderer = createChatMarkdownRenderer({
imageRenderer: ({ href, title, text }) =>
`<img src="${href}" alt="${text}" title="${title || ''}" class="markdown-image">`,
isValidImageUrl: (href) => href.startsWith('https://'),
})
const html = renderChatMarkdown(
[
'See <kb doc="sample-product-guide.pdf" chunk_id="chunk-1" kb_id="kb-1"/>',
'',
'Formula: \\(E=mc^2\\)',
'',
'| A | B |',
'| --- | --- |',
'| 1 | 2 |',
'',
'![ok](https://example.com/a.png "图")',
'',
'![bad](javascript:alert(1))',
].join('\n'),
{
renderer,
escapeMarkdown: (text) => text,
sanitizeHtml: (html) => html.replace(/javascript:alert\(1\)/g, ''),
},
)
assert.match(html, /class="citation citation-kb"/)
assert.match(html, /data-chunk-id="chunk-1"/)
assert.match(html, /katex/)
assert.match(html, /<div class="chat-markdown-table"><table>/)
assert.match(html, /<img src="https:\/\/example\.com\/a\.png"/)
assert.doesNotMatch(html, /javascript:alert/)
})
test('resolveCitationChunkId maps context index to retrieval chunk UUID', () => {
const refs = [
{ id: 'uuid-chunk-1', knowledge_title: 'Doc A', chunk_type: 'faq' },
{ id: 'uuid-chunk-2', knowledge_title: 'FAQ TEST - FAQ', chunk_type: 'faq' },
]
assert.equal(
resolveCitationChunkId('2', { doc: 'FAQ TEST - FAQ' }, refs),
'uuid-chunk-2',
)
assert.equal(
resolveCitationChunkId('FAQ-2', { doc: 'FAQ TEST - FAQ' }, refs),
'uuid-chunk-2',
)
assert.equal(
resolveCitationChunkId('uuid-chunk-1', { doc: 'Doc A' }, refs),
'uuid-chunk-1',
)
})
test('renderChatMarkdown preserves chunk UUIDs when escapeMarkdown strips UUIDs from prose', () => {
const renderer = createChatMarkdownRenderer({
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
isValidImageUrl: () => true,
})
const chunkId = SAMPLE_CHUNK_PRESERVE
const stripUuids = (text: string) => text.replace(
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
'',
)
const html = renderChatMarkdown(
`Sample text <kb doc="sample-topic.pdf" chunk_id="${chunkId}" />`,
{
renderer,
escapeMarkdown: stripUuids,
sanitizeHtml: (html) => html,
},
)
assert.match(html, /class="citation citation-kb"/)
assert.match(html, new RegExp(`data-chunk-id="${chunkId}"`))
})
test('renderChatMarkdown resolves indexed chunk_id when knowledge references are provided', () => {
const renderer = createChatMarkdownRenderer({
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
isValidImageUrl: () => true,
})
const html = renderChatMarkdown(
'See <kb doc="Sample FAQ" chunk_id="2" />',
{
renderer,
escapeMarkdown: (text) => text,
sanitizeHtml: (html) => html,
knowledgeReferences: [
{ id: 'resolved-chunk-id', knowledge_title: 'Sample FAQ', chunk_type: 'faq' },
{ id: 'other-chunk', knowledge_title: 'Other FAQ', chunk_type: 'faq' },
],
},
)
assert.match(html, /data-chunk-id="resolved-chunk-id"/)
assert.doesNotMatch(html, /data-chunk-id="2"/)
})
test('joinCitationTagsToPreviousLine removes blank lines before citation tags', () => {
const input = 'Setup is complete.\n\n<kb doc="faq.pdf" chunk_id="1" />'
assert.equal(joinCitationTagsToPreviousLine(input), 'Setup is complete. <kb doc="faq.pdf" chunk_id="1" />')
})
test('joinCitationTagsToPreviousLine inlines consecutive citation tags across single newlines', () => {
const tag1 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_A}" />`
const tag2 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_B}" />`
const tag3 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_C}" />`
const input = `${tag1}\n${tag2}\n${tag3}`
assert.equal(joinCitationTagsToPreviousLine(input), `${tag1} ${tag2} ${tag3}`)
})
test('renderChatMarkdown inlines consecutive citation tags across newlines', () => {
const renderer = createChatMarkdownRenderer({
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
isValidImageUrl: () => true,
})
const html = renderChatMarkdown(
[
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_A}" />`,
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_B}" />`,
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_C}" />`,
].join('\n'),
{
renderer,
escapeMarkdown: (text) => text,
sanitizeHtml: (html) => html,
},
)
assert.equal((html.match(/citation-kb/g) || []).length, 3)
assert.doesNotMatch(html, /<\/p>\s*<p>\s*<span class="citation citation-kb"/)
})
test('joinCitationTagsToPreviousLine keeps citations on a new line after a list', () => {
const tag = '<kb doc="doc.pdf" chunk_id="1" />'
const input = `1. first\n2. second\n\n${tag}`
assert.equal(joinCitationTagsToPreviousLine(input), `1. first\n2. second\n\n${tag}`)
})
test('collapseStandaloneCitationParagraphs merges citations across empty paragraphs', () => {
const html = '<p>Steps:</p><p></p><p><span class="citation citation-kb" data-chunk-id="x">doc</span></p>'
const out = collapseStandaloneCitationParagraphs(html)
assert.match(out, /Steps:.*citation-kb/s)
assert.doesNotMatch(out, /<p><\/p>/)
})
+143
View File
@@ -0,0 +1,143 @@
import { marked, type Renderer } from 'marked'
import markedKatex from 'marked-katex-extension'
import type { Tokens } from 'marked'
import {
collapseStandaloneCitationParagraphs,
extractCitationHtmlPlaceholders,
joinCitationTagsToPreviousLine,
preserveCitationTags,
restoreCitationHtmlPlaceholders,
restoreCitationTags,
type CitationKnowledgeRef,
} from './citationMarkdown.ts'
const STREAMING_IMAGE_PLACEHOLDER =
'<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>'
let markedConfigured = false
export type ImageRendererArgs = {
href: string
title: string | null
text: string
}
export type ChatMarkdownRendererOptions = {
codeRenderer?: Renderer['code']
imageRenderer?: (args: ImageRendererArgs) => string
invalidImageHtml?: (href: string) => string
isValidImageUrl?: (href: string) => boolean
}
export type RenderChatMarkdownOptions = {
renderer: Renderer
escapeMarkdown: (markdown: string) => string
sanitizeHtml: (html: string) => string
collapseStandaloneCitations?: boolean
knowledgeReferences?: CitationKnowledgeRef[] | null
cachedMermaidSvgHtml?: string | null
injectCachedMermaidSvg?: (html: string, cachedSvgHtml?: string | null) => string
prepareMarkdown?: (markdown: string, cachedSvgHtml?: string | null) => string
}
export function configureMarkedForChatMarkdown(): void {
if (markedConfigured) return
marked.use({ breaks: true, gfm: true })
marked.use(markedKatex({ throwOnError: false, nonStandard: true }))
markedConfigured = true
}
export function preprocessMathDelimiters(rawText: string): string {
if (!rawText || typeof rawText !== 'string') return ''
return rawText
.replace(/\\\[([\s\S]*?)\\\]/g, '$$$$$1$$$$')
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$')
}
export function 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
if (!hasBracketClose || (hasParenOpen && !hasParenClose)) {
return content.slice(0, lastImgStart) + STREAMING_IMAGE_PLACEHOLDER
}
return content
}
export function createChatMarkdownRenderer(options: ChatMarkdownRendererOptions = {}): Renderer {
const renderer = new marked.Renderer()
if (options.imageRenderer) {
renderer.image = ({ href, title, text }: Tokens.Image) => {
const imageHref = href || ''
if (options.isValidImageUrl && !options.isValidImageUrl(imageHref)) {
return options.invalidImageHtml?.(imageHref) ?? ''
}
return options.imageRenderer?.({
href: imageHref,
title: title || null,
text: text || '',
}) ?? ''
}
}
if (options.codeRenderer) {
renderer.code = options.codeRenderer
}
return renderer
}
export function wrapChatMarkdownTables(html: string): string {
if (!html || !html.includes('<table')) return html
return html.replace(
/<table\b[\s\S]*?<\/table>/gi,
(tableHtml) => `<div class="chat-markdown-table">${tableHtml}</div>`,
)
}
export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkdownOptions): string {
const rawText = typeof rawMarkdown === 'string' ? rawMarkdown : String(rawMarkdown || '')
if (!rawText.trim()) return ''
configureMarkedForChatMarkdown()
const { text: tagSafe, tags } = preserveCitationTags(rawText)
const imageSafe = replaceIncompleteImageWithPlaceholder(tagSafe)
const mathSafe = preprocessMathDelimiters(imageSafe)
const restoredTags = restoreCitationTags(mathSafe, tags)
const inlineTags = joinCitationTagsToPreviousLine(restoredTags)
const preparedMarkdown = options.prepareMarkdown
? options.prepareMarkdown(inlineTags, options.cachedMermaidSvgHtml)
: inlineTags
// Convert <kb>/<web>/wiki tags to HTML placeholders before escapeMarkdown so
// agent sanitizers (e.g. UUID stripping) cannot damage chunk_id attributes.
const { content: markdownWithPlaceholders, htmlSnippets } =
extractCitationHtmlPlaceholders(preparedMarkdown, options.knowledgeReferences)
const escapedMarkdown = options.escapeMarkdown(markdownWithPlaceholders)
const html = marked.parse(markdownWithPlaceholders, {
renderer: options.renderer,
breaks: true,
async: false,
}) as string
const restoredHtml = restoreCitationHtmlPlaceholders(html, htmlSnippets)
const citationHtml = options.collapseStandaloneCitations === false
? restoredHtml
: collapseStandaloneCitationParagraphs(restoredHtml)
const tableWrappedHtml = wrapChatMarkdownTables(citationHtml)
const sanitized = options.sanitizeHtml(tableWrappedHtml)
return options.injectCachedMermaidSvg
? options.injectCachedMermaidSvg(sanitized, options.cachedMermaidSvgHtml)
: sanitized
}
@@ -0,0 +1,17 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
domPurifyAllowedUriRegexp,
markdownDomPurifyConfig,
} from './markdownDomPurify.ts';
test('markdownDomPurifyConfig FORBID_TAGS includes script', () => {
assert.ok(Array.isArray(markdownDomPurifyConfig.FORBID_TAGS));
assert.ok(markdownDomPurifyConfig.FORBID_TAGS.includes('script'));
});
test('ALLOWED_URI_REGEXP allows s3:// and rejects javascript:', () => {
const re = markdownDomPurifyConfig.ALLOWED_URI_REGEXP ?? domPurifyAllowedUriRegexp;
assert.match('s3://bucket/key', re);
assert.doesNotMatch('javascript:alert(1)', re);
});
+83
View File
@@ -0,0 +1,83 @@
export const domPurifyForbidTags = ['script', 'style', 'object', 'embed', 'form', 'input'] as const;
export const domPurifyForbidAttr = ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur'] as const;
export const domPurifyAllowedUriRegexp =
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|(?:local|minio|cos|tos|s3|oss|ks3|obs):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
/** Shared DOMPurify security options (FORBID_*, URI scheme, DOM flags). */
export const domPurifySecurityOptions = {
ALLOWED_URI_REGEXP: domPurifyAllowedUriRegexp,
FORBID_TAGS: [...domPurifyForbidTags],
FORBID_ATTR: [...domPurifyForbidAttr],
KEEP_CONTENT: true,
RETURN_DOM: false,
RETURN_DOM_FRAGMENT: false,
RETURN_DOM_IMPORT: false,
SANITIZE_DOM: true,
SANITIZE_NAMED_PROPS: true,
WHOLE_DOCUMENT: false,
} as const;
/** Shared DOMPurify hooks: strip scripts/event attrs; noopener links; alt on images. */
export const domPurifySecurityHooks = {
beforeSanitizeElements: (currentNode: Element) => {
if (currentNode.tagName === 'SCRIPT') {
currentNode.remove();
return null;
}
domPurifyForbidAttr.forEach((attr) => {
if (currentNode.hasAttribute(attr)) {
currentNode.removeAttribute(attr);
}
});
},
afterSanitizeElements: (currentNode: Element) => {
if (currentNode.tagName === 'A') {
const href = currentNode.getAttribute('href');
if (href && href.startsWith('http')) {
currentNode.setAttribute('rel', 'noopener noreferrer');
currentNode.setAttribute('target', '_blank');
}
}
if (currentNode.tagName === 'IMG' && !currentNode.getAttribute('alt')) {
currentNode.setAttribute('alt', '');
}
},
};
/** Shared DOMPurify config for chat / dev markdown (KaTeX + Mermaid SVG). */
export const markdownDomPurifyConfig = {
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',
'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',
'math', 'annotation', 'semantics', 'mo', 'mi', 'mn', 'msup', 'mrow', 'mfrac', 'msqrt', 'mroot', 'mstyle',
'button',
],
ALLOWED_ATTR: [
'href', 'title', 'target', 'rel', 'data-tooltip', 'data-url', 'data-kb-id',
'data-chunk-id', 'data-doc', 'data-slug', 'class', 'role', 'tabindex', 'src', 'alt', 'data-protected-src',
'width', 'height', 'style', 'id', 'type', 'aria-label', 'data-mermaid', 'disabled',
'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',
'mathvariant', 'encoding', 'aria-hidden',
],
USE_PROFILES: { html: true, svg: true, mathMl: true },
...domPurifySecurityOptions,
HOOKS: domPurifySecurityHooks,
};
+231
View File
@@ -0,0 +1,231 @@
import i18n from '@/i18n';
import hljs from 'highlight.js';
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
const ENHANCE_FLAG = 'data-markdown-enhancements';
const boundMarkdownRoots = new WeakSet<HTMLElement>();
const MERMAID_DIAGRAM_SVG_SELECTOR = '.chat-mermaid-block__canvas svg, pre.mermaid svg';
function getMermaidDiagramSvg(block: Element | null | undefined): SVGElement | null {
if (!block) return null;
const svg = block.querySelector(MERMAID_DIAGRAM_SVG_SELECTOR);
return svg instanceof SVGElement ? svg : null;
}
function openMermaidFromBlock(block: Element | null | undefined): void {
const svg = getMermaidDiagramSvg(block);
if (svg) openMermaidFullscreen(svg.outerHTML);
}
export function syncMermaidExpandButtons(root: HTMLElement | null | undefined): void {
if (!root) return;
root.querySelectorAll<HTMLElement>('.chat-mermaid-block').forEach((block) => {
const expandBtn = block.querySelector<HTMLButtonElement>('.chat-mermaid-block__expand');
if (!expandBtn) return;
const hasSvg = !!getMermaidDiagramSvg(block);
expandBtn.disabled = !hasSvg;
expandBtn.classList.toggle('is-disabled', !hasSvg);
});
}
const COPY_ICON = '<svg class="chat-code-block__copy-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
const EXPAND_ICON = '<svg class="chat-mermaid-block__expand-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></svg>';
const LANG_LABELS: Record<string, string> = {
js: 'JavaScript',
javascript: 'JavaScript',
ts: 'TypeScript',
typescript: 'TypeScript',
py: 'Python',
python: 'Python',
go: 'Go',
rust: 'Rust',
java: 'Java',
kotlin: 'Kotlin',
swift: 'Swift',
rb: 'Ruby',
ruby: 'Ruby',
php: 'PHP',
cs: 'C#',
cpp: 'C++',
c: 'C',
sql: 'SQL',
bash: 'Bash',
sh: 'Shell',
shell: 'Shell',
json: 'JSON',
yaml: 'YAML',
yml: 'YAML',
xml: 'XML',
html: 'HTML',
css: 'CSS',
markdown: 'Markdown',
md: 'Markdown',
};
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
export function formatCodeLang(lang: string): string {
const normalized = (lang || 'Code').trim();
if (!normalized) return 'Code';
const key = normalized.toLowerCase();
return LANG_LABELS[key] || normalized.charAt(0).toUpperCase() + normalized.slice(1);
}
export function buildCodeBlockHtml(
lang: string,
highlighted: string,
highlightLang: string,
): string {
const displayLang = escapeHtml(formatCodeLang(lang));
const copyLabel = escapeHtml(i18n.global.t('embedPublish.copyCode'));
const safeLang = escapeHtml(highlightLang || lang || 'text');
return `<div class="chat-code-block">
<div class="chat-code-block__header">
<span class="chat-code-block__lang">${displayLang}</span>
<div class="chat-code-block__actions">
<button type="button" class="chat-code-block__copy" aria-label="${copyLabel}" title="${copyLabel}">
${COPY_ICON}<span class="chat-code-block__copy-text">${copyLabel}</span>
</button>
</div>
</div>
<pre class="chat-code-block__pre"><code class="hljs language-${safeLang}">${highlighted}</code></pre>
</div>`;
}
export function buildMermaidBlockHtml(innerHtml: string, preAttrs = ''): string {
const label = escapeHtml(i18n.global.t('mermaid.diagram'));
const expandLabel = escapeHtml(i18n.global.t('mermaid.expand'));
const attrs = preAttrs ? ` ${preAttrs}` : '';
return `<div class="chat-mermaid-block">
<div class="chat-mermaid-block__header">
<span class="chat-mermaid-block__badge">${label}</span>
<div class="chat-mermaid-block__actions">
<button type="button" class="chat-mermaid-block__expand" aria-label="${expandLabel}" title="${expandLabel}">${EXPAND_ICON}</button>
</div>
</div>
<pre class="chat-mermaid-block__canvas mermaid"${attrs}>${innerHtml}</pre>
</div>`;
}
export function buildMermaidLoadingHtml(): string {
const label = escapeHtml(i18n.global.t('mermaid.diagram'));
return `<div class="chat-mermaid-block chat-mermaid-block--loading">
<div class="chat-mermaid-block__header">
<span class="chat-mermaid-block__badge">${label}</span>
</div>
<div class="streaming-mermaid-loading" aria-hidden="true"><span class="streaming-mermaid-loading__skeleton"></span></div>
</div>`;
}
async function handleCodeCopy(btn: HTMLButtonElement): Promise<void> {
const code = btn.closest('.chat-code-block')?.querySelector('code')?.textContent ?? '';
if (!code) return;
const textEl = btn.querySelector<HTMLElement>('.chat-code-block__copy-text');
const copiedLabel = i18n.global.t('common.copied');
const defaultLabel = i18n.global.t('embedPublish.copyCode');
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(code);
} else {
const textArea = document.createElement('textarea');
textArea.value = code;
textArea.style.position = 'fixed';
textArea.style.opacity = '0';
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
btn.classList.add('is-copied');
if (textEl) textEl.textContent = copiedLabel;
window.setTimeout(() => {
btn.classList.remove('is-copied');
if (textEl) textEl.textContent = defaultLabel;
}, 1600);
} catch {
btn.classList.add('is-error');
window.setTimeout(() => btn.classList.remove('is-error'), 1600);
}
}
export function highlightCodeBlocksInContainer(root: HTMLElement | null | undefined): void {
if (!root) return;
root.querySelectorAll<HTMLElement>('.chat-code-block__pre code').forEach((codeEl) => {
if (codeEl.querySelector('span[class^="hljs-"], span.hljs')) return;
const language = [...codeEl.classList]
.find((cls) => cls.startsWith('language-'))
?.slice('language-'.length);
if (language && hljs.getLanguage(language)) {
try {
codeEl.innerHTML = hljs.highlight(codeEl.textContent || '', { language }).value;
codeEl.classList.add('hljs');
return;
} catch {
// fall through
}
}
hljs.highlightElement(codeEl);
});
}
export function refreshMarkdownEnhancements(root: HTMLElement | null | undefined): void {
if (!root) return;
highlightCodeBlocksInContainer(root);
syncMermaidExpandButtons(root);
}
export function attachMarkdownEnhancementListeners(
root: HTMLElement | null | undefined,
): void {
if (!root || boundMarkdownRoots.has(root)) return;
boundMarkdownRoots.add(root);
root.setAttribute(ENHANCE_FLAG, 'true');
const onClick = (event: Event) => {
const target = event.target as HTMLElement;
const copyBtn = target.closest<HTMLButtonElement>('.chat-code-block__copy');
if (copyBtn) {
event.preventDefault();
event.stopPropagation();
void handleCodeCopy(copyBtn);
return;
}
const expandBtn = target.closest<HTMLButtonElement>('.chat-mermaid-block__expand');
if (expandBtn) {
event.preventDefault();
event.stopPropagation();
if (expandBtn.disabled) return;
openMermaidFromBlock(expandBtn.closest('.chat-mermaid-block'));
return;
}
const canvas = target.closest<HTMLElement>(
'.chat-mermaid-block__canvas[data-mermaid="true"], .chat-mermaid-block__canvas[data-mermaid="cached"], pre.mermaid[data-mermaid="true"], pre.mermaid[data-mermaid="cached"]',
);
if (canvas && !target.closest('button')) {
const svg = canvas.querySelector('svg');
if (svg) {
event.preventDefault();
event.stopPropagation();
openMermaidFullscreen(svg.outerHTML);
}
}
};
root.addEventListener('click', onClick, true);
syncMermaidExpandButtons(root);
}
+187 -55
View File
@@ -1,37 +1,155 @@
import type { Tokens } from 'marked' import type { Tokens } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { openMermaidFullscreen } from '@/utils/mermaidViewer.ts' import { openMermaidFullscreen } from '@/utils/mermaidViewer.ts'
import {
buildCodeBlockHtml,
buildMermaidBlockHtml,
attachMarkdownEnhancementListeners,
highlightCodeBlocksInContainer,
syncMermaidExpandButtons,
} from '@/utils/markdownEnhancements'
hljs.registerAliases('mermaid', { languageName: 'plaintext' })
let mermaidMod: typeof import('mermaid') | null = null let mermaidMod: typeof import('mermaid') | null = null
let hljsMod: typeof import('highlight.js') | null = null
let mermaidInitialized = false let mermaidInitialized = false
let initPromise: Promise<void> | null = null let initPromise: Promise<void> | null = null
let hljsPromise: Promise<typeof import('highlight.js').default> | null = null
const MERMAID_LIGHT_THEME = {
darkMode: false,
background: '#ffffff',
primaryColor: '#e2e8f0',
primaryTextColor: '#334155',
primaryBorderColor: '#94a3b8',
secondaryColor: '#f1f5f9',
secondaryTextColor: '#475569',
secondaryBorderColor: '#cbd5e1',
tertiaryColor: '#f8fafc',
tertiaryTextColor: '#64748b',
tertiaryBorderColor: '#e2e8f0',
lineColor: '#94a3b8',
textColor: '#334155',
mainBkg: '#ffffff',
nodeBorder: '#94a3b8',
clusterBkg: '#f8fafc',
clusterBorder: '#cbd5e1',
titleColor: '#1e293b',
edgeLabelBackground: '#ffffff',
actorBorder: '#94a3b8',
actorBkg: '#f1f5f9',
actorTextColor: '#334155',
actorLineColor: '#94a3b8',
signalColor: '#94a3b8',
labelBoxBkgColor: '#f1f5f9',
labelBoxBorderColor: '#cbd5e1',
labelTextColor: '#334155',
loopTextColor: '#475569',
noteBkgColor: '#f8fafc',
noteTextColor: '#475569',
noteBorderColor: '#cbd5e1',
// Gantt
sectionBkgColor: '#f8fafc',
altSectionBkgColor: '#ffffff',
gridColor: '#e2e8f0',
todayLineColor: '#64748b',
taskBorderColor: '#94a3b8',
taskBkgColor: '#e2e8f0',
activeTaskBorderColor: '#64748b',
activeTaskBkgColor: '#94a3b8',
doneTaskBkgColor: '#cbd5e1',
doneTaskBorderColor: '#94a3b8',
critBkgColor: '#fecaca',
critBorderColor: '#f87171',
fontSize: '14px',
}
const MERMAID_DARK_THEME = {
darkMode: true,
background: '#1a1f28',
primaryColor: '#475569',
primaryTextColor: '#e2e8f0',
primaryBorderColor: '#64748b',
secondaryColor: '#334155',
secondaryTextColor: '#cbd5e1',
secondaryBorderColor: '#64748b',
tertiaryColor: '#1e293b',
tertiaryTextColor: '#94a3b8',
tertiaryBorderColor: '#475569',
lineColor: '#64748b',
textColor: '#e2e8f0',
mainBkg: '#1e293b',
nodeBorder: '#64748b',
clusterBkg: '#1a2332',
clusterBorder: '#475569',
titleColor: '#f1f5f9',
edgeLabelBackground: '#1e293b',
actorBorder: '#64748b',
actorBkg: '#1e293b',
actorTextColor: '#f1f5f9',
actorLineColor: '#64748b',
signalColor: '#64748b',
labelBoxBkgColor: '#334155',
labelBoxBorderColor: '#64748b',
labelTextColor: '#e2e8f0',
loopTextColor: '#cbd5e1',
noteBkgColor: '#334155',
noteTextColor: '#e2e8f0',
noteBorderColor: '#64748b',
// Gantt
sectionBkgColor: '#1a2332',
altSectionBkgColor: '#1e293b',
gridColor: '#334155',
todayLineColor: '#94a3b8',
taskBorderColor: '#64748b',
taskBkgColor: '#475569',
activeTaskBorderColor: '#94a3b8',
activeTaskBkgColor: '#64748b',
doneTaskBkgColor: '#334155',
doneTaskBorderColor: '#64748b',
critBkgColor: '#7f1d1d',
critBorderColor: '#ef4444',
fontSize: '14px',
}
function resolveMermaidThemeVariables() {
const isDark = document.documentElement.getAttribute('theme-mode') === 'dark'
return isDark ? MERMAID_DARK_THEME : MERMAID_LIGHT_THEME
}
const MERMAID_CONFIG = { const MERMAID_CONFIG = {
startOnLoad: false, startOnLoad: false,
theme: 'default', theme: 'base' as const,
securityLevel: 'strict', securityLevel: 'strict' as const,
fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif', fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
flowchart: { flowchart: {
useMaxWidth: true, useMaxWidth: true,
htmlLabels: true, htmlLabels: true,
curve: 'basis', curve: 'basis',
padding: 16,
}, },
sequence: { sequence: {
useMaxWidth: true, useMaxWidth: true,
diagramMarginX: 8, diagramMarginX: 12,
diagramMarginY: 8, diagramMarginY: 12,
actorMargin: 50, actorMargin: 56,
width: 150, width: 156,
height: 65, height: 68,
boxMargin: 10,
}, },
gantt: { gantt: {
useMaxWidth: true, useMaxWidth: true,
leftPadding: 75, leftPadding: 80,
gridLineStartPadding: 35, gridLineStartPadding: 40,
barHeight: 20, barHeight: 22,
barGap: 4, barGap: 6,
topPadding: 50, topPadding: 56,
},
er: {
useMaxWidth: true,
},
journey: {
useMaxWidth: true,
}, },
} }
@@ -42,15 +160,6 @@ async function getMermaid() {
return mermaidMod.default return mermaidMod.default
} }
async function getHljs() {
if (!hljsMod) {
hljsMod = await import('highlight.js')
await import('highlight.js/styles/github.css')
hljsMod.default.registerAliases('mermaid', { languageName: 'plaintext' })
}
return hljsMod.default
}
function escapeHtml(text: string) { function escapeHtml(text: string) {
return text return text
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
@@ -59,12 +168,29 @@ function escapeHtml(text: string) {
.replace(/"/g, '&quot;') .replace(/"/g, '&quot;')
} }
function highlightCode(text: string, lang?: string | null) {
const language = (lang || '').trim()
if (language && hljs.getLanguage(language)) {
try {
const result = hljs.highlight(text, { language })
return { html: result.value, language: result.language || language }
} catch {
// fall through
}
}
const auto = hljs.highlightAuto(text, language ? [language] : undefined)
return { html: auto.value, language: auto.language || language || 'plaintext' }
}
export const ensureMermaidInitialized = () => { export const ensureMermaidInitialized = () => {
if (!initPromise) { if (!initPromise) {
initPromise = (async () => { initPromise = (async () => {
const mermaid = await getMermaid() const mermaid = await getMermaid()
if (!mermaidInitialized) { if (!mermaidInitialized) {
mermaid.initialize(MERMAID_CONFIG as Parameters<typeof mermaid.initialize>[0]) mermaid.initialize({
...MERMAID_CONFIG,
themeVariables: resolveMermaidThemeVariables(),
} as Parameters<typeof mermaid.initialize>[0])
mermaidInitialized = true mermaidInitialized = true
} }
})() })()
@@ -74,34 +200,29 @@ export const ensureMermaidInitialized = () => {
let mermaidCount = 0 let mermaidCount = 0
export const createMermaidCodeRenderer = (idPrefix: string) => { export const createMermaidCodeRenderer = (idPrefix: string) => {
if (!hljsPromise) {
hljsPromise = getHljs()
}
return ({ text, lang }: Tokens.Code) => { return ({ text, lang }: Tokens.Code) => {
let highlighted = escapeHtml(text) const { html: highlighted, language: highlightLang } = highlightCode(text, lang)
let highlightLang: string = lang || 'Code'
const hljs = hljsMod?.default
if (hljs) {
if (highlightLang && hljs.getLanguage(highlightLang)) {
try {
highlighted = hljs.highlight(text, { language: highlightLang }).value
} catch {
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
} else {
const ret = hljs.highlightAuto(text)
highlighted = ret.value
highlightLang = ret.language || 'Code'
}
}
if (lang === 'mermaid') { if (lang === 'mermaid') {
const id = `${idPrefix}-${++mermaidCount}` const id = `${idPrefix}-${++mermaidCount}`
return `<pre id="${id}" data-mermaid="false"><code class="hljs language-${highlightLang}">${highlighted}</code></pre>` const inner = `<code class="hljs language-${highlightLang}">${highlighted}</code>`
return buildMermaidBlockHtml(inner, `id="${id}" data-mermaid="false"`)
} }
return `<pre><code class="hljs language-${highlightLang}">${highlighted}</code></pre>` return buildCodeBlockHtml(lang || highlightLang, highlighted, highlightLang)
}
}
export const renderMermaidToSvg = async (code: string, id: string): Promise<string | null> => {
if (!code.trim()) return null
try {
const mermaid = await getMermaid()
ensureMermaidInitialized()
await initPromise
await mermaid.parse(code)
const { svg } = await mermaid.render(id, code)
return svg
} catch (e) {
console.error('Mermaid rendering error:', e)
return null
} }
} }
@@ -109,25 +230,36 @@ export const renderMermaidInContainer = async (
rootElement: HTMLElement | null | undefined, rootElement: HTMLElement | null | undefined,
) => { ) => {
if (!rootElement) return if (!rootElement) return
const mermaid = await getMermaid() const mermaid = await getMermaid()
ensureMermaidInitialized() ensureMermaidInitialized()
await initPromise await initPromise
const mermaidElements = rootElement.querySelectorAll<HTMLElement>('pre[data-mermaid="false"]') const mermaidElements = rootElement.querySelectorAll<HTMLElement>(
'pre[data-mermaid="false"], .chat-mermaid-block__canvas[data-mermaid="false"]',
)
for (const el of mermaidElements) { for (const el of mermaidElements) {
try { try {
const code = el.innerText const code = el.innerText
await mermaid.parse(code) await mermaid.parse(code)
const { svg } = await mermaid.render(`${el.id}-svg`, code) const renderId = el.id ? `${el.id}-svg` : `mermaid-render-${++mermaidCount}`
const { svg } = await mermaid.render(renderId, code)
el.classList.add('mermaid') el.classList.add('mermaid')
el.innerHTML = svg el.innerHTML = svg
el.onclick = (event) => { el.setAttribute('data-mermaid', 'true')
event.stopPropagation()
openMermaidFullscreen(svg)
}
} catch (e) { } catch (e) {
console.error('Mermaid rendering error:', e) console.error('Mermaid rendering error:', e)
continue
} }
el.setAttribute('data-mermaid', 'true')
} }
} }
export async function enhanceMarkdownContainer(
rootElement: HTMLElement | null | undefined,
): Promise<void> {
if (!rootElement) return
attachMarkdownEnhancementListeners(rootElement)
highlightCodeBlocksInContainer(rootElement)
await renderMermaidInContainer(rootElement)
syncMermaidExpandButtons(rootElement)
}
+2 -2
View File
@@ -54,7 +54,7 @@ const downloadSvgAsImage = async (svgElement: SVGElement, filename = 'mermaid-di
const showBtnFeedback = (btn: HTMLElement, success: boolean, text?: string): void => { const showBtnFeedback = (btn: HTMLElement, success: boolean, text?: string): void => {
const origColor = btn.style.color const origColor = btn.style.color
const origTitle = btn.title const origTitle = btn.title
btn.style.color = success ? '#07c05f' : '#ef4444' btn.style.color = success ? '#374151' : '#ef4444'
btn.title = text || (success ? i18n.global.t('common.success') : i18n.global.t('common.failed')) btn.title = text || (success ? i18n.global.t('common.success') : i18n.global.t('common.failed'))
setTimeout(() => { setTimeout(() => {
btn.style.color = origColor btn.style.color = origColor
@@ -89,7 +89,7 @@ export const openMermaidFullscreen = (svgHtml: string): void => {
btn.title = title btn.title = title
btn.style.cssText = 'display:flex;align-items:center;justify-content:center;width:36px;height:36px;border:1px solid #e5e7eb;border-radius:6px;background:rgba(255,255,255,0.95);color:#6b7280;cursor:pointer;padding:0;box-shadow:0 2px 8px rgba(0,0,0,0.15);' btn.style.cssText = 'display:flex;align-items:center;justify-content:center;width:36px;height:36px;border:1px solid #e5e7eb;border-radius:6px;background:rgba(255,255,255,0.95);color:#6b7280;cursor:pointer;padding:0;box-shadow:0 2px 8px rgba(0,0,0,0.15);'
btn.innerHTML = icon btn.innerHTML = icon
btn.onmouseenter = () => { btn.style.background = '#f0fdf4'; btn.style.color = '#07c05f' } btn.onmouseenter = () => { btn.style.background = '#f3f4f6'; btn.style.color = '#374151' }
btn.onmouseleave = () => { btn.style.background = 'rgba(255,255,255,0.95)'; btn.style.color = '#6b7280' } btn.onmouseleave = () => { btn.style.background = 'rgba(255,255,255,0.95)'; btn.style.color = '#6b7280' }
return btn return btn
} }
+26 -52
View File
@@ -3,8 +3,12 @@
*/ */
import DOMPurify from 'dompurify'; import DOMPurify from 'dompurify';
import type { Config } from 'dompurify';
const PROVIDER_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; import {
domPurifySecurityHooks,
domPurifySecurityOptions,
markdownDomPurifyConfig,
} from '@/utils/markdownDomPurify';
// 配置 DOMPurify 的安全策略 // 配置 DOMPurify 的安全策略
const DOMPurifyConfig = { const DOMPurifyConfig = {
@@ -14,7 +18,7 @@ const DOMPurifyConfig = {
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code',
'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td',
'div', 'span', 'figure', 'figcaption', 'details', 'summary', 'think', 'div', 'span', 'figure', 'figcaption', 'details', 'summary', 'think', 'button',
// Mermaid SVG 支持的标签 // Mermaid SVG 支持的标签
'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polygon', 'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polygon',
'polyline', 'text', 'tspan', 'defs', 'marker', 'filter', 'use', 'polyline', 'text', 'tspan', 'defs', 'marker', 'filter', 'use',
@@ -27,6 +31,7 @@ const DOMPurifyConfig = {
ALLOWED_ATTR: [ ALLOWED_ATTR: [
'href', 'title', 'alt', 'src', 'class', 'id', 'style', 'data-protected-src', 'href', 'title', 'alt', 'src', 'class', 'id', 'style', 'data-protected-src',
'target', 'rel', 'width', 'height', 'open', 'target', 'rel', 'width', 'height', 'open',
'type', 'aria-label', 'disabled', 'role', 'tabindex',
// Mermaid SVG 支持的属性 // Mermaid SVG 支持的属性
'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity',
@@ -45,54 +50,8 @@ const DOMPurifyConfig = {
'mathvariant', 'encoding', 'aria-hidden' 'mathvariant', 'encoding', 'aria-hidden'
], ],
USE_PROFILES: { html: true, svg: true, mathMl: true }, USE_PROFILES: { html: true, svg: true, mathMl: true },
// 允许的协议 ...domPurifySecurityOptions,
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|(?:local|minio|cos|tos|s3|oss|ks3|obs):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i, HOOKS: domPurifySecurityHooks,
// 禁止的标签和属性
FORBID_TAGS: ['script', 'style', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur'],
// 其他安全配置
KEEP_CONTENT: true,
RETURN_DOM: false,
RETURN_DOM_FRAGMENT: false,
RETURN_DOM_IMPORT: false,
SANITIZE_DOM: true,
SANITIZE_NAMED_PROPS: true,
WHOLE_DOCUMENT: false,
// 自定义钩子函数
HOOKS: {
// 在清理前处理
beforeSanitizeElements: (currentNode: Element) => {
// 移除所有 script 标签
if (currentNode.tagName === 'SCRIPT') {
currentNode.remove();
return null;
}
// 移除所有事件处理器
const eventAttrs = ['onclick', 'onload', 'onerror', 'onmouseover', 'onfocus', 'onblur'];
eventAttrs.forEach(attr => {
if (currentNode.hasAttribute(attr)) {
currentNode.removeAttribute(attr);
}
});
},
// 在清理后处理
afterSanitizeElements: (currentNode: Element) => {
// 确保所有链接都有 rel="noopener noreferrer"
if (currentNode.tagName === 'A') {
const href = currentNode.getAttribute('href');
if (href && href.startsWith('http')) {
currentNode.setAttribute('rel', 'noopener noreferrer');
currentNode.setAttribute('target', '_blank');
}
}
// 确保所有图片都有 alt 属性
if (currentNode.tagName === 'IMG') {
if (!currentNode.getAttribute('alt')) {
currentNode.setAttribute('alt', '');
}
}
}
}
}; };
/** /**
@@ -115,7 +74,22 @@ export function sanitizeHTML(html: string): string {
} }
} }
function protectProviderImageSrcInHTML(html: string): string { /** Sanitize assistant markdown HTML (code/mermaid toolbars, KaTeX, SVG). */
export function sanitizeMarkdownHTML(html: string): string {
if (!html || typeof html !== 'string') {
return '';
}
try {
const preparedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(preparedHTML, markdownDomPurifyConfig as Config);
} catch (error) {
console.error('Markdown HTML sanitization failed:', error);
return escapeHTML(html);
}
}
export function protectProviderImageSrcInHTML(html: string): string {
if (!html) return html; if (!html) return html;
const decodeProviderURL = (raw: string): string => const decodeProviderURL = (raw: string): string =>
raw raw
+198 -109
View File
@@ -2,16 +2,25 @@
<div class="markdown-test-page"> <div class="markdown-test-page">
<h1 class="page-title">Markdown Rendering Test</h1> <h1 class="page-title">Markdown Rendering Test</h1>
<p class="page-desc"> <p class="page-desc">
Dev-only page for visual regression testing of markdown / LaTeX / Mermaid rendering. Dev-only page for visual regression testing of chat answer markdown
(same typography as botmsg / AgentStreamDisplay / embed).
Add new test cases or paste arbitrary markdown in the editor below. Add new test cases or paste arbitrary markdown in the editor below.
</p> </p>
<!-- Basic Text Styles (GPT markdown test doc alignment) -->
<section class="test-section">
<h2>Basic Text Styles</h2>
<div class="test-case">
<div class="test-rendered markdown-content" v-html="basicTextHtml"></div>
</div>
</section>
<!-- LaTeX Formulas --> <!-- LaTeX Formulas -->
<section class="test-section"> <section class="test-section">
<h2>LaTeX Formulas</h2> <h2>LaTeX Formulas</h2>
<div v-for="(tc, i) in latexCases" :key="'latex-'+i" class="test-case"> <div v-for="(tc, i) in latexCases" :key="'latex-' + i" class="test-case">
<div class="test-raw"><code>{{ tc.raw }}</code></div> <div class="test-raw"><code>{{ tc.raw }}</code></div>
<div class="test-rendered markdown-content" v-html="render(tc.raw)"></div> <div class="test-rendered markdown-content" v-html="tc.html"></div>
</div> </div>
</section> </section>
@@ -19,7 +28,7 @@
<section class="test-section"> <section class="test-section">
<h2>Code Blocks</h2> <h2>Code Blocks</h2>
<div class="test-case"> <div class="test-case">
<div class="test-rendered markdown-content" v-html="render(codeBlockSample)"></div> <div class="test-rendered markdown-content" v-html="codeBlockHtml"></div>
</div> </div>
</section> </section>
@@ -27,7 +36,7 @@
<section class="test-section"> <section class="test-section">
<h2>Tables</h2> <h2>Tables</h2>
<div class="test-case"> <div class="test-case">
<div class="test-rendered markdown-content" v-html="render(tableSample)"></div> <div class="test-rendered markdown-content" v-html="tableHtml"></div>
</div> </div>
</section> </section>
@@ -35,7 +44,7 @@
<section class="test-section"> <section class="test-section">
<h2>Lists &amp; Blockquotes</h2> <h2>Lists &amp; Blockquotes</h2>
<div class="test-case"> <div class="test-case">
<div class="test-rendered markdown-content" v-html="render(listsSample)"></div> <div class="test-rendered markdown-content" v-html="listsHtml"></div>
</div> </div>
</section> </section>
@@ -43,7 +52,7 @@
<section class="test-section"> <section class="test-section">
<h2>Mixed Content</h2> <h2>Mixed Content</h2>
<div class="test-case"> <div class="test-case">
<div class="test-rendered markdown-content" v-html="render(mixedSample)"></div> <div class="test-rendered markdown-content" v-html="mixedHtml"></div>
</div> </div>
</section> </section>
@@ -51,7 +60,7 @@
<section class="test-section"> <section class="test-section">
<h2>Mermaid Diagram</h2> <h2>Mermaid Diagram</h2>
<div class="test-case"> <div class="test-case">
<div ref="mermaidContainer" class="test-rendered markdown-content" v-html="render(mermaidSample)"></div> <div ref="mermaidContainer" class="test-rendered markdown-content" v-html="mermaidHtml"></div>
</div> </div>
</section> </section>
@@ -69,7 +78,7 @@
</label> </label>
</div> </div>
<div class="test-case"> <div class="test-case">
<div class="test-rendered markdown-content" v-html="render(streamBuffer)"></div> <div ref="streamContainer" class="test-rendered markdown-content" v-html="streamHtml"></div>
<div v-if="isStreaming" class="loading-typing"> <div v-if="isStreaming" class="loading-typing">
<span></span><span></span><span></span> <span></span><span></span><span></span>
</div> </div>
@@ -80,58 +89,84 @@
<section class="test-section"> <section class="test-section">
<h2>Custom Input</h2> <h2>Custom Input</h2>
<p class="test-hint">Paste any markdown here to test rendering.</p> <p class="test-hint">Paste any markdown here to test rendering.</p>
<textarea <textarea v-model="customInput" class="custom-textarea" rows="8"
v-model="customInput" placeholder="Type or paste markdown here..."></textarea>
class="custom-textarea"
rows="8"
placeholder="Type or paste markdown here..."
></textarea>
<div v-if="customInput.trim()" class="test-case"> <div v-if="customInput.trim()" class="test-case">
<div class="test-rendered markdown-content" v-html="render(customInput)"></div> <div ref="customContainer" class="test-rendered markdown-content" v-html="customHtml"></div>
</div> </div>
</section> </section>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'; import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { marked } from 'marked';
import markedKatex from 'marked-katex-extension';
import DOMPurify from 'dompurify';
import 'katex/dist/katex.min.css'; import 'katex/dist/katex.min.css';
import { sanitizeMarkdownHTML } from '@/utils/security';
import {
createChatMarkdownRenderer,
renderChatMarkdown,
} from '@/utils/chatMarkdownRenderer';
import { import {
ensureMermaidInitialized, ensureMermaidInitialized,
renderMermaidInContainer, enhanceMarkdownContainer,
renderMermaidToSvg,
createMermaidCodeRenderer, createMermaidCodeRenderer,
} from '@/utils/mermaidShared'; } from '@/utils/mermaidShared';
import {
// Configure marked replaceIncompleteMermaidWithPlaceholder,
marked.use({ breaks: true, gfm: true }); prepareStreamingMermaidMarkdown,
marked.use(markedKatex({ throwOnError: false, nonStandard: true })); extractFirstMermaidCode,
injectCachedMermaidSvg,
const mermaidRenderer = new marked.Renderer(); } from '@/utils/chatMessageShared';
mermaidRenderer.code = createMermaidCodeRenderer('mermaid-test');
ensureMermaidInitialized(); ensureMermaidInitialized();
const mermaidContainer = ref<HTMLElement | null>(null); const mermaidRenderer = createChatMarkdownRenderer({
codeRenderer: createMermaidCodeRenderer('mermaid-test'),
});
const preprocessMathDelimiters = (rawText: string): string => { const mermaidContainer = ref<HTMLElement | null>(null);
if (!rawText) return ''; const streamContainer = ref<HTMLElement | null>(null);
return rawText const customContainer = ref<HTMLElement | null>(null);
.replace(/\\\[([\s\S]*?)\\\]/g, '$$$$$1$$$$')
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$');
};
const render = (raw: string): string => { const render = (raw: string): string => {
if (!raw) return ''; if (!raw) return '';
const processed = preprocessMathDelimiters(raw); return renderChatMarkdown(raw, {
const html = marked.parse(processed, { renderer: mermaidRenderer }) as string; renderer: mermaidRenderer,
return DOMPurify.sanitize(html, { USE_PROFILES: { html: true, svg: true, mathMl: true } }); escapeMarkdown: (markdown) => markdown,
sanitizeHtml: sanitizeMarkdownHTML,
prepareMarkdown: (markdown) => replaceIncompleteMermaidWithPlaceholder(markdown),
});
};
const renderStreamMarkdown = (raw: string): string => {
if (!raw) return '';
return renderChatMarkdown(raw, {
renderer: mermaidRenderer,
escapeMarkdown: (markdown) => markdown,
sanitizeHtml: sanitizeMarkdownHTML,
cachedMermaidSvgHtml: streamMermaidSvgHtml.value,
prepareMarkdown: prepareStreamingMermaidMarkdown,
injectCachedMermaidSvg,
});
}; };
// --- Test Data --- // --- Test Data ---
const basicTextSample = `这是一段普通文本,包含 **加粗**、*斜体*、***加粗斜体***、~~删除线~~、行内 \`code\`。
也可以包含快捷键样式:<kbd>⌘</kbd> + <kbd>K</kbd>。
这里有一个链接:[GitHub](https://github.com)。
> 一级引用
>
> > 嵌套引用,用于对比 GPT 的引用层级与字重。
- [ ] 未完成任务
- [x] 已完成任务
`;
const latexCases = [ const latexCases = [
{ raw: 'Inline math: $E = mc^2$ in the middle of text.' }, { raw: 'Inline math: $E = mc^2$ in the middle of text.' },
{ raw: 'Block math:\n$$\\int_0^\\infty e^{-x}\\,dx = 1$$' }, { raw: 'Block math:\n$$\\int_0^\\infty e^{-x}\\,dx = 1$$' },
@@ -140,7 +175,7 @@ const latexCases = [
{ raw: 'Summation: $\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$' }, { raw: 'Summation: $\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$' },
{ raw: 'Matrix:\n$$\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}$$' }, { raw: 'Matrix:\n$$\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}$$' },
{ raw: 'Escaped delimiters: \\(\\alpha + \\beta = \\gamma\\) and \\[\\int_a^b f(x)\\,dx\\]' }, { raw: 'Escaped delimiters: \\(\\alpha + \\beta = \\gamma\\) and \\[\\int_a^b f(x)\\,dx\\]' },
]; ].map((tc) => ({ ...tc, html: '' }));
const codeBlockSample = `Here is some Python: const codeBlockSample = `Here is some Python:
@@ -240,12 +275,76 @@ def greet(name):
And the derivative rule: $\\frac{d}{dx}\\sin x = \\cos x$. And the derivative rule: $\\frac{d}{dx}\\sin x = \\cos x$.
\`\`\`mermaid
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Process A]
B -->|No| D[Process B]
C --> E[End]
D --> E
\`\`\`
### Ordered List
1. First item
2. Second item
1. Nested item A
2. Nested item B
3. Third item
### Unordered List
- Alpha
- Beta
- Sub-item
- Another sub-item
- Gamma
### Blockquote
> This is a blockquote with **bold** and *italic* text.
>
> It can span multiple paragraphs.
Done.`; Done.`;
const streamBuffer = ref(''); const streamBuffer = ref('');
const isStreaming = ref(false); const isStreaming = ref(false);
const streamSpeed = ref(30); const streamSpeed = ref(30);
const customInput = ref('');
const streamMermaidSvgHtml = ref('');
let streamTimer: ReturnType<typeof setInterval> | null = null; let streamTimer: ReturnType<typeof setInterval> | null = null;
let streamMermaidRenderId = 0;
let streamMermaidRenderTask: Promise<void> | null = null;
// Pre-render static fixtures once so streaming ticks do not reset other sections.
latexCases.forEach((tc) => {
tc.html = render(tc.raw);
});
const codeBlockHtml = render(codeBlockSample);
const basicTextHtml = render(basicTextSample);
const tableHtml = render(tableSample);
const listsHtml = render(listsSample);
const mixedHtml = render(mixedSample);
const mermaidHtml = render(mermaidSample);
const streamHtml = computed(() => renderStreamMarkdown(streamBuffer.value));
const customHtml = computed(() => render(customInput.value));
const cacheStreamMermaidSvg = async () => {
if (streamMermaidSvgHtml.value) return;
const code = extractFirstMermaidCode(streamBuffer.value);
if (!code) return;
if (!streamMermaidRenderTask) {
streamMermaidRenderTask = (async () => {
const svg = await renderMermaidToSvg(code, `mermaid-stream-${++streamMermaidRenderId}`);
if (svg) streamMermaidSvgHtml.value = svg;
})().finally(() => {
streamMermaidRenderTask = null;
});
}
await streamMermaidRenderTask;
};
const startStream = () => { const startStream = () => {
resetStream(); resetStream();
@@ -265,26 +364,49 @@ const startStream = () => {
const resetStream = () => { const resetStream = () => {
if (streamTimer) clearInterval(streamTimer); if (streamTimer) clearInterval(streamTimer);
streamBuffer.value = ''; streamBuffer.value = '';
streamMermaidSvgHtml.value = '';
streamMermaidRenderTask = null;
isStreaming.value = false; isStreaming.value = false;
}; };
// Custom input const refreshMermaid = async (root?: HTMLElement | null) => {
const customInput = ref('');
// Render mermaid after mount and content changes
const doMermaid = async () => {
await nextTick(); await nextTick();
if (mermaidContainer.value) { await enhanceMarkdownContainer(root ?? mermaidContainer.value);
await renderMermaidInContainer(mermaidContainer.value);
}
}; };
onMounted(doMermaid); onMounted(() => refreshMermaid());
watch(mermaidSample, doMermaid);
watch(streamBuffer, () => {
void cacheStreamMermaidSvg();
});
watch(streamHtml, () => {
nextTick(() => refreshMermaid(streamContainer.value));
});
watch(isStreaming, (streaming) => {
if (!streaming) {
void cacheStreamMermaidSvg().then(() => refreshMermaid(streamContainer.value));
}
});
let customMermaidTimer: ReturnType<typeof setTimeout> | null = null;
const COMPLETE_MERMAID_RE = /```mermaid[\s\S]*?```/;
watch(customInput, () => {
if (!COMPLETE_MERMAID_RE.test(customInput.value)) return;
if (customMermaidTimer) clearTimeout(customMermaidTimer);
customMermaidTimer = setTimeout(() => {
customMermaidTimer = null;
void refreshMermaid(customContainer.value);
}, 200);
});
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@import '../../components/css/markdown.less'; @import '../../components/css/chat-markdown.less';
@import '../../components/css/chat-citations.less';
@import '../../components/css/chat-message-shared.less';
.markdown-test-page { .markdown-test-page {
max-width: 860px; max-width: 860px;
@@ -409,71 +531,38 @@ watch(mermaidSample, doMermaid);
background: var(--td-brand-color, #0052d9); background: var(--td-brand-color, #0052d9);
animation: typingBounce 1.4s ease-in-out infinite; animation: typingBounce 1.4s ease-in-out infinite;
&:nth-child(1) { animation-delay: 0s; } &:nth-child(1) {
&:nth-child(2) { animation-delay: 0.2s; } animation-delay: 0s;
&:nth-child(3) { animation-delay: 0.4s; } }
&:nth-child(2) {
animation-delay: 0.2s;
}
&:nth-child(3) {
animation-delay: 0.4s;
}
} }
} }
@keyframes typingBounce { @keyframes typingBounce {
0%, 60%, 100% { transform: translateY(0); }
30% { transform: translateY(-8px); } 0%,
60%,
100% {
transform: translateY(0);
}
30% {
transform: translateY(-8px);
}
} }
// Markdown content styles (same as chat) // Chat answer markdown — shared with botmsg / AgentStreamDisplay / embed
.markdown-content { .markdown-content {
font-size: 15px; // Dev page intentionally uses the same chat Markdown mixin as runtime chat.
color: var(--td-text-color-primary); // Keep visual changes in chat-markdown.less so this page remains a regression target.
line-height: 1.6; .chat-markdown-typography();
.chat-citation-pills();
:deep(p) { margin: 6px 0; }
:deep(code) {
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
padding: 2px 5px;
border-radius: 3px;
font-family: var(--app-font-family-mono);
font-size: 13px;
}
:deep(pre) {
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
padding: 12px;
border-radius: 4px;
overflow-x: auto;
margin: 8px 0;
code { background: none; padding: 0; }
}
:deep(table) {
border-collapse: collapse;
margin: 8px 0;
width: 100%;
th, td {
border: 1px solid var(--td-component-stroke, #e5e5e5);
padding: 6px 10px;
text-align: left;
}
th {
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
font-weight: 600;
}
}
:deep(blockquote) {
border-left: 3px solid var(--td-brand-color, #0052d9);
padding-left: 12px;
margin: 8px 0;
color: var(--td-text-color-secondary);
}
:deep(img) {
max-width: 80%;
border-radius: 8px;
margin: 8px 0;
}
:deep(.mermaid) {
margin: 16px 0;
padding: 16px;
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
border-radius: 8px;
text-align: center;
svg { max-width: 100%; height: auto; }
}
} }
</style> </style>