示例工程 19-virtualized-lists
19-virtualized-lists/app/.tsc/src/App.js
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { VirtualList } from "./components/VirtualList";
const tabs = [
{ id: "virtual", label: "虚拟 vs 全量" },
{ id: "variable", label: "变高与分组" },
{ id: "log", label: "日志流" },
];
const fixedItems = Array.from({ length: 10_000 }, (_, index) => ({
id: index,
text: `日志行 ${index + 1}`,
}));
const variableItems = Array.from({ length: 5_000 }, (_, index) => ({
id: index,
text: `可变高度行 ${index + 1}`,
}));
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function raf2() {
return new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
}
function variableHeight(index) {
if (index % 100 === 0)
return 36;
return index % 7 === 0 ? 64 : 28;
}
export default function App() {
const [tab, setTab] = useState("virtual");
const [virtualCount, setVirtualCount] = useState(0);
const [naiveCount, setNaiveCount] = useState(0);
const [virtualMs, setVirtualMs] = useState(0);
const [naiveMs, setNaiveMs] = useState(0);
const [virtualNodes, setVirtualNodes] = useState(0);
const [naiveNodes, setNaiveNodes] = useState(0);
const [firstIndex, setFirstIndex] = useState(0);
const [variableCount, setVariableCount] = useState(0);
const [visibleStart, setVisibleStart] = useState(0);
const [logs, setLogs] = useState([]);
const [paused, setPaused] = useState(false);
const virtualMsRef = useRef(0);
const naiveMsRef = useRef(0);
const virtualRef = useRef(null);
const naiveRef = useRef(null);
const variableRef = useRef(null);
const logRef = useRef(null);
const pausedRef = useRef(false);
const logSeq = useRef(1);
const stickyGroup = Math.floor(visibleStart / 100) + 1;
const addLogs = useCallback((count) => {
setLogs((current) => {
const next = [...current];
for (let index = 0; index < count; index += 1) {
next.push(`[${String(logSeq.current).padStart(4, "0")}] 流式日志`);
logSeq.current += 1;
}
return next;
});
}, []);
useEffect(() => {
if (tab !== "log" || pausedRef.current || !logRef.current)
return;
requestAnimationFrame(() => {
if (logRef.current && !pausedRef.current) {
logRef.current.scrollTop = logRef.current.scrollHeight;
}
});
}, [logs.length, tab]);
const mountVirtual = useCallback(async () => {
const started = performance.now();
setVirtualCount(10_000);
await raf2();
await sleep(60);
const elapsed = Math.round(performance.now() - started);
virtualMsRef.current = elapsed;
setVirtualMs(elapsed);
setVirtualNodes(document.querySelectorAll('[data-testid="virtual-row"]').length);
}, []);
const mountNaive = useCallback(async () => {
const started = performance.now();
setNaiveCount(10_000);
await raf2();
await sleep(80);
const elapsed = Math.round(performance.now() - started);
naiveMsRef.current = elapsed;
setNaiveMs(elapsed);
setNaiveNodes(document.querySelectorAll('[data-testid="naive-row"]').length);
}, []);
const scrollVirtual = useCallback(async (index) => {
const list = virtualRef.current;
if (!list)
return;
list.scrollTop = index * 36;
list.dispatchEvent(new Event("scroll", { bubbles: true }));
await sleep(120);
const first = document.querySelector('[data-testid="virtual-row"]');
setFirstIndex(Number(first?.dataset.rowIndex ?? 0));
}, []);
useEffect(() => {
window.__setTab = (next) => setTab(next);
window.__snapshot = () => ({
tab,
virtualCount,
virtualNodes,
naiveCount,
naiveNodes,
firstIndex,
variableCount,
stickyGroup,
logs: logs.length,
paused,
});
window.__smoke = async () => {
setTab("virtual");
await sleep(50);
await mountVirtual();
const nodesVirtual = document.querySelectorAll('[data-testid="virtual-row"]').length;
await mountNaive();
const nodesNaive = document.querySelectorAll('[data-testid="naive-row"]').length;
setNaiveCount(0);
await scrollVirtual(5000);
const first = Number(document
.querySelector('[data-testid="virtual-row"]')
?.getAttribute("data-row-index") ?? 0);
setTab("variable");
setVariableCount(5000);
await sleep(150);
const varList = variableRef.current;
if (varList) {
varList.scrollTop = 3200;
varList.dispatchEvent(new Event("scroll", { bubbles: true }));
}
await sleep(150);
const sticky = document.querySelector('[data-testid="sticky-group"]')?.textContent;
setTab("log");
pausedRef.current = false;
setPaused(false);
addLogs(300);
await sleep(150);
if (logRef.current) {
logRef.current.scrollTop = logRef.current.scrollHeight;
logRef.current.dispatchEvent(new Event("scroll", { bubbles: true }));
}
addLogs(20);
await sleep(150);
const atBottom = logRef.current
? logRef.current.scrollHeight -
logRef.current.scrollTop -
logRef.current.clientHeight <
24
: false;
if (logRef.current) {
logRef.current.scrollTop = 0;
logRef.current.dispatchEvent(new Event("scroll", { bubbles: true }));
}
await sleep(80);
addLogs(5);
await sleep(120);
const pausedAfterScroll = pausedRef.current;
pausedRef.current = false;
setPaused(false);
const resumed = !pausedRef.current;
return {
virtualNodes: nodesVirtual,
naiveNodes: nodesNaive,
virtualMs: virtualMsRef.current,
naiveMs: naiveMsRef.current,
firstIndex: first,
variableTotal: 5000,
sticky: sticky ?? "",
atBottom,
pausedAfterScroll,
resumed,
};
};
window.__prepareShots = async () => {
setTab("virtual");
await mountVirtual();
await mountNaive();
setNaiveCount(0);
await scrollVirtual(5000);
};
window.__mountVariable = () => {
setTab("variable");
setVariableCount(5000);
};
window.__pauseLog = () => {
setTab("log");
addLogs(300);
pausedRef.current = true;
setPaused(true);
if (logRef.current)
logRef.current.scrollTop = 0;
};
}, [
addLogs,
firstIndex,
logs.length,
mountNaive,
mountVirtual,
naiveCount,
naiveNodes,
paused,
scrollVirtual,
stickyGroup,
tab,
variableCount,
virtualCount,
virtualNodes,
]);
return (_jsxs("div", { className: "min-h-screen bg-surface px-8 py-7 text-text", children: [_jsx("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: "\u957F\u5217\u8868\u5DE5\u4F5C\u53F0" }), _jsx("p", { className: "mt-1 text-sm text-muted", children: "\u865A\u62DF\u5316 \u00B7 \u53D8\u9AD8\u884C \u00B7 \u7C98\u6027\u5206\u7EC4 \u00B7 \u65E5\u5FD7\u8DDF\u968F" })] }) }), _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 === "virtual" && (_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 mountVirtual(), "data-testid": "mount-virtual", children: "\u6E32\u67D3\u865A\u62DF 10,000 \u884C" }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => void mountNaive(), "data-testid": "mount-naive", children: "\u6E32\u67D3\u5168\u91CF 10,000 \u884C" }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => {
setNaiveCount(0);
setNaiveNodes(0);
setNaiveMs(0);
}, children: "\u5378\u8F7D\u5168\u91CF" })] }), _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: "\u865A\u62DF DOM \u884C" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "virtual-nodes", children: virtualNodes })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u865A\u62DF\u8017\u65F6" }), _jsxs("div", { className: "font-mono text-xl", children: [virtualMs, " ms"] })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u5168\u91CF DOM \u884C" }), _jsx("div", { className: "font-mono text-xl", "data-testid": "naive-nodes", children: naiveNodes })] }), _jsxs("div", { className: "rounded-card border border-border bg-panel p-3", children: [_jsx("div", { className: "text-xs text-muted", children: "\u5168\u91CF\u8017\u65F6" }), _jsxs("div", { className: "font-mono text-xl", children: [naiveMs, " ms"] })] })] }), virtualCount > 0 && (_jsxs("div", { className: "mt-4", children: [_jsx(VirtualList, { items: fixedItems.slice(0, virtualCount), height: 320, rowHeight: 36, containerRef: virtualRef, renderRow: (item) => (_jsx("div", { className: "flex h-9 items-center border-b border-border px-3 text-xs", children: item.text })) }), _jsxs("p", { className: "mt-2 text-xs text-muted", children: ["\u5F53\u524D\u9996\u884C\u7D22\u5F15\uFF1A", _jsx("code", { "data-testid": "first-index", children: firstIndex })] })] })), naiveCount > 0 && (_jsx("div", { ref: naiveRef, className: "mt-4 h-40 overflow-auto rounded-card border border-border bg-panel", children: Array.from({ length: naiveCount }, (_, index) => (_jsxs("div", { "data-testid": "naive-row", className: "h-9 border-b border-border px-3 text-xs leading-9", children: ["\u65E5\u5FD7\u884C ", index + 1] }, index))) }))] })), tab === "variable" && (_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: () => setVariableCount(5000), "data-testid": "mount-variable", children: "\u6E32\u67D3 5,000 \u884C\uFF08\u53D8\u9AD8\uFF09" }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => setVariableCount(0), children: "\u5378\u8F7D" }), _jsx("span", { className: "self-center text-xs text-muted", children: "\u6BCF 100 \u884C\u4E00\u4E2A\u5206\u7EC4\u5934\uFF0C\u7B2C 7 \u884C\u66F4\u9AD8" })] }), variableCount > 0 && (_jsxs("div", { className: "relative mt-4", children: [_jsxs("div", { className: "sticky top-0 z-10 rounded-t-card border border-border bg-primary-soft px-3 py-2 text-xs font-medium text-primary", "data-testid": "sticky-group", children: ["\u5206\u7EC4 ", stickyGroup] }), _jsx(VirtualList, { items: variableItems.slice(0, variableCount), height: 360, rowHeight: variableHeight, containerRef: variableRef, onVisibleRange: (start) => setVisibleStart(start), renderRow: (item, index) => {
if (index % 100 === 0) {
return (_jsxs("div", { className: "flex h-9 items-center bg-panel px-3 text-xs font-semibold text-primary", children: ["\u5206\u7EC4 ", Math.floor(index / 100) + 1] }));
}
return (_jsx("div", { className: `flex items-center border-b border-border px-3 text-xs ${index % 7 === 0 ? "h-16" : "h-7"}`, children: item.text }));
} })] }))] })), tab === "log" && (_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": "log-state", children: paused ? "已暂停自动滚动" : "跟随最新" }), _jsx("button", { className: "rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground", onClick: () => addLogs(50), "data-testid": "append-log", children: "\u8FFD\u52A0 50 \u6761" }), _jsx("button", { className: "rounded-card border border-border px-3 py-1.5 text-sm", onClick: () => {
pausedRef.current = false;
setPaused(false);
if (logRef.current) {
logRef.current.scrollTop = logRef.current.scrollHeight;
}
}, "data-testid": "resume-log", children: "\u56DE\u5230\u5E95\u90E8" })] }), _jsx(VirtualList, { items: logs, height: 360, rowHeight: 24, containerRef: logRef, onScrollTop: (top) => {
const element = logRef.current;
if (!element)
return;
if (top === 0) {
pausedRef.current = true;
setPaused(true);
}
else if (element.scrollHeight - top - element.clientHeight <
24) {
pausedRef.current = false;
setPaused(false);
}
}, renderRow: (item) => (_jsx("div", { className: "flex h-6 items-center border-b border-border px-3 font-mono text-[11px]", children: item })) }), _jsx("p", { className: "mt-2 text-xs text-muted", children: "\u7528\u6237\u4E0A\u6ED1\u5373\u6682\u505C\uFF1B\u65B0\u65E5\u5FD7\u7EE7\u7EED\u8FDB\u5165\u5217\u8868\uFF0C\u4F4D\u7F6E\u4E0D\u53D8\u3002" })] }))] })] }));
}
//# sourceMappingURL=App.js.map