From f07f309c5174af9d1730e0bd8c67aa4f3ed52bc2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 13 Jun 2026 20:11:45 +0800 Subject: [PATCH] feat(webui): free-form draggable/resizable dashboard grid (phase 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- packages/core/src/webui/ui-config.ts | 31 +- packages/webui/package.json | 1 + .../src/components/pages/dashboard-grid.tsx | 109 +++++++ .../pages/overview-layout-editor.tsx | 103 +++--- .../src/components/pages/overview-page.tsx | 305 ++++++++---------- packages/webui/src/contexts/LayoutContext.tsx | 24 +- packages/webui/src/index.css | 32 ++ packages/webui/src/lib/dashboard-layout.ts | 99 ++++++ packages/webui/src/types.ts | 5 + pnpm-lock.yaml | 49 ++- 10 files changed, 532 insertions(+), 226 deletions(-) create mode 100644 packages/webui/src/components/pages/dashboard-grid.tsx create mode 100644 packages/webui/src/lib/dashboard-layout.ts diff --git a/packages/core/src/webui/ui-config.ts b/packages/core/src/webui/ui-config.ts index bea79ba0..63a03e37 100644 --- a/packages/core/src/webui/ui-config.ts +++ b/packages/core/src/webui/ui-config.ts @@ -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. diff --git a/packages/webui/package.json b/packages/webui/package.json index f3181e36..fd26fa05 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -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", diff --git a/packages/webui/src/components/pages/dashboard-grid.tsx b/packages/webui/src/components/pages/dashboard-grid.tsx new file mode 100644 index 00000000..f0b31596 --- /dev/null +++ b/packages/webui/src/components/pages/dashboard-grid.tsx @@ -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(null); + const gridRef = useRef(null); + const [contentEls, setContentEls] = useState>({}); + + // 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 = {}; + 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 ( +
+ {blocks.map((b) => + contentEls[b.id] + ? createPortal( +
+ {renderWidget(b.id)} +
, + contentEls[b.id], + ) + : null, + )} +
+ ); +} diff --git a/packages/webui/src/components/pages/overview-layout-editor.tsx b/packages/webui/src/components/pages/overview-layout-editor.tsx index 2c486970..f3a60cfa 100644 --- a/packages/webui/src/components/pages/overview-layout-editor.tsx +++ b/packages/webui/src/components/pages/overview-layout-editor.tsx @@ -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 ( +
+ {items.map((item) => ( +
+ {labelFor(item.id)} + +
+ ))} +
+ ); } -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 ( @@ -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 ( -
-
+ +
-

编辑布局

-

拖动排序,点眼睛图标显示/隐藏。改动会自动保存。

+ 编辑布局 + 在下方网格直接拖动卡片、拖角缩放;这里控制卡片显隐与导航。改动自动保存。
-
+
@@ -100,27 +125,17 @@ export function LayoutEditor({ 完成
-
- - - - 总览卡片 - 调整总览页各卡片的顺序与显隐。 - - - - - - - - - 导航栏 - 调整左侧导航的顺序与显隐(「系统设置」固定保留)。 - - - - - -
+ + +
+

总览卡片(显隐)

+ +
+
+

导航栏(拖动排序)

+ +
+
+ ); } diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index ee2606c7..8042a724 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -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 ; switch (id) { - case 'stats': return ; case 'connections': return ; case 'alerts': return ; case 'host': return ; @@ -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 ( - 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 ( -
-
- -
+
+ {/* Toolbar: edit toggle is desktop-only (free grid needs room to drag). */} + {isWide && !editing && ( +
+ +
+ )} - {/* 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 && ( + setEditingOn(false)} + /> + )} + + {/* First-run nudge — always shown (not a grid widget) so it can't be hidden. */} {qqList.length === 0 && ( ) : ( - visibleBlocks.map((b) =>
{renderBlock(b.id)}
) + )}
); @@ -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 = ( - +
{icon} @@ -177,68 +173,75 @@ function StatTile({ {to && } ); - if (to) { return ( - - {body} + + {body} ); } - return {body}; + return {body}; } -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 ( -
- } - label="服务状态" - value={online ? '运行中' : status} - subtext={online ? '已连接到后端' : '请检查后端进程'} - accent={online} - /> - } - label="在线账号" - value={qqList.length} - subtext={`已接入 ${qqList.length} 个会话`} - /> - } - label="进程注入" - value={`${onlineProcs} 在线`} - subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`} - to="/processes" - /> - } - label="主机名" - value={systemInfo?.hostname ?? '—'} - subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'} - /> - } - label="系统运行" - value={systemInfo ? formatUptime(systemInfo.uptime) : '—'} - subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined} - /> -
- ); + switch (id) { + case 'stat:status': + return ( + } + label="服务状态" + value={online ? '运行中' : status} + subtext={online ? '已连接到后端' : '请检查后端进程'} + accent={online} + /> + ); + case 'stat:accounts': + return ( + } + label="在线账号" + value={qqList.length} + subtext={`已接入 ${qqList.length} 个会话`} + /> + ); + case 'stat:processes': { + const onlineProcs = processList.filter((p) => p.status === 'online').length; + const loadableProcs = processList.filter((p) => !p.injected).length; + return ( + } + label="进程注入" + value={`${onlineProcs} 在线`} + subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`} + to="/processes" + /> + ); + } + case 'stat:host': + return ( + } + label="主机名" + value={systemInfo?.hostname ?? '—'} + subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'} + /> + ); + case 'stat:uptime': + return ( + } + 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 ( - +
主机资源 @@ -260,7 +263,7 @@ function HostBlock() { 刷新 - + {/* CPU */}
@@ -279,21 +282,13 @@ function HostBlock() { {systemInfo && systemInfo.cpu.perCore.length > 0 && (
{systemInfo.cpu.perCore.map((p, i) => ( -
-
+
+
))}
)}
- {/* Memory */}
@@ -311,7 +306,6 @@ function HostBlock() { 共 {systemInfo ? formatBytes(systemInfo.memory.total) : '—'}
- {/* Runtime */}
@@ -357,19 +351,19 @@ function HostBlock() { function SessionsBlock() { const { qqList } = useAppState(); return ( - + 在线会话 当前已接入并完成登录的 QQ 账号 - + {qqList.length === 0 ? (

暂无在线会话

) : ( - +
{qqList.map((q, idx) => ( = { disabled: 'bg-muted text-muted-foreground', }; const CONN_STATUS_LABEL: Record = { - ok: '正常', - warn: '注意', - down: '异常', - disabled: '未启用', + ok: '正常', warn: '注意', down: '异常', disabled: '未启用', }; const ADAPTER_KIND_LABEL: Record = { - httpServer: 'HTTP 服务端', - httpClient: 'HTTP 上报', - wsServer: 'WS 服务端', - wsClient: 'WS 客户端', + httpServer: 'HTTP 服务端', httpClient: 'HTTP 上报', wsServer: 'WS 服务端', wsClient: 'WS 客户端', }; function ConnectionsBlock() { const { connections } = useAppState(); - return ; -} - -function ConnectionsCard({ connections }: { connections: AccountConnections[] }) { return ( - + OneBot 连接 各账号协议端点的实时连接状态 - + {connections.length === 0 ? (
@@ -449,19 +433,12 @@ function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {acc.uin}
{acc.adapters.length === 0 ? ( -

- 未配置任何协议端点 -

+

未配置任何协议端点

) : (
{acc.adapters.map((adp) => (
- + {CONN_STATUS_LABEL[adp.status]}
@@ -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 ( - +
@@ -521,14 +495,11 @@ function RecentAlertsCard() { 最近的 warn / error 级别日志
- + 查看日志
- + {alerts.length === 0 ? (
@@ -542,9 +513,7 @@ function RecentAlertsCard() { {a.level.toUpperCase()} - - [{a.scope}] {a.message} - + [{a.scope}] {a.message}
))}
diff --git a/packages/webui/src/contexts/LayoutContext.tsx b/packages/webui/src/contexts/LayoutContext.tsx index e3d4fd7c..66237d65 100644 --- a/packages/webui/src/contexts/LayoutContext.tsx +++ b/packages/webui/src/contexts/LayoutContext.tsx @@ -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]); diff --git a/packages/webui/src/index.css b/packages/webui/src/index.css index 9a980971..f1d4f1f8 100644 --- a/packages/webui/src/index.css +++ b/packages/webui/src/index.css @@ -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); +} diff --git a/packages/webui/src/lib/dashboard-layout.ts b/packages/webui/src/lib/dashboard-layout.ts new file mode 100644 index 00000000..c7c78213 --- /dev/null +++ b/packages/webui/src/lib/dashboard-layout.ts @@ -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 { + 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(); + 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 }; +} diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 36193c7e..d92ab66f 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -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 { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e3d43194..3dbee74c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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(react@19.2.5) @@ -2315,6 +2318,9 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + gridstack@12.6.0: + resolution: {integrity: sha512-dUrqsormSybFn/2P4Dz8AgprftKD5e/IiV7UmC0XLQU+G+/WtkAeFiCSNLoAGhPDXoJ/O61Xtj3gljY/Ds83yQ==} + has-flag@4.0.0: 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/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) 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/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) '@vitest/expect@4.1.4': dependencies: @@ -4466,6 +4472,14 @@ snapshots: optionalDependencies: vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@vitest/mocker@4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': + dependencies: + '@vitest/spy': 4.1.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@vitest/pretty-format@4.1.4': dependencies: tinyrainbow: 3.1.0 @@ -4978,6 +4992,8 @@ snapshots: graceful-fs@4.2.11: {} + gridstack@12.6.0: {} + has-flag@4.0.0: {} has-symbols@1.1.0: {} @@ -5761,6 +5777,35 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): + dependencies: + '@vitest/expect': 4.1.4 + '@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + '@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/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 25.6.0 + '@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4) + '@vitest/coverage-v8': 4.1.4(vitest@4.1.4) + transitivePeerDependencies: + - msw + vp-runtime-helper@1.0.10: dependencies: '@types/fs-extra': 11.0.4