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:
wizardchen
2026-06-19 23:28:47 +08:00
committed by lyingbug
parent 58461a5b68
commit cc9de85c25
8 changed files with 222 additions and 35 deletions
@@ -16,6 +16,21 @@
letter-spacing: normal;
-webkit-font-smoothing: antialiased;
// Trailing fade on the newest streamed characters: the tail is wrapped in
// this span (see applyStreamingTailFade) so its right edge dissolves, giving
// a soft "just typed" reveal that settles once streaming stops and the wrap
// is no longer emitted.
:deep(.stream-fade-tail) {
-webkit-mask-image: linear-gradient(to right,
rgba(0, 0, 0, 1) 0%,
rgba(0, 0, 0, 0.7) 30%,
rgba(0, 0, 0, 0) 100%);
mask-image: linear-gradient(to right,
rgba(0, 0, 0, 1) 0%,
rgba(0, 0, 0, 0.7) 30%,
rgba(0, 0, 0, 0) 100%);
}
:deep(p) {
margin: 0 0 0.25em;
line-height: 1.625;
@@ -23,6 +23,61 @@
}
}
// A light sweep across in-progress text (the "光影" / shimmer effect). The base
// is the muted secondary color and a brighter band slides across, signalling
// "this step is still running" without the layout cost of a spinner.
// One full gradient width (background-size is 200%) so the loop is seamless.
@keyframes chatStreamShimmer {
0% {
background-position: 100% 50%;
}
100% {
background-position: -100% 50%;
}
}
.chat-stream-shimmer-text() {
// Stronger contrast: a dim placeholder base with a bright primary glint, so
// the sweeping band reads clearly rather than as a subtle shift.
background-image: linear-gradient(100deg,
var(--td-text-color-placeholder) 0%,
var(--td-text-color-placeholder) 36%,
var(--td-text-color-primary) 50%,
var(--td-text-color-placeholder) 64%,
var(--td-text-color-placeholder) 100%);
background-size: 200% 100%;
// Let the gradient tile (default repeat): the dim stops on both ends match,
// so the element is always fully painted and the band sweeps seamlessly.
// (no-repeat would leave the uncovered area transparent -> invisible text.)
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
animation: chatStreamShimmer 1.5s linear infinite;
// Keep the sweep on its own compositor layer so it stays smooth while the
// surrounding timeline relayouts on each streamed token.
will-change: background-position;
}
// In-progress step / thinking / tool-call titles shimmer while pending. Both the
// agent timeline (.action-pending) and the RAG pipeline (.is-running) opt in.
.action-card.action-pending .action-name,
.action-name.is-running {
.chat-stream-shimmer-text();
}
@media (prefers-reduced-motion: reduce) {
.action-card.action-pending .action-name,
.action-name.is-running {
animation: none;
background-image: none;
-webkit-text-fill-color: var(--td-text-color-secondary);
color: var(--td-text-color-secondary);
}
}
.streaming-loading-node {
.tree-child-content {
position: relative;
@@ -14,3 +14,17 @@ test('timeline loading uses shared gray bounce dots on the axis', () => {
assert.match(css, /animation:\s*chatTimelineTypingBounce/)
assert.match(css, /animation-delay:\s*0\.2s/)
})
test('in-progress step titles get the streaming shimmer sweep', () => {
// Both timelines opt into the shimmer: agent (.action-pending) and RAG (.is-running).
assert.match(css, /\.action-card\.action-pending \.action-name,\s*\.action-name\.is-running/)
assert.match(css, /-webkit-background-clip:\s*text/)
assert.match(css, /animation:\s*chatStreamShimmer/)
assert.match(css, /@keyframes chatStreamShimmer/)
})
test('shimmer is disabled under reduced motion', () => {
assert.match(css, /@media \(prefers-reduced-motion: reduce\)/)
const reducedBlock = css.slice(css.indexOf('@media (prefers-reduced-motion: reduce)'))
assert.match(reducedBlock, /animation:\s*none/)
})
+13 -28
View File
@@ -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" />'
+42 -1
View File
@@ -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
}
@@ -30,7 +30,7 @@
<div class="action-header no-results">
<div class="action-title">
<t-icon class="action-title-icon" :name="step.iconName" />
<span class="action-name">{{ step.title }}</span>
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
</div>
</div>
<div v-if="step.summaryHtml" class="search-results-summary-fixed">
@@ -114,7 +114,7 @@
<div class="action-header no-results">
<div class="action-title">
<t-icon class="action-title-icon" :name="step.iconName" />
<span class="action-name">{{ step.title }}</span>
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
</div>
</div>
<div v-if="step.summaryHtml" class="search-results-summary-fixed">
@@ -85,6 +85,32 @@
</div>
</section>
<!-- Streaming Shimmer (in-progress step titles) -->
<section class="test-section">
<h2>Streaming Shimmer</h2>
<p class="test-hint">
The "light sweep" applied to in-progress step titles in
AgentStreamDisplay / RagPipelineProgress. Running steps shimmer; finished ones are static.
</p>
<div class="test-case shimmer-demo">
<div class="action-card action-pending">
<div class="action-title">
<span class="action-name">正在检索知识库…</span>
</div>
</div>
<div class="action-card action-pending">
<div class="action-title">
<span class="action-name">正在生成回答…</span>
</div>
</div>
<div class="action-card">
<div class="action-title">
<span class="action-name is-done">检索完成(静态对照)</span>
</div>
</div>
</div>
</section>
<!-- Custom Editor -->
<section class="test-section">
<h2>Custom Input</h2>
@@ -441,6 +467,7 @@ watch(customInput, () => {
@import '../../components/css/chat-markdown.less';
@import '../../components/css/chat-citations.less';
@import '../../components/css/chat-message-shared.less';
@import '../../components/css/chat-timeline-loading.less';
.markdown-test-page {
max-width: 860px;
@@ -594,6 +621,22 @@ watch(customInput, () => {
}
}
.shimmer-demo {
display: flex;
flex-direction: column;
gap: 14px;
.action-card {
background: transparent;
}
.action-name {
font-size: 14px;
line-height: 1.55;
color: var(--td-text-color-secondary);
}
}
// Chat answer markdown — shared with botmsg / AgentStreamDisplay / embed
.markdown-content {
// Dev page intentionally uses the same chat Markdown mixin as runtime chat.