feat(webui): free-form draggable/resizable dashboard grid (phase 4)

The overview becomes a gridstack-backed free grid — drag, resize, and show/
hide 9 widgets (the 5 top stat tiles split out of the old single block, plus
connections/alerts/host/sessions), persisted to config/ui.json's
layout.overviewBlocks as {id,x,y,w,h,visible}.

- gridstack (zero-dep, vanilla; chosen over react-grid-layout whose
  react-draggable uses the React-19-removed findDOMNode). React renders each
  widget into a gridstack item via a portal (context flows through); gridstack
  owns layout/drag/resize. Per-widget minW/minH prevent content collapse.
- Desktop = editable in place; narrow screens = auto single-column, read-only.
  Fixed cellHeight => no ResizeObserver => the narrow column-clamp never
  persists over the desktop coords.
- Edit mode shows a panel: widget show/hide + nav reorder (the phase-3 motion
  list); the grid below is live-editable. Reset + empty-state preserved.
- Server UiLayoutItem gains optional x/y/w/h (clamped); the stats->5-tiles
  migration + default placement live client-side (lib/dashboard-layout.ts).

Verified across 2 adversarial review rounds (gridstack+React lifecycle traced
against the library source: StrictMode-safe, no mount-persist loop, no
re-init on coord change, no narrow-visit data loss).
This commit is contained in:
DrSmoothl committed 2026-06-13 21:17:23 +08:00
1 parent a5335687ec
commit f07f309c51
10 files changed
+532 -226

No files matched your search

+30 -1
View File
@@ -92,6 +92,16 @@ export interface UiAppearance {
export interface UiLayoutItem {
id: string;
visible: boolean;
/**
* Grid position/size (overview blocks only; nav items omit them). The
* client owns the widget catalogue, per-widget min sizes, and the
* `stats`→tiles migration — the server just preserves + clamps these to
* sane integer bounds so a corrupt file can't store absurd coords.
*/
x?: number;
y?: number;
w?: number;
h?: number;
}
export interface UiLayout {
@@ -188,6 +198,15 @@ function clampNum(value: unknown, min: number, max: number, fallback: number): n
return Math.min(max, Math.max(min, n));
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
return Math.trunc(clampNum(value, min, max, fallback));
}
function isFiniteNum(value: unknown): boolean {
if (typeof value === 'number') return Number.isFinite(value);
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
@@ -216,7 +235,17 @@ function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayou
const id = idOr(raw.id, '');
if (!id || seen.has(id)) continue;
seen.add(id);
out.push({ id, visible: boolOr(raw.visible, true) });
const item: UiLayoutItem = { id, visible: boolOr(raw.visible, true) };
// Grid coords are optional (overview blocks carry them; nav items don't).
// Preserve + clamp when any are present; missing ones get safe defaults
// and the client re-applies per-widget min sizes on load.
if (isFiniteNum(raw.x) || isFiniteNum(raw.y) || isFiniteNum(raw.w) || isFiniteNum(raw.h)) {
item.x = clampInt(raw.x, 0, 50, 0);
item.y = clampInt(raw.y, 0, 1000, 0);
item.w = clampInt(raw.w, 1, 12, 1);
item.h = clampInt(raw.h, 1, 100, 1);
}
out.push(item);
}
// An array that parsed to nothing usable is indistinguishable from corrupt;
// fall back so the frontend always has a baseline to reconcile against.
+1
View File
@@ -21,6 +21,7 @@
"@tanstack/react-router": "^1.169.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"gridstack": "^12.6.0",
"lucide-react": "^0.469.0",
"motion": "^12.0.0",
"react": "^19.2.5",
@@ -0,0 +1,109 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { GridStack, type GridStackWidget } from 'gridstack';
import 'gridstack/dist/gridstack.css';
import { GRID_CELL_HEIGHT, GRID_MARGIN, minSizeOf } from '@/lib/dashboard-layout';
import { cn } from '@/lib/utils';
import type { UiLayoutItem } from '@/types';
export interface GridCoord { id: string; x: number; y: number; w: number; h: number }
interface DashboardGridProps {
/** Visible blocks, each with x/y/w/h (already migrated/positioned). */
blocks: UiLayoutItem[];
editing: boolean;
/** Column count — 12 on desktop, 1 on narrow screens (auto single-column). */
cols: number;
/** Fired (debounced upstream) after a drag/resize settles. */
onChange: (coords: GridCoord[]) => void;
renderWidget: (id: string) => ReactNode;
}
/**
* gridstack-backed dashboard. gridstack owns the item shells (drag/resize/
* position); React renders each widget's content into the item's content div
* via a portal (React context still flows through portals). We re-init only
* when the visible widget SET or the edit mode changes — never on a pure
* coord change (gridstack already moved the item; the coord round-trips back
* through `onChange` → state and matches what gridstack has).
*/
export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }: DashboardGridProps) {
const elRef = useRef<HTMLDivElement | null>(null);
const gridRef = useRef<GridStack | null>(null);
const [contentEls, setContentEls] = useState<Record<string, HTMLElement>>({});
// Latest props mirrored into refs so the init effect (keyed only on the
// id-set + editing) reads current values without re-running on every render.
const blocksRef = useRef(blocks);
const onChangeRef = useRef(onChange);
useLayoutEffect(() => { blocksRef.current = blocks; onChangeRef.current = onChange; });
// Re-init when the visible widget set or the edit mode changes.
const idKey = blocks.map((b) => b.id).join('|');
useLayoutEffect(() => {
const host = elRef.current;
if (!host) return;
const grid = GridStack.init(
{
column: cols,
cellHeight: GRID_CELL_HEIGHT,
margin: GRID_MARGIN,
float: true, // free placement — items stay where dropped (no auto-compact)
disableDrag: !editing,
disableResize: !editing,
handle: '.grid-stack-item-content',
},
host,
);
gridRef.current = grid;
const els: Record<string, HTMLElement> = {};
grid.batchUpdate();
for (const b of blocksRef.current) {
const { minW, minH } = minSizeOf(b.id);
const itemEl = grid.addWidget({ id: b.id, x: b.x, y: b.y, w: b.w, h: b.h, minW, minH });
const content = itemEl.querySelector('.grid-stack-item-content') as HTMLElement | null;
if (content) els[b.id] = content;
}
grid.batchUpdate(false);
setContentEls(els);
// Attach AFTER the initial programmatic build so we don't persist the
// (unchanged) starting layout back to the server on mount.
const persist = () => {
const saved = grid.save(false) as GridStackWidget[];
onChangeRef.current(
saved
.filter((n): n is GridStackWidget & { id: string } => n.id != null)
.map((n) => ({ id: String(n.id), x: n.x ?? 0, y: n.y ?? 0, w: n.w ?? 1, h: n.h ?? 1 })),
);
};
grid.on('change', persist);
return () => {
grid.off('change');
grid.destroy(false); // tear down gridstack, keep the React-owned container
// Remove the item DOM gridstack created (React never owned these).
host.replaceChildren();
gridRef.current = null;
setContentEls({});
};
}, [idKey, editing, cols]);
return (
<div ref={elRef} className="grid-stack -mx-1">
{blocks.map((b) =>
contentEls[b.id]
? createPortal(
<div className={cn('h-full w-full overflow-auto', editing && 'pointer-events-none select-none')}>
{renderWidget(b.id)}
</div>,
contentEls[b.id],
)
: null,
)}
</div>
);
}
@@ -6,29 +6,54 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
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.
// 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
// motion Reorder drag from phase 3). Pinned nav items can't be hidden.
interface ReorderListProps {
items: UiLayoutItem[];
labelFor: (id: string) => string;
pinned?: readonly string[];
onChange: (items: UiLayoutItem[]) => void;
// ── widget visibility (no drag — grid owns position) ──
function VisibilityList({
items, labelFor, onToggle,
}: { items: UiLayoutItem[]; labelFor: (id: string) => string; onToggle: (id: string) => void }) {
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>
))}
</div>
);
}
function ReorderList({ items, labelFor, pinned = [], onChange }: ReorderListProps) {
// ── nav reorder + visibility (1-D list, motion drag) ──
function NavReorderList({
items, labelFor, pinned, onChange,
}: { items: UiLayoutItem[]; labelFor: (id: string) => string; pinned: readonly string[]; onChange: (items: UiLayoutItem[]) => void }) {
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[]) => {
const reorder = (newIds: string[]) =>
onChange(newIds.map((id) => byId.get(id)).filter((x): x is UiLayoutItem => !!x));
};
const toggle = (id: string) => {
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">
@@ -76,23 +101,23 @@ export interface LayoutEditorProps {
navItems: UiLayoutItem[];
navLabelFor: (id: string) => string;
navPinned: readonly string[];
onBlocks: (items: UiLayoutItem[]) => void;
onToggleBlock: (id: string) => void;
onNav: (items: UiLayoutItem[]) => void;
onReset: () => void;
onDone: () => void;
}
export function LayoutEditor({
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onBlocks, onNav, onReset, onDone,
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onNav, onReset, onDone,
}: LayoutEditorProps) {
return (
<div className="flex flex-col gap-5">
<div className="flex items-center justify-between gap-3">
<Card>
<CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">
<div>
<h2 className="text-lg font-semibold">编辑布局</h2>
<p className="text-[11px] text-muted-foreground">拖动排序,点眼睛图标显示/隐藏。改动会自动保存。</p>
<CardTitle className="text-base">编辑布局</CardTitle>
<CardDescription>在下方网格直接拖动卡片、拖角缩放;这里控制卡片显隐与导航。改动自动保存。</CardDescription>
</div>
<div className="flex items-center gap-2">
<div className="flex shrink-0 items-center gap-2">
<Button variant="ghost" size="sm" onClick={onReset} className="text-muted-foreground">
<RotateCcw className="size-4" /> 恢复默认
</Button>
@@ -100,27 +125,17 @@ export function LayoutEditor({
<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>
</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} />
</div>
<div className="flex flex-col gap-2">
<p className="text-xs font-medium text-muted-foreground">导航栏(拖动排序)</p>
<NavReorderList items={navItems} labelFor={navLabelFor} pinned={navPinned} onChange={onNav} />
</div>
</CardContent>
</Card>
);
}
@@ -2,18 +2,8 @@ import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { Link } from '@tanstack/react-router';
import {
Activity,
ArrowRight,
Bell,
Cable,
Cpu,
MemoryStick,
MonitorCog,
Pencil,
PlugZap,
RefreshCw,
Server,
Users,
Activity, ArrowRight, Bell, Cable, Cpu, MemoryStick, MonitorCog, Pencil, PlugZap,
RefreshCw, Server, Users,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -23,35 +13,27 @@ 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 { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types';
import type { AdapterStatus, AdapterStatusLevel, LogEntry } 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 { 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';
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 {
function renderWidget(id: string): ReactNode {
if (id.startsWith('stat:')) return <StatTileWidget id={id} />;
switch (id) {
case 'stats': return <StatsBlock />;
case 'connections': return <ConnectionsBlock />;
case 'alerts': return <RecentAlertsCard />;
case 'host': return <HostBlock />;
@@ -63,43 +45,57 @@ function renderBlock(id: string): ReactNode {
export function OverviewPage() {
const { qqList, processList } = useAppState();
const { overviewBlocks, navItems, setOverviewBlocks, setNavItems, resetLayout } = useLayout();
const [editing, setEditing] = useState(false);
const isWide = useMediaQuery('(min-width: 768px)');
const [editingOn, setEditingOn] = useState(false);
const editing = isWide && editingOn;
const blocks = useMemo(() => reconcileLayoutItems(overviewBlocks, BLOCK_IDS), [overviewBlocks]);
const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [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 onGridChange = (coords: GridCoord[]) => {
const cmap = new Map(coords.map((c) => [c.id, c]));
setOverviewBlocks(
overviewBlocks.map((b) => {
const c = cmap.get(b.id);
return c ? { ...b, x: c.x, y: c.y, w: c.w, h: c.h } : b;
}),
);
}
};
const toggleBlock = (id: string) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b)));
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>
<div className="flex flex-col gap-5">
{/* Toolbar: edit toggle is desktop-only (free grid needs room to drag). */}
{isWide && !editing && (
<div className="flex items-center justify-end">
<Button variant="outline" size="sm" onClick={() => setEditingOn(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. */}
{editing && (
<LayoutEditor
blocks={overviewBlocks}
blockLabelFor={widgetLabel}
navItems={nav}
navLabelFor={navLabelFor}
navPinned={PINNED_NAV}
onToggleBlock={toggleBlock}
onNav={setNavItems}
onReset={resetLayout}
onDone={() => setEditingOn(false)}
/>
)}
{/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */}
{qqList.length === 0 && (
<motion.div initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}>
<Link
@@ -125,7 +121,13 @@ export function OverviewPage() {
{visibleBlocks.length === 0 ? (
<EmptyLayout onReset={resetLayout} />
) : (
visibleBlocks.map((b) => <div key={b.id}>{renderBlock(b.id)}</div>)
<DashboardGrid
blocks={visibleBlocks}
editing={editing}
cols={isWide ? GRID_COLS : 1}
onChange={onGridChange}
renderWidget={renderWidget}
/>
)}
</div>
);
@@ -141,30 +143,24 @@ function EmptyLayout({ onReset }: { onReset: () => void }) {
);
}
// ─────────────── stat tiles ───────────────
// ─────────────── stat tiles (one widget each) ───────────────
function StatTile({
icon,
label,
value,
subtext,
accent = false,
to,
icon, label, value, subtext, accent = false, to,
}: {
icon: React.ReactNode;
icon: ReactNode;
label: string;
value: React.ReactNode;
subtext?: React.ReactNode;
value: ReactNode;
subtext?: ReactNode;
accent?: boolean;
/** When set, the whole tile becomes a link to this route. */
to?: AppPath;
}) {
const body = (
<CardContent className="flex items-center gap-3 p-4">
<CardContent className="flex h-full items-center gap-3 p-4">
<div
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-xl',
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary',
)}
>
{icon}
@@ -177,68 +173,75 @@ function StatTile({
{to && <ArrowRight className="size-4 shrink-0 text-muted-foreground/60" />}
</CardContent>
);
if (to) {
return (
<Link to={to} className="block rounded-xl outline-none">
<Card className="overflow-hidden transition-colors hover:border-primary/40 hover:bg-accent/30">{body}</Card>
<Link to={to} className="block h-full rounded-xl outline-none">
<Card className="h-full overflow-hidden transition-colors hover:border-primary/40 hover:bg-accent/30">{body}</Card>
</Link>
);
}
return <Card className="overflow-hidden">{body}</Card>;
return <Card className="h-full overflow-hidden">{body}</Card>;
}
function StatsBlock() {
function StatTileWidget({ id }: { id: string }) {
const { qqList, processList, systemInfo } = useAppState();
const { status } = useSession();
// Lightweight tick to refresh "uptime" pretty-print every 30s
const [, force] = useState(0);
useEffect(() => {
const t = setInterval(() => force((v) => v + 1), 30_000);
return () => clearInterval(t);
}, []);
const online = status === '已连接';
const onlineProcs = processList.filter((p) => p.status === 'online').length;
const loadableProcs = processList.filter((p) => !p.injected).length;
return (
<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>
);
switch (id) {
case 'stat:status':
return (
<StatTile
icon={<Activity className="size-5" />}
label="服务状态"
value={online ? '运行中' : status}
subtext={online ? '已连接到后端' : '请检查后端进程'}
accent={online}
/>
);
case 'stat:accounts':
return (
<StatTile
icon={<Users className="size-5" />}
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 (
<StatTile
icon={<PlugZap className="size-5" />}
label="进程注入"
value={`${onlineProcs} 在线`}
subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`}
to="/processes"
/>
);
}
case 'stat:host':
return (
<StatTile
icon={<Server className="size-5" />}
label="主机名"
value={systemInfo?.hostname ?? '—'}
subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'}
/>
);
case 'stat:uptime':
return (
<StatTile
icon={<MonitorCog className="size-5" />}
label="系统运行"
value={systemInfo ? formatUptime(systemInfo.uptime) : '—'}
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
/>
);
default:
return null;
}
}
// ─────────────── host resources ───────────────
@@ -246,7 +249,7 @@ function StatsBlock() {
function HostBlock() {
const { systemInfo, refreshSystem } = useAppState();
return (
<Card>
<Card className="flex h-full flex-col">
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle>主机资源</CardTitle>
@@ -260,7 +263,7 @@ function HostBlock() {
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<CardContent className="grid flex-1 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">
@@ -279,21 +282,13 @@ function HostBlock() {
{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
className="w-full bg-primary/70 transition-[height] duration-500"
style={{ height: `${Math.max(4, p)}%` }}
/>
<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">
@@ -311,7 +306,6 @@ function HostBlock() {
<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">
@@ -357,19 +351,19 @@ function HostBlock() {
function SessionsBlock() {
const { qqList } = useAppState();
return (
<Card>
<Card className="flex h-full flex-col">
<CardHeader>
<CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription>
</CardHeader>
<CardContent>
<CardContent className="min-h-0 flex-1">
{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">
<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) => (
<motion.div
@@ -408,33 +402,23 @@ const CONN_STATUS_STYLE: Record<AdapterStatusLevel, string> = {
disabled: 'bg-muted text-muted-foreground',
};
const CONN_STATUS_LABEL: Record<AdapterStatusLevel, string> = {
ok: '正常',
warn: '注意',
down: '异常',
disabled: '未启用',
ok: '正常', warn: '注意', down: '异常', disabled: '未启用',
};
const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
httpServer: 'HTTP 服务端',
httpClient: 'HTTP 上报',
wsServer: 'WS 服务端',
wsClient: 'WS 客户端',
httpServer: 'HTTP 服务端', httpClient: 'HTTP 上报', wsServer: 'WS 服务端', wsClient: 'WS 客户端',
};
function ConnectionsBlock() {
const { connections } = useAppState();
return <ConnectionsCard connections={connections} />;
}
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
return (
<Card>
<Card className="flex h-full flex-col">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Cable className="size-4 text-primary" /> OneBot 连接
</CardTitle>
<CardDescription>各账号协议端点的实时连接状态</CardDescription>
</CardHeader>
<CardContent>
<CardContent className="min-h-0 flex-1 overflow-auto">
{connections.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Cable className="size-7" strokeWidth={1.5} />
@@ -449,19 +433,12 @@ function ConnectionsCard({ connections }: { connections: AccountConnections[] })
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{acc.uin}</span>
</div>
{acc.adapters.length === 0 ? (
<p className="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground">
未配置任何协议端点
</p>
<p className="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground">未配置任何协议端点</p>
) : (
<div className="flex flex-col gap-1.5">
{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[adp.status],
)}
>
<span className={cn('shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium', CONN_STATUS_STYLE[adp.status])}>
{CONN_STATUS_LABEL[adp.status]}
</span>
<div className="min-w-0 flex-1">
@@ -506,14 +483,11 @@ function RecentAlertsCard() {
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5));
},
});
return () => {
active = false;
stop();
};
return () => { active = false; stop(); };
}, [api]);
return (
<Card>
<Card className="flex h-full flex-col">
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle className="flex items-center gap-2">
@@ -521,14 +495,11 @@ function RecentAlertsCard() {
</CardTitle>
<CardDescription>最近的 warn / error 级别日志</CardDescription>
</div>
<Link
to="/logs"
className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
<Link to="/logs" className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
查看日志 <ArrowRight className="size-3" />
</Link>
</CardHeader>
<CardContent>
<CardContent className="min-h-0 flex-1 overflow-auto">
{alerts.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Bell className="size-7" strokeWidth={1.5} />
@@ -542,9 +513,7 @@ function RecentAlertsCard() {
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
{a.level.toUpperCase()}
</span>
<span className="min-w-0 flex-1 truncate" title={a.message}>
[{a.scope}] {a.message}
</span>
<span className="min-w-0 flex-1 truncate" title={a.message}>[{a.scope}] {a.message}</span>
</div>
))}
</div>
+13 -11
View File
@@ -1,5 +1,6 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useApi } from '@/lib/api';
import { defaultOverviewGrid, migrateOverviewBlocks } from '@/lib/dashboard-layout';
import type { UiLayout, UiLayoutItem } from '@/types';
// Client-side layout customization (the "C" half). The server stores the
@@ -11,14 +12,6 @@ import type { UiLayout, UiLayoutItem } from '@/types';
// (`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 },
@@ -28,7 +21,9 @@ const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
];
export const DEFAULT_LAYOUT: UiLayout = {
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((i) => ({ ...i })),
// Overview blocks are the positioned grid widgets (the catalogue owns the
// default placement + the legacy `stats`→tiles migration).
overviewBlocks: defaultOverviewGrid(),
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
};
@@ -87,7 +82,14 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
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);
// Overview blocks are migrated to the current grid catalogue (legacy
// `stats`→tiles, default coords for new/coordless widgets).
if (!cancelled && !dirtyRef.current && config?.layout) {
setLayout({
overviewBlocks: migrateOverviewBlocks(config.layout.overviewBlocks),
navItems: config.layout.navItems,
});
}
} catch {
/* keep defaults — layout is non-critical */
}
@@ -125,7 +127,7 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
const resetLayout = useCallback(() => {
persist({
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((i) => ({ ...i })),
overviewBlocks: defaultOverviewGrid(),
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
});
}, [persist]);
+32
View File
@@ -215,3 +215,35 @@ html[data-reduce-motion="1"] *::after {
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
/* ──────────────────────────────────────────────
gridstack dashboard — mesh the library's item shell with our cards.
The widget content (a Card) owns its own bg/border/rounding, so the
gridstack content box is just a transparent, full-bleed container.
────────────────────────────────────────────── */
.grid-stack {
/* Negative inset cancels gridstack's per-item margin at the edges so the
grid lines up with surrounding page padding. */
background: transparent;
}
.grid-stack-item-content {
inset: 0;
overflow: visible;
background: transparent;
display: block;
}
/* The drag placeholder (drop target preview). */
.grid-stack > .grid-stack-placeholder > .placeholder-content {
border: 2px dashed var(--primary);
background: color-mix(in oklab, var(--primary) 8%, transparent);
border-radius: var(--radius);
}
/* Resize handle — only meaningful while editing (grid is interactive). */
.grid-stack-item > .ui-resizable-handle {
filter: none;
}
.grid-stack-item > .ui-resizable-se {
/* Make the bottom-right resize grip visible against either theme. */
border-right: 2px solid color-mix(in oklab, var(--primary) 70%, transparent);
border-bottom: 2px solid color-mix(in oklab, var(--primary) 70%, transparent);
}
@@ -0,0 +1,99 @@
import type { UiLayoutItem } from '@/types';
// The overview dashboard is a free 12-column gridstack grid. This module is
// the pure (React-free) catalogue + migration so it can be shared by the
// LayoutContext (defaults / reset / migrate-on-load), the DashboardGrid
// (render + min sizes), and the layout editor (labels) without import cycles.
export const GRID_COLS = 12;
/** px per grid row. Tiles are 1 row; cards a few rows. */
export const GRID_CELL_HEIGHT = 80;
export const GRID_MARGIN = 8;
export interface GridWidgetSpec {
id: string;
label: string;
/** Minimum width/height in grid units — prevents the content from collapsing. */
minW: number;
minH: number;
/** Default placement when the operator hasn't positioned it yet. */
def: { x: number; y: number; w: number; h: number };
}
/** The five top stat tiles, split out of the legacy single `stats` block. */
export const STAT_TILE_IDS = [
'stat:status', 'stat:accounts', 'stat:processes', 'stat:host', 'stat:uptime',
] as const;
export const GRID_WIDGETS: GridWidgetSpec[] = [
{ id: 'stat:status', label: '服务状态', minW: 2, minH: 1, def: { x: 0, y: 0, w: 2, h: 1 } },
{ id: 'stat:accounts', label: '在线账号', minW: 2, minH: 1, def: { x: 2, y: 0, w: 2, h: 1 } },
{ id: 'stat:processes', label: '进程注入', minW: 2, minH: 1, def: { x: 4, y: 0, w: 2, h: 1 } },
{ id: 'stat:host', label: '主机名', minW: 2, minH: 1, def: { x: 6, y: 0, w: 2, h: 1 } },
{ id: 'stat:uptime', label: '系统运行', minW: 2, minH: 1, def: { x: 8, y: 0, w: 2, h: 1 } },
{ id: 'connections', label: 'OneBot 连接', minW: 3, minH: 3, def: { x: 0, y: 1, w: 6, h: 4 } },
{ id: 'alerts', label: '最近告警', minW: 3, minH: 3, def: { x: 6, y: 1, w: 6, h: 4 } },
{ id: 'host', label: '主机资源', minW: 4, minH: 3, def: { x: 0, y: 5, w: 12, h: 4 } },
{ id: 'sessions', label: '在线会话', minW: 3, minH: 3, def: { x: 0, y: 9, w: 12, h: 5 } },
];
const WIDGET_BY_ID = new Map(GRID_WIDGETS.map((w) => [w.id, w]));
export function widgetLabel(id: string): string {
return WIDGET_BY_ID.get(id)?.label ?? id;
}
function isObj(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
function validCoords(item: UiLayoutItem | undefined): boolean {
return !!item
&& typeof item.x === 'number' && typeof item.y === 'number'
&& typeof item.w === 'number' && typeof item.h === 'number';
}
/** A fully-positioned overview block (coords always present). */
export function defaultOverviewGrid(): UiLayoutItem[] {
return GRID_WIDGETS.map((w) => ({ id: w.id, visible: true, ...w.def }));
}
/**
* Bring any stored overview layout up to the current grid catalogue:
* - expand the legacy single `stats` block into the 5 individual tiles
* (inheriting its visibility),
* - keep stored coords/visibility for known widgets, assign the default
* placement to any widget missing coords,
* - append catalogue widgets the stored layout predates (visible),
* - drop unknown ids.
* Output items always carry x/y/w/h.
*/
export function migrateOverviewBlocks(stored: UiLayoutItem[] | undefined): UiLayoutItem[] {
const byId = new Map<string, UiLayoutItem>();
for (const raw of Array.isArray(stored) ? stored : []) {
if (isObj(raw) && typeof raw.id === 'string') byId.set(raw.id, raw as UiLayoutItem);
}
// Legacy: a single `stats` block → seed the 5 tiles' visibility from it,
// but only when the tiles aren't already individually present.
const legacyStats = byId.get('stats');
return GRID_WIDGETS.map((spec) => {
const item = byId.get(spec.id);
const isStatTile = (STAT_TILE_IDS as readonly string[]).includes(spec.id);
const visible = item
? item.visible !== false
: isStatTile && legacyStats
? legacyStats.visible !== false
: true;
const coords = validCoords(item)
? { x: item!.x!, y: item!.y!, w: item!.w!, h: item!.h! }
: { ...spec.def };
return { id: spec.id, visible, ...coords };
});
}
export function minSizeOf(id: string): { minW: number; minH: number } {
const spec = WIDGET_BY_ID.get(id);
return { minW: spec?.minW ?? 1, minH: spec?.minH ?? 1 };
}
+5
View File
@@ -209,6 +209,11 @@ export interface UiAppearance {
export interface UiLayoutItem {
id: string;
visible: boolean;
/** Grid position/size — overview blocks only; nav items omit them. */
x?: number;
y?: number;
w?: number;
h?: number;
}
export interface UiLayout {
+47 -2
View File
@@ -381,6 +381,9 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
gridstack:
specifier: ^12.6.0
version: 12.6.0
lucide-react:
specifier: ^0.469.0
version: 0.469.0([email protected])
@@ -2315,6 +2318,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
[email protected]:
resolution: {integrity: sha512-dUrqsormSybFn/2P4Dz8AgprftKD5e/IiV7UmC0XLQU+G+/WtkAeFiCSNLoAGhPDXoJ/O61Xtj3gljY/Ds83yQ==}
[email protected]:
resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
engines: {node: '>=8'}
@@ -4431,7 +4437,7 @@ snapshots:
magicast: 0.5.3
obug: 2.1.1
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@24.12.2)([email protected])([email protected])([email protected])([email protected]))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@25.6.0)([email protected])([email protected])([email protected])([email protected]))
transitivePeerDependencies:
- supports-color
@@ -4447,7 +4453,7 @@ snapshots:
obug: 2.1.1
std-env: 4.1.0
tinyrainbow: 3.1.0
vitest: 4.1.4(@types/node@24.12.2)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@24.12.2)([email protected])([email protected])([email protected])([email protected]))
vitest: 4.1.4(@types/node@25.6.0)(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/node@25.6.0)([email protected])([email protected])([email protected])([email protected]))
'@vitest/[email protected]':
dependencies:
@@ -4466,6 +4472,14 @@ snapshots:
optionalDependencies:
vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':
dependencies:
'@vitest/spy': 4.1.4
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
'@vitest/[email protected]':
dependencies:
tinyrainbow: 3.1.0
@@ -4978,6 +4992,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -5761,6 +5777,35 @@ snapshots:
transitivePeerDependencies:
- msw
[email protected](@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):
dependencies:
'@vitest/expect': 4.1.4
'@vitest/mocker': 4.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
'@vitest/pretty-format': 4.1.4
'@vitest/runner': 4.1.4
'@vitest/snapshot': 4.1.4
'@vitest/spy': 4.1.4
'@vitest/utils': 4.1.4
es-module-lexer: 2.0.0
expect-type: 1.3.0
magic-string: 0.30.21
obug: 2.1.1
pathe: 2.0.3
picomatch: 4.0.4
std-env: 4.1.0
tinybench: 2.9.0
tinyexec: 1.1.1
tinyglobby: 0.2.16
tinyrainbow: 3.1.0
vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 25.6.0
'@vitest/coverage-istanbul': 4.1.4([email protected])
'@vitest/coverage-v8': 4.1.4([email protected])
transitivePeerDependencies:
- msw
[email protected]:
dependencies:
'@types/fs-extra': 11.0.4