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:
6 files changed
+435
-47
No files matched your search
@@ -6,6 +6,7 @@ import { Separator } from '@/components/ui/separator';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { APP_NAME, APP_VERSION } from '@/types';
|
import { APP_NAME, APP_VERSION } from '@/types';
|
||||||
import { useAppState } from '@/contexts/AppStateContext';
|
import { useAppState } from '@/contexts/AppStateContext';
|
||||||
|
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
|
||||||
import type { AppPath } from '@/router';
|
import type { AppPath } from '@/router';
|
||||||
|
|
||||||
export interface NavItem {
|
export interface NavItem {
|
||||||
@@ -23,6 +24,12 @@ export const NAV_ITEMS: NavItem[] = [
|
|||||||
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
|
{ 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 {
|
interface SidebarProps {
|
||||||
collapsed?: boolean;
|
collapsed?: boolean;
|
||||||
onItemClick?: () => void;
|
onItemClick?: () => void;
|
||||||
@@ -31,6 +38,14 @@ interface SidebarProps {
|
|||||||
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
|
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
|
||||||
const pathname = useRouterState({ select: (s) => s.location.pathname });
|
const pathname = useRouterState({ select: (s) => s.location.pathname });
|
||||||
const { updateInfo } = useAppState();
|
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 (
|
return (
|
||||||
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
|
<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 */}
|
{/* Nav */}
|
||||||
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
||||||
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
|
<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;
|
const isActive = pathname === to;
|
||||||
return (
|
return (
|
||||||
<Link
|
<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 { motion } from 'motion/react';
|
||||||
import { Link } from '@tanstack/react-router';
|
import { Link } from '@tanstack/react-router';
|
||||||
import {
|
import {
|
||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
Cpu,
|
Cpu,
|
||||||
MemoryStick,
|
MemoryStick,
|
||||||
MonitorCog,
|
MonitorCog,
|
||||||
|
Pencil,
|
||||||
PlugZap,
|
PlugZap,
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
Server,
|
Server,
|
||||||
@@ -27,11 +28,121 @@ import { useApi } from '@/lib/api';
|
|||||||
import { useAppState } from '@/contexts/AppStateContext';
|
import { useAppState } from '@/contexts/AppStateContext';
|
||||||
import { useSession } from '@/contexts/SessionContext';
|
import { useSession } from '@/contexts/SessionContext';
|
||||||
import { useTheme } from '@/contexts/ThemeContext';
|
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) {
|
function qqAvatarUrl(uin: string) {
|
||||||
return `/avatar/${encodeURIComponent(uin)}`;
|
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({
|
function StatTile({
|
||||||
icon,
|
icon,
|
||||||
label,
|
label,
|
||||||
@@ -77,8 +188,8 @@ function StatTile({
|
|||||||
return <Card className="overflow-hidden">{body}</Card>;
|
return <Card className="overflow-hidden">{body}</Card>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OverviewPage() {
|
function StatsBlock() {
|
||||||
const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState();
|
const { qqList, processList, systemInfo } = useAppState();
|
||||||
const { status } = useSession();
|
const { status } = useSession();
|
||||||
|
|
||||||
// Lightweight tick to refresh "uptime" pretty-print every 30s
|
// Lightweight tick to refresh "uptime" pretty-print every 30s
|
||||||
@@ -89,13 +200,10 @@ export function OverviewPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const online = status === '已连接';
|
const online = status === '已连接';
|
||||||
// Read-only injection health for the dashboard. Control lives on /processes.
|
|
||||||
const onlineProcs = processList.filter((p) => p.status === 'online').length;
|
const onlineProcs = processList.filter((p) => p.status === 'online').length;
|
||||||
const loadableProcs = processList.filter((p) => !p.injected).length;
|
const loadableProcs = processList.filter((p) => !p.injected).length;
|
||||||
|
|
||||||
return (
|
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">
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-5">
|
||||||
<StatTile
|
<StatTile
|
||||||
icon={<Activity className="size-5" />}
|
icon={<Activity className="size-5" />}
|
||||||
@@ -130,37 +238,14 @@ export function OverviewPage() {
|
|||||||
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
|
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
{/* First-run nudge: nothing online yet → point at the injection page. */}
|
// ─────────────── host resources ───────────────
|
||||||
{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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Operational health — connection status + recent alerts (side by side on wide screens) */}
|
function HostBlock() {
|
||||||
<div className="grid gap-6 xl:grid-cols-2">
|
const { systemInfo, refreshSystem } = useAppState();
|
||||||
<ConnectionsCard connections={connections} />
|
return (
|
||||||
<RecentAlertsCard />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* System metrics */}
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||||
<div>
|
<div>
|
||||||
@@ -264,8 +349,14 @@ export function OverviewPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
{/* Online accounts */}
|
// ─────────────── online sessions ───────────────
|
||||||
|
|
||||||
|
function SessionsBlock() {
|
||||||
|
const { qqList } = useAppState();
|
||||||
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>在线会话</CardTitle>
|
<CardTitle>在线会话</CardTitle>
|
||||||
@@ -305,7 +396,6 @@ export function OverviewPage() {
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -330,6 +420,11 @@ const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
|
|||||||
wsClient: 'WS 客户端',
|
wsClient: 'WS 客户端',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function ConnectionsBlock() {
|
||||||
|
const { connections } = useAppState();
|
||||||
|
return <ConnectionsCard connections={connections} />;
|
||||||
|
}
|
||||||
|
|
||||||
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
|
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
@@ -359,22 +454,22 @@ function ConnectionsCard({ connections }: { connections: AccountConnections[] })
|
|||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-1.5">
|
||||||
{acc.adapters.map((a) => (
|
{acc.adapters.map((adp) => (
|
||||||
<div key={a.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
|
<div key={adp.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium',
|
'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>
|
</span>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<span className="truncate text-sm font-medium">{a.name}</span>
|
<span className="truncate text-sm font-medium">{adp.name}</span>
|
||||||
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[a.kind]}</span>
|
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[adp.kind]}</span>
|
||||||
</div>
|
</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>
|
||||||
</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;
|
||||||
|
}
|
||||||
@@ -82,8 +82,9 @@ export interface ApiClient {
|
|||||||
ui: {
|
ui: {
|
||||||
/** Full config (appearance + layout). Bearer-gated. */
|
/** Full config (appearance + layout). Bearer-gated. */
|
||||||
get(): Promise<UiConfig>;
|
get(): Promise<UiConfig>;
|
||||||
/** Persist the full config; returns the normalized server view. */
|
/** Persist config. Section-level merge: a payload with only `appearance`
|
||||||
save(config: UiConfig): Promise<UiConfig>;
|
* 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). */
|
/** Cosmetic appearance subset, usable pre-auth (login page theming). */
|
||||||
getPublic(): Promise<UiAppearance>;
|
getPublic(): Promise<UiAppearance>;
|
||||||
/** Upload a background image (PNG/JPEG/WebP, ≤5MB). Returns updated config. */
|
/** Upload a background image (PNG/JPEG/WebP, ≤5MB). Returns updated config. */
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { MainLayout } from '@/components/layout/main-layout';
|
|||||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { AppStateProvider } from '@/contexts/AppStateContext';
|
import { AppStateProvider } from '@/contexts/AppStateContext';
|
||||||
|
import { LayoutProvider } from '@/contexts/LayoutContext';
|
||||||
import { useSession } from '@/contexts/SessionContext';
|
import { useSession } from '@/contexts/SessionContext';
|
||||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||||
|
|
||||||
@@ -125,6 +126,7 @@ export function AppLayout() {
|
|||||||
onLogout: handleLogout,
|
onLogout: handleLogout,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<LayoutProvider>
|
||||||
<MainLayout status={session.status} onLogout={handleLogout}>
|
<MainLayout status={session.status} onLogout={handleLogout}>
|
||||||
{/* Routes use `lazyRouteComponent` (router/index.tsx) for
|
{/* Routes use `lazyRouteComponent` (router/index.tsx) for
|
||||||
code-splitting, which suspends until the chunk is fetched.
|
code-splitting, which suspends until the chunk is fetched.
|
||||||
@@ -134,6 +136,7 @@ export function AppLayout() {
|
|||||||
<Outlet />
|
<Outlet />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</MainLayout>
|
</MainLayout>
|
||||||
|
</LayoutProvider>
|
||||||
|
|
||||||
<ConfirmDialog
|
<ConfirmDialog
|
||||||
open={!!unloadFailedAlert}
|
open={!!unloadFailedAlert}
|
||||||
|
|||||||
Reference in new issue
Block a user