feat(frontend): enhance chat streaming visuals with shimmer effect and fade tail
- Introduce a shimmer effect for in-progress step titles in chat components, providing visual feedback during processing. - Implement a trailing fade effect for the most recently streamed characters in chat markdown, enhancing the typing experience. - Update CSS styles to support the new shimmer and fade effects, ensuring smooth transitions and visual coherence. - Add tests to verify the functionality of the shimmer effect and the application of the fade tail in markdown rendering.
This commit is contained in:
@@ -1,30 +1,15 @@
|
||||
import {
|
||||
createChatMarkdownRenderer,
|
||||
renderChatMarkdown,
|
||||
} from './chatMarkdownRenderer.ts'
|
||||
import { joinCitationTagsToPreviousLine } from './citationMarkdown.ts'
|
||||
import { applyStreamingTailFade } from './chatMarkdownRenderer.ts'
|
||||
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const snippet = [
|
||||
'该数据集...例如:',
|
||||
'```',
|
||||
'APR = ((Fees + Interest) / Principal) × (365 / Days in Loan Term)',
|
||||
'```',
|
||||
'<kb doc="2502.08127v1.pdf" chunk_id="1ecdce8a-f922-4d0c-b124-257ab4634da2" />',
|
||||
const cases = [
|
||||
'<p>Great, that narrows it down a lot. Two more quick</p>',
|
||||
'<p>Great, that narrows it down a lot. <strong>Two</strong> more quick</p>\n',
|
||||
'<ol>\n<li>第一项</li>\n<li>正在生成的第二项内容</li>\n</ol>',
|
||||
'<p>结尾是引用 <span class="citation">doc</span></p>',
|
||||
'<p></p>',
|
||||
'',
|
||||
'### 重要性',
|
||||
'',
|
||||
'1. **AAAAA**',
|
||||
].join('\n')
|
||||
|
||||
console.log('--- joinCitationTagsToPreviousLine output ---')
|
||||
console.log(JSON.stringify(joinCitationTagsToPreviousLine(snippet)))
|
||||
|
||||
console.log('\n--- final render ---')
|
||||
console.log(renderChatMarkdown(snippet, {
|
||||
renderer,
|
||||
escapeMarkdown: (t) => t,
|
||||
sanitizeHtml: (h) => h,
|
||||
streaming: false,
|
||||
knowledgeReferences: [{ doc: '2502.08127v1.pdf', chunk_id: '1ecdce8a-f922-4d0c-b124-257ab4634da2' }],
|
||||
}))
|
||||
]
|
||||
for (const c of cases) {
|
||||
console.log('IN :', JSON.stringify(c))
|
||||
console.log('OUT:', JSON.stringify(applyStreamingTailFade(c)))
|
||||
console.log('')
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
applyStreamingTailFade,
|
||||
closeDanglingStreamingEmphasis,
|
||||
createChatMarkdownRenderer,
|
||||
markStandaloneStrongParagraphs,
|
||||
@@ -25,6 +26,11 @@ 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'
|
||||
|
||||
/** Remove the streaming tail-fade wrapper so structural assertions stay focused. */
|
||||
function stripFadeTail(html: string): string {
|
||||
return html.replace(/<span class="stream-fade-tail">([\s\S]*?)<\/span>/g, '$1')
|
||||
}
|
||||
|
||||
test('preprocessMathDelimiters converts escaped math delimiters for marked-katex', () => {
|
||||
assert.equal(
|
||||
preprocessMathDelimiters('inline \\(a+b\\) and block \\[x^2\\]'),
|
||||
@@ -103,7 +109,7 @@ test('renderChatMarkdown renders an unfinished bold line as bold immediately whi
|
||||
const partial = '**平台访问地址:chatbot.weixin.qq.com'
|
||||
// Streaming: optimistically bold so no raw `**` and no late layout jump.
|
||||
assert.match(
|
||||
renderChatMarkdown(partial, { ...options, streaming: true }),
|
||||
stripFadeTail(renderChatMarkdown(partial, { ...options, streaming: true })),
|
||||
/<p class="md-strong-title"><strong>平台访问地址:chatbot\.weixin\.qq\.com<\/strong><\/p>/,
|
||||
)
|
||||
// Completed: a genuinely unterminated marker stays literal (we never invent
|
||||
@@ -141,7 +147,7 @@ test('renderChatMarkdown bolds punctuation-adjacent emphasis both mid-stream and
|
||||
const text = '**XBRL(语言)**是一种标准'
|
||||
for (const streaming of [true, false]) {
|
||||
assert.match(
|
||||
renderChatMarkdown(text, { ...options, streaming }),
|
||||
stripFadeTail(renderChatMarkdown(text, { ...options, streaming })),
|
||||
/<strong>XBRL(语言)<\/strong>是一种标准/,
|
||||
)
|
||||
}
|
||||
@@ -172,7 +178,7 @@ test('renderChatMarkdown does not flash a setext heading when a nested bullet da
|
||||
// must not flash <h2>, and the next bullet's `*`/`**` (before its text) must
|
||||
// not flash an empty nested <li> under A.
|
||||
for (const partial of ['1. **AAAAA**\n - ', '1. **AAAAA**\n - *', '1. **AAAAA**\n - **']) {
|
||||
const html = renderChatMarkdown(partial, options)
|
||||
const html = stripFadeTail(renderChatMarkdown(partial, options))
|
||||
assert.doesNotMatch(html, /<h2/)
|
||||
assert.doesNotMatch(html, /<ul>/)
|
||||
assert.match(html, /<ol>\s*<li><strong>AAAAA<\/strong><\/li>\s*<\/ol>/)
|
||||
@@ -188,7 +194,7 @@ test('renderChatMarkdown streams a bold ordered list without literal-marker flic
|
||||
streaming: true,
|
||||
}
|
||||
// Next item's marker has arrived but its content/closing ** has not.
|
||||
const html = renderChatMarkdown('1. **速游**\n2. *', options)
|
||||
const html = stripFadeTail(renderChatMarkdown('1. **速游**\n2. *', options))
|
||||
assert.doesNotMatch(html, /<li>\*+<\/li>/)
|
||||
assert.match(html, /<li><strong>速游<\/strong><\/li>/)
|
||||
})
|
||||
@@ -417,6 +423,34 @@ test('joinCitationTagsToPreviousLine does not merge citations onto an unlabeled
|
||||
assert.equal(joinCitationTagsToPreviousLine(input), '```\nAPR = principal\n```\n' + tag)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade wraps the trailing text run', () => {
|
||||
const out = applyStreamingTailFade('<p>Great, that narrows it down a lot. Two more quick</p>')
|
||||
assert.match(out, /<span class="stream-fade-tail">[^<]*Two more quick<\/span><\/p>$/)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade skips whitespace-only runs and fades the last list item', () => {
|
||||
const out = applyStreamingTailFade('<ol>\n<li>第一项</li>\n<li>正在生成的第二项</li>\n</ol>')
|
||||
assert.match(out, /<li><span class="stream-fade-tail">正在生成的第二项<\/span><\/li>/)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade is a no-op for empty content', () => {
|
||||
assert.equal(applyStreamingTailFade(''), '')
|
||||
assert.equal(applyStreamingTailFade('<p></p>'), '<p></p>')
|
||||
})
|
||||
|
||||
test('renderChatMarkdown adds the tail fade only while streaming', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const opts = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
}
|
||||
const streamed = renderChatMarkdown('正在生成中的回答内容', { ...opts, streaming: true })
|
||||
assert.match(streamed, /stream-fade-tail/)
|
||||
const settled = renderChatMarkdown('正在生成中的回答内容', { ...opts, streaming: false })
|
||||
assert.doesNotMatch(settled, /stream-fade-tail/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown keeps an unlabeled fenced code block closed when a citation immediately follows', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const tag = '<kb doc="guide.pdf" chunk_id="1" />'
|
||||
|
||||
@@ -229,6 +229,46 @@ export function stripTrailingStreamingListMarker(text: string): string {
|
||||
return text.replace(/(^|\n)[ \t]*(?:[-*+]|[-=]{2,}|\d{1,9}[.)]?)[ \t]*$/, '$1')
|
||||
}
|
||||
|
||||
const TAIL_TEXT_RE = />([^<>]+)</g
|
||||
|
||||
/**
|
||||
* Soften the most-recently streamed characters with a trailing fade.
|
||||
*
|
||||
* While the answer streams, the newest tail text is wrapped in a
|
||||
* `stream-fade-tail` span so CSS can fade its trailing edge (the newest words
|
||||
* are faint and settle to full color as more text arrives — the "tail reveal"
|
||||
* look). Runs on the final HTML so the span is never touched by the markdown
|
||||
* parser or sanitizer, and only the innermost last text run is wrapped.
|
||||
*/
|
||||
export function applyStreamingTailFade(html: string, tailLength = 24): string {
|
||||
if (!html) return html
|
||||
|
||||
// Track the last text run that actually has visible characters. Whitespace-only
|
||||
// runs (e.g. the `\n` marked emits between `</li>` and `</ol>`) are skipped so
|
||||
// they do not win the "last run" and suppress the fade.
|
||||
let lastMatch: RegExpExecArray | null = null
|
||||
let match: RegExpExecArray | null
|
||||
TAIL_TEXT_RE.lastIndex = 0
|
||||
while ((match = TAIL_TEXT_RE.exec(html)) !== null) {
|
||||
if (match[1].trim()) lastMatch = match
|
||||
}
|
||||
if (!lastMatch) return html
|
||||
|
||||
const text = lastMatch[1]
|
||||
|
||||
const textStart = lastMatch.index + 1
|
||||
const textEnd = textStart + text.length
|
||||
const chars = Array.from(text)
|
||||
const tailChars = chars.slice(Math.max(0, chars.length - tailLength))
|
||||
const tail = tailChars.join('')
|
||||
// Fade only the trailing run, keeping any leading whitespace outside the span.
|
||||
const tailTrimmed = tail.replace(/^\s+/, '')
|
||||
if (!tailTrimmed) return html
|
||||
const head = text.slice(0, text.length - tailTrimmed.length)
|
||||
const wrapped = `${head}<span class="stream-fade-tail">${tailTrimmed}</span>`
|
||||
return html.slice(0, textStart) + wrapped + html.slice(textEnd)
|
||||
}
|
||||
|
||||
export function createChatMarkdownRenderer(options: ChatMarkdownRendererOptions = {}): Renderer {
|
||||
const renderer = new marked.Renderer()
|
||||
|
||||
@@ -335,7 +375,8 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMark
|
||||
const tableWrappedHtml = wrapChatMarkdownTables(citationHtml)
|
||||
const strongTitleHtml = markStandaloneStrongParagraphs(tableWrappedHtml)
|
||||
const sanitized = options.sanitizeHtml(strongTitleHtml)
|
||||
return options.injectCachedMermaidSvg
|
||||
const withMermaid = options.injectCachedMermaidSvg
|
||||
? options.injectCachedMermaidSvg(sanitized, options.cachedMermaidSvgHtml)
|
||||
: sanitized
|
||||
return options.streaming ? applyStreamingTailFade(withMermaid) : withMermaid
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user