Skip to content

Commit 28cd5fe

Browse files
committed
📝 docs(streamdown): enrich high TPS demo with mixed markdown
1 parent fc6e2e4 commit 28cd5fe

2 files changed

Lines changed: 167 additions & 3 deletions

File tree

‎packages/streamdown/site/src/lib/paragraphBatches.ts‎

Lines changed: 166 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,170 @@ const content = Array.from({ length: 20 }, (_, i) =>
44
paragraph.replace('01', String(i + 1).padStart(2, '0')),
55
).join('');
66

7+
const highTpsContent = `# Mixed markdown at two thousand characters per second
8+
9+
When an LLM streams at a few thousand characters per second, the renderer is no longer dealing with a polite trickle of tokens. Whole sentences land in a single animation frame, fences open and close before the smoother has drained the previous block, and the tail parse has to stay cheap even as the open paragraph grows past a thousand characters. This sample is built to look like that kind of answer: long prose, mixed inline marks, and heavier nodes that force the block lexer to reseal and reopen while the input rate stays at two thousand characters per second.
10+
11+
The point is not to flood the page with noise. A realistic high-throughput stream still has structure — headings that split the document, paragraphs that wrap for twenty lines, lists that nest, tables that arrive cell by cell, and code fences whose language tag is visible long before the closing backticks. If the animation only looks correct on twenty copies of "Paragraph 01 arrives as a complete block", it has not been tested against the document shape users actually see.
12+
13+
## Why the open paragraph is the expensive part
14+
15+
Every reveal commit re-parses the trailing block, so cost grows with the tail's length. A short "hello world" paragraph hides that; a six-hundred-character paragraph does not. Keep reading this block as it fills: **bold**, *italic*, ~~strike~~, \`inline code\`, a [link](https://ui.lobehub.com), and mixed punctuation all sit inside the same paragraph node. The smoother has to pace characters through that node without tearing the marks apart, and without treating a mid-word backtick as the start of a fence. That is the actual hot path at high TPS: not twenty identical stubs, but one text node that stays open long enough for the commit interval to widen.
16+
17+
A second long paragraph immediately follows so the lexer cannot treat the first one as a one-off. Streaming UIs fail at the boundary between two large text nodes more often than they fail inside a single node: the previous paragraph is sealed, its animation timeline is frozen, and the new paragraph has to start a fresh stagger while the input queue is still running at two thousand characters per second. If the seal is late, characters from this paragraph leak into the previous block's fade. If the seal is early, the last sentence of the previous paragraph pops in as a completed block instead of finishing its per-character reveal. This sentence exists so the second node is still long after that boundary has been crossed.
18+
19+
## A component that actually streams
20+
21+
The fence below is long enough that it stays open across many 20-character chunks. Code skips per-character animation and reveals as a block, then prose resumes the fade.
22+
23+
\`\`\`tsx
24+
import { memo, useMemo, useState } from 'react';
25+
import { Streamdown } from '@lobehub/streamdown';
26+
import remarkGfm from 'remark-gfm';
27+
import remarkMath from 'remark-math';
28+
import rehypeKatex from 'rehype-katex';
29+
30+
interface AssistantTurnProps {
31+
source: string;
32+
streaming: boolean;
33+
smoothing?: 'realtime' | 'balanced' | 'silky';
34+
}
35+
36+
export const AssistantTurn = memo(function AssistantTurn({
37+
source,
38+
streaming,
39+
smoothing = 'balanced',
40+
}: AssistantTurnProps) {
41+
const remarkPlugins = useMemo(() => [remarkGfm, remarkMath], []);
42+
const rehypePlugins = useMemo(() => [rehypeKatex], []);
43+
const [copied, setCopied] = useState(false);
44+
45+
if (!streaming) {
46+
return (
47+
<Streamdown
48+
content={source}
49+
granularity="char"
50+
remarkPlugins={remarkPlugins}
51+
rehypePlugins={rehypePlugins}
52+
smoothing={smoothing}
53+
/>
54+
);
55+
}
56+
57+
return (
58+
<div data-streaming={copied ? 'copied' : 'live'}>
59+
<Streamdown
60+
content={source}
61+
granularity="char"
62+
latexGuard
63+
remarkPlugins={remarkPlugins}
64+
rehypePlugins={rehypePlugins}
65+
smoothing={smoothing}
66+
onCopy={() => setCopied(true)}
67+
/>
68+
</div>
69+
);
70+
});
71+
\`\`\`
72+
73+
After the fence the per-character fade has to restart on a long prose node, not on a one-line caption. That transition is where a naive implementation either freezes the last code line's opacity or dumps the next paragraph in a single paint. The following paragraph is intentionally long so the restart is visible: the queue still holds hundreds of characters, the smoother is still pacing at a few dozen commits per second, and this sentence has to land one glyph at a time even though the model already finished the fence two hundred milliseconds ago. Inline marks keep arriving too — \`useMemo\`, **latexGuard**, and a trailing [docs link](https://ui.lobehub.com/components/markdown) — so the restarted node is not a plain string either.
74+
75+
## Lists, tasks, and a table in the same stream
76+
77+
High TPS is not only paragraphs. The nodes below arrive in the same 20-character chunks, which means list markers, table pipes, and quote prefixes are often split across batch boundaries.
78+
79+
1. Ordered items stream as one list block until a blank line seals them
80+
2. Nested content has to indent without breaking the parent list
81+
- Nested bullets with \`inline code\` and **emphasis**
82+
- A second nested bullet that wraps onto another line because the clause is long enough to force a break in a typical chat column, and it still has to keep the stagger continuous
83+
3. Back to the top level with a trailing clause so the last item is not a stub
84+
85+
- [x] Seal completed blocks so they never re-parse
86+
- [ ] Keep the open tail cheap as it grows past a thousand characters
87+
- [x] Resume character animation after a fence
88+
- [ ] Hold LaTeX until the closing delimiter arrives
89+
90+
> Streaming UIs should feel like typing, not like a slideshow. A blockquote is still a block: it has to fade as a unit once sealed, while any text that follows starts a new timeline. This quote is long on purpose so it cannot be mistaken for a one-line callout, and so the high-TPS case actually opens a quote node instead of skipping past it.
91+
92+
| Node | Why it is here | Risk at 2000 chars/s |
93+
| --- | --- | --- |
94+
| Long paragraph | Tail parse cost grows with length | Stutter, dropped stagger |
95+
| Code fence | Open fence spans many chunks | Flash of raw backticks |
96+
| Nested list | Indent + mixed inlines | Broken list or nested parse |
97+
| Table | Pipes arrive before the row is complete | Column collapse |
98+
| Quote | Separate block after prose | Animation reset at the boundary |
99+
100+
## A second fence, then JSON, math, and a diagram
101+
102+
Python so the highlighter switches language while the stream is still hot:
103+
104+
\`\`\`python
105+
from dataclasses import dataclass
106+
107+
@dataclass
108+
class RevealCommit:
109+
text: str
110+
delay_ms: int
111+
sealed: bool
112+
113+
def pace(source: str, chunk_size: int = 20, delay_ms: int = 10) -> list[RevealCommit]:
114+
commits: list[RevealCommit] = []
115+
offset = 0
116+
while offset < len(source):
117+
offset = min(len(source), offset + chunk_size)
118+
commits.append(
119+
RevealCommit(
120+
text=source[:offset],
121+
delay_ms=delay_ms,
122+
sealed=offset >= len(source),
123+
)
124+
)
125+
return commits
126+
\`\`\`
127+
128+
Configuration often arrives as a tight JSON fence. It is a different highlighter, a different block, and another chance to flash raw source if the closer is late:
129+
130+
\`\`\`json
131+
{
132+
"smoothing": "balanced",
133+
"granularity": "char",
134+
"latexGuard": true,
135+
"chunkSize": 20,
136+
"delayMs": 10,
137+
"plugins": ["remark-gfm", "remark-math", "rehype-katex"]
138+
}
139+
\`\`\`
140+
141+
Inline math like $E = mc^2$ sits in a sentence, and display math has to stay guarded until the closing \`$$\` lands:
142+
143+
$$
144+
\\hat{f}(\\xi) = \\int_{-\\infty}^{\\infty} f(x)\\, e^{-2\\pi i x \\xi} \\, dx
145+
$$
146+
147+
The Fourier pair is here so a formula node sits between fences and diagrams, not as its own isolated sample:
148+
149+
$$
150+
f(x) = \\int_{-\\infty}^{\\infty} \\hat{f}(\\xi) e^{2\\pi i \\xi x} \\, d\\xi
151+
$$
152+
153+
\`\`\`mermaid
154+
flowchart LR
155+
A[Token stream] --> B{Block boundary?}
156+
B -- no --> C[Append to tail]
157+
B -- yes --> D[Seal previous]
158+
D --> E[Memoize]
159+
C --> F[Reveal queue]
160+
E --> F
161+
F --> G[Per-char CSS stagger]
162+
\`\`\`
163+
164+
## Closing: two more long text nodes
165+
166+
The last two paragraphs exist so the demo does not end on a diagram. Ending on a heavy node hides whether the smoother can return to long-form prose after a fence, a table, and math. This paragraph is a single text node that should stay open for a long time: it talks about commit interval widening as the tail grows, about not flushing the whole remainder when a large append is actually just a fast model, and about keeping the character fade continuous even though React only commits a few times per frame. The input rate for this case is twenty characters every ten milliseconds, which is two thousand characters per second — well above what the display can animate, which is exactly the pressure a real high-TPS model puts on the queue.
167+
168+
Final paragraph, still long, still one node. If you can read this sentence appearing one character at a time after the mermaid block has already painted, the mixed-document path is doing its job. The previous samples used twenty identical short paragraphs; those never opened a fence, never wrapped a six-hundred-character text node, and never asked the lexer to reseal a table. This one does all three, then keeps the tail in prose until the stream ends, which is the shape of an actual assistant answer rather than a synthetic paragraph pump. Inline leftovers at the very end: \`chunkSize=20\`, **2000 chars/s**, and a last [reference](https://github.com/lobehub/lobe-ui) so the final node is still a mixed text node rather than a plain string.
169+
`;
170+
7171
export const paragraphBatchCases = {
8172
paragraph: {
9173
chunkSize: paragraph.length,
@@ -19,8 +183,8 @@ export const paragraphBatchCases = {
19183
},
20184
highTps: {
21185
chunkSize: 20,
22-
content,
186+
content: highTpsContent,
23187
delayMs: 10,
24-
label: 'High TPS paragraphs (2000 chars/s)',
188+
label: 'High TPS mixed markdown (2000 chars/s)',
25189
},
26190
};

‎src/Markdown/index.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ Use this demo to inspect stream-driven React commit frequency, block-level re-re
296296

297297
Noise-free page for CPU measurements: a single `Markdown` and plain HTML controls — no control panel, no chunk log, no spinner, no auto-scroll. Configure via query params: `?size=5&delay=50&granularity=char|word&preset=balanced`.
298298

299-
Use the Case selector or `?case=paragraph`, `?case=paragraphBurst`, or `?case=highTps` to compare complete paragraphs, two paragraphs arriving together, and 20-character chunks every 10ms. Completed paragraphs fade in together while unfinished text keeps streaming. Rates are measured in characters, not model tokens. `size` and `delay` override each case’s defaults; `anim=0` disables both character and block animations.
299+
Use the Case selector or `?case=paragraph`, `?case=paragraphBurst`, or `?case=highTps` to compare complete paragraphs, two paragraphs arriving together, and 20-character chunks every 10ms of mixed markdown (long paragraphs, code fences, lists, tables, math, mermaid). Completed paragraphs fade in together while unfinished text keeps streaming. Rates are measured in characters, not model tokens. `size` and `delay` override each case’s defaults; `anim=0` disables both character and block animations.
300300

301301
<Demo of={DemoStreamingBench} isolated layout="bare" />
302302

0 commit comments

Comments
 (0)