feat(webui): per-widget config — alerts levels/count, sessions sort/filter (phase 5)

Overview widgets can carry an opaque `config` (stored per grid item). v1:
- alerts: how many entries + which log levels (was fixed at 5 warn/error);
  the alert row colour now uses the full 6-level palette instead of a
  warn/error binary.
- sessions: sort (recent / uin / nickname) + a nickname/uin filter.

A gear in the layout editor opens an inline config form per configurable
widget; edits apply live (no grid re-init — config isn't in the grid key) and
persist via the section-merge save. Config is parsed client-side with total,
clamping parsers (count 1-50, known levels only, filter <=100 chars); the
server stores it opaquely within a 4KB bound. Widgets with no config render
exactly as before. Verified across 2 adversarial review rounds.
This commit is contained in:
DrSmoothl committed 2026-06-13 21:17:23 +08:00
1 parent f07f309c51
commit 3258300539
6 files changed
+233 -50

No files matched your search

@@ -16,7 +16,7 @@ interface DashboardGridProps {
cols: number;
/** Fired (debounced upstream) after a drag/resize settles. */
onChange: (coords: GridCoord[]) => void;
renderWidget: (id: string) => ReactNode;
renderWidget: (block: UiLayoutItem) => ReactNode;
}
/**
@@ -98,7 +98,7 @@ export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }:
contentEls[b.id]
? createPortal(
<div className={cn('h-full w-full overflow-auto', editing && 'pointer-events-none select-none')}>
{renderWidget(b.id)}
{renderWidget(b)}
</div>,
contentEls[b.id],
)
@@ -1,11 +1,18 @@
import { useMemo } from 'react';
import { useMemo, useState } from 'react';
import { Reorder } from 'motion/react';
import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw } from 'lucide-react';
import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw, Settings2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import {
ALL_LOG_LEVELS, CONFIGURABLE_WIDGETS, parseAlertsConfig, parseSessionsConfig,
} from '@/lib/dashboard-layout';
import type { UiLayoutItem } from '@/types';
type SortOpt = 'recent' | 'uin' | 'nickname';
const SORT_LABELS: Record<SortOpt, string> = { recent: '最近', uin: 'QQ 号', nickname: '昵称' };
// Edit panel for the overview's "编辑布局" mode. Overview-card POSITION/SIZE is
// edited in place on the gridstack grid below; this panel only toggles which
// cards are shown, and (re)orders the sidebar nav (a 1-D list, so it keeps the
@@ -13,31 +20,126 @@ import type { UiLayoutItem } from '@/types';
// ── widget visibility (no drag — grid owns position) ──
function AlertsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseAlertsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<label className="flex items-center justify-between gap-3 text-xs">
<span className="text-muted-foreground">显示条数</span>
<Input
type="number" min={1} max={50} value={c.count}
onChange={(e) => onChange({ count: Math.min(50, Math.max(1, Math.trunc(Number(e.target.value) || 1))) })}
className="h-8 w-20"
/>
</label>
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">级别</span>
<div className="flex flex-wrap gap-1.5">
{ALL_LOG_LEVELS.map((lv) => {
const on = c.levels.includes(lv);
return (
<button
key={lv}
type="button"
onClick={() => {
const next = on ? c.levels.filter((x) => x !== lv) : [...c.levels, lv];
if (next.length > 0) onChange({ levels: next });
}}
className={cn(
'rounded-md border px-2 py-1 text-[11px] uppercase transition-colors cursor-pointer',
on ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{lv}
</button>
);
})}
</div>
</div>
</div>
);
}
function SessionsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseSessionsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">排序</span>
<div className="flex flex-wrap gap-1.5">
{(['recent', 'uin', 'nickname'] as SortOpt[]).map((s) => (
<button
key={s}
type="button"
onClick={() => onChange({ sort: s })}
className={cn(
'rounded-md border px-2 py-1 text-[11px] transition-colors cursor-pointer',
c.sort === s ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{SORT_LABELS[s]}
</button>
))}
</div>
</div>
<label className="flex flex-col gap-1.5 text-xs">
<span className="text-muted-foreground">筛选(昵称 / QQ 号)</span>
<Input value={c.filter} placeholder="留空显示全部" maxLength={100} onChange={(e) => onChange({ filter: e.target.value })} className="h-8" />
</label>
</div>
);
}
function VisibilityList({
items, labelFor, onToggle,
}: { items: UiLayoutItem[]; labelFor: (id: string) => string; onToggle: (id: string) => void }) {
items, labelFor, onToggle, onConfig,
}: {
items: UiLayoutItem[];
labelFor: (id: string) => string;
onToggle: (id: string) => void;
onConfig: (id: string, config: Record<string, unknown>) => void;
}) {
const [open, setOpen] = useState<string | null>(null);
return (
<div className="flex flex-col gap-2">
{items.map((item) => (
<div
key={item.id}
className={cn(
'flex items-center gap-3 rounded-lg border bg-card/50 px-3 py-2.5',
!item.visible && 'opacity-50',
)}
>
<span className="flex-1 truncate text-sm font-medium">{labelFor(item.id)}</span>
<button
type="button"
onClick={() => onToggle(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
>
{item.visible ? <Eye className="size-4" /> : <EyeOff className="size-4" />}
</button>
</div>
))}
{items.map((item) => {
const configurable = CONFIGURABLE_WIDGETS.has(item.id);
const isOpen = open === item.id;
return (
<div key={item.id} className={cn('overflow-hidden rounded-lg border bg-card/50', !item.visible && 'opacity-50')}>
<div className="flex items-center gap-3 px-3 py-2.5">
<span className="flex-1 truncate text-sm font-medium">{labelFor(item.id)}</span>
{configurable && (
<button
type="button"
onClick={() => setOpen(isOpen ? null : item.id)}
title="设置"
aria-label="设置"
className={cn(
'inline-flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors hover:bg-accent/40',
isOpen ? 'text-primary' : 'text-muted-foreground hover:text-foreground',
)}
>
<Settings2 className="size-4" />
</button>
)}
<button
type="button"
onClick={() => onToggle(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
>
{item.visible ? <Eye className="size-4" /> : <EyeOff className="size-4" />}
</button>
</div>
{configurable && isOpen && (
item.id === 'alerts'
? <AlertsConfigForm config={item.config} onChange={(c) => onConfig('alerts', c)} />
: <SessionsConfigForm config={item.config} onChange={(c) => onConfig('sessions', c)} />
)}
</div>
);
})}
</div>
);
}
@@ -102,13 +204,14 @@ export interface LayoutEditorProps {
navLabelFor: (id: string) => string;
navPinned: readonly string[];
onToggleBlock: (id: string) => void;
onBlockConfig: (id: string, config: Record<string, unknown>) => void;
onNav: (items: UiLayoutItem[]) => void;
onReset: () => void;
onDone: () => void;
}
export function LayoutEditor({
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onNav, onReset, onDone,
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onBlockConfig, onNav, onReset, onDone,
}: LayoutEditorProps) {
return (
<Card>
@@ -128,8 +231,8 @@ export function LayoutEditor({
</CardHeader>
<CardContent className="grid gap-6 md:grid-cols-2">
<div className="flex flex-col gap-2">
<p className="text-xs font-medium text-muted-foreground">总览卡片(显隐)</p>
<VisibilityList items={blocks} labelFor={blockLabelFor} onToggle={onToggleBlock} />
<p className="text-xs font-medium text-muted-foreground">总览卡片(显隐 / 设置)</p>
<VisibilityList items={blocks} labelFor={blockLabelFor} onToggle={onToggleBlock} onConfig={onBlockConfig} />
</div>
<div className="flex flex-col gap-2">
<p className="text-xs font-medium text-muted-foreground">导航栏(拖动排序)</p>
@@ -13,14 +13,17 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { AppPath } from '@/router';
import type { AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types';
import type { AdapterStatus, AdapterStatusLevel, LogEntry, LogLevel, UiLayoutItem } from '@/types';
import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
import { useTheme } from '@/contexts/ThemeContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query';
import { GRID_COLS, widgetLabel } from '@/lib/dashboard-layout';
import {
GRID_COLS, parseAlertsConfig, parseSessionsConfig, widgetLabel,
type AlertsConfig, type SessionsConfig,
} from '@/lib/dashboard-layout';
import { NAV_ITEMS, PINNED_NAV } from '@/components/layout/sidebar';
import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid';
import { LayoutEditor } from '@/components/pages/overview-layout-editor';
@@ -31,13 +34,13 @@ function qqAvatarUrl(uin: string) {
const navLabelFor = (id: string) => NAV_ITEMS.find((n) => n.to === id)?.label ?? id;
function renderWidget(id: string): ReactNode {
if (id.startsWith('stat:')) return <StatTileWidget id={id} />;
switch (id) {
function renderWidget(block: UiLayoutItem): ReactNode {
if (block.id.startsWith('stat:')) return <StatTileWidget id={block.id} />;
switch (block.id) {
case 'connections': return <ConnectionsBlock />;
case 'alerts': return <RecentAlertsCard />;
case 'alerts': return <RecentAlertsCard config={parseAlertsConfig(block.config)} />;
case 'host': return <HostBlock />;
case 'sessions': return <SessionsBlock />;
case 'sessions': return <SessionsBlock config={parseSessionsConfig(block.config)} />;
default: return null;
}
}
@@ -68,6 +71,9 @@ export function OverviewPage() {
const toggleBlock = (id: string) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b)));
const setBlockConfig = (id: string, config: Record<string, unknown>) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b)));
const loadableProcs = processList.filter((p) => !p.injected).length;
return (
@@ -89,6 +95,7 @@ export function OverviewPage() {
navLabelFor={navLabelFor}
navPinned={PINNED_NAV}
onToggleBlock={toggleBlock}
onBlockConfig={setBlockConfig}
onNav={setNavItems}
onReset={resetLayout}
onDone={() => setEditingOn(false)}
@@ -348,24 +355,37 @@ function HostBlock() {
// ─────────────── online sessions ───────────────
function SessionsBlock() {
function SessionsBlock({ config }: { config: SessionsConfig }) {
const { qqList } = useAppState();
const list = useMemo(() => {
const f = config.filter.trim().toLowerCase();
let arr = f
? qqList.filter((q) => (q.nickname ?? '').toLowerCase().includes(f) || q.uin.includes(f))
: qqList;
if (config.sort === 'uin') arr = [...arr].sort((a, b) => a.uin.localeCompare(b.uin, undefined, { numeric: true }));
else if (config.sort === 'nickname') arr = [...arr].sort((a, b) => (a.nickname ?? '').localeCompare(b.nickname ?? ''));
// 'recent' keeps the server/insertion order.
return arr;
}, [qqList, config.sort, config.filter]);
return (
<Card className="flex h-full flex-col">
<CardHeader>
<CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription>
<CardDescription>
当前已接入并完成登录的 QQ 账号{config.filter.trim() ? `(筛选:${config.filter.trim()})` : ''}
</CardDescription>
</CardHeader>
<CardContent className="min-h-0 flex-1">
{qqList.length === 0 ? (
{list.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Users className="size-7" strokeWidth={1.5} />
<p className="text-sm">暂无在线会话</p>
<p className="text-sm">{qqList.length === 0 ? '暂无在线会话' : '无匹配的会话'}</p>
</div>
) : (
<ScrollArea className="h-full" viewportClassName="[&>div]:!block">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
{qqList.map((q, idx) => (
{list.map((q, idx) => (
<motion.div
key={q.uin}
initial={{ opacity: 0, y: 6 }}
@@ -463,28 +483,40 @@ function ConnectionsBlock() {
// ─────────────── recent alerts ───────────────
function RecentAlertsCard() {
const ALERT_LEVEL_CLASS: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
warn: 'text-warning',
error: 'text-destructive',
};
function RecentAlertsCard({ config }: { config: AlertsConfig }) {
const api = useApi();
const { formatClock } = useTheme();
const [alerts, setAlerts] = useState<LogEntry[]>([]);
const { count } = config;
const levelsKey = config.levels.join(',');
useEffect(() => {
const levels = new Set(levelsKey.split(',') as LogLevel[]);
let active = true;
api.logs
.list(200)
.list(Math.max(200, count * 4))
.then((list) => {
if (!active) return;
setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5));
setAlerts(list.filter((l) => levels.has(l.level)).slice(-count));
})
.catch(() => { /* ignore */ });
const stop = api.logs.stream({
onLine: (entry) => {
if (entry.level !== 'warn' && entry.level !== 'error') return;
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5));
if (!levels.has(entry.level)) return;
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-count));
},
});
return () => { active = false; stop(); };
}, [api]);
}, [api, count, levelsKey]);
return (
<Card className="flex h-full flex-col">
@@ -493,7 +525,7 @@ function RecentAlertsCard() {
<CardTitle className="flex items-center gap-2">
<Bell className="size-4 text-primary" /> 最近告警
</CardTitle>
<CardDescription>最近的 warn / error 级别日志</CardDescription>
<CardDescription>最近 {count} 条 · {config.levels.map((l) => l.toUpperCase()).join(' / ')}</CardDescription>
</div>
<Link to="/logs" className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
查看日志 <ArrowRight className="size-3" />
@@ -510,7 +542,7 @@ function RecentAlertsCard() {
{alerts.map((a) => (
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(a.time)}</span>
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
<span className={cn('shrink-0 font-semibold', ALERT_LEVEL_CLASS[a.level])}>
{a.level.toUpperCase()}
</span>
<span className="min-w-0 flex-1 truncate" title={a.message}>[{a.scope}] {a.message}</span>