Files
SnowLuma/packages/webui/src/components/pages/logs-page.tsx
T
DrSmoothl 4802dfe7aa 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.
2026-07-07 22:07:02 +08:00

613 lines
29 KiB
TypeScript

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';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry, LogLevel, LogsPreset, UiHighlightRule } from '@/types';
import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
// Dedicated log-level text tokens (see index.css): the app accent colors are
// too light as small text on the light canvas (WCAG AA fails), so these hit
// >=4.5:1 in light mode while keeping the bright values in dark. trace stays the
// faintest level (dimmer than debug) but at /90 it now also clears AA.
const levelClass: Record<LogLevel, string> = {
trace: 'text-muted-foreground/90',
debug: 'text-muted-foreground',
info: 'text-log-info',
success: 'text-log-success',
warn: 'text-log-warn',
error: 'text-log-error',
};
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
// View presets bundle the display prefs (levels/maxLines/autoScroll/wrap). The
// server stores only the id; 'custom' (any hand-tuned state) has no bundle.
interface PresetBundle { visibleLevels: LogLevel[]; maxLines: number; autoScroll: boolean; wrap: boolean }
const LOG_PRESETS: { id: Exclude<LogsPreset, 'custom'>; label: string; hint: string; bundle: PresetBundle }[] = [
{ id: 'dev', label: '开发', hint: '全部级别 · 2000 行 · 换行', bundle: { visibleLevels: [...LEVELS], maxLines: 2000, autoScroll: true, wrap: true } },
{ id: 'ops', label: '运维', hint: 'INFO 以上 · 1000 行', bundle: { visibleLevels: ['info', 'success', 'warn', 'error'], maxLines: 1000, autoScroll: true, wrap: false } },
{ id: 'minimal', label: '精简', hint: '仅 WARN/ERROR · 500 行', bundle: { visibleLevels: ['warn', 'error'], maxLines: 500, autoScroll: true, wrap: false } },
];
// Highlight palette — keyword rules tint a matching row. Stored as an id.
const HIGHLIGHT_COLORS: { id: string; label: string; swatch: string }[] = [
{ id: 'amber', label: '琥珀', swatch: '#f59e0b' },
{ id: 'rose', label: '玫瑰', swatch: '#f43f5e' },
{ id: 'emerald', label: '翡翠', swatch: '#10b981' },
{ id: 'sky', label: '天蓝', swatch: '#38bdf8' },
{ id: 'violet', label: '紫', swatch: '#8b5cf6' },
];
const colorSwatch = (id: string) => HIGHLIGHT_COLORS.find((c) => c.id === id)?.swatch ?? '#f59e0b';
function matchHighlight(message: string, rules: UiHighlightRule[]): string | null {
if (rules.length === 0) return null;
const m = message.toLowerCase();
for (const r of rules) {
if (r.keyword && m.includes(r.keyword.toLowerCase())) return colorSwatch(r.color);
}
return null;
}
// Apple-style toolbar icon button: icon-only, tooltip-labelled, calm hover.
interface ToolButtonProps {
label: string;
onClick: () => void;
children: ReactNode;
active?: boolean;
danger?: boolean;
disabled?: boolean;
}
function ToolButton({ label, onClick, children, active, danger, disabled }: ToolButtonProps) {
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
aria-pressed={active}
className={cn(
'inline-flex size-8 items-center justify-center rounded-lg transition-colors cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:size-4',
active ? 'bg-primary/10 text-primary' : 'text-muted-foreground hover:bg-accent hover:text-foreground',
danger && !active && 'hover:bg-destructive/10 hover:text-destructive',
)}
>
{children}
</button>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
export function LogsPage() {
const api = useApi();
const { formatClock } = useTheme();
const { pages, setPages } = useLayout();
const prefs = pages.logs;
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [filter, setFilter] = useState('');
const [confirmClear, setConfirmClear] = useState(false);
const [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
const [levelBusy, setLevelBusy] = useState(false);
const [showOptions, setShowOptions] = useState(false);
const [newKeyword, setNewKeyword] = useState('');
const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id);
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;
const maxLinesRef = useRef(maxLines);
useEffect(() => { maxLinesRef.current = maxLines; }, [maxLines]);
const enabled = useMemo(() => new Set(prefs.visibleLevels as LogLevel[]), [prefs.visibleLevels]);
const loadLogs = useCallback(async () => {
try {
// Backfill is capped at the server's ring-buffer size (1000); `maxLines`
// can exceed that, but only the live SSE stream grows the view past 1000.
setLogs(await api.logs.list(Math.min(1000, maxLinesRef.current)));
} catch (e) {
console.error('logs', e);
}
}, [api]);
useEffect(() => { void loadLogs(); }, [loadLogs]);
useEffect(() => {
api.logs.getLevel().then(({ level }) => setServerLevel(level)).catch((err) => {
console.error('getLevel', err);
});
}, [api]);
const changeServerLevel = useCallback(async (lv: LogLevel) => {
if (lv === serverLevel || levelBusy) return;
setLevelBusy(true);
try {
const { level } = await api.logs.setLevel(lv);
setServerLevel(level);
} catch (err) {
console.error('setLevel', err);
} finally {
setLevelBusy(false);
}
}, [api, serverLevel, levelBusy]);
useEffect(() => {
// Batch incoming lines: buffer in a ref and flush on a ~80ms timer instead
// of a per-line setState. Under a high log rate this turns N O(n) array
// copies + N React commits per window into one. Dedup-by-id and the
// maxLines cap are preserved (a reconnect can replay recent ids).
let pending: LogEntry[] = [];
let flushTimer: number | null = null;
const flush = () => {
flushTimer = null;
if (pending.length === 0) return;
const batchMap = new Map(pending.map((e) => [e.id, e] as const));
pending = [];
setLogs((prev) => {
const kept = prev.length ? prev.filter((it) => !batchMap.has(it.id)) : prev;
const merged = kept.length ? [...kept, ...batchMap.values()] : [...batchMap.values()];
return merged.length > maxLinesRef.current ? merged.slice(-maxLinesRef.current) : merged;
});
};
const dispose = api.logs.stream({
onLine: (entry) => {
pending.push(entry);
if (flushTimer == null) flushTimer = window.setTimeout(flush, 80);
},
onStatus: (s) => {
if (s === 'open') setStreamStatus('实时');
else if (s === 'reconnecting') setStreamStatus('重连中');
else setStreamStatus('已断开');
},
});
return () => {
dispose();
if (flushTimer != null) clearTimeout(flushTimer);
};
}, [api]);
const filtered = useMemo(() => {
const f = filter.trim().toLowerCase();
const capped = logs.slice(-maxLines);
return capped.filter((l) => {
if (!enabled.has(l.level)) return false;
if (!f) return true;
return (
l.message.toLowerCase().includes(f) ||
l.scope.toLowerCase().includes(f) ||
l.level.toLowerCase().includes(f) ||
(l.req !== undefined && String(l.req).includes(f))
);
});
}, [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);
if (next.has(lv)) next.delete(lv); else next.add(lv);
setPages({ logs: { ...prefs, visibleLevels: LEVELS.filter((l) => next.has(l)), preset: 'custom' } });
};
const clearFilters = useCallback(() => {
setFilter('');
setPages({ logs: { ...prefs, visibleLevels: [...LEVELS], preset: 'custom' } });
}, [prefs, setPages]);
const applyPreset = useCallback((p: typeof LOG_PRESETS[number]) => {
setPages({ logs: { ...prefs, ...p.bundle, preset: p.id } });
}, [prefs, setPages]);
// Dump the current (filtered) view to a .log text file — purely client-side.
const exportLogs = useCallback(() => {
if (filtered.length === 0) return;
const lines = filtered.map(
(l) => l.line || `${l.time} ${l.level.toUpperCase().padEnd(7)} [${l.scope}] ${l.message}`,
);
const blob = new Blob([lines.join('\n') + '\n'], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
a.href = url;
a.download = `snowluma-logs-${ts}.log`;
a.click();
URL.revokeObjectURL(url);
}, [filtered]);
const addHighlight = () => {
const kw = newKeyword.trim();
if (!kw) return;
setPages({ logs: { ...prefs, highlightRules: [...prefs.highlightRules, { keyword: kw, color: newColor }].slice(0, 20) } });
setNewKeyword('');
};
const removeHighlight = (idx: number) => {
setPages({ logs: { ...prefs, highlightRules: prefs.highlightRules.filter((_, i) => i !== idx) } });
};
const live = streamStatus === '实时';
const connecting = streamStatus === '连接中' || streamStatus === '重连中';
const levelsFiltered = enabled.size < LEVELS.length;
return (
<Card className="flex h-[calc(100vh-7rem)] min-h-[480px] flex-col overflow-hidden">
{/* ── Toolbar ─────────────────────────────────────────────── */}
<CardHeader className="gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex items-center gap-2.5">
<CardTitle>运行日志</CardTitle>
<span className="inline-flex items-center gap-1.5 text-xs font-medium">
<span
className={cn(
'size-1.5 rounded-full',
live ? 'bg-success animate-pulse' : connecting ? 'bg-warning' : 'bg-destructive',
)}
/>
<span className={cn(live ? 'text-success' : connecting ? 'text-warning' : 'text-destructive')}>
{streamStatus}
</span>
</span>
</div>
<CardDescription className="text-xs">
{filtered.length}/{logs.length} 条 · SSE 实时推送
{serverLevel && (
<>
{' · 服务端 '}
<span className={cn('font-medium', levelClass[serverLevel])}>{serverLevel.toUpperCase()}</span>
</>
)}
</CardDescription>
</div>
<div className="flex flex-wrap items-center gap-1.5 sm:justify-end">
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="搜索消息 / 模块 / 级别"
value={filter}
onChange={(e) => setFilter(e.target.value)}
className="h-8 w-44 rounded-lg pl-8 pr-7 sm:w-56"
/>
{filter && (
<button
type="button"
onClick={() => setFilter('')}
aria-label="清除搜索"
className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/40 cursor-pointer"
>
<X className="size-3.5" />
</button>
)}
</div>
<div className="flex items-center gap-0.5 rounded-lg bg-muted/40 p-0.5">
<ToolButton
label={prefs.autoScroll ? '自动滚动已开启' : '自动滚动已暂停'}
active={prefs.autoScroll}
onClick={() => setPages({ logs: { ...prefs, autoScroll: !prefs.autoScroll, preset: 'custom' } })}
>
{prefs.autoScroll ? <ArrowDownToLine /> : <Pause />}
</ToolButton>
<ToolButton
label="自动换行"
active={prefs.wrap}
onClick={() => setPages({ logs: { ...prefs, wrap: !prefs.wrap, preset: 'custom' } })}
>
<WrapText />
</ToolButton>
<ToolButton label="显示选项" active={showOptions} onClick={() => setShowOptions((v) => !v)}>
<SlidersHorizontal />
</ToolButton>
</div>
<span className="mx-0.5 h-5 w-px bg-border/70" />
<ToolButton label="刷新" onClick={() => void loadLogs()}>
<RefreshCw />
</ToolButton>
<ToolButton label="导出当前视图" onClick={exportLogs} disabled={filtered.length === 0}>
<Download />
</ToolButton>
<ToolButton label="清空视图" danger onClick={() => setConfirmClear(true)}>
<Trash2 />
</ToolButton>
</div>
</CardHeader>
{/* ── Level filter (segmented, always visible) ────────────── */}
<div className="flex items-center gap-2 px-5 pb-3">
<Filter className={cn('size-3.5 shrink-0', levelsFiltered ? 'text-primary' : 'text-muted-foreground/60')} />
<div className="flex flex-wrap items-center gap-1 rounded-lg bg-muted/50 p-1">
{LEVELS.map((lv) => {
const active = enabled.has(lv);
return (
<button
key={lv}
type="button"
onClick={() => toggleLevel(lv)}
aria-pressed={active}
className={cn(
'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium transition-all cursor-pointer',
active
? cn('bg-card shadow-sm ring-1 ring-border/60', levelClass[lv])
: 'text-muted-foreground/55 hover:text-foreground',
)}
>
<span className={cn('size-1.5 rounded-full', active ? 'bg-current' : 'bg-muted-foreground/30')} />
{lv.toUpperCase()}
</button>
);
})}
</div>
</div>
{/* ── Options panel (progressive disclosure) ──────────────── */}
<AnimatePresence initial={false}>
{showOptions && (
<motion.div
key="options"
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
className="overflow-hidden"
>
<div className="mx-5 mb-3 flex flex-col gap-4 rounded-xl border bg-muted/20 p-4">
{/* View presets */}
<div>
<div className="mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
<SlidersHorizontal className="size-3.5 text-muted-foreground" />
<span className="text-xs font-medium text-foreground">视图预设</span>
<span className="text-[10px] text-muted-foreground">· 一键套用级别 / 行数 / 换行;手动调整后变为「自定义」</span>
</div>
<div className="inline-flex flex-wrap gap-1 rounded-lg bg-muted/60 p-1">
{LOG_PRESETS.map((p) => {
const active = prefs.preset === p.id;
return (
<button
key={p.id}
type="button"
onClick={() => applyPreset(p)}
aria-pressed={active}
title={p.hint}
className={cn(
'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium transition-all cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
active ? 'bg-card text-foreground shadow-sm ring-1 ring-border/60' : 'text-muted-foreground/70 hover:text-foreground',
)}
>
{p.label}
</button>
);
})}
<span
className={cn(
'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium',
prefs.preset === 'custom' ? 'bg-card text-foreground shadow-sm ring-1 ring-border/60' : 'text-muted-foreground/40',
)}
>
自定义
</span>
</div>
</div>
{/* Server-side level */}
<div>
<div className="mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
<span className="text-xs font-medium text-foreground">服务端日志级别</span>
<span className="text-[10px] text-muted-foreground">· 仅影响控制台 / 实时流,文件始终落盘 debug</span>
</div>
<div className="inline-flex flex-wrap gap-1 rounded-lg bg-muted/60 p-1">
{LEVELS.map((lv) => {
const active = serverLevel === lv;
return (
<button
key={lv}
type="button"
onClick={() => void changeServerLevel(lv)}
disabled={levelBusy || serverLevel === null}
aria-pressed={active}
className={cn(
'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:opacity-50',
active
? cn('bg-card shadow-sm ring-1 ring-border/60', levelClass[lv])
: 'text-muted-foreground/70 hover:text-foreground',
)}
>
<span className={cn('size-1.5 rounded-full', active ? 'bg-current' : 'bg-muted-foreground/30')} />
{lv.toUpperCase()}
</button>
);
})}
</div>
</div>
{/* Highlight rules */}
<div>
<div className="mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
<Highlighter className="size-3.5 text-muted-foreground" />
<span className="text-xs font-medium text-foreground">高亮规则</span>
<span className="text-[10px] text-muted-foreground">· 命中关键词的行会被着色</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<Input
placeholder="高亮关键词"
value={newKeyword}
maxLength={50}
onChange={(e) => setNewKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') addHighlight(); }}
className="h-8 w-44 rounded-lg"
/>
<div className="flex items-center gap-1" role="radiogroup" aria-label="高亮颜色">
{HIGHLIGHT_COLORS.map((c) => (
<button
key={c.id}
type="button"
role="radio"
aria-checked={newColor === c.id}
onClick={() => setNewColor(c.id)}
title={c.label}
aria-label={c.label}
className={cn(
'size-6 rounded-full border transition-transform hover:scale-110 cursor-pointer',
newColor === c.id ? 'ring-2 ring-offset-1 ring-foreground/40' : 'border-border',
)}
style={{ backgroundColor: c.swatch }}
/>
))}
</div>
<Button variant="outline" size="sm" onClick={addHighlight} disabled={!newKeyword.trim()} className="rounded-lg">
<Plus className="size-3.5" /> 添加
</Button>
</div>
{prefs.highlightRules.length > 0 && (
<div className="mt-2.5 flex flex-wrap gap-1.5">
{prefs.highlightRules.map((r, i) => (
<span key={i} className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px]" style={{ borderColor: colorSwatch(r.color) }}>
<span className="size-2 rounded-full" style={{ backgroundColor: colorSwatch(r.color) }} />
{r.keyword}
<button type="button" onClick={() => removeHighlight(i)} className="text-muted-foreground hover:text-destructive cursor-pointer" aria-label={`移除高亮规则 ${r.keyword}`}>
<X className="size-3" />
</button>
</span>
))}
</div>
)}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
{/* ── 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">
{/* 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="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 ? (
<>
<Inbox className="size-9 opacity-30" />
<span className="text-sm">暂无日志</span>
</>
) : (
<>
<SearchX className="size-9 opacity-30" />
<span className="text-sm">没有符合筛选条件的日志</span>
<Button variant="outline" size="sm" onClick={clearFilters} className="rounded-lg">清除筛选</Button>
</>
)}
</div>
) : (
<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 (
<div
key={log.id}
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>
<span className={cn('flex w-[76px] shrink-0 items-center gap-1.5 font-semibold', levelClass[log.level])}>
<span className="size-1.5 shrink-0 rounded-full bg-current" />
{log.level.toUpperCase()}
</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground sm:w-28 sm:flex-none sm:shrink-0">[{log.scope}]</span>
</div>
<span
className={cn('min-w-0 flex-1 leading-5', prefs.wrap ? 'whitespace-pre-wrap break-all' : 'truncate')}
title={prefs.wrap ? undefined : log.message}
>
{log.req !== undefined && (
<span className="mr-1.5 rounded bg-primary/10 px-1 text-[10px] text-primary tabular-nums" title="请求关联号">#{log.req}</span>
)}
{log.message}
</span>
</div>
);
})}
</div>
)}
</div>
</ScrollArea>
</div>
</CardContent>
<ConfirmDialog
open={confirmClear}
onOpenChange={setConfirmClear}
title="清空当前日志视图?"
description="此操作仅清空浏览器视图中的日志,不会影响服务端的日志缓冲区。"
confirmText="清空"
destructive
onConfirm={() => setLogs([])}
/>
</Card>
);
}