feat(webui): in-place dashboard edit overlays + inline sidebar reorder

Rework the layout edit mode from a separate panel to in-place affordances:
- Each dashboard widget gets a semi-transparent floating overlay in edit mode:
  a "拖动" grip bar (the whole card is the drag target — forgiving +
  discoverable), an eye to show/hide, and a gear that opens the per-widget
  settings in a dialog. Hidden widgets show as re-enableable "已隐藏" ghosts;
  the bottom-right resize grip is now clearly visible.
- The sidebar nav becomes a drag-to-reorder list directly in the sidebar
  (show/hide + locked pinned items + a 完成 button); editing force-expands the
  sidebar (and disables the collapse toggle). Edit mode is a shared
  LayoutContext flag so one "编辑布局" toggle drives both the grid and the nav.
- The separate editor panel (overview-layout-editor) is removed; the gear
  opens config in a dialog instead.

Also: stat-tile typography tightened (leading-tight, smaller value, overflow
clip) so text no longer hugs the edge on small/short tiles. Verified by an
adversarial review round (no MUST-FIX).
This commit is contained in:
DrSmoothl committed 2026-06-13 21:45:41 +08:00
1 parent 056fff415c
commit a61e0a253d
9 files changed
+339 -349

No files matched your search

@@ -7,6 +7,7 @@ import { Sidebar } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar'; import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query'; import { useMediaQuery } from '@/hooks/use-media-query';
import { useTheme } from '@/contexts/ThemeContext'; import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
interface MainLayoutProps { interface MainLayoutProps {
@@ -27,6 +28,10 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
return appearance.sidebarDefaultCollapsed; return appearance.sidebarDefaultCollapsed;
}); });
const customBg = appearance.background.type !== 'none'; const customBg = appearance.background.type !== 'none';
const { editing } = useLayout();
// Force the sidebar open while editing layout so its drag-to-reorder list
// has room (it returns to the user's collapsed pref on 完成).
const effectiveCollapsed = collapsed && !editing;
const [mobileOpen, setMobileOpen] = useState(false); const [mobileOpen, setMobileOpen] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname }); const pathname = useRouterState({ select: (s) => s.location.pathname });
@@ -40,11 +45,11 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
{!isMobile && ( {!isMobile && (
<motion.aside <motion.aside
initial={false} initial={false}
animate={{ width: collapsed ? 64 : 248 }} animate={{ width: effectiveCollapsed ? 64 : 248 }}
transition={{ type: 'spring', stiffness: 280, damping: 32 }} transition={{ type: 'spring', stiffness: 280, damping: 32 }}
className="relative h-full shrink-0 border-r overflow-hidden" className="relative h-full shrink-0 border-r overflow-hidden"
> >
<Sidebar collapsed={collapsed} /> <Sidebar collapsed={effectiveCollapsed} />
</motion.aside> </motion.aside>
)} )}
@@ -66,11 +71,12 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col">
<TopBar <TopBar
status={status} status={status}
collapsed={collapsed} collapsed={effectiveCollapsed}
onToggleCollapse={() => setCollapsed((v) => !v)} onToggleCollapse={() => setCollapsed((v) => !v)}
onOpenMobile={() => setMobileOpen(true)} onOpenMobile={() => setMobileOpen(true)}
onLogout={onLogout} onLogout={onLogout}
isMobile={isMobile} isMobile={isMobile}
editing={editing}
/> />
<main className={cn('flex min-h-0 flex-1 flex-col')}> <main className={cn('flex min-h-0 flex-1 flex-col')}>
+101 -41
View File
@@ -1,5 +1,5 @@
import { LayoutDashboard, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react'; import { Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion } from 'motion/react'; import { motion, Reorder } from 'motion/react';
import { Link, useRouterState } from '@tanstack/react-router'; import { Link, useRouterState } from '@tanstack/react-router';
import { ScrollArea } from '@/components/ui/scroll-area'; import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator'; import { Separator } from '@/components/ui/separator';
@@ -38,15 +38,23 @@ 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(); const { navItems, setNavItems, editing, setEditing } = useLayout();
// Render nav in the operator's configured order, hidden items removed, // Full reconciled nav (incl. hidden) — pinned forced visible, forward-compat.
// pinned items forced on, and forward-compatible with future routes. const reconciled = reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV);
const orderedNav = reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV) // View mode: configured order, hidden removed.
const orderedNav = reconciled
.filter((i) => i.visible) .filter((i) => i.visible)
.map((i) => NAV_ITEMS.find((n) => n.to === i.id)) .map((i) => NAV_ITEMS.find((n) => n.to === i.id))
.filter((n): n is NavItem => !!n); .filter((n): n is NavItem => !!n);
const reorderNav = (ids: string[]) => {
const byId = new Map(reconciled.map((i) => [i.id, i]));
setNavItems(ids.map((id) => byId.get(id)).filter((x): x is NonNullable<typeof x> => !!x));
};
const toggleNav = (id: string) =>
setNavItems(reconciled.map((i) => (i.id === id ? { ...i, visible: !i.visible } : i)));
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">
{/* Brand */} {/* Brand */}
@@ -67,42 +75,94 @@ 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')}> {editing ? (
{orderedNav.map(({ to, label, icon: Icon, description }) => { <div className="flex flex-col gap-2 p-2">
const isActive = pathname === to; <div className="flex items-center justify-between px-1">
return ( <span className="text-[11px] font-medium text-muted-foreground">编辑导航</span>
<Link <button
key={to} type="button"
to={to} onClick={() => setEditing(false)}
title={collapsed ? label : undefined} className="inline-flex items-center gap-1 rounded-md border border-primary/40 bg-primary/10 px-2 py-0.5 text-[11px] text-primary transition-colors hover:bg-primary/15 cursor-pointer"
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
> >
{isActive && ( <Check className="size-3" /> 完成
<motion.span </button>
layoutId="sidebar-active-pill" </div>
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20" <Reorder.Group axis="y" values={reconciled.map((i) => i.id)} onReorder={reorderNav} className="flex flex-col gap-1">
transition={{ type: 'spring', stiffness: 380, damping: 32 }} {reconciled.map((item) => {
/> const meta = NAV_ITEMS.find((n) => n.to === item.id);
)} if (!meta) return null;
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} /> const Icon = meta.icon;
{!collapsed && ( const pinned = (PINNED_NAV as string[]).includes(item.id);
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start"> return (
<span className="truncate leading-tight">{label}</span> <Reorder.Item
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span> key={item.id}
</span> value={item.id}
)} className={cn(
</Link> 'flex select-none items-center gap-2 rounded-lg border bg-sidebar-accent/30 px-2 py-2 cursor-grab active:cursor-grabbing',
); !item.visible && 'opacity-50',
})} )}
</nav> >
<GripVertical className="size-3.5 shrink-0 text-muted-foreground" />
<Icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{meta.label}</span>
{pinned ? (
<span title="必选项,不可隐藏" className="inline-flex size-7 items-center justify-center text-muted-foreground/50">
<Lock className="size-3.5" />
</span>
) : (
<button
type="button"
onClick={() => toggleNav(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent/50 hover:text-foreground cursor-pointer"
>
{item.visible ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}
</button>
)}
</Reorder.Item>
);
})}
</Reorder.Group>
</div>
) : (
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{orderedNav.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<Link
key={to}
to={to}
title={collapsed ? label : undefined}
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
>
{isActive && (
<motion.span
layoutId="sidebar-active-pill"
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
)}
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
{!collapsed && (
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
<span className="truncate leading-tight">{label}</span>
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</Link>
);
})}
</nav>
)}
</ScrollArea> </ScrollArea>
<Separator /> <Separator />
@@ -15,6 +15,8 @@ interface TopBarProps {
onOpenMobile: () => void; onOpenMobile: () => void;
onLogout: () => void; onLogout: () => void;
isMobile: boolean; isMobile: boolean;
/** Layout edit mode force-expands the sidebar, so collapsing is disabled. */
editing?: boolean;
} }
export function TopBar({ export function TopBar({
@@ -24,6 +26,7 @@ export function TopBar({
onOpenMobile, onOpenMobile,
onLogout, onLogout,
isMobile, isMobile,
editing = false,
}: TopBarProps) { }: TopBarProps) {
const [confirmLogout, setConfirmLogout] = useState(false); const [confirmLogout, setConfirmLogout] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname }); const pathname = useRouterState({ select: (s) => s.location.pathname });
@@ -43,8 +46,9 @@ export function TopBar({
variant="ghost" variant="ghost"
size="icon-sm" size="icon-sm"
onClick={onToggleCollapse} onClick={onToggleCollapse}
disabled={editing}
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'} aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
title={collapsed ? '展开侧边栏' : '收起侧边栏'} title={editing ? '编辑布局时侧栏保持展开' : collapsed ? '展开侧边栏' : '收起侧边栏'}
> >
{collapsed ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />} {collapsed ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />}
</Button> </Button>
@@ -1,6 +1,7 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { GridStack, type GridStackWidget } from 'gridstack'; import { GridStack, type GridStackWidget } from 'gridstack';
import { Eye, EyeOff, GripVertical, Settings2 } from 'lucide-react';
import 'gridstack/dist/gridstack.css'; import 'gridstack/dist/gridstack.css';
import { GRID_CELL_HEIGHT, GRID_MARGIN, minSizeOf } from '@/lib/dashboard-layout'; import { GRID_CELL_HEIGHT, GRID_MARGIN, minSizeOf } from '@/lib/dashboard-layout';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -9,7 +10,8 @@ import type { UiLayoutItem } from '@/types';
export interface GridCoord { id: string; x: number; y: number; w: number; h: number } export interface GridCoord { id: string; x: number; y: number; w: number; h: number }
interface DashboardGridProps { interface DashboardGridProps {
/** Visible blocks, each with x/y/w/h (already migrated/positioned). */ /** Blocks to render — visible-only in view mode, ALL (incl. hidden) in edit
* mode so hidden widgets show as re-enableable ghosts. Each has x/y/w/h. */
blocks: UiLayoutItem[]; blocks: UiLayoutItem[];
editing: boolean; editing: boolean;
/** Column count — 12 on desktop, 1 on narrow screens (auto single-column). */ /** Column count — 12 on desktop, 1 on narrow screens (auto single-column). */
@@ -17,6 +19,11 @@ interface DashboardGridProps {
/** Fired (debounced upstream) after a drag/resize settles. */ /** Fired (debounced upstream) after a drag/resize settles. */
onChange: (coords: GridCoord[]) => void; onChange: (coords: GridCoord[]) => void;
renderWidget: (block: UiLayoutItem) => ReactNode; renderWidget: (block: UiLayoutItem) => ReactNode;
// ── edit overlay ──
labelFor: (id: string) => string;
configurableIds: ReadonlySet<string>;
onToggleVisible: (id: string) => void;
onConfigOpen: (id: string) => void;
} }
/** /**
@@ -27,7 +34,10 @@ interface DashboardGridProps {
* coord change (gridstack already moved the item; the coord round-trips back * coord change (gridstack already moved the item; the coord round-trips back
* through `onChange` → state and matches what gridstack has). * through `onChange` → state and matches what gridstack has).
*/ */
export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }: DashboardGridProps) { export function DashboardGrid({
blocks, editing, cols, onChange, renderWidget,
labelFor, configurableIds, onToggleVisible, onConfigOpen,
}: DashboardGridProps) {
const elRef = useRef<HTMLDivElement | null>(null); const elRef = useRef<HTMLDivElement | null>(null);
const gridRef = useRef<GridStack | null>(null); const gridRef = useRef<GridStack | null>(null);
const [contentEls, setContentEls] = useState<Record<string, HTMLElement>>({}); const [contentEls, setContentEls] = useState<Record<string, HTMLElement>>({});
@@ -53,7 +63,11 @@ export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }:
float: true, // free placement — items stay where dropped (no auto-compact) float: true, // free placement — items stay where dropped (no auto-compact)
disableDrag: !editing, disableDrag: !editing,
disableResize: !editing, disableResize: !editing,
handle: '.grid-stack-item-content', // Default handle (.grid-stack-item-content) = the whole card is a drag
// target in edit mode — forgiving + discoverable. The card body is
// pointer-events-none in edit mode so widget controls don't fire, and
// the eye/gear are <button>s which gridstack's skipMouseDown excludes
// from dragging. The overlay's grip + "拖动" label is the visual cue.
}, },
host, host,
); );
@@ -94,16 +108,55 @@ export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }:
return ( return (
<div ref={elRef} className="grid-stack -mx-1"> <div ref={elRef} className="grid-stack -mx-1">
{blocks.map((b) => {blocks.map((b) => {
contentEls[b.id] const target = contentEls[b.id];
? createPortal( if (!target) return null;
<div className={cn('h-full w-full overflow-auto', editing && 'pointer-events-none select-none')}> const hidden = editing && !b.visible;
{renderWidget(b)} return createPortal(
</div>, <div className="relative h-full w-full">
contentEls[b.id], {editing && (
) <div className="pointer-events-auto absolute inset-x-0 top-0 z-20 flex items-center gap-1 rounded-t-xl border-b border-border/50 bg-background/70 px-1.5 py-1 backdrop-blur-sm">
: null, <div
)} className="widget-drag-handle flex flex-1 cursor-grab items-center gap-1 rounded px-1 py-0.5 text-[11px] font-medium text-muted-foreground hover:bg-accent/50 active:cursor-grabbing"
title="拖动调整位置"
>
<GripVertical className="size-3.5" /> 拖动
</div>
{configurableIds.has(b.id) && b.visible && (
<button
type="button"
onClick={() => onConfigOpen(b.id)}
title="设置"
aria-label="设置"
className="inline-flex size-6 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
<Settings2 className="size-3.5" />
</button>
)}
<button
type="button"
onClick={() => onToggleVisible(b.id)}
title={b.visible ? '隐藏' : '显示'}
aria-label={b.visible ? '隐藏' : '显示'}
className="inline-flex size-6 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
{b.visible ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}
</button>
</div>
)}
{hidden ? (
<div className="flex h-full w-full items-center justify-center rounded-xl border border-dashed bg-muted/20 px-2 text-center text-[11px] text-muted-foreground">
{labelFor(b.id)} · 已隐藏
</div>
) : (
<div className={cn('h-full w-full overflow-auto rounded-xl', editing && 'pointer-events-none select-none')}>
{renderWidget(b)}
</div>
)}
</div>,
target,
);
})}
</div> </div>
); );
} }
@@ -1,244 +0,0 @@
import { useMemo, useState } from 'react';
import { Reorder } from 'motion/react';
import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw, Settings2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import {
ALL_LOG_LEVELS, CONFIGURABLE_WIDGETS, parseAlertsConfig, parseSessionsConfig,
} from '@/lib/dashboard-layout';
import type { UiLayoutItem } from '@/types';
type SortOpt = 'recent' | 'uin' | 'nickname';
const SORT_LABELS: Record<SortOpt, string> = { recent: '最近', uin: 'QQ 号', nickname: '昵称' };
// Edit panel for the overview's "编辑布局" mode. Overview-card POSITION/SIZE is
// edited in place on the gridstack grid below; this panel only toggles which
// cards are shown, and (re)orders the sidebar nav (a 1-D list, so it keeps the
// motion Reorder drag from phase 3). Pinned nav items can't be hidden.
// ── widget visibility (no drag — grid owns position) ──
function AlertsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseAlertsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<label className="flex items-center justify-between gap-3 text-xs">
<span className="text-muted-foreground">显示条数</span>
<Input
type="number" min={1} max={50} value={c.count}
onChange={(e) => onChange({ count: Math.min(50, Math.max(1, Math.trunc(Number(e.target.value) || 1))) })}
className="h-8 w-20"
/>
</label>
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">级别</span>
<div className="flex flex-wrap gap-1.5">
{ALL_LOG_LEVELS.map((lv) => {
const on = c.levels.includes(lv);
return (
<button
key={lv}
type="button"
onClick={() => {
const next = on ? c.levels.filter((x) => x !== lv) : [...c.levels, lv];
if (next.length > 0) onChange({ levels: next });
}}
className={cn(
'rounded-md border px-2 py-1 text-[11px] uppercase transition-colors cursor-pointer',
on ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{lv}
</button>
);
})}
</div>
</div>
</div>
);
}
function SessionsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseSessionsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">排序</span>
<div className="flex flex-wrap gap-1.5">
{(['recent', 'uin', 'nickname'] as SortOpt[]).map((s) => (
<button
key={s}
type="button"
onClick={() => onChange({ sort: s })}
className={cn(
'rounded-md border px-2 py-1 text-[11px] transition-colors cursor-pointer',
c.sort === s ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{SORT_LABELS[s]}
</button>
))}
</div>
</div>
<label className="flex flex-col gap-1.5 text-xs">
<span className="text-muted-foreground">筛选(昵称 / QQ 号)</span>
<Input value={c.filter} placeholder="留空显示全部" maxLength={100} onChange={(e) => onChange({ filter: e.target.value })} className="h-8" />
</label>
</div>
);
}
function VisibilityList({
items, labelFor, onToggle, onConfig,
}: {
items: UiLayoutItem[];
labelFor: (id: string) => string;
onToggle: (id: string) => void;
onConfig: (id: string, config: Record<string, unknown>) => void;
}) {
const [open, setOpen] = useState<string | null>(null);
return (
<div className="flex flex-col gap-2">
{items.map((item) => {
const configurable = CONFIGURABLE_WIDGETS.has(item.id);
const isOpen = open === item.id;
return (
<div key={item.id} className={cn('overflow-hidden rounded-lg border bg-card/50', !item.visible && 'opacity-50')}>
<div className="flex items-center gap-3 px-3 py-2.5">
<span className="flex-1 truncate text-sm font-medium">{labelFor(item.id)}</span>
{configurable && (
<button
type="button"
onClick={() => setOpen(isOpen ? null : item.id)}
title="设置"
aria-label="设置"
className={cn(
'inline-flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors hover:bg-accent/40',
isOpen ? 'text-primary' : 'text-muted-foreground hover:text-foreground',
)}
>
<Settings2 className="size-4" />
</button>
)}
<button
type="button"
onClick={() => onToggle(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
>
{item.visible ? <Eye className="size-4" /> : <EyeOff className="size-4" />}
</button>
</div>
{configurable && isOpen && (
item.id === 'alerts'
? <AlertsConfigForm config={item.config} onChange={(c) => onConfig('alerts', c)} />
: <SessionsConfigForm config={item.config} onChange={(c) => onConfig('sessions', c)} />
)}
</div>
);
})}
</div>
);
}
// ── 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[]) =>
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[];
onToggleBlock: (id: string) => void;
onBlockConfig: (id: string, config: Record<string, unknown>) => void;
onNav: (items: UiLayoutItem[]) => void;
onReset: () => void;
onDone: () => void;
}
export function LayoutEditor({
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onBlockConfig, onNav, onReset, onDone,
}: LayoutEditorProps) {
return (
<Card>
<CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">
<div>
<CardTitle className="text-base">编辑布局</CardTitle>
<CardDescription>在下方网格直接拖动卡片、拖角缩放;这里控制卡片显隐与导航。改动自动保存。</CardDescription>
</div>
<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>
<Button size="sm" onClick={onDone}>
<Check className="size-4" /> 完成
</Button>
</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} onConfig={onBlockConfig} />
</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,8 +2,8 @@ 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 {
Activity, ArrowRight, Bell, Cable, Cpu, MemoryStick, MonitorCog, Pencil, PlugZap, Activity, ArrowRight, Bell, Cable, Check, Cpu, MemoryStick, MonitorCog, Pencil, PlugZap,
RefreshCw, Server, Users, RefreshCw, RotateCcw, Server, Users,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -18,22 +18,20 @@ 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 { useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query'; import { useMediaQuery } from '@/hooks/use-media-query';
import { import {
GRID_COLS, parseAlertsConfig, parseSessionsConfig, widgetLabel, CONFIGURABLE_WIDGETS, GRID_COLS, parseAlertsConfig, parseSessionsConfig, widgetLabel,
type AlertsConfig, type SessionsConfig, type AlertsConfig, type SessionsConfig,
} from '@/lib/dashboard-layout'; } from '@/lib/dashboard-layout';
import { NAV_ITEMS, PINNED_NAV } from '@/components/layout/sidebar'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid'; import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid';
import { LayoutEditor } from '@/components/pages/overview-layout-editor'; import { AlertsConfigForm, SessionsConfigForm } from '@/components/pages/widget-config-forms';
function qqAvatarUrl(uin: string) { function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`; return `/avatar/${encodeURIComponent(uin)}`;
} }
const navLabelFor = (id: string) => NAV_ITEMS.find((n) => n.to === id)?.label ?? id;
function renderWidget(block: UiLayoutItem): ReactNode { function renderWidget(block: UiLayoutItem): ReactNode {
if (block.id.startsWith('stat:')) return <StatTileWidget id={block.id} />; if (block.id.startsWith('stat:')) return <StatTileWidget id={block.id} />;
switch (block.id) { switch (block.id) {
@@ -47,16 +45,15 @@ function renderWidget(block: UiLayoutItem): ReactNode {
export function OverviewPage() { export function OverviewPage() {
const { qqList, processList } = useAppState(); const { qqList, processList } = useAppState();
const { overviewBlocks, navItems, setOverviewBlocks, setNavItems, resetLayout } = useLayout(); const { overviewBlocks, setOverviewBlocks, resetLayout, editing: editingCtx, setEditing } = useLayout();
const isWide = useMediaQuery('(min-width: 768px)'); const isWide = useMediaQuery('(min-width: 768px)');
const [editingOn, setEditingOn] = useState(false); // Free-grid editing is desktop-only (no room to drag/resize on a phone).
const editing = isWide && editingOn; const editing = isWide && editingCtx;
const [configId, setConfigId] = useState<string | null>(null);
const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [overviewBlocks]); const visibleBlocks = useMemo(() => overviewBlocks.filter((b) => b.visible), [overviewBlocks]);
const nav = useMemo( // In edit mode show ALL blocks (hidden ones as re-enableable ghosts); else visible-only.
() => reconcileLayoutItems(navItems, NAV_ITEMS.map((i) => i.to), PINNED_NAV), const gridBlocks = editing ? overviewBlocks : visibleBlocks;
[navItems],
);
const onGridChange = (coords: GridCoord[]) => { const onGridChange = (coords: GridCoord[]) => {
const cmap = new Map(coords.map((c) => [c.id, c])); const cmap = new Map(coords.map((c) => [c.id, c]));
@@ -75,31 +72,30 @@ export function OverviewPage() {
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b))); setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b)));
const loadableProcs = processList.filter((p) => !p.injected).length; const loadableProcs = processList.filter((p) => !p.injected).length;
const configBlock = configId ? overviewBlocks.find((b) => b.id === configId) : null;
return ( return (
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
{/* Toolbar: edit toggle is desktop-only (free grid needs room to drag). */} {/* Toolbar: edit toggle is desktop-only. In edit mode the cards carry
{isWide && !editing && ( their own floating drag/hide/settings overlays, and the sidebar nav
<div className="flex items-center justify-end"> becomes drag-sortable — no separate editor panel. */}
<Button variant="outline" size="sm" onClick={() => setEditingOn(true)}> {isWide && (
<Pencil className="size-3.5" /> 编辑布局 <div className="flex items-center justify-end gap-2">
{editing && (
<Button variant="ghost" size="sm" onClick={resetLayout} className="text-muted-foreground">
<RotateCcw className="size-3.5" /> 恢复默认
</Button>
)}
<Button variant={editing ? 'default' : 'outline'} size="sm" onClick={() => setEditing(!editingCtx)}>
{editing ? <><Check className="size-3.5" /> 完成</> : <><Pencil className="size-3.5" /> 编辑布局</>}
</Button> </Button>
</div> </div>
)} )}
{editing && ( {editing && (
<LayoutEditor <p className="rounded-lg border border-primary/20 bg-primary/5 px-3 py-2 text-[11px] text-muted-foreground">
blocks={overviewBlocks} 拖动卡片顶部的「拖动」手柄移动位置、拖右下角缩放;眼睛图标显隐、齿轮改设置。左侧导航也可在编辑态拖动排序。
blockLabelFor={widgetLabel} </p>
navItems={nav}
navLabelFor={navLabelFor}
navPinned={PINNED_NAV}
onToggleBlock={toggleBlock}
onBlockConfig={setBlockConfig}
onNav={setNavItems}
onReset={resetLayout}
onDone={() => setEditingOn(false)}
/>
)} )}
{/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */} {/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */}
@@ -125,17 +121,31 @@ export function OverviewPage() {
</motion.div> </motion.div>
)} )}
{visibleBlocks.length === 0 ? ( {visibleBlocks.length === 0 && !editing ? (
<EmptyLayout onReset={resetLayout} /> <EmptyLayout onReset={resetLayout} />
) : ( ) : (
<DashboardGrid <DashboardGrid
blocks={visibleBlocks} blocks={gridBlocks}
editing={editing} editing={editing}
cols={isWide ? GRID_COLS : 1} cols={isWide ? GRID_COLS : 1}
onChange={onGridChange} onChange={onGridChange}
renderWidget={renderWidget} renderWidget={renderWidget}
labelFor={widgetLabel}
configurableIds={CONFIGURABLE_WIDGETS}
onToggleVisible={toggleBlock}
onConfigOpen={setConfigId}
/> />
)} )}
<Dialog open={!!configId} onOpenChange={(o) => { if (!o) setConfigId(null); }}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle>{configBlock ? `${widgetLabel(configBlock.id)} · 设置` : '设置'}</DialogTitle>
</DialogHeader>
{configBlock?.id === 'alerts' && <AlertsConfigForm config={configBlock.config} onChange={(c) => setBlockConfig('alerts', c)} />}
{configBlock?.id === 'sessions' && <SessionsConfigForm config={configBlock.config} onChange={(c) => setBlockConfig('sessions', c)} />}
</DialogContent>
</Dialog>
</div> </div>
); );
} }
@@ -163,19 +173,19 @@ function StatTile({
to?: AppPath; to?: AppPath;
}) { }) {
const body = ( const body = (
<CardContent className="flex h-full items-center gap-3 p-4"> <CardContent className="flex h-full items-center gap-2.5 overflow-hidden px-4 py-3">
<div <div
className={cn( className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-xl', 'flex size-9 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} {icon}
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p> <p className="truncate text-[11px] font-medium uppercase leading-tight tracking-wider text-muted-foreground">{label}</p>
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div> <div className="mt-1 truncate text-[15px] font-semibold leading-tight tabular-nums">{value}</div>
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>} {subtext && <p className="mt-1 truncate text-[11px] leading-tight text-muted-foreground">{subtext}</p>}
</div> </div>
{to && <ArrowRight className="size-4 shrink-0 text-muted-foreground/60" />} {to && <ArrowRight className="size-4 shrink-0 text-muted-foreground/60" />}
</CardContent> </CardContent>
@@ -0,0 +1,85 @@
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { ALL_LOG_LEVELS, parseAlertsConfig, parseSessionsConfig } from '@/lib/dashboard-layout';
// Per-widget config forms, shown inside a dialog opened from a dashboard
// widget's edit-overlay gear. `config` is the widget's opaque block.config;
// `onChange` merges a partial back via setBlockConfig.
type SortOpt = 'recent' | 'uin' | 'nickname';
const SORT_LABELS: Record<SortOpt, string> = { recent: '最近', uin: 'QQ 号', nickname: '昵称' };
interface FormProps {
config: Record<string, unknown> | undefined;
onChange: (c: Record<string, unknown>) => void;
}
export function AlertsConfigForm({ config, onChange }: FormProps) {
const c = parseAlertsConfig(config);
return (
<div className="flex flex-col gap-4">
<label className="flex items-center justify-between gap-3 text-sm">
<span className="text-muted-foreground">显示条数</span>
<Input
type="number" min={1} max={50} value={c.count}
onChange={(e) => onChange({ count: Math.min(50, Math.max(1, Math.trunc(Number(e.target.value) || 1))) })}
className="h-8 w-24"
/>
</label>
<div className="flex flex-col gap-1.5">
<span className="text-sm text-muted-foreground">显示级别</span>
<div className="flex flex-wrap gap-1.5">
{ALL_LOG_LEVELS.map((lv) => {
const on = c.levels.includes(lv);
return (
<button
key={lv}
type="button"
onClick={() => {
const next = on ? c.levels.filter((x) => x !== lv) : [...c.levels, lv];
if (next.length > 0) onChange({ levels: next });
}}
className={cn(
'rounded-md border px-2.5 py-1 text-xs uppercase transition-colors cursor-pointer',
on ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{lv}
</button>
);
})}
</div>
</div>
</div>
);
}
export function SessionsConfigForm({ config, onChange }: FormProps) {
const c = parseSessionsConfig(config);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<span className="text-sm text-muted-foreground">排序</span>
<div className="flex flex-wrap gap-1.5">
{(['recent', 'uin', 'nickname'] as SortOpt[]).map((s) => (
<button
key={s}
type="button"
onClick={() => onChange({ sort: s })}
className={cn(
'rounded-md border px-2.5 py-1 text-xs transition-colors cursor-pointer',
c.sort === s ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{SORT_LABELS[s]}
</button>
))}
</div>
</div>
<label className="flex flex-col gap-1.5 text-sm">
<span className="text-muted-foreground">筛选(昵称 / QQ 号)</span>
<Input value={c.filter} placeholder="留空显示全部" maxLength={100} onChange={(e) => onChange({ filter: e.target.value })} className="h-8" />
</label>
</div>
);
}
@@ -79,6 +79,10 @@ interface LayoutContextValue {
setPages: (patch: Partial<UiPages>) => void; setPages: (patch: Partial<UiPages>) => void;
/** True once the authed config load has resolved (gates the default-route redirect). */ /** True once the authed config load has resolved (gates the default-route redirect). */
ready: boolean; ready: boolean;
/** Shared "编辑布局" mode — the dashboard grid AND the sidebar read this so both
* show in-place edit affordances from a single toggle. */
editing: boolean;
setEditing: (v: boolean) => void;
} }
const LayoutContext = createContext<LayoutContextValue | null>(null); const LayoutContext = createContext<LayoutContextValue | null>(null);
@@ -88,6 +92,7 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT); const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES); const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES);
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const [editing, setEditing] = useState(false);
const layoutRef = useRef(layout); const layoutRef = useRef(layout);
const pagesRef = useRef(pages); const pagesRef = useRef(pages);
// Set once the user edits, so the initial GET (which may resolve AFTER the // Set once the user edits, so the initial GET (which may resolve AFTER the
@@ -186,7 +191,9 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
pages, pages,
setPages, setPages,
ready, ready,
}), [layout, setOverviewBlocks, setNavItems, resetLayout, pages, setPages, ready]); editing,
setEditing,
}), [layout, setOverviewBlocks, setNavItems, resetLayout, pages, setPages, ready, editing]);
return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>; return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
} }
+16 -7
View File
@@ -238,12 +238,21 @@ html[data-reduce-motion="1"] *::after {
background: color-mix(in oklab, var(--primary) 8%, transparent); background: color-mix(in oklab, var(--primary) 8%, transparent);
border-radius: var(--radius); border-radius: var(--radius);
} }
/* Resize handle — only meaningful while editing (grid is interactive). */ /* Resize handle — only present while editing (grid is interactive). Make the
.grid-stack-item > .ui-resizable-handle { bottom-right grip obvious so it's clearly draggable. */
filter: none;
}
.grid-stack-item > .ui-resizable-se { .grid-stack-item > .ui-resizable-se {
/* Make the bottom-right resize grip visible against either theme. */ width: 18px;
border-right: 2px solid color-mix(in oklab, var(--primary) 70%, transparent); height: 18px;
border-bottom: 2px solid color-mix(in oklab, var(--primary) 70%, transparent); right: 5px;
bottom: 5px;
background-image: none;
transform: none;
border-right: 3px solid var(--primary);
border-bottom: 3px solid var(--primary);
border-bottom-right-radius: 5px;
opacity: 0.65;
z-index: 30;
}
.grid-stack-item:hover > .ui-resizable-se {
opacity: 1;
} }