diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 2a759e7e..d6781eca 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -21,6 +21,11 @@ function AuthBoundary() { const [authed, setAuthed] = useState(false); const [mustChange, setMustChange] = useState(false); const [status, setStatus] = useState('未连接'); + // The password from *this* session's login, carried into the forced + // change-password gate so it doesn't have to render an old-password field + // (which browsers autofill, misleading users on upgrade). Stays undefined + // for a returning session that's already authed but still must change. + const [loginPassword, setLoginPassword] = useState(undefined); const client = useMemo( () => @@ -63,14 +68,21 @@ function AuthBoundary() { ) : !authed ? ( { + onAuthed={(needsChange, password) => { setAuthed(true); setStatus('已连接'); setMustChange(needsChange); + setLoginPassword(password); }} /> ) : mustChange ? ( - setMustChange(false)} /> + { + setMustChange(false); + setLoginPassword(undefined); + }} + /> ) : ( @@ -81,13 +93,13 @@ function AuthBoundary() { ); } -function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) { +function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) { const api = useApi(); const handleLogin = useCallback( async (password: string) => { const result = await api.login(password); if (!result.ok) return { success: false, error: result.message }; - onAuthed(result.mustChangePassword); + onAuthed(result.mustChangePassword, password); return { success: true }; }, [api, onAuthed], @@ -95,11 +107,17 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) { return ; } -function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) { +function ForcedChangePasswordGate({ + knownOldPassword, + onSuccess, +}: { + knownOldPassword?: string; + onSuccess: () => void; +}) { const api = useApi(); return ( api.checkPasswordStrength(p)} submit={(o, n) => api.changePassword(o, n)} onSuccess={onSuccess} diff --git a/packages/webui/src/components/change-password-dialog.tsx b/packages/webui/src/components/change-password-dialog.tsx new file mode 100644 index 00000000..1ccb992c --- /dev/null +++ b/packages/webui/src/components/change-password-dialog.tsx @@ -0,0 +1,48 @@ +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { ChangePasswordForm } from '@/components/pages/change-password-form'; +import { useApi } from '@/lib/api'; + +interface ChangePasswordDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** Fired after the password is changed successfully (dialog closes itself). */ + onSuccess: () => void; +} + +/** + * In-app "修改访问密码" modal. The forced first-time flow uses the full-screen + * ChangePasswordPage; this is the voluntary change a logged-in admin triggers + * from 设置 → 账号安全. Both share ChangePasswordForm, so behaviour is identical. + */ +export function ChangePasswordDialog({ open, onOpenChange, onSuccess }: ChangePasswordDialogProps) { + const api = useApi(); + + return ( + + + + 修改访问密码 + + 设置一个全新的强密码后,其它会话将被立即下线,需要重新登录。 + + + api.checkPasswordStrength(p)} + submit={(o, n) => api.changePassword(o, n)} + onSuccess={() => { + onSuccess(); + onOpenChange(false); + }} + onCancel={() => onOpenChange(false)} + idPrefix="dialog-cpw" + /> + + + ); +} diff --git a/packages/webui/src/components/pages/change-password-form.tsx b/packages/webui/src/components/pages/change-password-form.tsx new file mode 100644 index 00000000..f3bc2f4d --- /dev/null +++ b/packages/webui/src/components/pages/change-password-form.tsx @@ -0,0 +1,262 @@ +import { useEffect, useMemo, useState } from 'react'; +import { motion, AnimatePresence } from 'motion/react'; +import { Check, Eye, EyeOff, Loader2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { cn } from '@/lib/utils'; + +export interface PasswordRule { + id: string; + label: string; + ok: boolean; +} + +export interface ChangePasswordFormProps { + /** + * When provided, the "current password" field is omitted entirely and this + * value is used as the old password. + * + * Used by the forced first-time flow: the old password is *exactly* what + * the user just logged in with, so we fill it ourselves. Rendering the + * field at all let Edge/Chrome password-managers autofill it on upgrade — + * users saw it pre-filled, assumed it was correct, and could never save + * (the autofilled value was stale / not the temp password). Dropping the + * field removes the trap entirely. + */ + knownOldPassword?: string; + /** Sends `{ password }`; returns the rule list + valid flag. */ + checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>; + /** Sends `{ oldPassword, newPassword }`. Returns success or error message. */ + submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>; + /** Called after a successful submit. */ + onSuccess: () => void; + /** When provided, a cancel button is shown (used by the settings dialog). */ + onCancel?: () => void; + /** Disambiguates input ids if two instances ever mount at once. */ + idPrefix?: string; + submitLabel?: string; +} + +export function ChangePasswordForm({ + knownOldPassword, + checkStrength, + submit, + onSuccess, + onCancel, + idPrefix = 'cpw', + submitLabel = '保存新密码', +}: ChangePasswordFormProps) { + const carriesOld = knownOldPassword !== undefined; + + const [oldPassword, setOldPassword] = useState(''); + const [newPassword, setNewPassword] = useState(''); + const [confirmPassword, setConfirmPassword] = useState(''); + const [showOld, setShowOld] = useState(false); + const [showNew, setShowNew] = useState(false); + const [rules, setRules] = useState([]); + const [valid, setValid] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(''); + + const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword; + const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; + const canSubmit = + !submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword; + + // Debounce the strength check so we don't slam the API on every keystroke. + useEffect(() => { + let cancelled = false; + const handle = window.setTimeout(async () => { + try { + const res = await checkStrength(newPassword); + if (cancelled) return; + setRules(res.rules); + setValid(res.valid); + } catch { + /* ignore – the form will just stay disabled */ + } + }, 180); + return () => { + cancelled = true; + window.clearTimeout(handle); + }; + }, [newPassword, checkStrength]); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + if (!canSubmit) return; + setSubmitting(true); + setError(''); + try { + const res = await submit(effectiveOld, newPassword); + if (res.success) { + onSuccess(); + } else { + setError(res.message || '修改失败'); + } + } catch (err) { + setError(err instanceof Error ? err.message : '网络错误'); + } finally { + setSubmitting(false); + } + }; + + return ( +
+ {!carriesOld && ( +
+ +
+ setOldPassword(e.target.value)} + placeholder="输入当前访问密码" + className="h-10 pr-10 text-sm" + /> + +
+
+ )} + +
+ +
+ setNewPassword(e.target.value)} + placeholder="设置新的强密码" + className="h-10 pr-10 text-sm" + /> + +
+
+ +
+ + setConfirmPassword(e.target.value)} + placeholder="再次输入新密码" + className="h-10 text-sm" + /> + {confirmPassword.length > 0 && !confirmMatches && ( + 两次输入的密码不一致 + )} +
+ + + + + {error && ( + + {error} + + )} + + +
+ {onCancel && ( + + )} + +
+ + ); +} + +function RuleList({ rules }: { rules: PasswordRule[] }) { + // Initial empty state: show a placeholder set so the user knows the rules + // exist even before any input. + const display = useMemo(() => { + if (rules.length > 0) return rules; + return [ + { id: 'length', label: '长度不少于 10 位', ok: false }, + { id: 'lower', label: '至少包含一个小写字母', ok: false }, + { id: 'upper', label: '至少包含一个大写字母', ok: false }, + { id: 'special', label: '至少包含一个特殊字符', ok: false }, + { id: 'no-space', label: '不得包含空格', ok: false }, + ]; + }, [rules]); + + return ( +
    + {display.map((rule) => ( +
  • + + + {rule.ok && ( + + + + )} + + + + {rule.label} + +
  • + ))} +
+ ); +} diff --git a/packages/webui/src/components/pages/change-password-page.tsx b/packages/webui/src/components/pages/change-password-page.tsx index 7972b966..09aae42f 100644 --- a/packages/webui/src/components/pages/change-password-page.tsx +++ b/packages/webui/src/components/pages/change-password-page.tsx @@ -1,104 +1,40 @@ -import { useEffect, useMemo, useState } from 'react'; -import { motion, AnimatePresence } from 'motion/react'; -import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react'; -import { Button } from '@/components/ui/button'; +import { motion } from 'motion/react'; +import { ShieldAlert } from 'lucide-react'; import { Card, CardContent } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; import { ThemeToggle } from '@/components/theme-toggle'; -import { cn } from '@/lib/utils'; +import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form'; -export interface PasswordRule { - id: string; - label: string; - ok: boolean; -} +// Re-exported so existing importers (e.g. the API client) keep resolving +// `PasswordRule` from this module after the form was extracted. +export type { PasswordRule }; interface ChangePasswordPageProps { - /** When true, this is the forced first-time change flow. */ - forced?: boolean; - /** Heading shown above the form. */ + /** + * The password the user just logged in with. Passed straight through to the + * form as `knownOldPassword`, so the forced flow never renders an + * old-password field for a browser to autofill. See change-password-form. + */ + knownOldPassword?: string; title?: string; - /** Subheading. */ description?: string; - /** Sends `{ password }` and returns the rule list + valid flag. */ checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>; - /** Sends `{ oldPassword, newPassword }`. Returns success or error message. */ submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>; - /** Called after a successful submit. */ onSuccess: () => void; - /** Called when user cancels (only available when not forced). */ - onCancel?: () => void; } +/** + * Full-screen "you must set a new password before continuing" gate, shown + * once right after the first login with a generated temp password. The + * in-app "修改访问密码" action uses ChangePasswordDialog instead. + */ export function ChangePasswordPage({ - forced = false, - title, - description, + knownOldPassword, + title = '请先设置新的访问密码', + description = '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。', checkStrength, submit, onSuccess, - onCancel, }: ChangePasswordPageProps) { - const [oldPassword, setOldPassword] = useState(''); - const [newPassword, setNewPassword] = useState(''); - const [confirmPassword, setConfirmPassword] = useState(''); - const [showOld, setShowOld] = useState(false); - const [showNew, setShowNew] = useState(false); - const [rules, setRules] = useState([]); - const [valid, setValid] = useState(false); - const [submitting, setSubmitting] = useState(false); - const [error, setError] = useState(''); - - const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; - const canSubmit = - !submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword; - - // Debounce the strength check so we don't slam the API on every keystroke. - useEffect(() => { - let cancelled = false; - const handle = window.setTimeout(async () => { - try { - const res = await checkStrength(newPassword); - if (cancelled) return; - setRules(res.rules); - setValid(res.valid); - } catch { - /* ignore – the form will just stay disabled */ - } - }, 180); - return () => { - cancelled = true; - window.clearTimeout(handle); - }; - }, [newPassword, checkStrength]); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - if (!canSubmit) return; - setSubmitting(true); - setError(''); - try { - const res = await submit(oldPassword, newPassword); - if (res.success) { - onSuccess(); - } else { - setError(res.message || '修改失败'); - } - } catch (err) { - setError(err instanceof Error ? err.message : '网络错误'); - } finally { - setSubmitting(false); - } - }; - - const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码'); - const computedDescription = - description ?? - (forced - ? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。' - : '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。'); - return (
- {forced ? ( - - ) : ( - - )} +
-

{computedTitle}

-

{computedDescription}

+

{title}

+

{description}

-
-
- -
- setOldPassword(e.target.value)} - placeholder="输入当前访问密码" - className="h-10 pr-10 text-sm" - /> - -
-
- -
- -
- setNewPassword(e.target.value)} - placeholder="设置新的强密码" - className="h-10 pr-10 text-sm" - /> - -
-
- -
- - setConfirmPassword(e.target.value)} - placeholder="再次输入新密码" - className="h-10 text-sm" - /> - {confirmPassword.length > 0 && !confirmMatches && ( - 两次输入的密码不一致 - )} -
- - - - - {error && ( - - {error} - - )} - - -
- {!forced && onCancel && ( - - )} - -
- +
+ +
); } - -function RuleList({ rules }: { rules: PasswordRule[] }) { - // Initial empty state: show a placeholder set so the user knows the rules - // exist even before any input. - const display = useMemo(() => { - if (rules.length > 0) return rules; - return [ - { id: 'length', label: '长度不少于 10 位', ok: false }, - { id: 'lower', label: '至少包含一个小写字母', ok: false }, - { id: 'upper', label: '至少包含一个大写字母', ok: false }, - { id: 'special', label: '至少包含一个特殊字符', ok: false }, - { id: 'no-space', label: '不得包含空格', ok: false }, - ]; - }, [rules]); - - return ( -
    - {display.map((rule) => ( -
  • - - - {rule.ok && ( - - - - )} - - - - {rule.label} - -
  • - ))} -
- ); -} diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index fa7594f4..0c0abc64 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -68,40 +68,47 @@ export function ConfigPage() { [pendingSwitchUin, qqList], ); - // Per-kind helpers (typed at the call site so the dialog's onSubmit - // payload is exactly the kind's adapter shape). - function updateKind(kind: K, next: OneBotNetworks[K]): void { + // A discrete node mutation (create / edit / delete / enable-toggle) is + // persisted the moment it happens — clicking 保存 inside the editor dialog + // (or flipping the enable switch) IS the save. This removes the old + // two-step trap where editing a token in the dialog only marked the config + // "dirty" until you also pressed the top-right 保存, which silently cost + // many users their token edits. The general-settings tab keeps its explicit + // top-right save (it's a continuously-edited free-form surface). + function commitKind(kind: K, nextList: OneBotNetworks[K]): void { if (!config) return; - setConfig({ ...config, networks: { ...config.networks, [kind]: next } }); + const next = { ...config, networks: { ...config.networks, [kind]: nextList } }; + setConfig(next); + void save(next); } function handleCreate(kind: K, item: OneBotNetworks[K][number]): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - updateKind(kind, [...list, item] as OneBotNetworks[K]); + commitKind(kind, [...list, item] as OneBotNetworks[K]); } function handleEdit(kind: K, index: number, item: OneBotNetworks[K][number]): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind(kind, list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]); } function handleDelete(kind: K, index: number): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.filter((_, i) => i !== index) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind(kind, list.filter((_, i) => i !== index) as OneBotNetworks[K]); } function handleToggleEnabled(kind: K, index: number, enabled: boolean): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.map((it, i) => - i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it, - ) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind( + kind, + list.map((it, i) => + i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it, + ) as OneBotNetworks[K], + ); } const openCreate = (kind: NetworkKind) => { diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index a969f34c..b58daf5d 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { motion } from 'motion/react'; -import { Check, KeyRound, Loader2, Monitor, Moon, Sun } from 'lucide-react'; +import { Check, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sun } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; @@ -14,8 +14,7 @@ import { type Density, type ThemeMode, } from '@/contexts/ThemeContext'; -import { ChangePasswordPage } from '@/components/pages/change-password-page'; -import { useApi } from '@/lib/api'; +import { ChangePasswordDialog } from '@/components/change-password-dialog'; import { useAppState } from '@/contexts/AppStateContext'; import { cn } from '@/lib/utils'; @@ -30,233 +29,279 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[] { value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' }, ]; +type SettingsTab = 'appearance' | 'data' | 'account'; + +const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ + { key: 'appearance', label: '外观', icon: Palette }, + { key: 'data', label: '数据刷新', icon: RefreshCw }, + { key: 'account', label: '账号安全', icon: ShieldCheck }, +]; + export function SettingsPage() { - const api = useApi(); - const { onLogout } = useAppState(); - const { - mode, setMode, - accent, setAccent, - radius, setRadius, - density, setDensity, - pollInterval, setPollInterval, - } = useTheme(); - - const [showChangePwd, setShowChangePwd] = useState(false); - const [pwdSavedAt, setPwdSavedAt] = useState(null); - - if (showChangePwd) { - return ( - api.checkPasswordStrength(p)} - submit={(o, n) => api.changePassword(o, n)} - onSuccess={() => { - setShowChangePwd(false); - setPwdSavedAt(Date.now()); - }} - onCancel={() => setShowChangePwd(false)} - /> - ); - } + const [tab, setTab] = useState('appearance'); return ( -
- {/* Appearance */} - - - 外观 - 调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。 - - - {/* Mode */} -
- -
- {MODE_OPTIONS.map((opt) => { - const Icon = opt.icon; - const active = mode === opt.value; - return ( - - ); - })} -
-
+
+ - - - {/* Accent color */} -
- -
- {ACCENTS.map((spec) => { - const active = accent === spec.id; - return ( - - ); - })} -
-

当前:{ACCENTS.find((a) => a.id === accent)?.label}

-
- - - - {/* Radius */} -
- -
- {RADIUS_OPTIONS.map((opt) => { - const active = Math.abs(radius - opt.value) < 1e-6; - return ( - - ); - })} -
-
- - - - {/* Density */} -
- -
- {DENSITY_OPTIONS.map((opt) => { - const active = density === opt.value; - return ( - - ); - })} -
-
- - - - {/* Behavior */} - - - 数据刷新 - 控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。 - - -
- -
- {POLL_INTERVAL_OPTIONS.map((opt) => { - const active = pollInterval === opt.value; - return ( - - ); - })} -
-

当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}

-
-
-
- - {/* Account */} - - - 账号安全 - WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。 - - - - {pwdSavedAt && ( - - 密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。 - - )} - - - -
-

退出登录

-

立即清除当前浏览器的会话令牌。

- -
-
-
+ {tab === 'appearance' && } + {tab === 'data' && } + {tab === 'account' && }
); } + +// ─────────────── mini tab strip ─────────────── + +function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) { + return ( +
+ {TABS.map((t) => { + const Icon = t.icon; + const active = tab === t.key; + return ( + + ); + })} +
+ ); +} + +// ─────────────── 外观 ─────────────── + +function AppearancePanel() { + const { mode, setMode, accent, setAccent, radius, setRadius, density, setDensity } = useTheme(); + return ( + + + 外观 + 调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。 + + + {/* Mode */} +
+ +
+ {MODE_OPTIONS.map((opt) => { + const Icon = opt.icon; + const active = mode === opt.value; + return ( + + ); + })} +
+
+ + + + {/* Accent color */} +
+ +
+ {ACCENTS.map((spec) => { + const active = accent === spec.id; + return ( + + ); + })} +
+

当前:{ACCENTS.find((a) => a.id === accent)?.label}

+
+ + + + {/* Radius */} +
+ +
+ {RADIUS_OPTIONS.map((opt) => { + const active = Math.abs(radius - opt.value) < 1e-6; + return ( + + ); + })} +
+
+ + + + {/* Density */} +
+ +
+ {DENSITY_OPTIONS.map((opt) => { + const active = density === opt.value; + return ( + + ); + })} +
+
+
+
+ ); +} + +// ─────────────── 数据刷新 ─────────────── + +function DataPanel() { + const { pollInterval, setPollInterval } = useTheme(); + return ( + + + 数据刷新 + 控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。 + + +
+ +
+ {POLL_INTERVAL_OPTIONS.map((opt) => { + const active = pollInterval === opt.value; + return ( + + ); + })} +
+

+ 当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`} +

+
+
+
+ ); +} + +// ─────────────── 账号安全 ─────────────── + +function AccountPanel() { + const { onLogout } = useAppState(); + const [showChangePwd, setShowChangePwd] = useState(false); + const [pwdSavedAt, setPwdSavedAt] = useState(null); + + return ( + + + 账号安全 + WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。 + + + + {pwdSavedAt && ( + + 密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。 + + )} + + + +
+

退出登录

+

立即清除当前浏览器的会话令牌。

+ +
+
+ + setPwdSavedAt(Date.now())} + /> +
+ ); +} diff --git a/packages/webui/src/components/pages/status-screens.tsx b/packages/webui/src/components/pages/status-screens.tsx new file mode 100644 index 00000000..b2c290ee --- /dev/null +++ b/packages/webui/src/components/pages/status-screens.tsx @@ -0,0 +1,95 @@ +import type { ReactNode } from 'react'; +import { motion } from 'motion/react'; +import { AlertTriangle, Compass, Home, RotateCw } from 'lucide-react'; +import { Button } from '@/components/ui/button'; + +type Tone = 'primary' | 'destructive'; + +function StatusShell({ + tone, + icon, + code, + title, + description, + children, +}: { + tone: Tone; + icon: ReactNode; + code?: string; + title: string; + description: string; + children: ReactNode; +}) { + return ( +
+ +
+ {icon} +
+ {code && ( + + {code} + + )} +

{title}

+

{description}

+
{children}
+
+
+ ); +} + +/** Rendered by the router for any unmatched path. */ +export function NotFoundPage() { + return ( + } + code="404" + title="页面不存在" + description="你访问的地址没有对应的页面,可能链接已失效或输入有误。" + > + + + ); +} + +/** Rendered by the router when a route component throws while rendering. */ +export function ErrorPage({ error, reset }: { error?: Error; reset?: () => void }) { + const message = error?.message?.trim(); + return ( + } + title="页面出错了" + description="渲染该页面时发生了意外错误。可以重试,或返回首页继续操作。" + > + {reset && ( + + )} + + {message && ( +
+          {message}
+        
+ )} +
+ ); +} diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts index dc4b2cd0..b3d61031 100644 --- a/packages/webui/src/hooks/use-onebot-instance-config.ts +++ b/packages/webui/src/hooks/use-onebot-instance-config.ts @@ -25,7 +25,13 @@ export interface UseOneBotInstanceConfig { pendingSwitchUin: string | null; confirmSwitch: () => void; cancelSwitch: () => void; - save: () => Promise; + /** + * Persist to the backend. Pass an explicit config to save it directly — + * the node dialog / enable-toggle / delete persist their freshly-computed + * config in the same tick, before React has flushed `setConfig`, so they + * can't rely on the (still-stale) closed-over `config`. + */ + save: (override?: OneBotConfig) => Promise; saveStatus: string; } @@ -117,11 +123,12 @@ export function useOneBotInstanceConfig( }, CLEAR_SAVE_STATUS_MS); }, []); - const save = useCallback(async () => { - if (!selectedUin || !config) return; + const save = useCallback(async (override?: OneBotConfig) => { + const target = override ?? config; + if (!selectedUin || !target) return; setSaveStatus('保存中...'); try { - const serverView = await api.config.save(selectedUin, config); + const serverView = await api.config.save(selectedUin, target); setConfigState(serverView); setSavedSnapshot(JSON.stringify(serverView)); setSaveStatus('保存成功'); diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index 791dc490..4f871197 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -6,6 +6,9 @@ import { Outlet, } from '@tanstack/react-router'; import { AppLayout } from './app-layout'; +// Imported eagerly (not lazy): the error / not-found fallbacks must render +// even when a route's own chunk failed to load. +import { ErrorPage, NotFoundPage } from '@/components/pages/status-screens'; // Page components are loaded on demand so the initial paint only ships // the auth surface + layout shell. With `defaultPreload: 'intent'` set @@ -68,6 +71,8 @@ const routeTree = rootRoute.addChildren([ export const appRouter = createRouter({ routeTree, defaultPreload: 'intent', + defaultNotFoundComponent: () => , + defaultErrorComponent: ({ error, reset }) => , }); declare module '@tanstack/react-router' {