perf(webui): virtualize the log viewer row list (#185)

The logs page rendered every filtered row, so a full 2000-line view mounted
~10k DOM nodes and cost ~66ms of layout per commit. Switch to a virtualized
list (@tanstack/react-virtual) that mounts only the visible window plus a small
overscan — a few dozen nodes regardless of how many lines the view holds.

Rows are dynamically measured (measureElement) so wrap mode's variable-height
lines need no fixed row-height assumption; the size cache is keyed by row id so
the maxLines front-drop doesn't mis-attribute heights across the index shift.
The column header moved just outside the scroll viewport so the virtual list is
the sole scroll content (no sticky-offset math). Auto-scroll now follows the
tail via scrollToIndex with a next-frame re-pin (freshly-appended rows carry the
size estimate until measured, which otherwise left wrap-mode tails short), and
re-runs on filter/level/wrap/maxLines changes, not just new logs. ScrollArea
gained an optional viewportRef so the virtualizer can drive off the real Radix
scroll element. The per-row entrance fade is dropped (rows mount/unmount on
scroll); divide-y became a per-row border.
This commit is contained in:
DrSmoothl committed 2026-07-07 22:07:02 +08:00
1 parent 8fbcbd29ff
commit 4802dfe7aa
4 files changed
+126 -30

No files matched your search

+1
View File
@@ -20,6 +20,7 @@
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.9",
"@tanstack/react-router": "^1.169.2",
"@tanstack/react-virtual": "^3.14.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"gridstack": "^12.6.0",
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { motion, AnimatePresence } from 'motion/react';
import { ArrowDownToLine, Download, Filter, Highlighter, Inbox, Pause, Plus, RefreshCw, Search, SearchX, SlidersHorizontal, Trash2, WrapText, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -91,7 +92,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool
export function LogsPage() {
const api = useApi();
const { formatClock, appearance } = useTheme();
const { formatClock } = useTheme();
const { pages, setPages } = useLayout();
const prefs = pages.logs;
@@ -104,7 +105,7 @@ export function LogsPage() {
const [showOptions, setShowOptions] = useState(false);
const [newKeyword, setNewKeyword] = useState('');
const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id);
const endRef = useRef<HTMLDivElement | null>(null);
const scrollRef = useRef<HTMLDivElement | null>(null);
// maxLines is read through a ref so changing it doesn't re-subscribe the SSE.
const maxLines = prefs.maxLines;
@@ -179,11 +180,6 @@ export function LogsPage() {
};
}, [api]);
useEffect(() => {
if (!prefs.autoScroll) return;
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs, prefs.autoScroll]);
const filtered = useMemo(() => {
const f = filter.trim().toLowerCase();
const capped = logs.slice(-maxLines);
@@ -199,6 +195,40 @@ export function LogsPage() {
});
}, [logs, filter, enabled, maxLines]);
// Virtualize the log rows: only the visible window (+overscan) is mounted, so
// the DOM stays at a few dozen nodes regardless of how many lines the view
// holds. Rows are dynamically measured (measureElement) so wrap mode's
// variable-height lines are handled without a fixed row-height assumption.
const rowVirtualizer = useVirtualizer({
count: filtered.length,
getScrollElement: () => scrollRef.current,
estimateSize: () => 28,
overscan: 12,
// Key the size cache by row id, not index: the list is front-dropped at the
// maxLines cap, so every surviving row's index shifts down each flush. Keying
// by id keeps each measured height with its content (and matches the React
// key), avoiding a one-frame height mis-attribution on off-screen rows.
getItemKey: (index) => filtered[index]?.id ?? index,
});
// Toggling wrap changes every row's height — force a clean re-measure so the
// cached sizes don't leave gaps/overlaps.
useEffect(() => { rowVirtualizer.measure(); }, [prefs.wrap, rowVirtualizer]);
// Follow the tail while auto-scroll is on. Re-run on anything that changes the
// visible set or row heights (new logs, filter/level/maxLines → filtered.length,
// wrap → heights), not just new logs. Freshly-appended rows still carry the
// estimate on this pass, so a second pin on the next frame (after ResizeObserver
// measures them) reaches the true bottom in wrap mode.
useEffect(() => {
if (!prefs.autoScroll || filtered.length === 0) return;
const last = filtered.length - 1;
rowVirtualizer.scrollToIndex(last, { align: 'end' });
const raf = requestAnimationFrame(() => rowVirtualizer.scrollToIndex(last, { align: 'end' }));
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [logs, filtered.length, prefs.autoScroll, prefs.wrap]);
// Any hand edit to the bundled prefs drops the active preset to 'custom'.
const toggleLevel = (lv: LogLevel) => {
const next = new Set(enabled);
@@ -497,17 +527,18 @@ export function LogsPage() {
{/* ── Log stream ──────────────────────────────────────────── */}
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-muted/20">
<ScrollArea className="min-h-0 flex-1" viewportClassName="[&>div]:!block">
{/* Column header lives OUTSIDE the scroll viewport so the virtualizer's
scroll element contains only the rows (no sticky-offset math). */}
{filtered.length > 0 && (
<div className="hidden items-center gap-3 border-b border-border/60 bg-card/60 px-3 py-2 font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 sm:flex">
<span className="w-[104px] shrink-0">时间</span>
<span className="w-[76px] shrink-0">级别</span>
<span className="w-28 shrink-0">模块</span>
<span className="flex-1">消息</span>
</div>
)}
<ScrollArea viewportRef={scrollRef} className="min-h-0 flex-1" viewportClassName="[&>div]:!block">
<div className="font-mono text-xs">
{filtered.length > 0 && (
<div className="sticky top-0 z-10 hidden items-center gap-3 border-b border-border/60 bg-card/75 px-3 py-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 backdrop-blur-md sm:flex">
<span className="w-[104px] shrink-0">时间</span>
<span className="w-[76px] shrink-0">级别</span>
<span className="w-28 shrink-0">模块</span>
<span className="flex-1">消息</span>
</div>
)}
{filtered.length === 0 ? (
<div className="flex min-h-60 flex-col items-center justify-center gap-3 px-4 py-10 text-center font-sans text-muted-foreground">
{logs.length === 0 ? (
@@ -524,17 +555,21 @@ export function LogsPage() {
)}
</div>
) : (
<div className="divide-y divide-border/30">
{filtered.map((log) => {
<div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>
{rowVirtualizer.getVirtualItems().map((vRow) => {
const log = filtered[vRow.index];
if (!log) return null; // guard a transient count/measurement skew
const hl = matchHighlight(log.message, prefs.highlightRules);
return (
<motion.div
<div
key={log.id}
initial={appearance.disableMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
transition={appearance.disableMotion ? { duration: 0 } : { duration: 0.12 }}
className="flex flex-col gap-0.5 px-3 py-1.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-start sm:gap-3 sm:py-1"
style={hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : undefined}
data-index={vRow.index}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 flex w-full flex-col gap-0.5 border-b border-border/30 px-3 py-1.5 transition-colors hover:bg-accent/40 sm:flex-row sm:items-start sm:gap-3 sm:py-1"
style={{
transform: `translateY(${vRow.start}px)`,
...(hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : {}),
}}
>
<div className="flex items-center gap-3 sm:contents">
<span className="w-[104px] shrink-0 tabular-nums text-muted-foreground">{formatClock(log.time)}</span>
@@ -553,12 +588,11 @@ export function LogsPage() {
)}
{log.message}
</span>
</motion.div>
</div>
);
})}
</div>
)}
<div ref={endRef} />
</div>
</ScrollArea>
</div>
@@ -4,16 +4,20 @@ import { cn } from '@/lib/utils';
interface ScrollAreaProps extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
viewportClassName?: string;
/** Ref to the scrollable viewport element — needed to drive a virtualizer
* (TanStack Virtual's getScrollElement) off the actual scroll container. */
viewportRef?: React.Ref<HTMLDivElement>;
}
const ScrollArea = React.forwardRef<React.ElementRef<typeof ScrollAreaPrimitive.Root>, ScrollAreaProps>(
({ className, children, viewportClassName, ...props }, ref) => (
({ className, children, viewportClassName, viewportRef, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
ref={viewportRef}
className={cn('size-full rounded-[inherit] [&>div]:!block', viewportClassName)}
>
{children}
+59 -2
View File
@@ -379,6 +379,9 @@ importers:
'@tanstack/react-router':
specifier: ^1.169.2
version: 1.169.2([email protected]([email protected]))([email protected])
'@tanstack/react-virtual':
specifier: ^3.14.5
version: 3.14.5([email protected]([email protected]))([email protected])
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -1720,6 +1723,12 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/[email protected]':
resolution: {integrity: sha512-4EKRXh7zBLkbKbFmG3AUVkircuHd+7OdT1pocJSepxtfBd3qnrJgJ5rtPkRYyo9fmyVb2+pI2xPy5oYvMLQy6A==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/[email protected]':
resolution: {integrity: sha512-5sm0DJF1A7Mz+9gy4Gz/lLovNailK3yot4vYvz9MkBUPw26uLnhQiR8hSCYxucjE0wD6Mdlc5l+Z0/XTlZ7xHw==}
engines: {node: '>=20.19'}
@@ -1727,6 +1736,9 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
'@tanstack/[email protected]':
resolution: {integrity: sha512-8Np/TFELpI0ySuJoVmjvOrQYXH/8sTX0Biv9szhFhY39xOdAAY+smrMxjxOum/ux3eM8MUJQsEJ0/R0UpvC8dw==}
'@tybys/[email protected]':
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
@@ -4308,6 +4320,12 @@ snapshots:
react-dom: 19.2.5([email protected])
use-sync-external-store: 1.6.0([email protected])
'@tanstack/[email protected]([email protected]([email protected]))([email protected])':
dependencies:
'@tanstack/virtual-core': 3.17.3
react: 19.2.5
react-dom: 19.2.5([email protected])
'@tanstack/[email protected]':
dependencies:
'@tanstack/history': 1.161.6
@@ -4317,6 +4335,8 @@ snapshots:
'@tanstack/[email protected]': {}
'@tanstack/[email protected]': {}
'@tybys/[email protected]':
dependencies:
tslib: 2.8.1
@@ -4476,7 +4496,7 @@ snapshots:
magicast: 0.5.3
obug: 2.1.1
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@24.12.2)([email protected])([email protected])([email protected])([email protected]))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@25.6.0)([email protected])([email protected])([email protected])([email protected]))
transitivePeerDependencies:
- supports-color
@@ -4492,7 +4512,7 @@ snapshots:
obug: 2.1.1
std-env: 4.1.0
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@24.12.2)([email protected])([email protected])([email protected])([email protected]))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@25.6.0)([email protected])([email protected])([email protected])([email protected]))
'@vitest/[email protected]':
dependencies:
@@ -4511,6 +4531,14 @@ snapshots:
optionalDependencies:
vite: 8.1.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':
dependencies:
'@vitest/spy': 4.1.4
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.1.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
'@vitest/[email protected]':
dependencies:
tinyrainbow: 3.1.0
@@ -5813,6 +5841,35 @@ snapshots:
transitivePeerDependencies:
- msw
[email protected](@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):
dependencies:
'@vitest/expect': 4.1.4
'@vitest/mocker': 4.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
'@vitest/pretty-format': 4.1.4
'@vitest/runner': 4.1.4
'@vitest/snapshot': 4.1.4
'@vitest/spy': 4.1.4
'@vitest/utils': 4.1.4
es-module-lexer: 2.0.0
expect-type: 1.3.0
magic-string: 0.30.21
obug: 2.1.1
pathe: 2.0.3
picomatch: 4.0.4
std-env: 4.1.0
tinybench: 2.9.0
tinyexec: 1.1.1
tinyglobby: 0.2.16
tinyrainbow: 3.1.0
vite: 8.1.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 25.6.0
'@vitest/coverage-istanbul': 4.1.4([email protected])
'@vitest/coverage-v8': 4.1.4([email protected])
transitivePeerDependencies:
- msw
[email protected]:
dependencies:
'@types/fs-extra': 11.0.4