import { useEffect, useMemo, useState, type ReactNode } from 'react'; import { motion, Reorder } from 'motion/react'; import { Link } from '@tanstack/react-router'; import { Activity, ArrowRight, Bell, Cable, Check, Cpu, ExternalLink, Eye, EyeOff, GripVertical, LayoutGrid, MemoryStick, MonitorCog, Pencil, Plus, PlugZap, RefreshCw, RotateCcw, Server, Settings2, Users, } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Progress } from '@/components/ui/progress'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; 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, 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 { CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, HIDDEN_BY_DEFAULT_IDS, MOBILE_WIDGET_IDS, mobileHeightOf, parseAccountConfig, parseAlertsConfig, parseConnectionsConfig, parseHostConfig, parseLinkConfig, parseNoteConfig, parseSessionsConfig, widgetLabel, type AccountConfig, type AlertsConfig, type ConnectionsConfig, type HostConfig, type LinkConfig, type NoteConfig, type SessionsConfig, } from '@/lib/dashboard-layout'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { DashboardGrid, WIDGET_DRAG_TYPE, type GridCoord } from '@/components/pages/dashboard-grid'; import { AccountConfigForm, AlertsConfigForm, ConnectionsConfigForm, HostConfigForm, LinkConfigForm, LINK_ICON_COMPONENTS, NoteConfigForm, SessionsConfigForm, } from '@/components/pages/widget-config-forms'; import { DeliveriesWidget } from '@/components/overview/deliveries-widget'; function qqAvatarUrl(uin: string) { return `/avatar/${encodeURIComponent(uin)}`; } function renderWidget(block: UiLayoutItem): ReactNode { if (block.id.startsWith('stat:')) return ; switch (block.id) { case 'connections': return ; case 'alerts': return ; case 'host': return ; case 'sessions': return ; case 'note': return ; case 'link': return ; case 'account': return ; case 'deliveries': return ; default: return null; } } export function OverviewPage() { const { qqList, processList } = useAppState(); const { overviewBlocks, setOverviewBlocks, overviewMobile, setOverviewMobile, resetLayout, editing, setEditing, } = useLayout(); const off = useTheme().appearance.disableMotion; const isWide = useMediaQuery('(min-width: 768px)'); // Free-grid 2D editing is desktop-only; on a phone, editing surfaces a // single-column drag-sort panel (overviewMobile) instead. const [configId, setConfigId] = useState(null); // The grid shows only visible widgets (Apple-widgets model); hidden ones live // in the gallery and are dragged in/out to add/remove. const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [overviewBlocks]); const hiddenBlocks = useMemo(() => overviewBlocks.filter((b) => !b.visible), [overviewBlocks]); // Per-widget config lives on the desktop blocks; mobile widgets reuse it. const configById = useMemo( () => new Map(overviewBlocks.map((b) => [b.id, b.config])), [overviewBlocks], ); // Reconcile the mobile order against the live widget catalogue (drop unknown, // append new as visible) — so a widget added later just appears on phones too. const mobileItems = useMemo( () => reconcileLayoutItems(overviewMobile, MOBILE_WIDGET_IDS, [], HIDDEN_BY_DEFAULT_IDS), [overviewMobile], ); // Single writer for the grid: move/resize updates coords; a visible block no // longer present in the snapshot was dragged out to the gallery → hide it. const onGridChange = (coords: GridCoord[]) => { const cmap = new Map(coords.map((c) => [c.id, c])); setOverviewBlocks( overviewBlocks.map((b) => { if (!b.visible) return b; // hidden (in the gallery) — leave untouched const c = cmap.get(b.id); if (c) return { ...b, x: c.x, y: c.y, w: c.w, h: c.h }; return { ...b, visible: false }; // was in the grid, now gone → removed }), ); }; // Add a widget dragged from the gallery at the dropped cell (catalogue size). const addWidget = (id: string, x: number, y: number) => { const spec = GRID_WIDGETS.find((w) => w.id === id); setOverviewBlocks(overviewBlocks.map((b) => ( b.id === id ? { ...b, visible: true, x, y, w: spec?.def.w ?? 3, h: spec?.def.h ?? 2 } : b ))); }; const toggleMobile = (id: string) => setOverviewMobile(mobileItems.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b))); const reorderMobile = (ids: string[]) => { const byId = new Map(mobileItems.map((i) => [i.id, i])); setOverviewMobile(ids.map((id) => byId.get(id)).filter((x): x is UiLayoutItem => !!x)); }; const setBlockConfig = (id: string, config: Record) => setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b))); const loadableProcs = processList.filter((p) => !p.injected).length; const configBlock = configId ? overviewBlocks.find((b) => b.id === configId) : null; return (
{/* Toolbar: edit toggle on both desktop (2D grid overlays) and mobile (single-column drag-sort panel). The sidebar nav is drag-sortable in edit mode on both — no separate editor panel. Hidden in kiosk mode (data-kiosk-hide → CSS) so a wall display has no edit entry. */}
{editing && ( )}
{editing && (

{isWide ? '拖动卡片移动位置、拖右下角缩放,右上齿轮改设置;把卡片拖回右侧「部件库」即可移除,从部件库拖到画布即可添加。左侧导航也可在编辑态拖动排序。' : '拖动手柄调整卡片顺序,眼睛图标显隐,齿轮改设置。手机为单列布局,与桌面网格各自独立。'}

)} {/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */} {qqList.length === 0 && (

{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}

前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。

)} {isWide ? (
{visibleBlocks.length === 0 ? ( editing ? ( ) : ( ) ) : ( )}
{editing &&
) : ( )} { if (!o) setConfigId(null); }}> {configBlock ? `${widgetLabel(configBlock.id)} · 设置` : '设置'} {configBlock?.id === 'alerts' && setBlockConfig('alerts', c)} />} {configBlock?.id === 'sessions' && setBlockConfig('sessions', c)} />} {configBlock?.id === 'host' && setBlockConfig('host', c)} />} {configBlock?.id === 'connections' && setBlockConfig('connections', c)} />} {configBlock?.id === 'note' && setBlockConfig('note', c)} />} {configBlock?.id === 'link' && setBlockConfig('link', c)} />} {configBlock?.id === 'account' && setBlockConfig('account', c)} />}
); } function EmptyLayout({ onReset }: { onReset: () => void }) { return (

所有总览卡片都已隐藏

); } // ─────────────── mobile single-column overview ─────────────── // Phones get a one-dimensional layout (`overviewMobile`), fully disjoint from // the desktop 2D grid. View mode reuses the grid renderer (drag disabled) so // each widget keeps its cell height; edit mode is a drag-sort panel. function MobileOverview({ items, editing, configById, onReorder, onToggle, onConfigOpen, onReset, }: { items: UiLayoutItem[]; editing: boolean; configById: Map | undefined>; onReorder: (ids: string[]) => void; onToggle: (id: string) => void; onConfigOpen: (id: string) => void; onReset: () => void; }) { if (editing) { return ( i.id)} onReorder={onReorder} className="flex flex-col gap-2"> {items.map((item) => ( {widgetLabel(item.id)} {CONFIGURABLE_WIDGETS.has(item.id) && item.visible && ( )} ))} ); } const visible = items.filter((i) => i.visible); if (visible.length === 0) return ; // Stack widgets in a single column with cumulative y + catalogue heights // (pure prefix-sum; the widget count is tiny so the O(n²) is negligible). const heights = visible.map((item) => mobileHeightOf(item.id)); const blocks: UiLayoutItem[] = visible.map((item, i) => ({ id: item.id, visible: true, x: 0, y: heights.slice(0, i).reduce((sum, h) => sum + h, 0), w: 1, h: heights[i], config: configById.get(item.id), })); return ( { /* no drag on mobile — order edited via the panel */ }} renderWidget={renderWidget} configurableIds={CONFIGURABLE_WIDGETS} onConfigOpen={onConfigOpen} /> ); } // ─────────────── widget gallery (desktop edit mode) ─────────────── // The right-hand "store": hidden widgets shown as draggable tiles. Dragging a // tile onto the canvas adds it (HTML5 DnD); dragging a canvas card back onto // this panel removes it (gridstack `removable`, matched by the .widget-gallery // class). Edit-mode only, desktop only. function WidgetGallery({ hidden }: { hidden: UiLayoutItem[] }) { return (
部件库

拖到左侧画布添加;把卡片拖回此处即可移除。

{hidden.length === 0 ? (
全部部件已添加
) : (
{hidden.map((b) => (
{ e.dataTransfer.setData(WIDGET_DRAG_TYPE, b.id); e.dataTransfer.effectAllowed = 'copy'; }} className="flex cursor-grab items-center gap-2 rounded-lg border bg-card/70 px-2.5 py-2 text-sm transition-colors active:cursor-grabbing hover:border-primary/40 hover:bg-accent/30" > {widgetLabel(b.id)}
))}
)}
); } // Empty-canvas drop target shown in edit mode when no widget is on the grid — // keeps an HTML5 drop zone so the first widget can still be dragged in. function DropPlaceholder({ onAdd }: { onAdd: (id: string, x: number, y: number) => void }) { return (
e.preventDefault()} onDrop={(e) => { e.preventDefault(); const id = e.dataTransfer.getData(WIDGET_DRAG_TYPE); if (id) onAdd(id, 0, 0); }} className="flex min-h-60 flex-col items-center justify-center gap-3 rounded-xl border-2 border-dashed py-16 text-center text-muted-foreground" >

从右侧「部件库」拖动部件到这里

); } // ─────────────── stat tiles (one widget each) ─────────────── function shortDistro(distro: string): string { let s = distro; s = s.replace(/^Debian GNU\/Linux /, 'Debian '); s = s.replace(/^Red Hat Enterprise Linux /, 'RHEL '); s = s.replace(/^CentOS (?:Linux )?release /, 'CentOS '); s = s.replace(/^Rocky Linux /, 'Rocky '); s = s.replace(/^Alma(?:Linux)? /, 'Alma '); s = s.replace(/^Oracle Linux /, 'Oracle '); s = s.replace(/^Amazon Linux /, 'Amazon '); s = s.replace(/^Scientific Linux /, 'Scientific '); s = s.replace(/^SUSE Linux Enterprise (?:Server |Desktop )?/, 'SUSE '); s = s.replace(/^Anolis OS /, 'Anolis '); s = s.replace(/^TencentOS Server /, 'TencentOS '); s = s.replace(/^Ubuntu Kylin /, 'Ubuntu '); s = s.replace(/^Manjaro Linux /, 'Manjaro '); s = s.replace(/^Void Linux /, 'Void '); s = s.replace(/^Alibaba Cloud Linux /, 'Alibaba '); s = s.replace(/^Raspbian GNU\/Linux /, 'Raspbian '); s = s.replace(/^DietPi v /, 'DietPi '); s = s.replace(/^Kali GNU\/Linux /, 'Kali '); s = s.replace(/^Proxmox VE /, 'Proxmox '); s = s.replace(/^Windows Server /, 'Win Svr '); s = s.replace(/^Windows (\d+)/, 'Win $1'); s = s.replace(/\s*\([^)]+\)/g, ''); s = s.replace(/\s{2,}/g, ' '); return s.trim(); } function StatTile({ icon, label, value, subtext, accent = false, to, }: { icon: ReactNode; label: string; value: ReactNode; subtext?: ReactNode; accent?: boolean; to?: AppPath; }) { const body = (
{icon}

{label}

{value}
{subtext &&

{subtext}

}
{to && }
); if (to) { return ( {body} ); } return {body}; } function StatTileWidget({ id }: { id: string }) { const { qqList, processList, systemInfo } = useAppState(); const { status } = useSession(); const online = status === '已连接'; switch (id) { case 'stat:status': return ( } label="服务状态" value={online ? '运行中' : status} subtext={online ? '已连接到后端' : '请检查后端进程'} accent={online} /> ); case 'stat:accounts': return ( } label="在线账号" value={qqList.length} subtext={`已接入 ${qqList.length} 个会话`} /> ); case 'stat:processes': { const onlineProcs = processList.filter((p) => p.status === 'online').length; const loadableProcs = processList.filter((p) => !p.injected).length; return ( } label="进程注入" value={`${onlineProcs} 在线`} subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`} to="/processes" /> ); } case 'stat:host': return ( } label="主机名" value={systemInfo?.hostname ?? '—'} subtext={systemInfo ? {shortDistro(systemInfo.distro)} · {systemInfo.archLabel}{systemInfo.distro} · {systemInfo.archLabel} : '加载中'} /> ); case 'stat:uptime': return ( } label="系统运行" value={systemInfo ? formatUptime(systemInfo.uptime) : '—'} subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined} /> ); default: return null; } } // ─────────────── host resources ─────────────── const HOST_GRID_COLS: Record = { 1: 'lg:grid-cols-1', 2: 'lg:grid-cols-2', 3: 'lg:grid-cols-3' }; function HostBlock({ config }: { config: HostConfig }) { const { systemInfo, refreshSystem } = useAppState(); const panelCount = [config.cpu, config.memory, config.runtime].filter(Boolean).length; return (
主机资源 {systemInfo ? `${systemInfo.cpu.model.trim()} · ${systemInfo.cpu.cores} 核 · Node ${systemInfo.nodeVersion}` : '正在采集主机信息…'}
{/* CPU */} {config.cpu && (
CPU 使用率 {systemInfo && ( {systemInfo.cpu.perCore.length} 核 )}
{systemInfo ? `${systemInfo.cpu.average.toFixed(1)}%` : '—'}

负载: {systemInfo ? systemInfo.cpu.loadAvg.map((v) => v.toFixed(2)).join(' / ') : '—'}

{systemInfo && systemInfo.cpu.perCore.length > 0 && (
{systemInfo.cpu.perCore.map((p, i) => (
{i}
))}
)}
)} {/* Memory */} {config.memory && (
内存使用
{systemInfo ? `${systemInfo.memory.usagePercent.toFixed(1)}%` : '—'}
{systemInfo ? (() => { const m = systemInfo.memory; const rss = Math.min(systemInfo.runtime.rss, m.used); const other = Math.max(0, m.used - rss); const segs = [ { key: 'proc', label: '本进程', bytes: rss, grow: (rss / m.total) * 100, color: 'var(--primary)' }, { key: 'other', label: '其他已用', bytes: other, grow: (other / m.total) * 100, color: 'color-mix(in oklab, var(--primary) 45%, transparent)' }, { key: 'free', label: '空闲', bytes: m.free, grow: (m.free / m.total) * 100, color: 'color-mix(in oklab, var(--muted) 85%, transparent)' }, ]; return ( <>
{segs.map((seg) => ( ))}
{segs.map((seg) => ( {seg.label} {formatBytes(seg.bytes)} ))}
); })() : }
)} {/* Runtime */} {config.runtime && (
运行进程
{systemInfo ? `PID ${systemInfo.runtime.pid}` : '—'}
{!systemInfo ? (
) : (
RSS {formatBytes(systemInfo.runtime.rss)}
堆内存 {formatBytes(systemInfo.runtime.heapUsed)} / {formatBytes(systemInfo.runtime.heapTotal)}
外部内存 {formatBytes(systemInfo.runtime.external)}
)}
)}
); } // ─────────────── online sessions ─────────────── function SessionsBlock({ config }: { config: SessionsConfig }) { const { qqList } = useAppState(); const off = useTheme().appearance.disableMotion; 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 ( 在线会话 当前已接入并完成登录的 QQ 账号{config.filter.trim() ? `(筛选:${config.filter.trim()})` : ''} {list.length === 0 ? (

{qqList.length === 0 ? '暂无在线会话' : '无匹配的会话'}

) : (
{list.map((q, idx) => ( {(q.nickname || q.uin).slice(0, 2)}
{q.nickname}
{q.uin}
))}
)}
); } // ─────────────── connection health ─────────────── const CONN_STATUS_STYLE: Record = { ok: 'bg-success/10 text-success', warn: 'bg-warning/10 text-warning', down: 'bg-destructive/10 text-destructive', degraded: 'bg-destructive/10 text-destructive', disabled: 'bg-muted text-muted-foreground', }; const CONN_STATUS_LABEL: Record = { ok: '正常', warn: '注意', down: '异常', degraded: '应用失败', disabled: '未启用', }; const ADAPTER_KIND_LABEL: Record = { httpServer: 'HTTP 服务端', httpClient: 'HTTP 上报', wsServer: 'WS 服务端', wsClient: 'WS 客户端', }; // Worst-status-first ordering (down → warn → disabled → ok). const CONN_STATUS_RANK: Record = { degraded: 0, down: 1, warn: 2, disabled: 3, ok: 4, }; function ConnectionsBlock({ config }: { config: ConnectionsConfig }) { const { connections } = useAppState(); const list = useMemo(() => { const f = config.filter.trim().toLowerCase(); // Optionally drop healthy adapters, then accounts left with none. let arr = connections.map((acc) => ({ ...acc, adapters: config.onlyIssues ? acc.adapters.filter((a) => a.status !== 'ok') : acc.adapters, })); if (config.onlyIssues) arr = arr.filter((acc) => acc.adapters.length > 0); if (f) arr = arr.filter((acc) => (acc.nickname ?? '').toLowerCase().includes(f) || acc.uin.includes(f)); if (config.sort === 'name') { arr = [...arr].sort((a, b) => (a.nickname || a.uin).localeCompare(b.nickname || b.uin)); } else if (config.sort === 'status') { const worst = (acc: typeof arr[number]) => acc.adapters.reduce((m, a) => Math.min(m, CONN_STATUS_RANK[a.status]), 99); arr = [...arr].sort((a, b) => worst(a) - worst(b)); } return arr; }, [connections, config.filter, config.onlyIssues, config.sort]); const filtered = config.filter.trim() !== '' || config.onlyIssues; return ( OneBot 连接 各账号协议端点的实时连接状态{config.onlyIssues ? ' · 仅异常' : ''}{config.filter.trim() ? ` · 筛选:${config.filter.trim()}` : ''} {list.length === 0 ? (

{filtered ? '无匹配的连接' : '暂无已接入的账号实例'}

) : (
{list.map((acc) => (
{acc.nickname || acc.uin} {acc.uin}
{acc.adapters.length === 0 ? (

未配置任何协议端点

) : (
{acc.adapters.map((adp) => (
{CONN_STATUS_LABEL[adp.status]}
{adp.name} {ADAPTER_KIND_LABEL[adp.kind]}
{adp.detail}
{adp.lastError && adp.lastErrorAt && (
{new Date(adp.lastErrorAt).toLocaleString()} · {adp.lastError}
)}
))}
)}
))}
)}
); } // ─────────────── static widgets (note / link / account) ─────────────── function NoteWidget({ config }: { config: NoteConfig }) { return ( {config.text.trim() ? (

{config.text}

) : (

空便签 · 在编辑模式点齿轮填写内容

)}
); } function LinkWidget({ config }: { config: LinkConfig }) { const Icon = LINK_ICON_COMPONENTS[config.icon] ?? LINK_ICON_COMPONENTS.link; if (!config.url) { return ( 未配置链接 · 点齿轮设置 ); } return (

{config.label || config.url}

{config.url}

); } function AccountWidget({ config }: { config: AccountConfig }) { const { qqList } = useAppState(); const acct = qqList.find((q) => q.uin === config.uin); if (!config.uin) { return ( 未指定账号 · 点齿轮设置 ); } return ( {(acct?.nickname || config.uin).slice(0, 2)}

{acct?.nickname || '未接入账号'}

{config.uin}

); } // ─────────────── recent alerts ─────────────── // Same WCAG-tuned log-level text tokens as the logs page (see index.css / the // levelClass note there): the raw accent colors fail AA as small text on the // light canvas. const ALERT_LEVEL_CLASS: Record = { 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', }; function RecentAlertsCard({ config }: { config: AlertsConfig }) { const api = useApi(); const { formatClock } = useTheme(); const [alerts, setAlerts] = useState([]); const { count } = config; const levelsKey = config.levels.join(','); useEffect(() => { const levels = new Set(levelsKey.split(',') as LogLevel[]); let active = true; api.logs .list(Math.max(200, count * 4)) .then((list) => { if (!active) return; setAlerts(list.filter((l) => levels.has(l.level)).slice(-count)); }) .catch(() => { /* ignore */ }); const stop = api.logs.stream({ onLine: (entry) => { if (!levels.has(entry.level)) return; setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-count)); }, }); return () => { active = false; stop(); }; }, [api, count, levelsKey]); return (
最近告警 最近 {count} 条 · {config.levels.map((l) => l.toUpperCase()).join(' / ')}
查看日志
{alerts.length === 0 ? (

暂无告警

) : (
{alerts.map((a) => (
{formatClock(a.time)} {a.level.toUpperCase()} [{a.scope}] {a.message}
))}
)}
); }