feat(webui): per-page preferences (phase 7)

A `pages` section in config/ui.json (3rd section-merge alongside appearance +
layout):
- defaultRoute: the page to open after login (chosen in Settings → 数据与格式;
  DefaultRouteRedirect navigates there once, only from '/', respecting
  deep-links + later navigation).
- logs: persisted visible levels, max lines, auto-scroll, line-wrap, and
  keyword→colour highlight rules — edited live on the logs page; maxLines is
  read via a ref so it never re-subscribes the SSE.
- processes: pid / name / status sort (persisted, default from prefs).
- config: remembers the last-used tab.

"重置全部" now also clears pages. The server normalizer is total and caps the
logs fields (levels subset, maxLines 100-5000, <=20 highlight rules, trimmed
keywords). Verified by an adversarial review round (normalizePages total
against 30 adversarial inputs; zero MUST/SHOULD-FIX).
This commit is contained in:
DrSmoothl committed 2026-06-13 21:17:24 +08:00
1 parent 7c2923dd04
commit 056fff415c
8 files changed
+412 -91

No files matched your search

+83
View File
@@ -124,10 +124,37 @@ export interface UiLayout {
navItems: UiLayoutItem[];
}
export interface UiHighlightRule {
keyword: string;
color: string;
}
export interface UiLogsPrefs {
/** Log levels shown by default (client display filter). */
visibleLevels: string[];
/** Ring-buffer cap for the live view (100…5000). */
maxLines: number;
autoScroll: boolean;
wrap: boolean;
/** Keyword → colour row highlights. */
highlightRules: UiHighlightRule[];
}
export interface UiPages {
/** Route the operator lands on after login (a nav path; '/' if unset). */
defaultRoute: string;
logs: UiLogsPrefs;
/** Default sort key for the processes page. */
processesSort: string;
/** Default tab id for the node-config page ('' = first). */
configTab: string;
}
export interface UiConfig {
version: typeof UI_CONFIG_VERSION;
appearance: UiAppearance;
layout: UiLayout;
pages: UiPages;
}
// ─── Defaults ────────────────────────────────────────────────────────────
@@ -183,6 +210,21 @@ const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
{ id: '/settings', visible: true },
];
const LOG_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
const DEFAULT_PAGES: UiPages = {
defaultRoute: '/',
logs: {
visibleLevels: [...LOG_LEVELS],
maxLines: 1000,
autoScroll: true,
wrap: true,
highlightRules: [],
},
processesSort: 'pid',
configTab: '',
};
export function defaultUiConfig(): UiConfig {
return {
version: UI_CONFIG_VERSION,
@@ -191,9 +233,14 @@ export function defaultUiConfig(): UiConfig {
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })),
},
pages: defaultPages(),
};
}
function defaultPages(): UiPages {
return { ...DEFAULT_PAGES, logs: { ...DEFAULT_PAGES.logs, visibleLevels: [...LOG_LEVELS], highlightRules: [] } };
}
// ─── Normalization helpers ─────────────────────────────────────────────────
function isObject(value: unknown): value is Record<string, unknown> {
@@ -362,12 +409,47 @@ export function normalizeLayout(value: unknown): UiLayout {
};
}
function normalizeHighlightRules(value: unknown): UiHighlightRule[] {
if (!Array.isArray(value)) return [];
const out: UiHighlightRule[] = [];
for (const raw of value) {
if (!isObject(raw) || typeof raw.keyword !== 'string') continue;
const keyword = raw.keyword.trim().slice(0, 50);
if (!keyword) continue; // drop empty / whitespace-only (would match every row)
const color = typeof raw.color === 'string' ? raw.color.slice(0, 32) : '';
out.push({ keyword, color });
if (out.length >= 20) break; // cap the rule count
}
return out;
}
export function normalizePages(value: unknown): UiPages {
const v = isObject(value) ? value : {};
const logs = isObject(v.logs) ? v.logs : {};
const levels = Array.isArray(logs.visibleLevels)
? LOG_LEVELS.filter((l) => (logs.visibleLevels as unknown[]).includes(l))
: DEFAULT_PAGES.logs.visibleLevels;
return {
defaultRoute: idOr(v.defaultRoute, DEFAULT_PAGES.defaultRoute),
logs: {
visibleLevels: levels.length > 0 ? levels : [...LOG_LEVELS],
maxLines: clampInt(logs.maxLines, 100, 5000, DEFAULT_PAGES.logs.maxLines),
autoScroll: boolOr(logs.autoScroll, DEFAULT_PAGES.logs.autoScroll),
wrap: boolOr(logs.wrap, DEFAULT_PAGES.logs.wrap),
highlightRules: normalizeHighlightRules(logs.highlightRules),
},
processesSort: idOr(v.processesSort, DEFAULT_PAGES.processesSort),
configTab: typeof v.configTab === 'string' ? v.configTab.slice(0, 64) : DEFAULT_PAGES.configTab,
};
}
export function normalizeUiConfig(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiConfig {
const v = isObject(value) ? value : {};
return {
version: UI_CONFIG_VERSION,
appearance: normalizeAppearance(v.appearance, imageState),
layout: normalizeLayout(v.layout),
pages: normalizePages(v.pages),
};
}
@@ -446,6 +528,7 @@ export function saveUiConfig(incoming: unknown): UiConfig {
? normalizeAppearance(v.appearance, current.appearance.background)
: current.appearance,
layout: isObject(v.layout) ? normalizeLayout(v.layout) : current.layout,
pages: isObject(v.pages) ? normalizePages(v.pages) : (current.pages ?? defaultPages()),
};
atomicWrite(next);
cached = next;
@@ -22,6 +22,7 @@ import type {
} from '@/types';
import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config';
import { useAppState } from '@/contexts/AppStateContext';
import { useLayout } from '@/contexts/LayoutContext';
import { AccountSidebar } from '@/components/config/account-sidebar';
import { GeneralSettingsTab } from '@/components/config/general-settings-tab';
import { NodeSummaryCard } from '@/components/config/node-summary-card';
@@ -55,7 +56,16 @@ export function ConfigPage() {
onSelectedUinChange: setSelectedUin,
});
const [activeTab, setActiveTab] = useState<TabKey>('general');
const { pages, setPages } = useLayout();
const [activeTab, setActiveTabState] = useState<TabKey>(() => {
const t = pages.configTab;
return t === 'general' || (!!t && t in NETWORK_TABS) ? (t as TabKey) : 'general';
});
// Persist the last-used tab as the default for next time.
const setActiveTab = useCallback((t: TabKey) => {
setActiveTabState(t);
setPages({ configTab: t });
}, [setPages]);
// Default the account strip to its 56px avatar-only form on narrow screens
// (≤lg) so the editor pane isn't squeezed; the user can still expand it.
const [sidebarCollapsed, setSidebarCollapsed] = useState(
+143 -70
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
import { ArrowDownToLine, Highlighter, Pause, Plus, RefreshCw, Trash2, WrapText, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -8,9 +8,10 @@ import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry, LogLevel } from '@/types';
import type { LogEntry, LogLevel, UiHighlightRule } from '@/types';
import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
const levelClass: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
@@ -23,31 +24,60 @@ const levelClass: Record<LogLevel, string> = {
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
// Highlight palette — keyword rules tint a matching row. Stored as an id.
const HIGHLIGHT_COLORS: { id: string; label: string; swatch: string }[] = [
{ id: 'amber', label: '琥珀', swatch: '#f59e0b' },
{ id: 'rose', label: '玫瑰', swatch: '#f43f5e' },
{ id: 'emerald', label: '翡翠', swatch: '#10b981' },
{ id: 'sky', label: '天蓝', swatch: '#38bdf8' },
{ id: 'violet', label: '紫', swatch: '#8b5cf6' },
];
const colorSwatch = (id: string) => HIGHLIGHT_COLORS.find((c) => c.id === id)?.swatch ?? '#f59e0b';
function matchHighlight(message: string, rules: UiHighlightRule[]): string | null {
if (rules.length === 0) return null;
const m = message.toLowerCase();
for (const r of rules) {
if (r.keyword && m.includes(r.keyword.toLowerCase())) return colorSwatch(r.color);
}
return null;
}
export function LogsPage() {
const api = useApi();
const { formatClock } = useTheme();
const { pages, setPages } = useLayout();
const prefs = pages.logs;
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
const [filter, setFilter] = useState('');
const [enabledLevels, setEnabledLevels] = useState<Set<LogLevel>>(new Set(LEVELS));
const [confirmClear, setConfirmClear] = useState(false);
const [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
const [levelBusy, setLevelBusy] = useState(false);
const [showHighlights, setShowHighlights] = useState(false);
const [newKeyword, setNewKeyword] = useState('');
const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id);
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
// maxLines is read through a ref so changing it doesn't re-subscribe the SSE.
const maxLines = prefs.maxLines;
const maxLinesRef = useRef(maxLines);
useEffect(() => { maxLinesRef.current = maxLines; }, [maxLines]);
const enabled = useMemo(() => new Set(prefs.visibleLevels as LogLevel[]), [prefs.visibleLevels]);
const loadLogs = useCallback(async () => {
try {
setLogs(await api.logs.list(500));
// Backfill is capped at the server's ring-buffer size (1000); `maxLines`
// can exceed that, but only the live SSE stream grows the view past 1000.
setLogs(await api.logs.list(Math.min(1000, maxLinesRef.current)));
} catch (e) {
console.error('logs', e);
}
}, [api]);
useEffect(() => {
void loadLogs();
}, [loadLogs]);
useEffect(() => { void loadLogs(); }, [loadLogs]);
useEffect(() => {
api.logs.getLevel().then(({ level }) => setServerLevel(level)).catch((err) => {
@@ -71,7 +101,7 @@ export function LogsPage() {
useEffect(() => {
return api.logs.stream({
onLine: (entry) => {
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-maxLinesRef.current));
},
onStatus: (s) => {
if (s === 'open') setStreamStatus('实时');
@@ -82,14 +112,15 @@ export function LogsPage() {
}, [api]);
useEffect(() => {
if (paused) return;
if (!prefs.autoScroll) return;
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs, paused]);
}, [logs, prefs.autoScroll]);
const filtered = useMemo(() => {
const f = filter.trim().toLowerCase();
return logs.filter((l) => {
if (!enabledLevels.has(l.level)) return false;
const capped = logs.slice(-maxLines);
return capped.filter((l) => {
if (!enabled.has(l.level)) return false;
if (!f) return true;
return (
l.message.toLowerCase().includes(f) ||
@@ -98,15 +129,22 @@ export function LogsPage() {
(l.req !== undefined && String(l.req).includes(f))
);
});
}, [logs, filter, enabledLevels]);
}, [logs, filter, enabled, maxLines]);
const toggleLevel = (lv: LogLevel) => {
setEnabledLevels((prev) => {
const next = new Set(prev);
if (next.has(lv)) next.delete(lv);
else next.add(lv);
return next;
});
const next = new Set(enabled);
if (next.has(lv)) next.delete(lv); else next.add(lv);
setPages({ logs: { ...prefs, visibleLevels: LEVELS.filter((l) => next.has(l)) } });
};
const addHighlight = () => {
const kw = newKeyword.trim();
if (!kw) return;
setPages({ logs: { ...prefs, highlightRules: [...prefs.highlightRules, { keyword: kw, color: newColor }].slice(0, 20) } });
setNewKeyword('');
};
const removeHighlight = (idx: number) => {
setPages({ logs: { ...prefs, highlightRules: prefs.highlightRules.filter((_, i) => i !== idx) } });
};
return (
@@ -117,9 +155,7 @@ export function LogsPage() {
运行日志
<Badge variant={streamStatus === '实时' ? 'success' : 'secondary'}>{streamStatus}</Badge>
</CardTitle>
<CardDescription>
最近 {filtered.length} / {logs.length} 条 · 通过 SSE 推送
</CardDescription>
<CardDescription>最近 {filtered.length} / {logs.length} 条 · 通过 SSE 推送</CardDescription>
</div>
<div className="flex flex-wrap items-center gap-2">
<Input
@@ -128,28 +164,73 @@ export function LogsPage() {
onChange={(e) => setFilter(e.target.value)}
className="h-8 w-48"
/>
<Button variant="outline" size="sm" onClick={() => setPaused((v) => !v)}>
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
{paused ? '继续' : '暂停'}
<Button variant="outline" size="sm" onClick={() => setPages({ logs: { ...prefs, autoScroll: !prefs.autoScroll } })} title="自动滚动到底部">
{prefs.autoScroll ? <ArrowDownToLine className="size-3.5 text-primary" /> : <Pause className="size-3.5" />}
{prefs.autoScroll ? '自动滚动' : '已暂停'}
</Button>
<Button variant="outline" size="sm" onClick={() => setPages({ logs: { ...prefs, wrap: !prefs.wrap } })} title="自动换行">
<WrapText className={cn('size-3.5', prefs.wrap && 'text-primary')} /> 换行
</Button>
<Button variant="outline" size="sm" onClick={() => setShowHighlights((v) => !v)} title="高亮规则">
<Highlighter className={cn('size-3.5', prefs.highlightRules.length > 0 && 'text-primary')} /> 高亮
</Button>
<Button variant="outline" size="sm" onClick={() => void loadLogs()}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setConfirmClear(true)}
className="text-muted-foreground hover:text-destructive"
>
<Button variant="outline" size="sm" onClick={() => setConfirmClear(true)} className="text-muted-foreground hover:text-destructive">
<Trash2 className="size-3.5" /> 清空视图
</Button>
</div>
</CardHeader>
{showHighlights && (
<div className="mx-5 mb-2 flex flex-col gap-2 rounded-lg border bg-muted/20 p-3">
<div className="flex flex-wrap items-center gap-2">
<Input
placeholder="高亮关键词"
value={newKeyword}
maxLength={50}
onChange={(e) => setNewKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') addHighlight(); }}
className="h-8 w-44"
/>
<div className="flex items-center gap-1">
{HIGHLIGHT_COLORS.map((c) => (
<button
key={c.id}
type="button"
onClick={() => setNewColor(c.id)}
title={c.label}
aria-label={c.label}
className={cn('size-6 rounded-full border transition-transform hover:scale-110 cursor-pointer', newColor === c.id ? 'ring-2 ring-offset-1 ring-foreground/40' : 'border-border')}
style={{ backgroundColor: c.swatch }}
/>
))}
</div>
<Button variant="outline" size="sm" onClick={addHighlight} disabled={!newKeyword.trim()}>
<Plus className="size-3.5" /> 添加
</Button>
</div>
{prefs.highlightRules.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{prefs.highlightRules.map((r, i) => (
<span key={i} className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px]" style={{ borderColor: colorSwatch(r.color) }}>
<span className="size-2 rounded-full" style={{ backgroundColor: colorSwatch(r.color) }} />
{r.keyword}
<button type="button" onClick={() => removeHighlight(i)} className="text-muted-foreground hover:text-destructive cursor-pointer" aria-label="移除">
<X className="size-3" />
</button>
</span>
))}
</div>
)}
</div>
)}
<div className="flex flex-wrap items-center gap-1 px-5 pb-2">
<span className="mr-2 text-[11px] text-muted-foreground/80">视图过滤</span>
{LEVELS.map((lv) => {
const active = enabledLevels.has(lv);
const active = enabled.has(lv);
return (
<button
key={lv}
@@ -157,9 +238,7 @@ export function LogsPage() {
onClick={() => toggleLevel(lv)}
className={cn(
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer',
active
? cn('border-transparent', levelClass[lv], 'bg-muted')
: 'border-border text-muted-foreground/60 line-through'
active ? cn('border-transparent', levelClass[lv], 'bg-muted') : 'border-border text-muted-foreground/60 line-through',
)}
>
{lv.toUpperCase()}
@@ -182,9 +261,7 @@ export function LogsPage() {
disabled={levelBusy || serverLevel === null}
className={cn(
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50',
active
? cn('border-primary', levelClass[lv], 'bg-primary/10')
: 'border-border text-muted-foreground/70 hover:text-foreground'
active ? cn('border-primary', levelClass[lv], 'bg-primary/10') : 'border-border text-muted-foreground/70 hover:text-foreground',
)}
>
{lv.toUpperCase()}
@@ -195,40 +272,36 @@ export function LogsPage() {
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
<ScrollArea
className="flex-1 min-h-0"
viewportClassName="[&>div]:!block"
>
<div ref={viewportRef} className="font-mono text-xs">
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<div className="font-mono text-xs">
{filtered.length === 0 ? (
<div className="flex h-40 items-center justify-center text-muted-foreground">暂无日志</div>
) : (
filtered.map((log) => (
<motion.div
key={log.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.12 }}
className="flex flex-col gap-0.5 px-3 py-1 leading-5 hover:bg-accent/30 sm:flex-row sm:gap-2 sm:py-0.5"
>
{/* Meta drops to its own line on phones so the message gets
the full width instead of a ~40px column that breaks
every few characters. On sm+ it's the dense single row. */}
<div className="flex shrink-0 items-center gap-2">
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(log.time)}</span>
<span className={cn('shrink-0 font-semibold sm:w-14', levelClass[log.level])}>
{log.level.toUpperCase()}
filtered.map((log) => {
const hl = matchHighlight(log.message, prefs.highlightRules);
return (
<motion.div
key={log.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.12 }}
className="flex flex-col gap-0.5 px-3 py-1 leading-5 hover:bg-accent/30 sm:flex-row sm:gap-2 sm:py-0.5"
style={hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : undefined}
>
<div className="flex shrink-0 items-center gap-2">
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(log.time)}</span>
<span className={cn('shrink-0 font-semibold sm:w-14', levelClass[log.level])}>{log.level.toUpperCase()}</span>
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
{log.req !== undefined && (
<span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] text-primary tabular-nums" title="请求关联号">#{log.req}</span>
)}
</div>
<span className={cn('min-w-0', prefs.wrap ? 'whitespace-pre-wrap break-all' : 'truncate')} title={prefs.wrap ? undefined : log.message}>
{log.message}
</span>
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
{log.req !== undefined && (
<span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] text-primary tabular-nums" title="请求关联号">
#{log.req}
</span>
)}
</div>
<span className="min-w-0 whitespace-pre-wrap break-all">{log.message}</span>
</motion.div>
))
</motion.div>
);
})
)}
<div ref={endRef} />
</div>
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useMemo, useState } from 'react';
import { motion } from 'motion/react';
import { AlertCircle, CheckCircle2, Cpu, Eye, Loader2, RefreshCw, Unplug } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -9,6 +9,17 @@ import { ProcessProbeDialog } from '@/components/process-probe-dialog';
import { cn } from '@/lib/utils';
import type { HookProcessInfo } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { useLayout } from '@/contexts/LayoutContext';
const SORT_OPTIONS: { id: string; label: string }[] = [
{ id: 'pid', label: 'PID' },
{ id: 'name', label: '名称' },
{ id: 'status', label: '状态' },
];
// Online-first, then by how actionable the state is.
const STATUS_ORDER: Record<HookProcessInfo['status'], number> = {
online: 0, loaded: 1, connecting: 2, loading: 3, available: 4, disconnected: 5, error: 6,
};
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
@@ -38,9 +49,19 @@ function processBadgeVariant(status: HookProcessInfo['status']) {
export function ProcessesPage() {
const { processList, processOps, refreshProcesses } = useAppState();
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
const { pages, setPages } = useLayout();
const [confirm, setConfirm] = useState<{ kind: 'load' | 'unload'; pid: number; name: string } | null>(null);
const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null);
const sortKey = pages.processesSort;
const sorted = useMemo(() => {
const arr = [...processList];
if (sortKey === 'name') arr.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
else if (sortKey === 'status') arr.sort((a, b) => (STATUS_ORDER[a.status] ?? 9) - (STATUS_ORDER[b.status] ?? 9) || a.pid - b.pid);
else arr.sort((a, b) => a.pid - b.pid);
return arr;
}, [processList, sortKey]);
return (
<div className="flex flex-col gap-6">
<Card>
@@ -49,9 +70,29 @@ export function ProcessesPage() {
<CardTitle>进程注入</CardTitle>
<CardDescription>加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={refreshProcesses}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
<div className="flex items-center gap-2">
{processList.length > 1 && (
<div className="hidden items-center gap-1 sm:flex">
<span className="text-[11px] text-muted-foreground">排序</span>
{SORT_OPTIONS.map((o) => (
<button
key={o.id}
type="button"
onClick={() => setPages({ processesSort: o.id })}
className={cn(
'rounded-md border px-2 py-1 text-[11px] transition-colors cursor-pointer',
sortKey === o.id ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{o.label}
</button>
))}
</div>
)}
<Button variant="outline" size="sm" onClick={refreshProcesses}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</div>
</CardHeader>
<CardContent>
{processActionStatus && (
@@ -71,7 +112,7 @@ export function ProcessesPage() {
</div>
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2 2xl:grid-cols-3">
{processList.map((proc, idx) => {
{sorted.map((proc, idx) => {
const op = statusOf(proc.pid);
const loading = op === 'load' || proc.status === 'loading';
const unloading = op === 'unload';
@@ -28,7 +28,8 @@ import {
type ThemeMode,
type TimeFormat,
} from '@/contexts/ThemeContext';
import { DEFAULT_LAYOUT } from '@/contexts/LayoutContext';
import { DEFAULT_LAYOUT, DEFAULT_PAGES, useLayout } from '@/contexts/LayoutContext';
import { NAV_ITEMS } from '@/components/layout/sidebar';
import { ChangePasswordDialog } from '@/components/change-password-dialog';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useApi } from '@/lib/api';
@@ -112,7 +113,7 @@ function AdvancedPanel() {
const doReset = async () => {
setBusy(true);
try {
await api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT });
await api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT, pages: DEFAULT_PAGES });
window.location.reload();
} catch {
setBusy(false);
@@ -644,6 +645,7 @@ const TIME_FORMAT_OPTIONS: Opt<TimeFormat>[] = [
function DataPanel() {
const { appearance, setAppearance } = useTheme();
const { pages, setPages } = useLayout();
return (
<div className="flex flex-col gap-5">
<Card>
@@ -662,6 +664,22 @@ function DataPanel() {
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>登录后落地页</CardTitle>
<CardDescription>登录后默认打开的页面。</CardDescription>
</CardHeader>
<CardContent>
<Field label="默认页面">
<Segmented
value={pages.defaultRoute}
options={NAV_ITEMS.map((n) => ({ value: n.to as string, label: n.label }))}
onChange={(defaultRoute) => setPages({ defaultRoute })}
/>
</Field>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><Clock className="size-4 text-primary" /> 时间格式</CardTitle>
+58 -10
View File
@@ -1,7 +1,7 @@
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';
import type { UiLayout, UiLayoutItem, UiPages } 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`),
@@ -27,6 +27,19 @@ export const DEFAULT_LAYOUT: UiLayout = {
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
};
const ALL_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
export function defaultPages(): UiPages {
return {
defaultRoute: '/',
logs: { visibleLevels: [...ALL_LEVELS], maxLines: 1000, autoScroll: true, wrap: true, highlightRules: [] },
processesSort: 'pid',
configTab: '',
};
}
export const DEFAULT_PAGES: UiPages = defaultPages();
/**
* Order + visibility for a known catalogue: keep stored items that still exist
* (in their stored order + visibility), then append any catalogue entries the
@@ -58,8 +71,14 @@ interface LayoutContextValue {
setOverviewBlocks: (items: UiLayoutItem[]) => void;
/** Persist a new nav order/visibility. */
setNavItems: (items: UiLayoutItem[]) => void;
/** Reset both to defaults. */
/** Reset layout (blocks + nav) to defaults. */
resetLayout: () => void;
/** Per-page preferences (default route, logs/processes/config prefs). */
pages: UiPages;
/** Merge a partial pages-prefs update (debounced-persisted). */
setPages: (patch: Partial<UiPages>) => void;
/** True once the authed config load has resolved (gates the default-route redirect). */
ready: boolean;
}
const LayoutContext = createContext<LayoutContextValue | null>(null);
@@ -67,13 +86,18 @@ const LayoutContext = createContext<LayoutContextValue | null>(null);
export function LayoutProvider({ children }: { children: ReactNode }) {
const api = useApi();
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES);
const [ready, setReady] = useState(false);
const layoutRef = useRef(layout);
const pagesRef = useRef(pages);
// 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);
const pagesTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => { layoutRef.current = layout; }, [layout]);
useEffect(() => { pagesRef.current = pages; }, [pages]);
useEffect(() => {
let cancelled = false;
@@ -84,26 +108,35 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
// overview + editor are interactive immediately, before this resolves).
// 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,
});
if (!cancelled && !dirtyRef.current && config) {
if (config.layout) {
setLayout({
overviewBlocks: migrateOverviewBlocks(config.layout.overviewBlocks),
navItems: config.layout.navItems,
});
}
if (config.pages) setPagesState(config.pages);
}
} catch {
/* keep defaults — layout is non-critical */
/* keep defaults — layout/pages are non-critical */
} finally {
if (!cancelled) setReady(true);
}
})();
return () => { cancelled = true; };
}, [api]);
// On unmount (e.g. logout), flush a pending debounced save so a last-moment
// On unmount (e.g. logout), flush pending debounced saves 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 */ });
}
if (pagesTimer.current) {
clearTimeout(pagesTimer.current);
void api.ui.save({ pages: pagesRef.current }).catch(() => { /* best-effort */ });
}
}, [api]);
const persist = useCallback((next: UiLayout) => {
@@ -132,13 +165,28 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
});
}, [persist]);
const setPages = useCallback((patch: Partial<UiPages>) => {
dirtyRef.current = true;
const next = { ...pagesRef.current, ...patch };
pagesRef.current = next;
setPagesState(next);
if (pagesTimer.current) clearTimeout(pagesTimer.current);
pagesTimer.current = setTimeout(() => {
pagesTimer.current = null;
void api.ui.save({ pages: next }).catch(() => { /* best-effort */ });
}, 300);
}, [api]);
const value = useMemo<LayoutContextValue>(() => ({
overviewBlocks: layout.overviewBlocks,
navItems: layout.navItems,
setOverviewBlocks,
setNavItems,
resetLayout,
}), [layout, setOverviewBlocks, setNavItems, resetLayout]);
pages,
setPages,
ready,
}), [layout, setOverviewBlocks, setNavItems, resetLayout, pages, setPages, ready]);
return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
}
+30 -3
View File
@@ -1,16 +1,42 @@
import { Suspense, useCallback, useEffect, useState } from 'react';
import { Outlet } from '@tanstack/react-router';
import { Suspense, useCallback, useEffect, useRef, useState } from 'react';
import { Outlet, useNavigate, useRouterState } from '@tanstack/react-router';
import { useTheme } from '@/contexts/ThemeContext';
import { useApi } from '@/lib/api';
import { useHookProcessOps } from '@/hooks/use-hook-process-ops';
import { MainLayout } from '@/components/layout/main-layout';
import { NAV_ITEMS } from '@/components/layout/sidebar';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { AppStateProvider } from '@/contexts/AppStateContext';
import { LayoutProvider } from '@/contexts/LayoutContext';
import { LayoutProvider, useLayout } from '@/contexts/LayoutContext';
import { useSession } from '@/contexts/SessionContext';
import type { AppPath } from '@/router';
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
/**
* Redirects to the operator's configured landing page once (after the layout
* config loads), but only when arriving at the root and the target is a real,
* non-root nav route — so deep-links and later navigation are respected.
* Rendered INSIDE LayoutProvider (needs useLayout).
*/
function DefaultRouteRedirect() {
const { pages, ready } = useLayout();
const navigate = useNavigate();
const pathname = useRouterState({ select: (s) => s.location.pathname });
const done = useRef(false);
useEffect(() => {
if (!ready || done.current) return;
done.current = true;
const target = pages.defaultRoute;
if (target && target !== '/' && pathname === '/' && NAV_ITEMS.some((n) => n.to === target)) {
void navigate({ to: target as AppPath });
}
}, [ready, pages.defaultRoute, pathname, navigate]);
return null;
}
/**
* The layout route. Owns the live state shared across the four pages
* (polling lists, processOps, selectedUin) and renders `<Outlet />` inside
@@ -131,6 +157,7 @@ export function AppLayout() {
}}
>
<LayoutProvider>
<DefaultRouteRedirect />
<MainLayout status={session.status} onLogout={handleLogout}>
{/* Routes use `lazyRouteComponent` (router/index.tsx) for
code-splitting, which suspends until the chunk is fetched.
+21
View File
@@ -225,8 +225,29 @@ export interface UiLayout {
navItems: UiLayoutItem[];
}
export interface UiHighlightRule {
keyword: string;
color: string;
}
export interface UiLogsPrefs {
visibleLevels: string[];
maxLines: number;
autoScroll: boolean;
wrap: boolean;
highlightRules: UiHighlightRule[];
}
export interface UiPages {
defaultRoute: string;
logs: UiLogsPrefs;
processesSort: string;
configTab: string;
}
export interface UiConfig {
version: number;
appearance: UiAppearance;
layout: UiLayout;
pages: UiPages;
}