Skip to content

Commit e67f932

Browse files
authored
⚡️ perf: bound concurrent stream fades and fold faded tail spans (#8)
* 🔧 chore: add streaming benchmark against words and vercel streamdown * 🔧 chore: settle bench replays on DOM quiet instead of getAnimations * 🐛 fix: chain word-granularity fade births across whitespace * ⚡️ perf: share one fade span per display frame in the stream tail * ⚡️ perf: fold faded tail spans back into text after the last commit
1 parent a1fdebd commit e67f932

15 files changed

Lines changed: 948 additions & 16 deletions

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ dist
88
# docs
99
.react-router
1010

11+
# bench
12+
bench/.cache
13+
1114
# ci
1215
coverage
1316
.eslintcache

‎bench/pages/harness.ts‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
import { createElement, type ReactElement, useEffect, useLayoutEffect, useState } from 'react';
2+
import { createRoot } from 'react-dom/client';
3+
4+
export interface RendererProps {
5+
active: boolean;
6+
animated: boolean;
7+
value: string;
8+
}
9+
10+
export interface ReplayResult {
11+
completedMs: number;
12+
elements: number;
13+
errors: string[];
14+
fences: number;
15+
frames: number[];
16+
paragraphs: number;
17+
settledMs: number;
18+
textHash: string;
19+
textLength: number;
20+
updates: number[];
21+
}
22+
23+
const params = new URLSearchParams(location.search);
24+
const fixture = params.get('fixture')!;
25+
const chunk = Number(params.get('chunk'));
26+
const interval = Number(params.get('interval'));
27+
const animated = params.get('mode') === 'animated';
28+
29+
const errors: string[] = [];
30+
window.addEventListener('error', (event) => errors.push(event.message));
31+
window.addEventListener('unhandledrejection', (event) => errors.push(String(event.reason)));
32+
33+
const generate = (name: string) => {
34+
const [, kind, size] = /^gen-(paragraph|fence)-(\d+)$/.exec(name) ?? [];
35+
if (!kind) return;
36+
const line =
37+
kind === 'fence'
38+
? 'const value = "<&>"; // é 中, ordinary code\n'
39+
: 'Ordinary prose, with words and numbers 12345. ';
40+
const body = line.repeat(Math.ceil(Number(size) / line.length)).slice(0, Number(size));
41+
return kind === 'fence' ? `\`\`\`typescript\n${body}\n\`\`\`\n` : `${body}\n\n`;
42+
};
43+
44+
const source = generate(fixture) ?? (await (await fetch(`/fixtures/${fixture}`)).text());
45+
const ends: number[] = [];
46+
for (let end = 0; end < source.length;) {
47+
end = Math.min(end + chunk, source.length);
48+
const code = source.charCodeAt(end - 1);
49+
if (code >= 0xD800 && code <= 0xDBFF && end < source.length) end++;
50+
ends.push(end);
51+
}
52+
53+
const warmupSource = [
54+
'Warmup **formatting**, *emphasis*, `code` and [navigation](/warmup).',
55+
'- one\n- two',
56+
'| a | b |\n| - | - |\n| 1 | 2 |',
57+
'> quote',
58+
'```ts\nconst warmup = 1;\n```',
59+
].join('\n\n');
60+
61+
const normalize = (text: string) => text.replaceAll(/\s+/g, '');
62+
63+
const hash = (text: string) => {
64+
let value = 2_166_136_261;
65+
for (let i = 0; i < text.length; i++)
66+
value = Math.imul(value ^ text.charCodeAt(i), 16_777_619) >>> 0;
67+
return value.toString(16);
68+
};
69+
70+
let markReady!: () => void;
71+
let play!: (done: (result: ReplayResult) => void) => void;
72+
Object.assign(window, {
73+
bench: {
74+
ready: new Promise<void>((resolve) => (markReady = resolve)),
75+
run: () => new Promise<ReplayResult>((resolve) => play(resolve)),
76+
},
77+
});
78+
79+
const SETTLE_QUIET_MS = 600;
80+
81+
const waitForSettle = (preview: HTMLElement, since: number) =>
82+
new Promise<number>((resolve) => {
83+
let lastMutation = since;
84+
const observer = new MutationObserver(() => {
85+
lastMutation = performance.now();
86+
});
87+
observer.observe(preview, { characterData: true, childList: true, subtree: true });
88+
const check = () => {
89+
const quiet = performance.now() - lastMutation;
90+
if (quiet < SETTLE_QUIET_MS) {
91+
setTimeout(check, SETTLE_QUIET_MS - quiet);
92+
return;
93+
}
94+
observer.disconnect();
95+
resolve(lastMutation);
96+
};
97+
setTimeout(check, SETTLE_QUIET_MS);
98+
});
99+
100+
export function mount(Renderer: (props: RendererProps) => ReactElement): void {
101+
const updates: number[] = [];
102+
const frames: number[] = [];
103+
let requested = 0;
104+
let startedAt = 0;
105+
let completedAt = 0;
106+
let finished = false;
107+
let done: (result: ReplayResult) => void;
108+
109+
function App() {
110+
const [stage, setStage] = useState<'warmup' | 'idle' | 'playing'>('warmup');
111+
const [step, setStep] = useState(0);
112+
const cursor = step === 0 ? 0 : ends[step - 1];
113+
114+
useEffect(() => {
115+
play = (resolve) => {
116+
done = resolve;
117+
let previous = performance.now();
118+
const frame = (now: number) => {
119+
if (finished) return;
120+
frames.push(Math.round((now - previous) * 10) / 10);
121+
previous = now;
122+
requestAnimationFrame(frame);
123+
};
124+
requestAnimationFrame(frame);
125+
startedAt = performance.now();
126+
setStage('playing');
127+
};
128+
const preview = document.querySelector<HTMLElement>('#preview')!;
129+
void waitForSettle(preview, performance.now()).then(() => setStage('idle'));
130+
}, []);
131+
132+
useLayoutEffect(() => {
133+
if (stage === 'idle') requestAnimationFrame(() => requestAnimationFrame(markReady));
134+
if (stage !== 'playing' || step === 0) return;
135+
updates.push(Math.round((performance.now() - requested) * 10) / 10);
136+
if (step === ends.length) completedAt = performance.now();
137+
}, [stage, step]);
138+
139+
useEffect(() => {
140+
if (stage !== 'playing') return;
141+
if (step < ends.length) {
142+
const timer = setTimeout(() => {
143+
requested = performance.now();
144+
setStep(step + 1);
145+
}, interval);
146+
return () => clearTimeout(timer);
147+
}
148+
const preview = document.querySelector<HTMLElement>('#preview')!;
149+
void waitForSettle(preview, completedAt).then((settledAt) => {
150+
finished = true;
151+
const paragraphs = [...preview.querySelectorAll('p')];
152+
const fences = [...preview.querySelectorAll('pre code')];
153+
const text = normalize(preview.textContent ?? '');
154+
done({
155+
completedMs: Math.round(completedAt - startedAt),
156+
elements: preview.getElementsByTagName('*').length,
157+
errors,
158+
fences: fences.length,
159+
frames,
160+
paragraphs: paragraphs.length,
161+
settledMs: Math.round(settledAt - startedAt),
162+
textHash: hash(text),
163+
textLength: text.length,
164+
updates,
165+
});
166+
});
167+
}, [stage, step]);
168+
169+
return createElement(
170+
'main',
171+
{ id: 'preview' },
172+
createElement(Renderer, {
173+
active: stage === 'playing' && step < ends.length,
174+
animated,
175+
key: stage === 'warmup' ? 0 : 1,
176+
value: stage === 'warmup' ? warmupSource : source.slice(0, cursor),
177+
}),
178+
);
179+
}
180+
181+
createRoot(document.querySelector('#app')!).render(createElement(App));
182+
}

‎bench/pages/lobe.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>lobe</title>
6+
</head>
7+
<body>
8+
<div id="app"></div>
9+
<script type="module" src="./lobe.ts"></script>
10+
</body>
11+
</html>

‎bench/pages/lobe.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Streamdown } from '@lobehub/streamdown';
2+
import { createElement } from 'react';
3+
4+
import { mount } from './harness';
5+
6+
const params = new URLSearchParams(location.search);
7+
const granularity = params.get('granularity') === 'word' ? 'word' : 'char';
8+
const smoothing = (params.get('smoothing') ?? 'balanced') as 'balanced' | 'realtime' | 'silky';
9+
10+
mount(({ value }) => createElement(Streamdown, { content: value, granularity, smoothing }));

‎bench/pages/vercel.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>vercel</title>
6+
</head>
7+
<body>
8+
<div id="app"></div>
9+
<script type="module" src="./vercel.ts"></script>
10+
</body>
11+
</html>

‎bench/pages/vercel.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import 'streamdown/styles.css';
2+
3+
import { createElement } from 'react';
4+
import { Streamdown } from 'streamdown';
5+
6+
import { mount } from './harness';
7+
8+
mount(({ value, active, animated }) =>
9+
createElement(
10+
Streamdown,
11+
{
12+
animated: animated
13+
? {
14+
animation: 'fadeIn',
15+
duration: 180,
16+
easing: 'ease-out',
17+
sep: 'word',
18+
stagger: 0,
19+
}
20+
: false,
21+
codeBlockMaxHeight: 0,
22+
controls: false,
23+
dir: 'ltr',
24+
isAnimating: active,
25+
lineNumbers: false,
26+
mode: 'streaming',
27+
} as never,
28+
value,
29+
),
30+
);

‎bench/pages/words.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>words</title>
6+
</head>
7+
<body>
8+
<div id="app"></div>
9+
<script type="module" src="./words.ts"></script>
10+
</body>
11+
</html>

‎bench/pages/words.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import '@pierre/words/styles.css';
2+
3+
import { Markdown } from '@pierre/words/react';
4+
import { createElement } from 'react';
5+
6+
import { mount } from './harness';
7+
8+
mount(({ value, active, animated }) =>
9+
createElement(
10+
Markdown,
11+
{
12+
animated: animated ? { animation: 'fadeIn', duration: 180 } : false,
13+
controls: false,
14+
isAnimating: active,
15+
lineNumbers: false,
16+
mode: 'streaming',
17+
},
18+
value,
19+
),
20+
);

0 commit comments

Comments
 (0)