示例工程 18-streaming-ui
18-streaming-ui/app/src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import type { StreamMessage } from "../shared/ipc";
type TabId = "compare" | "reorder" | "scroll";
type Mode = "compare" | "reorder" | "scroll" | "idle";
type Status = "idle" | "running" | "done" | "cancelled";
declare global {
interface Window {
api: {
start(options: {
chunks: number;
intervalMs: number;
shuffle: boolean;
from: number;
}): Promise<
| { ok: true; streamId: string; from: number; to: number }
| { ok: false; code: string }
>;
cancel(): Promise<{ ok: boolean }>;
onStream(cb: (message: StreamMessage) => void): () => void;
};
__setTab?: (tab: TabId) => void;
__snapshot?: () => unknown;
__smoke?: () => Promise<unknown>;
__prepareShots?: () => Promise<void>;
__startReorder?: () => Promise<void>;
__cancel?: () => Promise<void>;
__fillScroll?: () => void;
__pauseScroll?: () => void;
}
}
const tabs: Array<{ id: TabId; label: string }> = [
{ id: "compare", label: "增量渲染" },
{ id: "reorder", label: "乱序与重连" },
{ id: "scroll", label: "滚动锚定" },
];
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default function App() {
const [tab, setTab] = useState<TabId>("compare");
const [status, setStatus] = useState<Status>("idle");
const [chunks, setChunks] = useState(0);
const [naiveText, setNaiveText] = useState("");
const [batchedText, setBatchedText] = useState("");
const [naiveCommits, setNaiveCommits] = useState(0);
const [batchedCommits, setBatchedCommits] = useState(0);
const [frames, setFrames] = useState(0);
const [reorderApplied, setReorderApplied] = useState(0);
const [reorderBuffered, setReorderBuffered] = useState(0);
const [reorderText, setReorderText] = useState("");
const [nextSeq, setNextSeq] = useState(1);
const [lines, setLines] = useState<string[]>([]);
const [paused, setPaused] = useState(false);
const modeRef = useRef<Mode>("idle");
const statusRef = useRef<Status>("idle");
const naiveCommitsRef = useRef(0);
const batchedCommitsRef = useRef(0);
const naiveTextRef = useRef("");
const batchedTextRef = useRef("");
const framesRef = useRef(0);
const bufferRef = useRef<string[]>([]);
const rafRef = useRef<number | null>(null);
const frameRafRef = useRef<number | null>(null);
const nextSeqRef = useRef(1);
const reorderBufferRef = useRef(new Map<number, string>());
const pausedRef = useRef(false);
const scrollRef = useRef<HTMLDivElement | null>(null);
const setStatusSafe = useCallback((next: Status) => {
statusRef.current = next;
setStatus(next);
}, []);
const stopFrames = useCallback(() => {
if (frameRafRef.current !== null) cancelAnimationFrame(frameRafRef.current);
frameRafRef.current = null;
}, []);
const startFrames = useCallback(() => {
stopFrames();
const tick = () => {
if (statusRef.current !== "running") return;
framesRef.current += 1;
frameRafRef.current = requestAnimationFrame(tick);
};
frameRafRef.current = requestAnimationFrame(tick);
}, [stopFrames]);
const flushBatched = useCallback(() => {
if (bufferRef.current.length === 0) return;
const next = bufferRef.current.join("");
bufferRef.current = [];
setBatchedText((current) => current + next);
}, []);
const scheduleFlush = useCallback(() => {
if (rafRef.current !== null) return;
rafRef.current = requestAnimationFrame(() => {
rafRef.current = null;
flushBatched();
});
}, [flushBatched]);
useEffect(() => {
naiveTextRef.current = naiveText;
if (statusRef.current === "running" && naiveText.length > 0) {
naiveCommitsRef.current += 1;
setNaiveCommits(naiveCommitsRef.current);
}
}, [naiveText]);
useEffect(() => {
batchedTextRef.current = batchedText;
if (statusRef.current === "running" && batchedText.length > 0) {
batchedCommitsRef.current += 1;
setBatchedCommits(batchedCommitsRef.current);
}
}, [batchedText]);
const onStream = useCallback(
(message: StreamMessage) => {
if (message.type === "done") {
if (modeRef.current === "compare") {
flushBatched();
}
setStatusSafe("done");
setFrames(framesRef.current);
stopFrames();
return;
}
if (message.type === "cancelled") {
setStatusSafe("cancelled");
setFrames(framesRef.current);
stopFrames();
return;
}
setChunks((value) => value + 1);
if (modeRef.current === "compare") {
setNaiveText((current) => current + message.token);
bufferRef.current.push(message.token);
scheduleFlush();
} else if (modeRef.current === "reorder") {
if (message.seq === nextSeqRef.current) {
setReorderText((current) => current + message.token);
nextSeqRef.current += 1;
let applied = 0;
while (reorderBufferRef.current.has(nextSeqRef.current)) {
const token = reorderBufferRef.current.get(nextSeqRef.current);
reorderBufferRef.current.delete(nextSeqRef.current);
if (token !== undefined) {
setReorderText((current) => current + token);
nextSeqRef.current += 1;
applied += 1;
}
}
const totalApplied = nextSeqRef.current - 1;
setReorderApplied(totalApplied);
setReorderBuffered(reorderBufferRef.current.size);
void applied;
setNextSeq(nextSeqRef.current);
} else {
reorderBufferRef.current.set(message.seq, message.token);
setReorderBuffered(reorderBufferRef.current.size);
}
} else if (modeRef.current === "scroll") {
setLines((current) => [...current, message.token]);
if (!pausedRef.current && scrollRef.current) {
requestAnimationFrame(() => {
if (scrollRef.current && !pausedRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
});
}
}
},
[flushBatched, scheduleFlush, setStatusSafe, stopFrames],
);
useEffect(() => {
const off = window.api.onStream(onStream);
return off;
}, [onStream]);
const resetCompare = useCallback(() => {
bufferRef.current = [];
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
rafRef.current = null;
naiveCommitsRef.current = 0;
batchedCommitsRef.current = 0;
framesRef.current = 0;
setChunks(0);
setNaiveText("");
setBatchedText("");
setNaiveCommits(0);
setBatchedCommits(0);
setFrames(0);
}, []);
const resetReorder = useCallback(() => {
nextSeqRef.current = 1;
reorderBufferRef.current.clear();
setReorderApplied(0);
setReorderBuffered(0);
setReorderText("");
setNextSeq(1);
setChunks(0);
}, []);
const start = useCallback(
async (
mode: Mode,
options: {
chunks: number;
intervalMs: number;
shuffle: boolean;
from: number;
},
) => {
modeRef.current = mode;
if (mode === "compare") resetCompare();
if (mode === "reorder") resetReorder();
setStatusSafe("running");
startFrames();
const result = await window.api.start(options);
if (!result.ok) setStatusSafe("idle");
},
[resetCompare, resetReorder, setStatusSafe, startFrames],
);
const cancel = useCallback(async () => {
await window.api.cancel();
setStatusSafe("cancelled");
stopFrames();
}, [setStatusSafe, stopFrames]);
const waitForDone = useCallback(async (timeout = 6000) => {
const started = Date.now();
while (statusRef.current === "running" && Date.now() - started < timeout) {
await sleep(30);
}
await sleep(80);
}, []);
useEffect(() => {
window.__setTab = (next) => setTab(next);
window.__snapshot = () => ({
tab,
status,
chunks,
naiveCommits: naiveCommitsRef.current,
batchedCommits: batchedCommitsRef.current,
frames: framesRef.current,
reorderApplied,
reorderBuffered,
paused,
lines: lines.length,
});
window.__smoke = async () => {
setTab("compare");
await start("compare", {
chunks: 60,
intervalMs: 5,
shuffle: false,
from: 1,
});
await waitForDone();
const naive = naiveCommitsRef.current;
const batched = batchedCommitsRef.current;
const sameText =
naiveTextRef.current.length > 0 &&
naiveTextRef.current === batchedTextRef.current;
setTab("reorder");
await start("reorder", {
chunks: 20,
intervalMs: 5,
shuffle: true,
from: 1,
});
await waitForDone();
const applied = nextSeqRef.current - 1;
const buffered = reorderBufferRef.current.size;
setTab("compare");
await start("compare", {
chunks: 200,
intervalMs: 5,
shuffle: false,
from: 1,
});
await sleep(120);
await cancel();
await waitForDone(1000);
const cancelled = statusRef.current === "cancelled";
setTab("scroll");
pausedRef.current = true;
setPaused(true);
setLines(Array.from({ length: 40 }, (_, index) => `${index + 1} `));
await start("scroll", {
chunks: 3,
intervalMs: 10,
shuffle: false,
from: 41,
});
await waitForDone();
const scrollPaused = pausedRef.current;
pausedRef.current = false;
setPaused(false);
const scrollResumed = !pausedRef.current;
return {
naiveCommits: naive,
batchedCommits: batched,
sameText,
reorderApplied: applied,
reorderBuffered: buffered,
cancelled,
scrollPaused,
scrollResumed,
};
};
window.__prepareShots = async () => {
setTab("compare");
await start("compare", {
chunks: 60,
intervalMs: 5,
shuffle: false,
from: 1,
});
await waitForDone();
};
window.__startReorder = async () => {
setTab("reorder");
await start("reorder", {
chunks: 20,
intervalMs: 40,
shuffle: true,
from: 1,
});
};
window.__cancel = async () => {
await cancel();
};
window.__fillScroll = () => {
modeRef.current = "scroll";
setTab("scroll");
setLines(Array.from({ length: 40 }, (_, index) => `${index + 1} `));
setStatusSafe("done");
};
window.__pauseScroll = () => {
pausedRef.current = true;
setPaused(true);
if (scrollRef.current) scrollRef.current.scrollTop = 0;
};
}, [
cancel,
lines.length,
paused,
reorderApplied,
reorderBuffered,
start,
status,
tab,
waitForDone,
]);
const handleScroll = () => {
const element = scrollRef.current;
if (!element) return;
const atBottom =
element.scrollHeight - element.scrollTop - element.clientHeight < 24;
const next = !atBottom;
pausedRef.current = next;
setPaused(next);
};
return (
<div className="min-h-screen bg-surface px-8 py-7 text-text">
<header className="flex items-end justify-between gap-6 border-b border-border pb-4">
<div>
<h1 className="text-2xl font-semibold" data-testid="app-title">
流式 UI 工作台
</h1>
<p className="mt-1 text-sm text-muted">
增量渲染 · 乱序缓冲 · 滚动锚定
</p>
</div>
<span
className="rounded-full border border-border px-3 py-1 text-xs text-muted"
data-testid="status"
>
{status}
</span>
</header>
<nav className="mt-5 flex gap-1">
{tabs.map((item) => (
<button
key={item.id}
className={`rounded-md border px-3 py-1.5 text-sm ${
tab === item.id
? "border-border bg-panel font-semibold text-primary"
: "border-transparent text-muted hover:bg-panel"
}`}
data-testid={`tab-${item.id}`}
onClick={() => setTab(item.id)}
>
{item.label}
</button>
))}
</nav>
<main className="mt-6">
{tab === "compare" && (
<section>
<div className="flex gap-2">
<button
className="rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
onClick={() =>
void start("compare", {
chunks: 60,
intervalMs: 5,
shuffle: false,
from: 1,
})
}
data-testid="start-compare"
>
开始 60 块
</button>
<button
className="rounded-card border border-border px-3 py-1.5 text-sm"
onClick={() => void cancel()}
>
取消
</button>
</div>
<div className="mt-4 grid grid-cols-2 gap-4">
<div className="rounded-card border border-border bg-panel p-4">
<h2 className="text-sm font-semibold">每块 setState(反例)</h2>
<pre
className="mt-2 h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs"
data-testid="naive-text"
>
{naiveText}
</pre>
</div>
<div className="rounded-card border border-border bg-panel p-4">
<h2 className="text-sm font-semibold">缓冲 + RAF 合并</h2>
<pre
className="mt-2 h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs"
data-testid="batched-text"
>
{batchedText}
</pre>
</div>
</div>
<div className="mt-4 grid grid-cols-4 gap-3">
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">块数</div>
<div className="font-mono text-xl" data-testid="chunks">
{chunks}
</div>
</div>
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">naive 提交</div>
<div className="font-mono text-xl" data-testid="naive-commits">
{naiveCommits}
</div>
</div>
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">batched 提交</div>
<div
className="font-mono text-xl"
data-testid="batched-commits"
>
{batchedCommits}
</div>
</div>
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">动画帧</div>
<div className="font-mono text-xl" data-testid="frames">
{frames}
</div>
</div>
</div>
</section>
)}
{tab === "reorder" && (
<section>
<div className="flex gap-2">
<button
className="rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
onClick={() =>
void start("reorder", {
chunks: 20,
intervalMs: 20,
shuffle: true,
from: 1,
})
}
data-testid="start-reorder"
>
乱序发送 20 块
</button>
<button
className="rounded-card border border-border px-3 py-1.5 text-sm"
onClick={() =>
void start("reorder", {
chunks: 10,
intervalMs: 20,
shuffle: false,
from: nextSeq,
})
}
data-testid="reconnect"
>
从 {nextSeq} 重连
</button>
<button
className="rounded-card border border-border px-3 py-1.5 text-sm"
onClick={() => void cancel()}
>
取消
</button>
</div>
<div className="mt-4 grid grid-cols-3 gap-3">
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">已应用</div>
<div className="font-mono text-xl" data-testid="applied">
{reorderApplied}
</div>
</div>
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">缓冲中</div>
<div className="font-mono text-xl" data-testid="buffered">
{reorderBuffered}
</div>
</div>
<div className="rounded-card border border-border bg-panel p-3">
<div className="text-xs text-muted">期待 seq</div>
<div className="font-mono text-xl">{nextSeq}</div>
</div>
</div>
<pre
className="mt-4 h-48 overflow-auto whitespace-pre-wrap break-words rounded-card border border-border bg-panel p-4 font-mono text-xs"
data-testid="reorder-text"
>
{reorderText}
</pre>
</section>
)}
{tab === "scroll" && (
<section>
<div className="flex items-center gap-2">
<span
className={`rounded-full px-3 py-1 text-xs ${
paused
? "bg-primary-soft text-primary"
: "border border-border text-muted"
}`}
data-testid="scroll-state"
>
{paused ? "已暂停自动滚动" : "跟随最新"}
</span>
<button
className="rounded-card border border-border px-3 py-1.5 text-sm"
onClick={() => {
pausedRef.current = false;
setPaused(false);
if (scrollRef.current) {
scrollRef.current.scrollTop =
scrollRef.current.scrollHeight;
}
}}
data-testid="resume-scroll"
>
回到底部
</button>
<button
className="rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
onClick={() =>
void start("scroll", {
chunks: 40,
intervalMs: 10,
shuffle: false,
from: 41,
})
}
data-testid="start-scroll"
>
继续追加 40 块
</button>
</div>
<div
ref={scrollRef}
className="mt-4 h-64 overflow-auto rounded-card border border-border bg-panel p-4 font-mono text-xs leading-6"
data-testid="scroll-box"
onScroll={handleScroll}
>
{lines.map((line, index) => (
<div key={`${index}-${line}`}>{line}</div>
))}
</div>
<p className="mt-2 text-xs text-muted">
用户上滑超过 24px 就暂停自动滚动;回到底部后恢复。
</p>
</section>
)}
</main>
</div>
);
}