feat(webui): customizable dashboard + nav layout (phase 3)

The "C" half — reorder + show/hide the overview cards and the sidebar nav,
persisted to config/ui.json's layout section.

- LayoutContext loads the layout (authed GET /api/ui) and persists edits via
  the section-merge POST /api/ui {layout} (debounced). reconcileLayoutItems
  keeps stored order/visibility, appends new catalogue entries (forward-compat),
  and forces pinned items visible.
- Overview is refactored into a block registry (stats/connections/alerts/host/
  sessions). A 「编辑布局」 mode (motion Reorder — zero new deps) edits both the
  cards and the nav in place, with per-item show/hide and a reset; an all-hidden
  dashboard shows an empty state with 恢复默认.
- Anti-self-lock: PINNED_NAV = ['/', '/settings'] can be reordered but never
  hidden — the overview hosts the layout editor and settings hosts
  account/appearance, so the user can never strand themselves.
- api.ui.save now takes Partial<UiConfig> (the section-merge contract).

A late initial GET can't clobber an in-flight edit (dirtyRef); a pending edit
flushes on unmount. Verified across 2 adversarial review rounds.
This commit is contained in:
DrSmoothl committed 2026-06-13 01:15:00 +08:00
1 parent ac1ffc46d3
commit 69ed8fc722
6 files changed
+613 -225

No files matched your search

@@ -6,6 +6,7 @@ import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import type { AppPath } from '@/router';
export interface NavItem {
@@ -23,6 +24,12 @@ export const NAV_ITEMS: NavItem[] = [
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
];
// Anti-self-lock: these nav items can be reordered but never hidden.
// '/' — hosts the 「编辑布局」 entry point; hiding it would strand the
// user with no way back to un-hide anything.
// '/settings'— account + appearance.
export const PINNED_NAV: AppPath[] = ['/', '/settings'];
interface SidebarProps {
collapsed?: boolean;
onItemClick?: () => void;
@@ -31,6 +38,14 @@ interface SidebarProps {
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const { updateInfo } = useAppState();
const { navItems } = useLayout();
// Render nav in the operator's configured order, hidden items removed,
// pinned items forced on, and forward-compatible with future routes.
const orderedNav = reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV)
.filter((i) => i.visible)
.map((i) => NAV_ITEMS.find((n) => n.to === i.id))
.filter((n): n is NavItem => !!n);
return (
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
@@ -53,7 +68,7 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
{/* Nav */}
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{NAV_ITEMS.map(({ to, label, icon: Icon, description }) => {
{orderedNav.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<Link
@@ -0,0 +1,126 @@
import { useMemo } from 'react';
import { Reorder } from 'motion/react';
import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import type { UiLayoutItem } from '@/types';
// In-place layout editor for the overview page: two drag-to-reorder lists
// (overview cards + sidebar nav) with per-item show/hide. Uses motion's
// `Reorder` (zero new deps). Pinned items can be reordered but not hidden.
// Edits apply live through the LayoutContext setters (debounced-persisted), so
// "完成" just leaves edit mode.
interface ReorderListProps {
items: UiLayoutItem[];
labelFor: (id: string) => string;
pinned?: readonly string[];
onChange: (items: UiLayoutItem[]) => void;
}
function ReorderList({ items, labelFor, pinned = [], onChange }: ReorderListProps) {
const ids = useMemo(() => items.map((i) => i.id), [items]);
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items]);
const reorder = (newIds: string[]) => {
onChange(newIds.map((id) => byId.get(id)).filter((x): x is UiLayoutItem => !!x));
};
const toggle = (id: string) => {
onChange(items.map((i) => (i.id === id ? { ...i, visible: !i.visible } : i)));
};
return (
<Reorder.Group axis="y" values={ids} onReorder={reorder} className="flex flex-col gap-2">
{ids.map((id) => {
const item = byId.get(id);
if (!item) return null;
const isPinned = pinned.includes(id);
return (
<Reorder.Item
key={id}
value={id}
className={cn(
'flex items-center gap-3 rounded-lg border bg-card/50 px-3 py-2.5 select-none',
'cursor-grab active:cursor-grabbing',
!item.visible && 'opacity-50',
)}
>
<GripVertical className="size-4 shrink-0 text-muted-foreground" />
<span className="flex-1 truncate text-sm font-medium">{labelFor(id)}</span>
{isPinned ? (
<span title="必选项,不可隐藏" className="inline-flex size-8 items-center justify-center text-muted-foreground/60">
<Lock className="size-4" />
</span>
) : (
<button
type="button"
onClick={() => toggle(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>
)}
</Reorder.Item>
);
})}
</Reorder.Group>
);
}
export interface LayoutEditorProps {
blocks: UiLayoutItem[];
blockLabelFor: (id: string) => string;
navItems: UiLayoutItem[];
navLabelFor: (id: string) => string;
navPinned: readonly string[];
onBlocks: (items: UiLayoutItem[]) => void;
onNav: (items: UiLayoutItem[]) => void;
onReset: () => void;
onDone: () => void;
}
export function LayoutEditor({
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onBlocks, onNav, onReset, onDone,
}: LayoutEditorProps) {
return (
<div className="flex flex-col gap-5">
<div className="flex items-center justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">编辑布局</h2>
<p className="text-[11px] text-muted-foreground">拖动排序,点眼睛图标显示/隐藏。改动会自动保存。</p>
</div>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" onClick={onReset} className="text-muted-foreground">
<RotateCcw className="size-4" /> 恢复默认
</Button>
<Button size="sm" onClick={onDone}>
<Check className="size-4" /> 完成
</Button>
</div>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">总览卡片</CardTitle>
<CardDescription>调整总览页各卡片的顺序与显隐。</CardDescription>
</CardHeader>
<CardContent>
<ReorderList items={blocks} labelFor={blockLabelFor} onChange={onBlocks} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">导航栏</CardTitle>
<CardDescription>调整左侧导航的顺序与显隐(「系统设置」固定保留)。</CardDescription>
</CardHeader>
<CardContent>
<ReorderList items={navItems} labelFor={navLabelFor} pinned={navPinned} onChange={onNav} />
</CardContent>
</Card>
</div>
);
}
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { Link } from '@tanstack/react-router';
import {
@@ -9,6 +9,7 @@ import {
Cpu,
MemoryStick,
MonitorCog,
Pencil,
PlugZap,
RefreshCw,
Server,
@@ -27,11 +28,121 @@ 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 { NAV_ITEMS, PINNED_NAV } from '@/components/layout/sidebar';
import { LayoutEditor } from '@/components/pages/overview-layout-editor';
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
// ─────────────── overview block registry ───────────────
const BLOCK_META: { id: string; label: string }[] = [
{ id: 'stats', label: '概览指标' },
{ id: 'connections', label: 'OneBot 连接' },
{ id: 'alerts', label: '最近告警' },
{ id: 'host', label: '主机资源' },
{ id: 'sessions', label: '在线会话' },
];
const BLOCK_IDS = BLOCK_META.map((b) => b.id);
const blockLabelFor = (id: string) => BLOCK_META.find((b) => b.id === id)?.label ?? id;
const navLabelFor = (id: string) => NAV_ITEMS.find((n) => n.to === id)?.label ?? id;
function renderBlock(id: string): ReactNode {
switch (id) {
case 'stats': return <StatsBlock />;
case 'connections': return <ConnectionsBlock />;
case 'alerts': return <RecentAlertsCard />;
case 'host': return <HostBlock />;
case 'sessions': return <SessionsBlock />;
default: return null;
}
}
export function OverviewPage() {
const { qqList, processList } = useAppState();
const { overviewBlocks, navItems, setOverviewBlocks, setNavItems, resetLayout } = useLayout();
const [editing, setEditing] = useState(false);
const blocks = useMemo(() => reconcileLayoutItems(overviewBlocks, BLOCK_IDS), [overviewBlocks]);
const nav = useMemo(
() => reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV),
[navItems],
);
if (editing) {
return (
<LayoutEditor
blocks={blocks}
blockLabelFor={blockLabelFor}
navItems={nav}
navLabelFor={navLabelFor}
navPinned={PINNED_NAV}
onBlocks={setOverviewBlocks}
onNav={setNavItems}
onReset={resetLayout}
onDone={() => setEditing(false)}
/>
);
}
const loadableProcs = processList.filter((p) => !p.injected).length;
const visibleBlocks = blocks.filter((b) => b.visible);
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-end">
<Button variant="outline" size="sm" onClick={() => setEditing(true)}>
<Pencil className="size-3.5" /> 编辑布局
</Button>
</div>
{/* First-run nudge: nothing online yet → point at the injection page.
Always shown (not a reorderable block) so it can't be hidden away. */}
{qqList.length === 0 && (
<motion.div initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}>
<Link
to="/processes"
className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 px-4 py-3 transition-colors hover:bg-primary/10"
>
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
<PlugZap className="size-5" />
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">
{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}
</p>
<p className="text-[11px] text-muted-foreground">
前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。
</p>
</div>
<ArrowRight className="size-4 shrink-0 text-primary" />
</Link>
</motion.div>
)}
{visibleBlocks.length === 0 ? (
<EmptyLayout onReset={resetLayout} />
) : (
visibleBlocks.map((b) => <div key={b.id}>{renderBlock(b.id)}</div>)
)}
</div>
);
}
function EmptyLayout({ onReset }: { onReset: () => void }) {
return (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
<MonitorCog className="size-8" strokeWidth={1.5} />
<p className="text-sm">所有总览卡片都已隐藏</p>
<Button variant="outline" size="sm" onClick={onReset}>恢复默认布局</Button>
</div>
);
}
// ─────────────── stat tiles ───────────────
function StatTile({
icon,
label,
@@ -77,8 +188,8 @@ function StatTile({
return <Card className="overflow-hidden">{body}</Card>;
}
export function OverviewPage() {
const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState();
function StatsBlock() {
const { qqList, processList, systemInfo } = useAppState();
const { status } = useSession();
// Lightweight tick to refresh "uptime" pretty-print every 30s
@@ -89,223 +200,202 @@ export function OverviewPage() {
}, []);
const online = status === '已连接';
// Read-only injection health for the dashboard. Control lives on /processes.
const onlineProcs = processList.filter((p) => p.status === 'online').length;
const loadableProcs = processList.filter((p) => !p.injected).length;
return (
<div className="flex flex-col gap-6">
{/* Top stats */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-5">
<StatTile
icon={<Activity className="size-5" />}
label="服务状态"
value={online ? '运行中' : status}
subtext={online ? '已连接到后端' : '请检查后端进程'}
accent={online}
/>
<StatTile
icon={<Users className="size-5" />}
label="在线账号"
value={qqList.length}
subtext={`已接入 ${qqList.length} 个会话`}
/>
<StatTile
icon={<PlugZap className="size-5" />}
label="进程注入"
value={`${onlineProcs} 在线`}
subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`}
to="/processes"
/>
<StatTile
icon={<Server className="size-5" />}
label="主机名"
value={systemInfo?.hostname ?? '—'}
subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'}
/>
<StatTile
icon={<MonitorCog className="size-5" />}
label="系统运行"
value={systemInfo ? formatUptime(systemInfo.uptime) : '—'}
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
/>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-5">
<StatTile
icon={<Activity className="size-5" />}
label="服务状态"
value={online ? '运行中' : status}
subtext={online ? '已连接到后端' : '请检查后端进程'}
accent={online}
/>
<StatTile
icon={<Users className="size-5" />}
label="在线账号"
value={qqList.length}
subtext={`已接入 ${qqList.length} 个会话`}
/>
<StatTile
icon={<PlugZap className="size-5" />}
label="进程注入"
value={`${onlineProcs} 在线`}
subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`}
to="/processes"
/>
<StatTile
icon={<Server className="size-5" />}
label="主机名"
value={systemInfo?.hostname ?? '—'}
subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'}
/>
<StatTile
icon={<MonitorCog className="size-5" />}
label="系统运行"
value={systemInfo ? formatUptime(systemInfo.uptime) : '—'}
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
/>
</div>
);
}
{/* First-run nudge: nothing online yet → point at the injection page. */}
{qqList.length === 0 && (
<motion.div initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}>
<Link
to="/processes"
className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 px-4 py-3 transition-colors hover:bg-primary/10"
>
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
<PlugZap className="size-5" />
// ─────────────── host resources ───────────────
function HostBlock() {
const { systemInfo, refreshSystem } = useAppState();
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle>主机资源</CardTitle>
<CardDescription>
{systemInfo
? `${systemInfo.cpu.model.trim()} · ${systemInfo.cpu.cores} 核 · Node ${systemInfo.nodeVersion}`
: '正在采集主机信息…'}
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={refreshSystem}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-3">
{/* CPU */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<Cpu className="size-4 text-primary" />
<span className="text-sm font-semibold">CPU 使用率</span>
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">
{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}
</p>
<p className="text-[11px] text-muted-foreground">
前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。
</p>
</div>
<ArrowRight className="size-4 shrink-0 text-primary" />
</Link>
</motion.div>
)}
{/* Operational health — connection status + recent alerts (side by side on wide screens) */}
<div className="grid gap-6 xl:grid-cols-2">
<ConnectionsCard connections={connections} />
<RecentAlertsCard />
</div>
{/* System metrics */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle>主机资源</CardTitle>
<CardDescription>
{systemInfo
? `${systemInfo.cpu.model.trim()} · ${systemInfo.cpu.cores} 核 · Node ${systemInfo.nodeVersion}`
: '正在采集主机信息…'}
</CardDescription>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.cpu.average.toFixed(1)}%` : '—'}
</span>
</div>
<Button variant="outline" size="sm" onClick={refreshSystem}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-3">
{/* CPU */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<Cpu className="size-4 text-primary" />
<span className="text-sm font-semibold">CPU 使用率</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.cpu.average.toFixed(1)}%` : '—'}
</span>
</div>
<Progress value={systemInfo?.cpu.average ?? 0} />
<p className="mt-2 text-[11px] text-muted-foreground">
负载: {systemInfo ? systemInfo.cpu.loadAvg.map((v) => v.toFixed(2)).join(' / ') : '—'}
</p>
{systemInfo && systemInfo.cpu.perCore.length > 0 && (
<div className="mt-3 grid grid-cols-8 gap-1">
{systemInfo.cpu.perCore.map((p, i) => (
<Progress value={systemInfo?.cpu.average ?? 0} />
<p className="mt-2 text-[11px] text-muted-foreground">
负载: {systemInfo ? systemInfo.cpu.loadAvg.map((v) => v.toFixed(2)).join(' / ') : '—'}
</p>
{systemInfo && systemInfo.cpu.perCore.length > 0 && (
<div className="mt-3 grid grid-cols-8 gap-1">
{systemInfo.cpu.perCore.map((p, i) => (
<div
key={i}
title={`Core ${i}: ${p.toFixed(1)}%`}
className="h-6 rounded-sm bg-muted overflow-hidden flex items-end"
>
<div
key={i}
title={`Core ${i}: ${p.toFixed(1)}%`}
className="h-6 rounded-sm bg-muted overflow-hidden flex items-end"
>
<div
className="w-full bg-primary/70 transition-[height] duration-500"
style={{ height: `${Math.max(4, p)}%` }}
/>
</div>
))}
</div>
)}
</div>
{/* Memory */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<MemoryStick className="size-4 text-primary" />
<span className="text-sm font-semibold">内存使用</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.memory.usagePercent.toFixed(1)}%` : '—'}
</span>
</div>
<Progress value={systemInfo?.memory.usagePercent ?? 0} />
<div className="mt-3 flex items-center justify-between text-[11px] text-muted-foreground tabular-nums">
<span>已用 {systemInfo ? formatBytes(systemInfo.memory.used) : '—'}</span>
<span>共 {systemInfo ? formatBytes(systemInfo.memory.total) : '—'}</span>
</div>
</div>
{/* Runtime */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<Server className="size-4 text-primary" />
<span className="text-sm font-semibold">运行进程</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `PID ${systemInfo.runtime.pid}` : '—'}
</span>
</div>
{!systemInfo ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
) : (
<div className="space-y-1.5 text-xs">
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">RSS</span>
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.rss)}</span>
className="w-full bg-primary/70 transition-[height] duration-500"
style={{ height: `${Math.max(4, p)}%` }}
/>
</div>
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">堆内存</span>
<span className="font-medium tabular-nums">
{formatBytes(systemInfo.runtime.heapUsed)} / {formatBytes(systemInfo.runtime.heapTotal)}
</span>
</div>
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">外部内存</span>
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.external)}</span>
</div>
</div>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
{/* Online accounts */}
<Card>
<CardHeader>
<CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription>
</CardHeader>
<CardContent>
{qqList.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>
{/* Memory */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<MemoryStick className="size-4 text-primary" />
<span className="text-sm font-semibold">内存使用</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.memory.usagePercent.toFixed(1)}%` : '—'}
</span>
</div>
<Progress value={systemInfo?.memory.usagePercent ?? 0} />
<div className="mt-3 flex items-center justify-between text-[11px] text-muted-foreground tabular-nums">
<span>已用 {systemInfo ? formatBytes(systemInfo.memory.used) : '—'}</span>
<span>共 {systemInfo ? formatBytes(systemInfo.memory.total) : '—'}</span>
</div>
</div>
{/* Runtime */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<Server className="size-4 text-primary" />
<span className="text-sm font-semibold">运行进程</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `PID ${systemInfo.runtime.pid}` : '—'}
</span>
</div>
{!systemInfo ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
) : (
<ScrollArea className="max-h-[420px]" 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) => (
<motion.div
key={q.uin}
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.03 + idx * 0.04, duration: 0.22 }}
whileHover={{ y: -2 }}
className="flex items-center gap-3 rounded-lg border bg-card/40 p-3"
>
<Avatar size={40}>
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{q.nickname}</div>
<div className="truncate font-mono text-[11px] text-muted-foreground tabular-nums">{q.uin}</div>
</div>
<span className="size-2 shrink-0 animate-pulse rounded-full bg-success shadow-[0_0_8px_color-mix(in_oklab,var(--success)_60%,transparent)]" />
</motion.div>
))}
<div className="space-y-1.5 text-xs">
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">RSS</span>
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.rss)}</span>
</div>
</ScrollArea>
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">堆内存</span>
<span className="font-medium tabular-nums">
{formatBytes(systemInfo.runtime.heapUsed)} / {formatBytes(systemInfo.runtime.heapTotal)}
</span>
</div>
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
<span className="text-muted-foreground">外部内存</span>
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.external)}</span>
</div>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</CardContent>
</Card>
);
}
// ─────────────── online sessions ───────────────
function SessionsBlock() {
const { qqList } = useAppState();
return (
<Card>
<CardHeader>
<CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription>
</CardHeader>
<CardContent>
{qqList.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>
</div>
) : (
<ScrollArea className="max-h-[420px]" 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) => (
<motion.div
key={q.uin}
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.03 + idx * 0.04, duration: 0.22 }}
whileHover={{ y: -2 }}
className="flex items-center gap-3 rounded-lg border bg-card/40 p-3"
>
<Avatar size={40}>
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{q.nickname}</div>
<div className="truncate font-mono text-[11px] text-muted-foreground tabular-nums">{q.uin}</div>
</div>
<span className="size-2 shrink-0 animate-pulse rounded-full bg-success shadow-[0_0_8px_color-mix(in_oklab,var(--success)_60%,transparent)]" />
</motion.div>
))}
</div>
</ScrollArea>
)}
</CardContent>
</Card>
);
}
@@ -330,6 +420,11 @@ const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
wsClient: 'WS 客户端',
};
function ConnectionsBlock() {
const { connections } = useAppState();
return <ConnectionsCard connections={connections} />;
}
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
return (
<Card>
@@ -359,22 +454,22 @@ function ConnectionsCard({ connections }: { connections: AccountConnections[] })
</p>
) : (
<div className="flex flex-col gap-1.5">
{acc.adapters.map((a) => (
<div key={a.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
{acc.adapters.map((adp) => (
<div key={adp.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
<span
className={cn(
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium',
CONN_STATUS_STYLE[a.status],
CONN_STATUS_STYLE[adp.status],
)}
>
{CONN_STATUS_LABEL[a.status]}
{CONN_STATUS_LABEL[adp.status]}
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-sm font-medium">{a.name}</span>
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[a.kind]}</span>
<span className="truncate text-sm font-medium">{adp.name}</span>
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[adp.kind]}</span>
</div>
<div className="truncate text-[11px] text-muted-foreground">{a.detail}</div>
<div className="truncate text-[11px] text-muted-foreground">{adp.detail}</div>
</div>
</div>
))}
@@ -0,0 +1,148 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useApi } from '@/lib/api';
import type { UiLayout, UiLayoutItem } from '@/types';
// Client-side layout customization (the "C" half). The server stores the
// layout in config/ui.json; this context loads it (authed `GET /api/ui`),
// hands it to the sidebar + overview, and persists edits via the section-merge
// `POST /api/ui {layout}` (so it never clobbers appearance).
//
// Reconciliation against the *known* catalogue is the CONSUMER's job
// (`reconcileLayoutItems`), so the context stays a dumb store and adding a new
// block / nav item later doesn't need a context change — it just appears.
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
{ id: 'stats', visible: true },
{ id: 'connections', visible: true },
{ id: 'alerts', visible: true },
{ id: 'host', visible: true },
{ id: 'sessions', visible: true },
];
const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
{ id: '/', visible: true },
{ id: '/processes', visible: true },
{ id: '/config', visible: true },
{ id: '/logs', visible: true },
{ id: '/settings', visible: true },
];
export const DEFAULT_LAYOUT: UiLayout = {
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((i) => ({ ...i })),
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
};
/**
* Order + visibility for a known catalogue: keep stored items that still exist
* (in their stored order + visibility), then append any catalogue entries the
* stored layout predates (visible). `pinned` ids are forced visible.
*/
export function reconcileLayoutItems(
stored: UiLayoutItem[] | undefined,
known: readonly string[],
pinned: readonly string[] = [],
): UiLayoutItem[] {
const knownSet = new Set(known);
const seen = new Set<string>();
const out: UiLayoutItem[] = [];
for (const item of stored ?? []) {
if (!item || !knownSet.has(item.id) || seen.has(item.id)) continue;
seen.add(item.id);
out.push({ id: item.id, visible: pinned.includes(item.id) ? true : item.visible !== false });
}
for (const id of known) {
if (!seen.has(id)) out.push({ id, visible: true });
}
return out;
}
interface LayoutContextValue {
overviewBlocks: UiLayoutItem[];
navItems: UiLayoutItem[];
/** Persist a new overview-block order/visibility. */
setOverviewBlocks: (items: UiLayoutItem[]) => void;
/** Persist a new nav order/visibility. */
setNavItems: (items: UiLayoutItem[]) => void;
/** Reset both to defaults. */
resetLayout: () => void;
}
const LayoutContext = createContext<LayoutContextValue | null>(null);
export function LayoutProvider({ children }: { children: ReactNode }) {
const api = useApi();
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
const layoutRef = useRef(layout);
// Set once the user edits, so the initial GET (which may resolve AFTER the
// first edit) never clobbers their change.
const dirtyRef = useRef(false);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => { layoutRef.current = layout; }, [layout]);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const config = await api.ui.get();
// Seed from the server only if the user hasn't already edited (the
// overview + editor are interactive immediately, before this resolves).
if (!cancelled && !dirtyRef.current && config?.layout) setLayout(config.layout);
} catch {
/* keep defaults — layout is non-critical */
}
})();
return () => { cancelled = true; };
}, [api]);
// On unmount (e.g. logout), flush a pending debounced save so a last-moment
// edit isn't lost; best-effort (a cleared token just 401s harmlessly).
useEffect(() => () => {
if (saveTimer.current) {
clearTimeout(saveTimer.current);
void api.ui.save({ layout: layoutRef.current }).catch(() => { /* best-effort */ });
}
}, [api]);
const persist = useCallback((next: UiLayout) => {
dirtyRef.current = true;
layoutRef.current = next;
setLayout(next);
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => {
saveTimer.current = null; // mark not-pending so the unmount flush can't double-fire
void api.ui.save({ layout: next }).catch(() => { /* best-effort */ });
}, 300);
}, [api]);
const setOverviewBlocks = useCallback((items: UiLayoutItem[]) => {
persist({ ...layoutRef.current, overviewBlocks: items });
}, [persist]);
const setNavItems = useCallback((items: UiLayoutItem[]) => {
persist({ ...layoutRef.current, navItems: items });
}, [persist]);
const resetLayout = useCallback(() => {
persist({
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((i) => ({ ...i })),
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
});
}, [persist]);
const value = useMemo<LayoutContextValue>(() => ({
overviewBlocks: layout.overviewBlocks,
navItems: layout.navItems,
setOverviewBlocks,
setNavItems,
resetLayout,
}), [layout, setOverviewBlocks, setNavItems, resetLayout]);
return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
}
export function useLayout(): LayoutContextValue {
const ctx = useContext(LayoutContext);
if (!ctx) throw new Error('useLayout must be used within LayoutProvider');
return ctx;
}
+3 -2
View File
@@ -82,8 +82,9 @@ export interface ApiClient {
ui: {
/** Full config (appearance + layout). Bearer-gated. */
get(): Promise<UiConfig>;
/** Persist the full config; returns the normalized server view. */
save(config: UiConfig): Promise<UiConfig>;
/** Persist config. Section-level merge: a payload with only `appearance`
* or only `layout` keeps the other section. Returns the normalized view. */
save(config: Partial<UiConfig>): Promise<UiConfig>;
/** Cosmetic appearance subset, usable pre-auth (login page theming). */
getPublic(): Promise<UiAppearance>;
/** Upload a background image (PNG/JPEG/WebP, ≤5MB). Returns updated config. */
+12 -9
View File
@@ -7,6 +7,7 @@ import { MainLayout } from '@/components/layout/main-layout';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { AppStateProvider } from '@/contexts/AppStateContext';
import { LayoutProvider } from '@/contexts/LayoutContext';
import { useSession } from '@/contexts/SessionContext';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
@@ -125,15 +126,17 @@ export function AppLayout() {
onLogout: handleLogout,
}}
>
<MainLayout status={session.status} onLogout={handleLogout}>
{/* Routes use `lazyRouteComponent` (router/index.tsx) for
code-splitting, which suspends until the chunk is fetched.
The chrome (sidebar / top bar) stays mounted across this
boundary so only the page surface flashes a skeleton. */}
<Suspense fallback={<PageFallback />}>
<Outlet />
</Suspense>
</MainLayout>
<LayoutProvider>
<MainLayout status={session.status} onLogout={handleLogout}>
{/* Routes use `lazyRouteComponent` (router/index.tsx) for
code-splitting, which suspends until the chunk is fetched.
The chrome (sidebar / top bar) stays mounted across this
boundary so only the page surface flashes a skeleton. */}
<Suspense fallback={<PageFallback />}>
<Outlet />
</Suspense>
</MainLayout>
</LayoutProvider>
<ConfirmDialog
open={!!unloadFailedAlert}