示例工程 18-streaming-ui
18-streaming-ui/app/.tsc/src/App.js
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
const tabs = [
{ id: "compare", label: "增量渲染" },
{ id: "reorder", label: "乱序与重连" },
{ id: "scroll", label: "滚动锚定" },
];
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default function App() {
const [tab, setTab] = useState("compare");
const [status, setStatus] = useState("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([]);
const [paused, setPaused] = useState(false);
const modeRef = useRef("idle");
const statusRef = useRef("idle");
const naiveCommitsRef = useRef(0);
const batchedCommitsRef = useRef(0);
const naiveTextRef = useRef("");
const batchedTextRef = useRef("");
const framesRef = useRef(0);
const bufferRef = useRef([]);
const rafRef = useRef(null);
const frameRafRef = useRef(null);
const nextSeqRef = useRef(1);
const reorderBufferRef = useRef(new Map());
const pausedRef = useRef(false);
const scrollRef = useRef(null);
const setStatusSafe = useCallback((next) => {
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) => {
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, options) => {
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 (_jsxs("div", { className: "min-h-screen bg-surface px-8 py-7 text-text", children: [_jsxs("header", { className: "flex items-end justify-between gap-6 border-b border-border pb-4", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-2xl font-semibold", "data-testid": "app-title", children: "\u6D41\u5F0F UI \u5DE5\u4F5C\u53F0" }), _jsx("p", { className: "mt-1 text-sm text-muted", children: "\u589E\u91CF\u6E32\u67D3 \u00B7 \u4E71\u5E8F\u7F13\u51B2 \u00B7 \u6EDA\u52A8\u951A\u5B9A" })] }), _jsx("span", { className: "rounded-full border border-border px-3 py-1 text-xs text-muted", "data-testid": "status", children: status })] }), _jsx("nav", { className: "mt-5 flex gap-1", children: tabs.map((item) => (_jsx("button", { 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), children: item.label }, item.id))) }), _jsxs("main", { className: "mt-6", children: [tab === "compare" && (_jsxs("section", { children: [_jsxs("div", { className: "flex gap-2", children: [_jsx("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", children: "\u5F00\u59CB 60 \u5757" }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => void cancel(), children: "\u53D6\u6D88" })] }), _jsxs("div", { className: "mt-4 grid grid-cols-2 gap-4", children: [_jsxs("div", { className: "rounded-card border border-border bg-panel p-4", children: [_jsx("h2", { className: "text-sm font-semibold", children: "\u6BCF\u5757 setState\uFF08\u53CD\u4F8B\uFF09" }), _jsx("pre", { className: "mt-2 h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs", "data-testid": "naive-text", children: naiveText })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-4", children: [_jsx("h2", { className: "text-sm font-semibold", children: "\u7F13\u51B2 + RAF \u5408\u5E76" }), _jsx("pre", { className: "mt-2 h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs", "data-testid": "batched-text", children: batchedText })] })] }), _jsxs("div", { className: "mt-4 grid grid-cols-4 gap-3", children: [_jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u5757\u6570" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "chunks", children: chunks })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "naive \u63D0\u4EA4" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "naive-commits", children: naiveCommits })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "batched \u63D0\u4EA4" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "batched-commits", children: batchedCommits })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u52A8\u753B\u5E27" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "frames", children: frames })] })] })] })), tab === "reorder" && (_jsxs("section", { children: [_jsxs("div", { className: "flex gap-2", children: [_jsx("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", children: "\u4E71\u5E8F\u53D1\u9001 20 \u5757" }), _jsxs("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", children: ["\u4ECE ", nextSeq, " \u91CD\u8FDE"] }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => void cancel(), children: "\u53D6\u6D88" })] }), _jsxs("div", { className: "mt-4 grid grid-cols-3 gap-3", children: [_jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u5DF2\u5E94\u7528" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "applied", children: reorderApplied })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u7F13\u51B2\u4E2D" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "buffered", children: reorderBuffered })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u671F\u5F85 seq" }), _jsx("div", { className: "font-mono text-xl", children: nextSeq })] })] }), _jsx("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", children: reorderText })] })), tab === "scroll" && (_jsxs("section", { children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("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", children: paused ? "已暂停自动滚动" : "跟随最新" }), _jsx("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", children: "\u56DE\u5230\u5E95\u90E8" }), _jsx("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", children: "\u7EE7\u7EED\u8FFD\u52A0 40 \u5757" })] }), _jsx("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, children: lines.map((line, index) => (_jsx("div", { children: line }, `${index}-${line}`))) }), _jsx("p", { className: "mt-2 text-xs text-muted", children: "\u7528\u6237\u4E0A\u6ED1\u8D85\u8FC7 24px \u5C31\u6682\u505C\u81EA\u52A8\u6EDA\u52A8\uFF1B\u56DE\u5230\u5E95\u90E8\u540E\u6062\u590D\u3002" })] }))] })] }));
}
//# sourceMappingURL=App.js.map