refactor(webui): extract ApiClient + lift OneBotInstance config editor
App.tsx was the single source of truth for token, fetch policy, 401 handling, and per-UIN config edit state — fetchApi was drilled into every page and LogsPage read localStorage directly to build its SSE URL, giving two parallel truths for the bearer token. Promote the closure to a deep ApiClient module (domain methods + request() escape hatch) injected via ApiProvider/useApi, and lift selectedUin/config/saveStatus into useOneBotInstanceConfig so ConfigPage is self-contained. normalizeOneBotConfig becomes a pure function. ConfigPage now guards UIN switches when the editor is dirty and refetches the server-normalised config after save. ConfigPage prop count drops from 7 to 1; App.tsx from 421 to 270 LOC.
This commit is contained in:
11 files changed
+818
-398
No files matched your search
@@ -19,15 +19,10 @@ import type {
|
||||
QQInfo,
|
||||
WsRole,
|
||||
} from '@/types';
|
||||
import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config';
|
||||
|
||||
interface ConfigPageProps {
|
||||
qqList: QQInfo[];
|
||||
selectedUin: string | null;
|
||||
config: OneBotConfig | null;
|
||||
saveStatus: string;
|
||||
onSelectAccount: (uin: string) => void;
|
||||
onSave: () => Promise<void> | void;
|
||||
onConfigChange: (config: OneBotConfig) => void;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
@@ -98,18 +93,25 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfigPage({
|
||||
qqList,
|
||||
selectedUin,
|
||||
config,
|
||||
saveStatus,
|
||||
onSelectAccount,
|
||||
onSave,
|
||||
onConfigChange,
|
||||
}: ConfigPageProps) {
|
||||
export function ConfigPage({ qqList }: ConfigPageProps) {
|
||||
const {
|
||||
selectedUin,
|
||||
config,
|
||||
setConfig,
|
||||
dirty,
|
||||
requestSwitchUin,
|
||||
pendingSwitchUin,
|
||||
confirmSwitch,
|
||||
cancelSwitch,
|
||||
save,
|
||||
saveStatus,
|
||||
} = useOneBotInstanceConfig(qqList);
|
||||
const [confirmSave, setConfirmSave] = useState(false);
|
||||
|
||||
const update = (next: OneBotConfig) => onConfigChange(next);
|
||||
const update = (next: OneBotConfig) => setConfig(next);
|
||||
const pendingSwitchAccount = pendingSwitchUin
|
||||
? qqList.find((q) => q.uin === pendingSwitchUin) ?? null
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
|
||||
@@ -132,7 +134,7 @@ export function ConfigPage({
|
||||
type="button"
|
||||
whileHover={{ scale: 1.01 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={() => onSelectAccount(q.uin)}
|
||||
onClick={() => requestSwitchUin(q.uin)}
|
||||
className={cn(
|
||||
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
|
||||
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
|
||||
@@ -193,7 +195,12 @@ export function ConfigPage({
|
||||
{saveStatus}
|
||||
</span>
|
||||
)}
|
||||
<Button onClick={() => setConfirmSave(true)} size="sm">
|
||||
{dirty && !saveStatus && (
|
||||
<span className="rounded-full border border-warning/30 bg-warning/10 px-2.5 py-1 text-[11px] font-medium text-warning">
|
||||
未保存
|
||||
</span>
|
||||
)}
|
||||
<Button onClick={() => setConfirmSave(true)} size="sm" disabled={!dirty}>
|
||||
<Save className="size-3.5" /> 保存设定
|
||||
</Button>
|
||||
</div>
|
||||
@@ -421,7 +428,27 @@ export function ConfigPage({
|
||||
title="保存配置变更?"
|
||||
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
|
||||
confirmText="保存"
|
||||
onConfirm={onSave}
|
||||
onConfirm={save}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingSwitchUin != null}
|
||||
onOpenChange={(open) => !open && cancelSwitch()}
|
||||
title="放弃未保存的修改?"
|
||||
description={
|
||||
<>
|
||||
<p>
|
||||
当前会话 <code className="font-mono">{selectedUin}</code> 还有未保存的修改。
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
切换到 <code className="font-mono">{pendingSwitchAccount?.uin ?? pendingSwitchUin}</code>
|
||||
{pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。
|
||||
</p>
|
||||
</>
|
||||
}
|
||||
confirmText="放弃并切换"
|
||||
destructive
|
||||
onConfirm={confirmSwitch}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { LogEntry } from '@/types';
|
||||
|
||||
interface LogsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
const levelClass: Record<LogEntry['level'], string> = {
|
||||
debug: 'text-muted-foreground',
|
||||
@@ -24,7 +21,8 @@ const levelClass: Record<LogEntry['level'], string> = {
|
||||
|
||||
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
export function LogsPage() {
|
||||
const api = useApi();
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [streamStatus, setStreamStatus] = useState('连接中');
|
||||
const [paused, setPaused] = useState(false);
|
||||
@@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
const endRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
|
||||
|
||||
async function loadLogs() {
|
||||
const res = await fetchApi('/api/logs?limit=500');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setLogs(data.list || []);
|
||||
}
|
||||
const loadLogs = useCallback(async () => {
|
||||
try {
|
||||
setLogs(await api.logs.list(500));
|
||||
} catch (e) {
|
||||
console.error('logs', e);
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
loadLogs().catch(console.error);
|
||||
}, []);
|
||||
void loadLogs();
|
||||
}, [loadLogs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => setStreamStatus('实时');
|
||||
source.onerror = () => setStreamStatus('重连中');
|
||||
source.onmessage = (event) => {
|
||||
try {
|
||||
const entry = JSON.parse(event.data) as LogEntry | { type: string };
|
||||
if ('type' in entry) return;
|
||||
return api.logs.stream({
|
||||
onLine: (entry) => {
|
||||
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
return () => source.close();
|
||||
}, [token]);
|
||||
},
|
||||
onStatus: (s) => {
|
||||
if (s === 'open') setStreamStatus('实时');
|
||||
else if (s === 'reconnecting') setStreamStatus('重连中');
|
||||
else setStreamStatus('已断开');
|
||||
},
|
||||
});
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (paused) return;
|
||||
@@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
|
||||
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
|
||||
{paused ? '继续' : '暂停'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => loadLogs().catch(console.error)}>
|
||||
<Button variant="outline" size="sm" onClick={() => void loadLogs()}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
<Button
|
||||
|
||||
@@ -14,14 +14,11 @@ import {
|
||||
type Density,
|
||||
type ThemeMode,
|
||||
} from '@/contexts/ThemeContext';
|
||||
import {
|
||||
ChangePasswordPage,
|
||||
type PasswordRule,
|
||||
} from '@/components/pages/change-password-page';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsPageProps {
|
||||
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
|
||||
/** Called after successful logout (e.g. all-sessions invalidated). */
|
||||
onLogout: () => void;
|
||||
}
|
||||
@@ -37,7 +34,8 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
|
||||
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
|
||||
];
|
||||
|
||||
export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
|
||||
export function SettingsPage({ onLogout }: SettingsPageProps) {
|
||||
const api = useApi();
|
||||
const {
|
||||
mode, setMode,
|
||||
accent, setAccent,
|
||||
@@ -49,30 +47,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
const checkStrength = async (password: string) => {
|
||||
const res = await fetchApi('/api/auth/check-strength', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
|
||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
||||
};
|
||||
|
||||
const submitPwd = async (oldPassword: string, newPassword: string) => {
|
||||
const res = await fetchApi('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ oldPassword, newPassword }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
|
||||
return { success: !!data.success, message: data.message };
|
||||
};
|
||||
|
||||
if (showChangePwd) {
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced={false}
|
||||
checkStrength={checkStrength}
|
||||
submit={submitPwd}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
setShowChangePwd(false);
|
||||
setPwdSavedAt(Date.now());
|
||||
|
||||
Reference in new issue
Block a user