feat(webui): improve operation feedback

Keep confirmations in dialogs while showing clear progress and results for long-running actions.

Auto-close completed notices, preserve important outcomes across reloads, and avoid noise from routine edits.
This commit is contained in:
DrSmoothl committed 2026-07-31 15:35:03 +08:00
1 parent b099dbe8cd
commit b982927b4a
20 files changed
+1863 -222

No files matched your search

+20 -66
View File
@@ -1,73 +1,27 @@
# React + TypeScript + Vite
# SnowLuma WebUI
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
SnowLuma's browser console is a Vite + React application for managing runtime
status, OneBot configuration, logs, storage, and server settings.
Currently, two official plugins are available:
## Interaction conventions
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
- Destructive actions and second confirmations stay in modal dialogs.
- Operations that may take time show a bottom-right running state.
- Completed and failed operations use bottom-right result notices that close
automatically after a visible countdown.
- Routine, high-frequency adjustments should not generate a notice for every
intermediate edit.
- Failures must remain visible in the affected control and in the operation
result; do not convert failed responses into successful feedback.
## React Compiler
## Local development
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
From the repository root:
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```bash
pnpm --filter webui dev
pnpm --filter webui typecheck
pnpm --filter webui lint
pnpm --filter webui test
pnpm --filter webui build
```
+37 -8
View File
@@ -11,16 +11,24 @@ import { DebugTaskProvider } from '@/contexts/DebugTaskContext';
import { TaskBadge } from '@/components/debug/task-badge';
import { AdaptivePointer } from '@/components/ui/adaptive-pointer';
import { GlobalContextMenu } from '@/components/ui/global-context-menu';
import {
ActionFeedbackProvider,
ActionFeedbackViewport,
useActionFeedback,
} from '@/contexts/ActionFeedbackContext';
import type { AgreementsPayload } from '@/lib/api/types';
import { appRouter } from '@/router';
export default function App() {
return (
<ThemeProvider>
<AdaptivePointer />
<GlobalContextMenu />
<AuthBoundary />
</ThemeProvider>
<ActionFeedbackProvider>
<ThemeProvider>
<ActionFeedbackViewport />
<AdaptivePointer />
<GlobalContextMenu />
<AuthBoundary />
</ThemeProvider>
</ActionFeedbackProvider>
);
}
@@ -191,14 +199,25 @@ function Splash({ children }: { children: React.ReactNode }) {
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) {
const api = useApi();
const { runAction } = useActionFeedback();
const handleLogin = useCallback(
async (password: string) => {
const result = await api.login(password);
const result = await runAction(
{
title: '正在登录',
detail: '正在验证 WebUI 访问密码',
successTitle: '登录成功',
successDetail: '正在进入控制台',
errorTitle: '登录失败',
resultError: (login) => login.ok ? null : login.message,
},
() => api.login(password),
);
if (!result.ok) return { success: false, error: result.message };
onAuthed(result.mustChangePassword, password);
return { success: true };
},
[api, onAuthed],
[api, onAuthed, runAction],
);
return <LoginPage onLogin={handleLogin} />;
}
@@ -215,13 +234,23 @@ function ConsentGate({
onDecline: () => void;
}) {
const api = useApi();
const { runAction } = useActionFeedback();
return (
<ConsentPage
documents={payload.documents}
version={payload.version}
onDecline={onDecline}
onAccept={async () => {
const result = await api.agreements.recordConsent(payload.version);
const result = await runAction(
{
title: '正在记录协议确认',
detail: `协议版本 ${payload.version.slice(0, 8)}`,
successTitle: '协议确认已记录',
errorTitle: '协议确认失败',
resultError: (consent) => consent.success ? null : consent.message,
},
() => api.agreements.recordConsent(payload.version),
);
if (result.success) {
onAccepted();
return { success: true };
@@ -10,6 +10,11 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { buttonVariants } from '@/components/ui/button';
import {
actionErrorMessage,
useActionFeedback,
type ActionFeedbackOptions,
} from '@/contexts/ActionFeedbackContext';
import { cn } from '@/lib/utils';
interface ConfirmDialogProps {
@@ -20,6 +25,9 @@ interface ConfirmDialogProps {
confirmText?: string;
cancelText?: string;
destructive?: boolean;
content?: ReactNode;
confirmDisabled?: boolean;
activity?: ActionFeedbackOptions<void>;
onConfirm: () => void | Promise<void>;
}
@@ -31,25 +39,57 @@ export function ConfirmDialog({
confirmText = '确认',
cancelText = '取消',
destructive = false,
content,
confirmDisabled = false,
activity,
onConfirm,
}: ConfirmDialogProps) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const { runAction } = useActionFeedback();
const handleConfirm = async () => {
setBusy(true);
setError(null);
try {
await onConfirm();
if (!activity) {
await onConfirm();
} else {
await runAction(activity, onConfirm);
}
onOpenChange(false);
} catch (caught) {
const message = actionErrorMessage(caught);
setError(message);
console.error('confirm action failed', caught);
} finally {
setBusy(false);
}
};
const handleOpenChange = (nextOpen: boolean) => {
if (busy && !nextOpen) return;
if (!nextOpen) setError(null);
onOpenChange(nextOpen);
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialog open={open} onOpenChange={handleOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
{description && (
<AlertDialogDescription asChild>
<div>{description}</div>
</AlertDialogDescription>
)}
</AlertDialogHeader>
{error && (
<div role="alert" className="rounded-lg bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</div>
)}
{content}
<AlertDialogFooter>
<AlertDialogCancel disabled={busy}>{cancelText}</AlertDialogCancel>
<AlertDialogAction
@@ -58,7 +98,7 @@ export function ConfirmDialog({
void handleConfirm();
}}
className={cn(destructive && buttonVariants({ variant: 'destructive' }))}
disabled={busy}
disabled={busy || confirmDisabled}
>
{busy ? '处理中…' : confirmText}
</AlertDialogAction>
@@ -0,0 +1,304 @@
"use client";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { motion, useReducedMotion } from "motion/react";
const EASE = [0.23, 1, 0.32, 1] as const;
const DISCLOSE = { type: "spring", stiffness: 190, damping: 30, mass: 1 } as const;
const NUDGE = { type: "spring", stiffness: 700, damping: 46, mass: 0.5 } as const;
const INSTANT = { duration: 0 } as const;
export type BannerState = "open" | "folded" | "dismissed";
export type UseCollapsibleBannerOptions = {
state?: BannerState;
defaultState?: BannerState;
onStateChange?: (state: BannerState) => void;
onDismiss?: () => void;
};
export type UseCollapsibleBannerResult = {
state: BannerState;
open: boolean;
folded: boolean;
dismissed: boolean;
fold: () => void;
expand: () => void;
toggle: () => void;
dismiss: () => void;
restore: () => void;
};
export function useCollapsibleBanner({
state: controlled,
defaultState = "open",
onStateChange,
onDismiss,
}: UseCollapsibleBannerOptions = {}): UseCollapsibleBannerResult {
const [uncontrolled, setUncontrolled] = useState<BannerState>(defaultState);
const state = controlled ?? uncontrolled;
const changed = useRef(onStateChange);
const closed = useRef(onDismiss);
useEffect(() => {
changed.current = onStateChange;
}, [onStateChange]);
useEffect(() => {
closed.current = onDismiss;
}, [onDismiss]);
const commit = useCallback((next: BannerState) => {
setUncontrolled(next);
changed.current?.(next);
}, []);
const fold = useCallback(() => commit("folded"), [commit]);
const expand = useCallback(() => commit("open"), [commit]);
const restore = useCallback(() => commit("open"), [commit]);
const toggle = useCallback(
() => commit(state === "open" ? "folded" : "open"),
[commit, state],
);
const dismiss = useCallback(() => {
commit("dismissed");
closed.current?.();
}, [commit]);
return {
state,
open: state === "open",
folded: state === "folded",
dismissed: state === "dismissed",
fold,
expand,
toggle,
dismiss,
restore,
};
}
const NOTICE_GLYPH = (
<svg width="16" height="16" viewBox="0 0 256 256" fill="none" aria-hidden="true">
<circle cx="128" cy="128" r="96" stroke="currentColor" strokeWidth="16" />
<polyline
points="120 120 128 120 128 176 136 176"
stroke="currentColor"
strokeWidth="16"
strokeLinecap="round"
strokeLinejoin="round"
/>
<circle cx="124" cy="84" r="12" fill="currentColor" />
</svg>
);
const CARET_DOWN = (
<svg width="14" height="14" viewBox="0 0 256 256" fill="none" aria-hidden="true">
<polyline
points="208 96 128 176 48 96"
stroke="currentColor"
strokeWidth="16"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
const CLOSE = (
<svg width="13" height="13" viewBox="0 0 256 256" fill="none" aria-hidden="true">
<line
x1="200"
y1="56"
x2="56"
y2="200"
stroke="currentColor"
strokeWidth="16"
strokeLinecap="round"
/>
<line
x1="200"
y1="200"
x2="56"
y2="56"
stroke="currentColor"
strokeWidth="16"
strokeLinecap="round"
/>
</svg>
);
export type CollapsibleBannerProps = {
title: React.ReactNode;
description?: React.ReactNode;
children?: React.ReactNode;
action?: React.ReactNode;
icon?: React.ReactNode;
dismissible?: boolean;
state?: BannerState;
defaultState?: BannerState;
onStateChange?: (state: BannerState) => void;
onDismiss?: () => void;
onDismissed?: () => void;
dismissLabel?: string;
dismissedMessage?: string;
className?: string;
};
export function CollapsibleBanner({
title,
description,
children,
action,
icon,
dismissible = true,
state: controlled,
defaultState = "open",
onStateChange,
onDismiss,
onDismissed,
dismissLabel = "Dismiss notice",
dismissedMessage = "Notice dismissed.",
className = "",
}: CollapsibleBannerProps) {
const reduced = useReducedMotion();
const uid = useId();
const bodyId = `${uid}-body`;
const titleId = `${uid}-title`;
const { state, open, dismissed, toggle, fold, dismiss } = useCollapsibleBanner({
state: controlled,
defaultState,
onStateChange,
onDismiss,
});
const wasVisible = useRef(false);
useEffect(() => {
if (!dismissed) wasVisible.current = true;
}, [dismissed]);
const hasBody = Boolean(description || children || action);
const disclose = reduced
? INSTANT
: {
height: DISCLOSE,
opacity: { duration: 0.14, ease: EASE, delay: open ? 0.05 : 0 },
y: DISCLOSE,
};
return (
<>
<motion.div
initial={false}
animate={{ height: dismissed ? 0 : "auto", opacity: dismissed ? 0 : 1 }}
transition={
reduced
? INSTANT
: { height: DISCLOSE, opacity: { duration: 0.14, ease: EASE } }
}
style={{ overflow: "hidden" }}
onAnimationComplete={() => {
if (dismissed && wasVisible.current) onDismissed?.();
}}
className="rounded-[11px]"
>
<div
role="region"
aria-labelledby={titleId}
className={`rounded-[11px] border border-border/80 bg-popover/95 text-popover-foreground shadow-[0_1px_2px_rgb(0_0_0/0.06),0_16px_36px_-18px_rgb(0_0_0/0.5)] backdrop-blur-xl ${className}`}
>
<div className="flex items-center gap-2.5 p-2.5">
<span
aria-hidden="true"
className="grid size-[26px] shrink-0 place-items-center rounded-[7px] bg-muted/70 text-muted-foreground shadow-[inset_0_1px_2px_rgb(0_0_0/0.08)]"
>
{icon ?? NOTICE_GLYPH}
</span>
{hasBody ? (
<button
type="button"
onClick={toggle}
onKeyDown={(e) => {
if (e.key !== "Escape" || !open) return;
e.stopPropagation();
fold();
}}
aria-expanded={open}
aria-controls={bodyId}
className="group flex min-w-0 flex-1 items-center gap-2 rounded-[7px] text-left outline-none focus-visible:bg-primary/10 focus-visible:ring-1 focus-visible:ring-primary"
>
<span
id={titleId}
className="min-w-0 flex-1 truncate text-[13px] font-medium leading-5 text-foreground"
>
{title}
</span>
<motion.span
aria-hidden="true"
className="flex shrink-0 text-muted-foreground group-hover:text-foreground"
initial={false}
animate={{ rotate: open ? 180 : 0 }}
transition={reduced ? INSTANT : NUDGE}
>
{CARET_DOWN}
</motion.span>
</button>
) : (
<span
id={titleId}
className="min-w-0 flex-1 truncate text-[13px] font-medium leading-5 text-foreground"
>
{title}
</span>
)}
{dismissible ? (
<button
type="button"
onClick={dismiss}
aria-label={dismissLabel}
className="grid size-[26px] shrink-0 place-items-center rounded-[7px] text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground focus-visible:bg-primary/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
>
{CLOSE}
</button>
) : null}
</div>
{hasBody ? (
<motion.div
id={bodyId}
inert={!open}
initial={false}
animate={{ height: open ? "auto" : 0, opacity: open ? 1 : 0 }}
transition={disclose}
style={{ overflow: "hidden" }}
>
<motion.div
initial={false}
animate={{ y: open ? 0 : -6 }}
transition={reduced ? INSTANT : DISCLOSE}
className="pb-2.5 pl-[46px] pr-2.5"
>
{description ? (
<p className="text-[12.5px] leading-relaxed text-muted-foreground">
{description}
</p>
) : null}
{children}
{action ? <div className="mt-2">{action}</div> : null}
</motion.div>
</motion.div>
) : null}
</div>
</motion.div>
<span role="status" aria-live="polite" className="sr-only">
{state === "dismissed" ? dismissedMessage : ""}
</span>
</>
);
}
@@ -0,0 +1,468 @@
"use client";
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
const SURFACE = { type: "spring", stiffness: 420, damping: 36, mass: 0.9 } as const;
const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const;
const SMALL = { type: "spring", stiffness: 700, damping: 46, mass: 0.5 } as const;
const FILL = { type: "spring", stiffness: 210, damping: 34, mass: 0.9 } as const;
const EASE = [0.23, 1, 0.32, 1] as const;
const LEAVE = [0.4, 0, 1, 1] as const;
const DRAW = { duration: 0.3, ease: EASE } as const;
const INSTANT = { duration: 0 } as const;
const SPIN = { duration: 0.85, ease: "linear", repeat: Infinity } as const;
const PEEK_FOR = 2600;
const LEAVE_DELAY = 160;
const face = (on: boolean) => (on ? "" : "pointer-events-none");
const useIsoLayoutEffect =
typeof window === "undefined" ? useEffect : useLayoutEffect;
export type ActivityPhase = "running" | "success" | "error";
export type Activity = {
id: string;
title: string;
detail?: string;
progress?: number | null;
phase: ActivityPhase;
action?: { label: string; onClick: () => void };
};
export type ActivityInput = {
title: string;
detail?: string;
progress?: number | null;
};
export type UseLiveActivityOptions = {
linger?: number;
};
export function useLiveActivity({ linger = 2000 }: UseLiveActivityOptions = {}) {
const [activity, setActivity] = useState<Activity | null>(null);
const seq = useRef(0);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const clear = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
}, []);
const start = useCallback(
(input: ActivityInput) => {
clear();
seq.current += 1;
const id = `activity-${seq.current}`;
setActivity({ progress: null, ...input, id, phase: "running" });
return id;
},
[clear],
);
const update = useCallback((patch: Partial<ActivityInput>) => {
setActivity((prev) => (prev ? { ...prev, ...patch } : prev));
}, []);
const dismiss = useCallback(() => {
clear();
setActivity(null);
}, [clear]);
const succeed = useCallback(
(patch?: Partial<ActivityInput>) => {
setActivity((prev) =>
prev ? { ...prev, ...patch, phase: "success", progress: 1 } : prev,
);
clear();
timer.current = setTimeout(() => {
timer.current = null;
setActivity(null);
}, linger);
},
[clear, linger],
);
const fail = useCallback(
(patch?: Partial<ActivityInput>, action?: Activity["action"]) => {
clear();
setActivity((prev) =>
prev ? { ...prev, ...patch, phase: "error", action } : prev,
);
},
[clear],
);
useEffect(() => clear, [clear]);
return { activity, start, update, succeed, fail, dismiss };
}
export type UseLiveActivityReturn = ReturnType<typeof useLiveActivity>;
export type LiveActivityProps = {
activity: Activity | null;
onDismiss?: () => void;
width?: number;
dismissLabel?: string;
label?: string;
className?: string;
};
export function LiveActivity({
activity,
onDismiss,
width = 300,
dismissLabel = "Dismiss activity",
label = "Activity",
className = "",
}: LiveActivityProps) {
const reduced = useReducedMotion() === true;
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const [peeking, setPeeking] = useState(false);
const [spoken, setSpoken] = useState("");
const compactRef = useRef<HTMLDivElement>(null);
const expandedRef = useRef<HTMLDivElement>(null);
const sizes = useRef({ c: { w: 0, h: 0 }, e: { w: 0, h: 0 } });
const [dims, setDims] = useState<{ w: number; h: number } | null>(null);
const leaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const peekTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const said = useRef<Set<string>>(new Set());
const phase = activity?.phase ?? "running";
const expanded =
activity !== null && (hovered || focused || peeking || phase === "error");
const apply = useCallback((open: boolean) => {
const target = open ? sizes.current.e : sizes.current.c;
if (target.w === 0 || target.h === 0) return;
setDims((prev) =>
prev &&
Math.abs(prev.w - target.w) < 0.5 &&
Math.abs(prev.h - target.h) < 0.5
? prev
: { w: target.w, h: target.h },
);
}, []);
useIsoLayoutEffect(() => {
if (!activity) return;
const read = () => {
const c = compactRef.current;
const e = expandedRef.current;
if (c) sizes.current.c = { w: c.offsetWidth, h: c.offsetHeight };
if (e) sizes.current.e = { w: e.offsetWidth, h: e.offsetHeight };
apply(expanded);
};
read();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(read);
if (compactRef.current) observer.observe(compactRef.current);
if (expandedRef.current) observer.observe(expandedRef.current);
return () => observer.disconnect();
}, [activity, expanded, apply]);
useEffect(() => {
if (!activity) {
setPeeking(false);
setHovered(false);
setFocused(false);
setDims(null);
return;
}
setPeeking(true);
if (peekTimer.current) clearTimeout(peekTimer.current);
peekTimer.current = setTimeout(() => {
peekTimer.current = null;
setPeeking(false);
}, PEEK_FOR);
}, [activity?.id, activity?.phase, activity]);
useEffect(
() => () => {
if (leaveTimer.current) clearTimeout(leaveTimer.current);
if (peekTimer.current) clearTimeout(peekTimer.current);
},
[],
);
useEffect(() => {
if (!activity) return;
const key = `${activity.id}:${activity.phase}`;
if (said.current.has(key)) return;
if (said.current.size > 64) said.current.clear();
said.current.add(key);
setSpoken(
activity.phase === "running"
? `${activity.title} started.`
: activity.phase === "success"
? `${activity.title} finished.`
: `${activity.title} failed.`,
);
}, [activity]);
const enter = () => {
if (leaveTimer.current) clearTimeout(leaveTimer.current);
leaveTimer.current = null;
setHovered(true);
};
const leave = () => {
if (leaveTimer.current) clearTimeout(leaveTimer.current);
leaveTimer.current = setTimeout(() => {
leaveTimer.current = null;
setHovered(false);
}, LEAVE_DELAY);
};
const percent =
activity?.progress === null || activity?.progress === undefined
? null
: Math.round(Math.min(1, Math.max(0, activity.progress)) * 100);
return (
<div
role="region"
aria-label={label}
className={`pointer-events-none flex justify-end ${className}`}
>
<AnimatePresence initial={false}>
{activity ? (
<motion.div
key="pod"
initial={
reduced
? { opacity: 0 }
: { opacity: 0, y: -10, scale: 0.9, filter: "blur(6px)" }
}
animate={{
opacity: 1,
y: 0,
scale: 1,
filter: "blur(0px)",
width: dims?.w,
height: dims?.h,
}}
exit={
reduced
? { opacity: 0, transition: INSTANT }
: {
opacity: 0,
y: -8,
scale: 0.97,
filter: "blur(3px)",
transition: { duration: 0.16, ease: LEAVE },
}
}
transition={
reduced
? INSTANT
: {
...SURFACE,
opacity: { duration: 0.2, ease: EASE },
filter: { duration: 0.2, ease: EASE },
}
}
style={{ transformOrigin: "50% 0%" }}
onPointerEnter={enter}
onPointerLeave={leave}
onFocusCapture={() => setFocused(true)}
onBlurCapture={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setFocused(false);
}
}}
onKeyDown={(e) => {
if (e.key !== "Escape") return;
e.preventDefault();
if (phase === "running") setHovered(false);
else onDismiss?.();
}}
className="pointer-events-auto relative overflow-hidden rounded-[11px] border border-border/80 bg-popover/95 text-popover-foreground shadow-[0_1px_2px_rgb(0_0_0/0.07),0_16px_36px_-18px_rgb(0_0_0/0.5)] backdrop-blur-xl"
>
<motion.div
ref={compactRef}
aria-hidden={expanded}
inert={expanded}
initial={false}
animate={{ opacity: expanded ? 0 : 1 }}
transition={reduced ? INSTANT : CROSSFADE}
className={`absolute left-0 top-0 flex h-8 w-max items-center gap-1.5 px-2.5 ${face(!expanded)}`}
>
<PhaseGlyph phase={phase} reduced={reduced} />
{percent !== null && phase === "running" ? (
<span className="font-mono text-[10.5px] tabular-nums text-muted-foreground">
{percent}%
</span>
) : (
<span className="max-w-[120px] truncate text-[12px] font-medium text-foreground">
{activity.title}
</span>
)}
</motion.div>
<motion.div
ref={expandedRef}
aria-hidden={!expanded}
inert={!expanded}
initial={false}
animate={{ opacity: expanded ? 1 : 0 }}
transition={reduced ? INSTANT : CROSSFADE}
style={{ width, maxWidth: "calc(100vw - 2rem)" }}
className={`absolute left-0 top-0 px-3.5 py-3 ${face(expanded)}`}
>
<div className="flex items-center gap-2">
<PhaseGlyph phase={phase} reduced={reduced} />
<span className="min-w-0 flex-1 truncate text-[13px] font-medium text-foreground">
{activity.title}
</span>
{activity.action ? (
<button
type="button"
tabIndex={expanded ? 0 : -1}
onClick={activity.action.onClick}
className="inline-flex h-[24px] shrink-0 select-none items-center whitespace-nowrap rounded-[6px] border border-border bg-background px-2 text-[11px] font-medium text-foreground shadow-sm outline-none transition-[background-color,border-color,box-shadow] duration-150 hover:bg-muted focus-visible:border-primary active:translate-y-px"
>
{activity.action.label}
</button>
) : null}
{onDismiss && phase !== "running" ? (
<button
type="button"
tabIndex={expanded ? 0 : -1}
aria-label={dismissLabel}
onClick={onDismiss}
className="grid size-[22px] shrink-0 place-items-center rounded-[6px] text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground focus-visible:bg-primary/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
>
<svg width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden>
<path
d="M2.8 2.8l6.4 6.4M9.2 2.8l-6.4 6.4"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
/>
</svg>
</button>
) : null}
</div>
{activity.detail ? (
<p className="mt-1 truncate pl-[26px] text-[11.5px] text-muted-foreground">
{activity.detail}
</p>
) : null}
{percent !== null && phase !== "error" ? (
<div className="mt-2.5 flex items-center gap-2 pl-[26px]">
<div className="min-w-0 flex-1 rounded-[4px] bg-muted p-[2px] shadow-[inset_0_1px_2px_rgb(0_0_0/0.12)]">
<div className="relative h-[4px] overflow-hidden rounded-[2px]">
<motion.span
aria-hidden
className="absolute inset-0 block origin-left rounded-[2px] bg-primary shadow-[inset_0_1px_0_rgb(255_255_255/0.28)]"
initial={false}
animate={{ scaleX: (percent ?? 0) / 100 }}
transition={reduced ? INSTANT : FILL}
/>
</div>
</div>
<span className="shrink-0 font-mono text-[10.5px] tabular-nums text-muted-foreground">
{percent}%
</span>
</div>
) : null}
</motion.div>
</motion.div>
) : null}
</AnimatePresence>
<span role="status" aria-live="polite" className="sr-only">
{spoken}
</span>
</div>
);
}
function PhaseGlyph({ phase, reduced }: { phase: ActivityPhase; reduced: boolean }) {
return (
<span className="grid size-[18px] shrink-0 place-items-center">
<motion.span
className="col-start-1 row-start-1 flex"
initial={false}
animate={{
opacity: phase === "running" ? 1 : 0,
scale: reduced ? 1 : phase === "running" ? 1 : 0.7,
}}
transition={reduced ? INSTANT : SMALL}
>
{reduced ? (
<svg width="13" height="13" viewBox="0 0 12 12" aria-hidden>
<circle cx="6" cy="6" r="4.4" stroke="currentColor" strokeWidth="1.6" fill="none" className="text-muted-foreground" opacity="0.4" />
</svg>
) : (
<motion.svg
width="13"
height="13"
viewBox="0 0 12 12"
aria-hidden
style={{ transformOrigin: "50% 50%" }}
animate={{ rotate: 360 }}
transition={SPIN}
className="text-primary"
>
<circle cx="6" cy="6" r="4.4" stroke="currentColor" strokeWidth="1.6" fill="none" opacity="0.25" />
<path d="M6 1.6a4.4 4.4 0 0 1 4.4 4.4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" fill="none" />
</motion.svg>
)}
</motion.span>
<motion.span
className="col-start-1 row-start-1 flex text-success"
initial={false}
animate={{
opacity: phase === "success" ? 1 : 0,
scale: reduced ? 1 : phase === "success" ? 1 : 0.7,
}}
transition={reduced ? INSTANT : SMALL}
>
<svg width="13" height="13" viewBox="0 0 12 12" fill="none" aria-hidden>
<motion.path
d="M2.4 6.4 4.8 8.8 9.6 3.4"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
initial={false}
animate={{ pathLength: phase === "success" ? 1 : 0 }}
transition={reduced ? INSTANT : DRAW}
/>
</svg>
</motion.span>
<motion.span
className="col-start-1 row-start-1 flex text-destructive"
initial={false}
animate={{
opacity: phase === "error" ? 1 : 0,
scale: reduced ? 1 : phase === "error" ? 1 : 0.7,
}}
transition={reduced ? INSTANT : SMALL}
>
<svg width="13" height="13" viewBox="0 0 12 12" fill="none" aria-hidden>
<path d="M6 2.6v3.6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
<rect x="5.2" y="8.2" width="1.6" height="1.6" rx="0.4" fill="currentColor" />
</svg>
</motion.span>
</span>
);
}
@@ -121,6 +121,11 @@ export function TopBar({
description="登出后将清除当前会话令牌,您需要重新输入访问密码才能进入控制台。"
confirmText="登出"
destructive
activity={{
title: '正在退出登录',
successTitle: '已退出登录',
errorTitle: '退出登录失败',
}}
onConfirm={onLogout}
/>
</header>
@@ -18,6 +18,7 @@ import {
} from '@/lib/server-log-level';
import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
// Dedicated log-level text tokens (see index.css): the app accent colors are
// too light as small text on the light canvas (WCAG AA fails), so these hit
@@ -100,6 +101,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool
export function LogsPage() {
const api = useApi();
const { runAction } = useActionFeedback();
const { formatClock, appearance } = useTheme();
const { pages, setPages } = useLayout();
const prefs = pages.logs;
@@ -152,14 +154,23 @@ export function LogsPage() {
if (lv === serverLevel || levelBusy) return;
setLevelBusy(true);
try {
const { level } = await api.logs.setLevel(lv);
const { level } = await runAction(
{
title: '正在更新服务端日志级别',
detail: `切换为 ${lv.toUpperCase()}`,
successTitle: '日志级别已更新',
successDetail: `${lv.toUpperCase()} 已生效`,
errorTitle: '日志级别更新失败',
},
() => api.logs.setLevel(lv),
);
setServerLevel(level);
} catch (err) {
console.error('setLevel', err);
} finally {
setLevelBusy(false);
}
}, [api, serverLevel, levelBusy]);
}, [api, serverLevel, levelBusy, runAction]);
const changeServerLevel = useCallback((lv: LogLevel) => {
if (levelBusy) return;
@@ -351,7 +362,15 @@ export function LogsPage() {
if (traceExportBusy) return;
setTraceExportBusy(true);
try {
const { text, filename } = await api.logs.exportTrace();
const { text, filename } = await runAction(
{
title: '正在导出完整 TRACE',
detail: '正在读取服务端 TRACE 文件',
successTitle: '完整 TRACE 已导出',
errorTitle: 'TRACE 导出失败',
},
() => api.logs.exportTrace(),
);
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -364,7 +383,7 @@ export function LogsPage() {
} finally {
setTraceExportBusy(false);
}
}, [api, traceExportBusy]);
}, [api, traceExportBusy, runAction]);
const addHighlight = () => {
const kw = newKeyword.trim();
@@ -762,6 +781,11 @@ export function LogsPage() {
description="此操作仅清空浏览器视图中的日志,不会影响服务端的日志缓冲区。"
confirmText="清空"
destructive
activity={{
title: '正在清空日志视图',
successTitle: '日志视图已清空',
errorTitle: '日志视图清空失败',
}}
onConfirm={() => setLogs([])}
/>
</Card>
@@ -33,6 +33,7 @@ import {
type TimeFormat,
} from '@/contexts/ThemeContext';
import { DEFAULT_LAYOUT, DEFAULT_PAGES, reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { NAV_ITEMS } from '@/components/layout/sidebar';
import { TOPBAR_CATALOGUE } from '@/components/layout/top-bar';
import { ChangePasswordDialog } from '@/components/change-password-dialog';
@@ -956,18 +957,28 @@ function validateCss(css: string): string | null {
function AdvancedPanel() {
const { appearance, setAppearance } = useTheme();
const { runAction } = useActionFeedback();
const cssRef = useRef<HTMLTextAreaElement>(null);
const [cssWarn, setCssWarn] = useState<string | null>(null);
const api = useApi();
const fileRef = useRef<HTMLInputElement>(null);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const [confirmReset, setConfirmReset] = useState(false);
const [pendingImport, setPendingImport] = useState<File | null>(null);
const [busy, setBusy] = useState(false);
const onExport = async () => {
setMsg(null);
try {
const config = await api.ui.get();
const config = await runAction(
{
title: '正在导出界面配置',
detail: '外观、布局与自定义 CSS',
successTitle: '界面配置已导出',
errorTitle: '界面配置导出失败',
},
() => api.ui.get(),
);
const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -975,7 +986,8 @@ function AdvancedPanel() {
a.download = 'snowluma-ui-config.json';
a.click();
URL.revokeObjectURL(url);
} catch {
} catch (error) {
console.error('export UI config failed', error);
setMsg({ kind: 'err', text: '导出失败' });
}
};
@@ -988,28 +1000,59 @@ function AdvancedPanel() {
setMsg({ kind: 'err', text: '导入失败:文件过大(上限 256KB)' });
return;
}
setPendingImport(file);
};
const importUiConfig = async (file: File) => {
setMsg(null);
setBusy(true);
try {
const parsed = JSON.parse(await file.text()) as unknown;
if (typeof parsed !== 'object' || parsed === null) throw new Error('shape');
await api.ui.save(parsed as Parameters<typeof api.ui.save>[0]);
await runAction(
{
title: '正在导入界面配置',
detail: file.name,
successTitle: '界面配置已导入',
successDetail: '即将重新载入界面',
errorTitle: '界面配置导入失败',
surviveReload: true,
},
() => api.ui.save(parsed as Parameters<typeof api.ui.save>[0]),
);
// The server normalized it; reload so appearance + layout both re-read.
window.location.reload();
} catch {
} catch (error) {
setBusy(false);
setMsg({ kind: 'err', text: '导入失败:不是有效的配置 JSON' });
setMsg({
kind: 'err',
text: error instanceof SyntaxError || (error instanceof Error && error.message === 'shape')
? '导入失败:不是有效的配置 JSON'
: `导入失败:${error instanceof Error ? error.message : '未知错误'}`,
});
throw error;
}
};
const doReset = async () => {
setBusy(true);
try {
await api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT, pages: DEFAULT_PAGES });
await runAction(
{
title: '正在重置界面配置',
detail: '恢复外观、布局、导航与自定义 CSS',
successTitle: '界面配置已重置',
successDetail: '即将重新载入界面',
errorTitle: '界面配置重置失败',
surviveReload: true,
},
() => api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT, pages: DEFAULT_PAGES }),
);
window.location.reload();
} catch {
} catch (error) {
setBusy(false);
setMsg({ kind: 'err', text: '重置失败' });
throw error;
}
};
@@ -1114,8 +1157,27 @@ function AdvancedPanel() {
title="重置全部界面配置"
description="将外观、仪表盘布局、导航与自定义 CSS 全部恢复为默认。此操作不可撤销。"
confirmText="重置"
destructive
onConfirm={doReset}
/>
<ConfirmDialog
open={pendingImport !== null}
onOpenChange={(open) => {
if (!open) setPendingImport(null);
}}
title="导入并覆盖界面配置?"
description={pendingImport
? `将使用 ${pendingImport.name} 覆盖当前外观、布局、导航与自定义 CSS,随后重新载入界面。`
: ''}
confirmText="确认导入"
destructive
onConfirm={async () => {
if (!pendingImport) return;
await importUiConfig(pendingImport);
setPendingImport(null);
}}
/>
</div>
);
}
@@ -1126,6 +1188,7 @@ function AccountPanel() {
const { onLogout } = useAppState();
const [showChangePwd, setShowChangePwd] = useState(false);
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
const [confirmLogout, setConfirmLogout] = useState(false);
return (
<Group title="账号安全" icon={ShieldCheck} description="WebUI 仅有 admin 一个账号,密码以 scrypt 哈希持久化到 config/webui.json。">
@@ -1140,11 +1203,26 @@ function AccountPanel() {
</Button>
</SettingRow>
<SettingRow label="退出登录" hint="立即清除当前浏览器的会话令牌。">
<Button variant="ghost" size="sm" onClick={onLogout} className="text-destructive hover:text-destructive">
<Button variant="ghost" size="sm" onClick={() => setConfirmLogout(true)} className="text-destructive hover:text-destructive">
退出登录
</Button>
</SettingRow>
<ConfirmDialog
open={confirmLogout}
onOpenChange={setConfirmLogout}
title="确认退出登录?"
description="退出后将清除当前会话令牌,需要重新输入访问密码才能进入控制台。"
confirmText="退出登录"
destructive
activity={{
title: '正在退出登录',
successTitle: '已退出登录',
errorTitle: '退出登录失败',
}}
onConfirm={onLogout}
/>
<ChangePasswordDialog
open={showChangePwd}
onOpenChange={setShowChangePwd}
@@ -1173,11 +1251,36 @@ function assetHint(latest: string, platform?: string, arch?: string): string | n
// GitHub release; SnowLuma never downloads or applies anything itself.
function UpdateGroup() {
const { updateInfo, refreshUpdate, systemInfo } = useAppState();
const { runAction } = useActionFeedback();
const [checking, setChecking] = useState(false);
const onCheck = async () => {
setChecking(true);
try { await refreshUpdate(true); } finally { setChecking(false); }
try {
await runAction(
{
title: '正在检查更新',
detail: `当前版本 v${__APP_VERSION__}`,
successTitle: '更新检查完成',
successDetail: (result) => (
result?.hasUpdate && result.latest
? `发现新版本 v${result.latest}`
: '当前已是最新版本'
),
errorTitle: '更新检查失败',
resultError: (result) => {
if (!result) return '更新检查未返回结果';
if (result.error === 'disabled') return '更新检查已关闭';
return result.error || null;
},
},
() => refreshUpdate(true),
);
} catch (error) {
console.error('manual update check failed', error);
} finally {
setChecking(false);
}
};
const disabledCheck = updateInfo?.error === 'disabled';
@@ -10,6 +10,7 @@ import { AlertTriangle, KeyRound, Loader2, Music, Plus, RefreshCw, Trash2 } from
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
@@ -28,6 +29,7 @@ function isHttpUrl(value: string): boolean {
export function GlobalConfigPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [config, setConfig] = useState<GlobalSettings | null>(null);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
@@ -61,23 +63,41 @@ export function GlobalConfigPanel() {
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
* inputs from the server's normalized response (it would wipe a half-typed
* URL); a generation guard just confirms the latest save. */
const commit = (next: GlobalSettings) => {
const commit = (
next: GlobalSettings,
feedback: false | { title: string; successTitle: string } = {
title: '正在更新全局配置',
successTitle: '全局配置已更新',
},
) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.globalConfig
.save(next)
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
const save = feedback === false
? api.globalConfig.save(next)
: runAction(
{
title: feedback.title,
detail: '正在同步 config/snowluma.json',
successTitle: feedback.successTitle,
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
errorTitle: '全局配置更新失败',
},
() => api.globalConfig.save(next),
);
void save
.then(() => {
if (saveGen.current !== gen) return;
// The server drops invalid (non-http) entries; say so rather than a
// bare "已保存" next to a still-visible rejected value.
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
})
.catch(() => {
.catch((error) => {
if (saveGen.current !== gen) return;
console.error('save global config failed', error);
flash('err', '保存失败,请检查服务器日志');
});
}, 500);
@@ -104,7 +124,8 @@ export function GlobalConfigPanel() {
}
const servers = config.rkey.fallbackServers;
const setServers = (next: string[]) => commit({ ...config, rkey: { fallbackServers: next } });
const setServers = (next: string[]) =>
commit({ ...config, rkey: { fallbackServers: next } }, false);
return (
<div className="flex flex-col gap-4">
@@ -123,7 +144,11 @@ export function GlobalConfigPanel() {
<div className="flex flex-col gap-2 border-t pt-3">
<div className="flex items-center justify-between">
<Label>rkey 回退服务器</Label>
<Button variant="outline" size="sm" onClick={() => setServers([...servers, ''])}>
<Button
variant="outline"
size="sm"
onClick={() => setServers([...servers, ''])}
>
<Plus className="size-3.5" /> 添加
</Button>
</div>
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useTheme } from '@/contexts/ThemeContext';
@@ -38,6 +39,7 @@ interface DialogState {
export function NotificationsPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [config, setConfig] = useState<NotificationsConfig | null>(null);
const [loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<DialogState>({ open: false, index: null, seed: blankChannel([]) });
@@ -72,13 +74,27 @@ export function NotificationsPanel() {
/** Apply locally + debounced auto-save. A generation guard reconciles with
* the server's normalized result only if no newer edit landed meanwhile. */
const commit = (next: NotificationsConfig) => {
const commit = (
next: NotificationsConfig,
copy: { title: string; successTitle: string } = {
title: '正在更新通知配置',
successTitle: '通知配置已更新',
},
) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.notifications
.saveConfig(next)
void runAction(
{
title: copy.title,
detail: '正在同步通知渠道设置',
successTitle: copy.successTitle,
successDetail: '通知配置已同步',
errorTitle: '通知配置更新失败',
},
() => api.notifications.saveConfig(next),
)
.then((result) => {
// Only the latest save reconciles + confirms; a superseded in-flight
// save stays silent (its successor will confirm).
@@ -86,7 +102,10 @@ export function NotificationsPanel() {
setConfig(result);
flash('ok', '已保存');
})
.catch(() => flash('err', '保存失败,请检查服务器日志'));
.catch((error) => {
console.error('save notifications config failed', error);
flash('err', '保存失败,请检查服务器日志');
});
}, 350);
};
@@ -99,14 +118,26 @@ export function NotificationsPanel() {
}
const channels = config.channels;
const setChannels = (next: NotificationChannel[]) => commit({ ...config, channels: next });
const setChannels = (
next: NotificationChannel[],
copy?: { title: string; successTitle: string },
) => commit({ ...config, channels: next }, copy);
const otherIds = (index: number | null) => channels.filter((_, i) => i !== index).map((c) => c.id);
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
const submitChannel = (ch: NotificationChannel) => {
if (dialog.index == null) setChannels([...channels, ch]);
else setChannels(channels.map((c, idx) => (idx === dialog.index ? ch : c)));
if (dialog.index == null) {
setChannels(
[...channels, ch],
{ title: '正在新增通知渠道', successTitle: '通知渠道已新增' },
);
} else {
setChannels(
channels.map((c, idx) => (idx === dialog.index ? ch : c)),
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
);
}
};
const test = async (id: string) => {
@@ -117,10 +148,23 @@ export function NotificationsPanel() {
saveTimer.current = null;
}
try {
await api.notifications.saveConfig(config);
const res = await api.notifications.test(id);
const res = await runAction(
{
title: '正在测试通知渠道',
detail: id,
successTitle: '测试通知已发送',
successDetail: id,
errorTitle: '通知渠道测试失败',
resultError: (result) => result.success ? null : result.message || '测试发送失败',
},
async () => {
await api.notifications.saveConfig(config);
return api.notifications.test(id);
},
);
flash(res.success ? 'ok' : 'err', res.message ?? (res.success ? '测试发送成功' : '测试发送失败'));
} catch {
} catch (error) {
console.error('test notification channel failed', error);
flash('err', '测试请求失败');
} finally {
setTesting(null);
@@ -182,10 +226,16 @@ export function NotificationsPanel() {
key={ch.id}
channel={ch}
testing={testing === ch.id}
onToggle={(v) => setChannels(channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)))}
onToggle={(v) => setChannels(
channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)),
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
)}
onTest={() => void test(ch.id)}
onEdit={() => openEdit(i)}
onDelete={() => setChannels(channels.filter((_, idx) => idx !== i))}
onDelete={() => setChannels(
channels.filter((_, idx) => idx !== i),
{ title: '正在删除通知渠道', successTitle: '通知渠道已删除' },
)}
/>
))}
</div>
@@ -18,16 +18,9 @@ import {
type LucideIcon,
} from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge, type BadgeProps } from '@/components/ui/badge';
Badge,
type BadgeProps,
} from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
@@ -35,6 +28,7 @@ import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useApi } from '@/lib/api';
import {
@@ -53,6 +47,7 @@ import {
type LogStorageSettings,
type LogStorageSettingsField,
type StorageCleanupRequest,
type StorageCleanupResponse,
type StorageOverviewResponse,
} from '@/types';
@@ -90,6 +85,7 @@ interface PendingCleanup {
export function StoragePanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [data, setData] = useState<StorageOverviewResponse | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
@@ -159,13 +155,21 @@ export function StoragePanel() {
data.settings.envOverrides,
);
if (Object.keys(patch).length === 0) {
flash('ok', '没有需要保存的更改');
return;
}
setSaving(true);
try {
const result = await api.storage.saveSettings(patch);
const result = await runAction(
{
title: '正在更新日志策略',
detail: '正在保存并应用存储限制',
successTitle: '日志策略已更新',
successDetail: '新策略已立即生效',
errorTitle: '日志策略更新失败',
},
() => api.storage.saveSettings(patch),
);
applyOverview({
settings: result.settings,
snapshot: result.snapshot,
@@ -185,7 +189,17 @@ export function StoragePanel() {
const key = cleanupKey(request);
setOperation(key);
try {
const result = await api.storage.cleanup(request);
const result = await runAction(
{
title: '正在清理存储数据',
detail: cleanupLabel(request),
successTitle: '存储数据清理完成',
successDetail: cleanupResultSummary,
errorTitle: '存储数据清理失败',
resultError: (outcome) => outcome.success ? null : cleanupResultSummary(outcome),
},
() => api.storage.cleanup(request),
);
if (result.snapshot) {
setData((previous) => previous
? {
@@ -197,17 +211,7 @@ export function StoragePanel() {
} else {
await load();
}
const summary = [
`删除 ${result.cleanup.deletedFiles} 个文件`,
`释放 ${formatBytes(result.cleanup.freedBytes)}`,
];
if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) {
summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`);
}
if (result.cleanup.failures.length > 0) {
summary.push(`${result.cleanup.failures.length} 项失败`);
}
flash(result.success ? 'ok' : 'err', summary.join(','));
flash(result.success ? 'ok' : 'err', cleanupResultSummary(result));
return result.success;
} catch (error) {
flash('err', error instanceof Error ? error.message : '清理失败');
@@ -741,23 +745,20 @@ function AllAccountsCleanupDialog({
onOpenChange(false);
};
return (
<AlertDialog
<ConfirmDialog
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && !busy) close();
}}
>
<AlertDialogContent className="max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto p-5 sm:p-6">
<AlertDialogHeader>
<AlertDialogTitle>
清理全部账号的{category ? CATEGORY_INFO[category].label : '数据'}?
</AlertDialogTitle>
<AlertDialogDescription className="leading-relaxed">
该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入
<strong className="mx-1 text-foreground">{ALL_ACCOUNTS_CONFIRMATION}</strong>
继续。
</AlertDialogDescription>
</AlertDialogHeader>
title={`清理全部账号的${category ? CATEGORY_INFO[category].label : '数据'}?`}
description={
<>
该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入
<strong className="mx-1 text-foreground">{ALL_ACCOUNTS_CONFIRMATION}</strong>
继续。
</>
}
content={(
<div className="flex flex-col gap-1.5">
<Label htmlFor="all-account-cleanup-confirmation">确认短语</Label>
<Input
@@ -769,25 +770,16 @@ function AllAccountsCleanupDialog({
disabled={busy}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel disabled={busy} onClick={() => setConfirmation('')}>
取消
</AlertDialogCancel>
<AlertDialogAction
disabled={!isAllAccountsConfirmation(confirmation) || busy || !category}
onClick={(event) => {
event.preventDefault();
if (!category || !isAllAccountsConfirmation(confirmation)) return;
void onConfirm(category);
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
确认清理
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
confirmText="确认清理"
destructive
confirmDisabled={!isAllAccountsConfirmation(confirmation) || busy || !category}
onConfirm={async () => {
if (!category || !isAllAccountsConfirmation(confirmation)) return;
await onConfirm(category);
setConfirmation('');
}}
/>
);
}
@@ -797,6 +789,27 @@ function cleanupKey(request: StorageCleanupRequest): string {
return request.scope;
}
function cleanupLabel(request: StorageCleanupRequest): string {
if (request.scope === 'logs') return '全部日志';
if (request.scope === 'temporary') return '非活动文件传输临时数据';
const label = CATEGORY_INFO[request.category].label;
return request.scope === 'allAccounts' ? `全部账号的${label}` : `账号 ${request.uin} 的${label}`;
}
function cleanupResultSummary(result: StorageCleanupResponse): string {
const summary = [
`删除 ${result.cleanup.deletedFiles} 个文件`,
`释放 ${formatBytes(result.cleanup.freedBytes)}`,
];
if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) {
summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`);
}
if (result.cleanup.failures.length > 0) {
summary.push(`${result.cleanup.failures.length} 项失败`);
}
return summary.join(',');
}
function toneBadgeVariant(tone: StorageTone): BadgeProps['variant'] {
if (tone === 'success') return 'success';
if (tone === 'warning') return 'warning';
@@ -15,6 +15,8 @@ import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { cn } from '@/lib/utils';
@@ -22,6 +24,7 @@ import type { SystemSettingsResponse } from '@/types';
export function SystemPanel() {
const api = useApi();
const { runAction } = useActionFeedback();
const [data, setData] = useState<SystemSettingsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -41,6 +44,8 @@ export function SystemPanel() {
// backup / restore
const [exportCreds, setExportCreds] = useState(false);
const [restoreCreds, setRestoreCreds] = useState(false);
const [confirmDeleteCert, setConfirmDeleteCert] = useState(false);
const [pendingBackup, setPendingBackup] = useState<File | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const load = async (): Promise<boolean> => {
@@ -72,7 +77,16 @@ export function SystemPanel() {
}
setSaving(true);
try {
await api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled });
await runAction(
{
title: '正在更新服务设置',
detail: `${host.trim()}:${portNum}`,
successTitle: '服务设置已更新',
successDetail: '重启 SnowLuma 后生效',
errorTitle: '服务设置更新失败',
},
() => api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled }),
);
await load();
flash('ok', '已保存,重启 SnowLuma 后生效');
} catch (e) {
@@ -86,7 +100,16 @@ export function SystemPanel() {
if (!certPem.trim() || !keyPem.trim()) { flash('err', '请同时填入证书与私钥'); return; }
setSaving(true);
try {
await api.systemSettings.uploadCert(certPem, keyPem);
await runAction(
{
title: '正在更新 TLS 证书',
detail: '正在校验证书与私钥',
successTitle: 'TLS 证书已更新',
successDetail: '重启 SnowLuma 后生效',
errorTitle: 'TLS 证书更新失败',
},
() => api.systemSettings.uploadCert(certPem, keyPem),
);
setCertPem(''); setKeyPem('');
setEditingCert(false);
await load();
@@ -101,12 +124,21 @@ export function SystemPanel() {
const deleteCert = async () => {
setSaving(true);
try {
await api.systemSettings.deleteCert();
await runAction(
{
title: '正在删除 TLS 证书',
detail: '正在移除服务器上的证书与私钥',
successTitle: 'TLS 证书已删除',
errorTitle: 'TLS 证书删除失败',
},
() => api.systemSettings.deleteCert(),
);
setEditingCert(false);
await load();
flash('ok', '证书已删除');
} catch (e) {
flash('err', e instanceof Error ? e.message : '删除失败');
throw e;
} finally {
setSaving(false);
}
@@ -115,7 +147,15 @@ export function SystemPanel() {
const exportBackup = async () => {
setSaving(true);
try {
const bundle = await api.systemSettings.exportBackup(exportCreds);
const bundle = await runAction(
{
title: '正在导出配置备份',
detail: exportCreds ? '包含敏感配置' : '不包含敏感配置',
successTitle: '配置备份已导出',
errorTitle: '配置备份导出失败',
},
() => api.systemSettings.exportBackup(exportCreds),
);
const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -136,8 +176,21 @@ export function SystemPanel() {
try {
const text = await file.text();
let parsed: Record<string, unknown>;
try { parsed = JSON.parse(text); } catch { flash('err', '文件不是有效的 JSON'); return; }
const res = await api.systemSettings.importBackup(parsed, restoreCreds);
try {
parsed = JSON.parse(text);
} catch {
throw new Error('文件不是有效的 JSON');
}
const res = await runAction(
{
title: '正在恢复配置备份',
detail: file.name,
successTitle: '配置备份已恢复',
successDetail: '恢复结果已写入服务器',
errorTitle: '配置备份恢复失败',
},
() => api.systemSettings.importBackup(parsed, restoreCreds),
);
const parts = res.restored.length ? [`已恢复 ${res.restored.length} 项`] : ['没有可恢复的配置'];
if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(敏感配置,含 OneBot 配置)`);
if (res.migrated.length) parts.push(`兼容转换 ${res.migrated.length} 项`);
@@ -151,6 +204,7 @@ export function SystemPanel() {
const message = e instanceof Error ? e.message : '恢复失败';
const refreshed = await load();
flash('err', refreshed ? message : `${message};界面状态刷新失败,请手动刷新页面`);
throw e;
} finally {
setSaving(false);
if (fileRef.current) fileRef.current.value = '';
@@ -237,7 +291,7 @@ export function SystemPanel() {
<Button variant="outline" onClick={() => setEditingCert(true)} className="gap-1.5">
<Pencil className="h-4 w-4" /> 更改证书
</Button>
<Button variant="outline" onClick={deleteCert} disabled={saving} className="gap-1.5">
<Button variant="outline" onClick={() => setConfirmDeleteCert(true)} disabled={saving} className="gap-1.5">
<Trash2 className="h-4 w-4" /> 删除证书
</Button>
</div>
@@ -306,7 +360,11 @@ export function SystemPanel() {
type="file"
accept="application/json,.json"
className="hidden"
onChange={(e) => { const f = e.target.files?.[0]; if (f) void importBackup(f); }}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) setPendingBackup(file);
e.target.value = '';
}}
/>
<div>
<Button variant="outline" onClick={() => fileRef.current?.click()} disabled={saving} className="gap-1.5">
@@ -317,6 +375,36 @@ export function SystemPanel() {
</div>
</CardContent>
</Card>
<ConfirmDialog
open={confirmDeleteCert}
onOpenChange={setConfirmDeleteCert}
title="删除 TLS 证书?"
description="将移除服务器上的证书与私钥。若 HTTPS 仍处于启用状态,下次启动将无法继续使用当前证书。"
confirmText="删除证书"
destructive
onConfirm={deleteCert}
/>
<ConfirmDialog
open={pendingBackup !== null}
onOpenChange={(open) => {
if (!open) setPendingBackup(null);
}}
title="恢复配置备份?"
description={
pendingBackup
? `将从 ${pendingBackup.name} 覆盖当前系统配置${restoreCreds ? ',包括敏感配置、TLS 私钥与 OneBot 配置' : ''}。成功后需要重启 SnowLuma。`
: ''
}
confirmText="确认恢复"
destructive
onConfirm={async () => {
if (!pendingBackup) return;
await importBackup(pendingBackup);
setPendingBackup(null);
}}
/>
</motion.div>
);
}
@@ -0,0 +1,356 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from 'react';
import { CircleAlert, CircleCheck } from 'lucide-react';
import { motion } from 'motion/react';
import {
CollapsibleBanner,
type BannerState,
} from '@/components/interior/collapsible-banner';
import {
LiveActivity,
useLiveActivity,
type ActivityInput,
} from '@/components/interior/live-activity';
type ResultDetail<T> = string | ((result: T) => string | undefined);
type ErrorDetail = string | ((error: unknown) => string);
export interface ActionFeedbackOptions<T = void> extends ActivityInput {
successTitle?: string;
successDetail?: ResultDetail<T>;
errorTitle?: string;
errorDetail?: ErrorDetail;
/** Re-show a successful result after an imminent full-page reload. */
surviveReload?: boolean;
/**
* Some APIs resolve transport-successfully while reporting a failed domain
* result. Return its user-facing reason here so the activity ends in error
* without changing the caller's result/control flow.
*/
resultError?: (result: T) => string | null | undefined;
}
export interface ActionFeedbackHandle {
update: (patch: Partial<ActivityInput>) => void;
succeed: (patch?: Partial<ActivityInput>) => void;
fail: (detail: string, patch?: Partial<ActivityInput>) => void;
}
interface ActionFeedbackValue {
startAction: (input: ActivityInput) => ActionFeedbackHandle;
runAction: <T>(options: ActionFeedbackOptions<T>, action: () => Promise<T> | T) => Promise<T>;
activity: ReturnType<typeof useLiveActivity>['activity'];
notices: ActionNotice[];
removeNotice: (id: number) => void;
dismiss: () => void;
}
interface ActionNotice {
id: number;
tone: 'success' | 'error';
title: string;
detail?: string;
}
const ActionFeedbackContext = createContext<ActionFeedbackValue | null>(null);
const RESULT_NOTICE_DURATION_MS = 5_000;
const RELOAD_NOTICE_MAX_AGE_MS = 30_000;
const RELOAD_NOTICE_KEY = 'snowluma_action_feedback_reload_notice';
interface ReloadNotice extends Omit<ActionNotice, 'id'> {
createdAt: number;
}
function preserveReloadNotice(notice: Omit<ActionNotice, 'id'>): void {
try {
sessionStorage.setItem(
RELOAD_NOTICE_KEY,
JSON.stringify({ ...notice, createdAt: Date.now() } satisfies ReloadNotice),
);
} catch (error) {
console.error('preserve action feedback across reload failed', error);
}
}
function takeReloadNotice(): Omit<ActionNotice, 'id'> | null {
let raw: string | null;
try {
raw = sessionStorage.getItem(RELOAD_NOTICE_KEY);
sessionStorage.removeItem(RELOAD_NOTICE_KEY);
} catch (error) {
console.error('read action feedback after reload failed', error);
return null;
}
if (!raw) return null;
try {
const parsed = JSON.parse(raw) as Partial<ReloadNotice>;
if (
(parsed.tone !== 'success' && parsed.tone !== 'error')
|| typeof parsed.title !== 'string'
|| typeof parsed.createdAt !== 'number'
|| Date.now() - parsed.createdAt > RELOAD_NOTICE_MAX_AGE_MS
) {
throw new Error('invalid or expired reload notice');
}
return {
tone: parsed.tone,
title: parsed.title,
...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}),
};
} catch (error) {
console.error('parse action feedback after reload failed', error);
return null;
}
}
export function actionErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim()) return error.message;
if (typeof error === 'string' && error.trim()) return error;
return '未知错误';
}
function resolveResultDetail<T>(detail: ResultDetail<T> | undefined, result: T): string | undefined {
return typeof detail === 'function' ? detail(result) : detail;
}
function resolveErrorDetail(detail: ErrorDetail | undefined, error: unknown): string {
if (typeof detail === 'function') return detail(error);
return detail ?? actionErrorMessage(error);
}
export function publishActionResult(
ownsSurface: boolean,
updateCurrentActivity: () => void,
publishNotice: () => void,
): void {
if (ownsSurface) updateCurrentActivity();
publishNotice();
}
export function scheduleActionNoticeDismiss(onDismiss: () => void): () => void {
const timeout = setTimeout(onDismiss, RESULT_NOTICE_DURATION_MS);
return () => clearTimeout(timeout);
}
export function ActionFeedbackProvider({ children }: { children: ReactNode }) {
const {
activity,
start,
update,
succeed,
fail,
dismiss: dismissActivity,
} = useLiveActivity();
const activeId = useRef<string | null>(null);
const noticeId = useRef(0);
const [notices, setNotices] = useState<ActionNotice[]>([]);
const pushNotice = useCallback((notice: Omit<ActionNotice, 'id'>) => {
const next = { ...notice, id: ++noticeId.current };
setNotices((current) => [...current.slice(-2), next]);
}, []);
useEffect(() => {
const notice = takeReloadNotice();
if (notice) pushNotice(notice);
}, [pushNotice]);
const startAction = useCallback((input: ActivityInput): ActionFeedbackHandle => {
const id = start(input);
activeId.current = id;
const ownsSurface = () => activeId.current === id;
return {
update: (patch) => {
if (ownsSurface()) update(patch);
},
succeed: (patch) => {
publishActionResult(
ownsSurface(),
() => succeed(patch),
() => pushNotice({
tone: 'success',
title: patch?.title ?? input.title,
detail: patch?.detail ?? input.detail,
}),
);
},
fail: (detail, patch) => {
publishActionResult(
ownsSurface(),
() => fail({ ...patch, detail }),
() => pushNotice({
tone: 'error',
title: patch?.title ?? input.title,
detail,
}),
);
},
};
}, [start, update, succeed, fail, pushNotice]);
const runAction = useCallback(async <T,>(
options: ActionFeedbackOptions<T>,
action: () => Promise<T> | T,
): Promise<T> => {
const {
successTitle,
successDetail,
errorTitle,
errorDetail,
resultError,
surviveReload,
...input
} = options;
const handle = startAction(input);
try {
const result = await action();
const failed = resultError?.(result);
if (failed) {
handle.fail(failed, errorTitle ? { title: errorTitle } : undefined);
} else {
const detail = resolveResultDetail(successDetail, result);
if (surviveReload) {
preserveReloadNotice({
tone: 'success',
title: successTitle ?? input.title,
detail: detail ?? input.detail,
});
}
handle.succeed({
...(successTitle ? { title: successTitle } : {}),
...(detail !== undefined ? { detail } : {}),
});
}
return result;
} catch (error) {
handle.fail(resolveErrorDetail(errorDetail, error), errorTitle ? { title: errorTitle } : undefined);
throw error;
}
}, [startAction]);
const dismiss = useCallback(() => {
activeId.current = null;
dismissActivity();
}, [dismissActivity]);
const removeNotice = useCallback((id: number) => {
setNotices((current) => current.filter((notice) => notice.id !== id));
}, []);
const value = useMemo<ActionFeedbackValue>(
() => ({ startAction, runAction, activity, notices, removeNotice, dismiss }),
[startAction, runAction, activity, notices, removeNotice, dismiss],
);
return (
<ActionFeedbackContext.Provider value={value}>
{children}
</ActionFeedbackContext.Provider>
);
}
/**
* Rendered inside ThemeProvider's MotionConfig so SnowLuma's existing reduced
* motion / disable-motion preference also reaches Interior's component.
*/
export function ActionFeedbackViewport() {
const {
activity,
notices,
removeNotice,
dismiss,
} = useActionFeedback();
const runningActivity = activity?.phase === 'running' ? activity : null;
return (
<div className="pointer-events-none fixed bottom-4 right-4 z-[80] flex w-[min(360px,calc(100vw-2rem))] flex-col items-end gap-2">
{notices.map((notice) => (
<ActionNoticeBanner
key={notice.id}
notice={notice}
onRemoved={() => removeNotice(notice.id)}
/>
))}
<LiveActivity
activity={runningActivity}
onDismiss={dismiss}
dismissLabel="关闭操作反馈"
label="操作反馈"
className="w-full"
/>
</div>
);
}
function ActionNoticeBanner({
notice,
onRemoved,
}: {
notice: ActionNotice;
onRemoved: () => void;
}) {
const [state, setState] = useState<BannerState>('dismissed');
const visible = state !== 'dismissed';
useEffect(() => {
const frame = requestAnimationFrame(() => setState('open'));
return () => cancelAnimationFrame(frame);
}, []);
useEffect(() => {
if (!visible) return;
return scheduleActionNoticeDismiss(() => setState('dismissed'));
}, [visible]);
return (
<div className="pointer-events-auto relative w-full">
<CollapsibleBanner
state={state}
onStateChange={setState}
onDismissed={onRemoved}
title={notice.title}
description={notice.detail}
icon={notice.tone === 'success'
? <CircleCheck className="size-4 text-success" />
: <CircleAlert className="size-4 text-destructive" />}
dismissLabel="关闭通知"
dismissedMessage="操作通知已关闭。"
className={notice.tone === 'success'
? 'border-success/25'
: 'border-destructive/30'}
/>
{state !== 'dismissed' ? (
<div
aria-hidden="true"
data-action-feedback-countdown-track=""
className="pointer-events-none absolute inset-x-[8px] bottom-0.5 h-[3px] overflow-hidden rounded-full bg-border/45"
>
<motion.div
data-action-feedback-countdown=""
className={notice.tone === 'success'
? 'h-full w-full origin-left rounded-full bg-success shadow-[0_0_5px_color-mix(in_oklab,var(--success)_45%,transparent)]'
: 'h-full w-full origin-left rounded-full bg-destructive shadow-[0_0_5px_color-mix(in_oklab,var(--destructive)_45%,transparent)]'}
initial={{ scaleX: 1 }}
animate={{ scaleX: 0 }}
transition={{ duration: RESULT_NOTICE_DURATION_MS / 1_000, ease: 'linear' }}
/>
</div>
) : null}
</div>
);
}
export function useActionFeedback(): ActionFeedbackValue {
const value = useContext(ActionFeedbackContext);
if (!value) throw new Error('useActionFeedback must be used within ActionFeedbackProvider');
return value;
}
@@ -22,7 +22,7 @@ export interface AppStateValue {
refreshSystem: () => void;
refreshConnections: () => void;
/** Re-run the update check; `force` bypasses the server-side cache. */
refreshUpdate: (force?: boolean) => Promise<void>;
refreshUpdate: (force?: boolean) => Promise<UpdateInfo | null>;
/** Triggered from the topbar logout button. */
onLogout: () => void;
}
+32 -6
View File
@@ -1,4 +1,5 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import { defaultOverviewGrid, defaultOverviewMobile, migrateOverviewBlocks } from '@/lib/dashboard-layout';
import type { UiLayout, UiLayoutItem, UiPages } from '@/types';
@@ -104,6 +105,7 @@ const LayoutContext = createContext<LayoutContextValue | null>(null);
export function LayoutProvider({ children }: { children: ReactNode }) {
const api = useApi();
const { runAction } = useActionFeedback();
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES);
const [ready, setReady] = useState(false);
@@ -155,11 +157,15 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
useEffect(() => () => {
if (saveTimer.current) {
clearTimeout(saveTimer.current);
void api.ui.save({ layout: layoutRef.current }).catch(() => { /* best-effort */ });
void api.ui.save({ layout: layoutRef.current }).catch((error) => {
console.error('layout unmount flush failed', error);
});
}
if (pagesTimer.current) {
clearTimeout(pagesTimer.current);
void api.ui.save({ pages: pagesRef.current }).catch(() => { /* best-effort */ });
void api.ui.save({ pages: pagesRef.current }).catch((error) => {
console.error('page preferences unmount flush failed', error);
});
}
}, [api]);
@@ -170,9 +176,19 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => {
saveTimer.current = null; // mark not-pending so the unmount flush can't double-fire
void api.ui.save({ layout: next }).catch(() => { /* best-effort */ });
void runAction(
{
title: '正在更新界面布局',
detail: '正在同步仪表盘与导航布局',
successTitle: '界面布局已更新',
errorTitle: '界面布局更新失败',
},
() => api.ui.save({ layout: next }),
).catch((error) => {
console.error('persist layout failed', error);
});
}, 300);
}, [api]);
}, [api, runAction]);
const setOverviewBlocks = useCallback((items: UiLayoutItem[]) => {
persist({ ...layoutRef.current, overviewBlocks: items });
@@ -207,9 +223,19 @@ export function LayoutProvider({ children }: { children: ReactNode }) {
if (pagesTimer.current) clearTimeout(pagesTimer.current);
pagesTimer.current = setTimeout(() => {
pagesTimer.current = null;
void api.ui.save({ pages: next }).catch(() => { /* best-effort */ });
void runAction(
{
title: '正在更新页面设置',
detail: '正在同步当前页面偏好',
successTitle: '页面设置已更新',
errorTitle: '页面设置更新失败',
},
() => api.ui.save({ pages: next }),
).catch((error) => {
console.error('persist page preferences failed', error);
});
}, 300);
}, [api]);
}, [api, runAction]);
const value = useMemo<LayoutContextValue>(() => ({
overviewBlocks: layout.overviewBlocks,
+70 -35
View File
@@ -1,6 +1,7 @@
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { flushSync } from 'react-dom';
import { MotionConfig } from 'motion/react';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import type { Palette, ThemeMode, UiAppearance, UiBackground } from '@/types';
// Re-export the appearance value types so consumers (settings page etc.) can
@@ -524,15 +525,15 @@ function isSafeMode(): boolean {
async function persistAppearance(appearance: UiAppearance): Promise<void> {
const token = authToken();
if (!token) return; // pre-auth: local cache only (no settings UI exists there anyway)
try {
await fetch('/api/ui', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
// Section-level save: only `appearance`; the server preserves `layout`.
body: JSON.stringify({ appearance }),
});
} catch {
/* best-effort — the local cache already holds the change */
const response = await fetch('/api/ui', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
// Section-level save: only `appearance`; the server preserves `layout`.
body: JSON.stringify({ appearance }),
});
if (!response.ok) {
const payload = (await response.json().catch(() => ({}))) as { message?: string; error?: string };
throw new Error(payload.message || payload.error || `外观保存失败(HTTP ${response.status})`);
}
}
@@ -634,6 +635,7 @@ function getSystemTheme(): 'light' | 'dark' {
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const { runAction } = useActionFeedback();
const [appearance, setAppearanceState] = useState<UiAppearance>(readCache);
const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme);
const [ready, setReady] = useState(false);
@@ -671,7 +673,9 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
// clobber a look already set from another device.
if (legacy && server && isPristine(server)) {
next = { ...server, ...legacy, background: server.background };
void persistAppearance(next);
void persistAppearance(next).catch((error) => {
console.error('appearance migration save failed', error);
});
}
}
@@ -714,8 +718,21 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
setAppearanceState(next);
writeCache(next);
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => void persistAppearance(next), 400);
}, []);
saveTimer.current = setTimeout(() => {
void runAction(
{
title: '正在更新外观',
detail: '正在同步界面设置',
successTitle: '外观已更新',
successDetail: '界面设置已同步',
errorTitle: '外观更新失败',
},
() => persistAppearance(next),
).catch((error) => {
console.error('persist appearance failed', error);
});
}, 400);
}, [runAction]);
const setAppearance = useCallback((patch: AppearancePatch) => {
const prev = appearanceRef.current;
@@ -732,30 +749,48 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
}
}, [commit]);
const uploadBackground = useMemo(() => async (file: File) => {
const token = authToken();
if (!token) throw new Error('未登录');
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/ui/background', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form });
if (!res.ok) {
const e = (await res.json().catch(() => ({}))) as { message?: string };
throw new Error(e.message || '上传失败');
}
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
}, []);
const uploadBackground = useMemo(() => async (file: File) => runAction(
{
title: '正在上传背景',
detail: file.name,
successTitle: '背景已更新',
successDetail: file.name,
errorTitle: '背景上传失败',
},
async () => {
const token = authToken();
if (!token) throw new Error('未登录');
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/ui/background', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form });
if (!res.ok) {
const e = (await res.json().catch(() => ({}))) as { message?: string };
throw new Error(e.message || '上传失败');
}
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
},
), [runAction]);
const removeBackground = useMemo(() => async () => {
const token = authToken();
if (!token) throw new Error('未登录');
const res = await fetch('/api/ui/background', { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error('删除失败');
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
}, []);
const removeBackground = useMemo(() => async () => runAction(
{
title: '正在删除背景',
detail: '移除已上传的壁纸',
successTitle: '背景已删除',
successDetail: '已恢复为无壁纸状态',
errorTitle: '背景删除失败',
},
async () => {
const token = authToken();
if (!token) throw new Error('未登录');
const res = await fetch('/api/ui/background', { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error('删除失败');
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
},
), [runAction]);
const formatClock = useMemo(() => (input: string | number | Date) => {
const d = input instanceof Date ? input : new Date(input);
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi, type ProcessActionResult } from '@/lib/api';
export type HookProcessOpKind = 'load' | 'unload' | 'refresh';
@@ -60,6 +61,7 @@ export function useHookProcessOps(
opts: { onAfterOp?: () => Promise<void> | void } = {},
): UseHookProcessOpsResult {
const api = useApi();
const { runAction } = useActionFeedback();
const [byPid, setByPid] = useState<Map<number, HookProcessOpKind>>(() => new Map());
const [banner, setBanner] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<UnloadFailedAlert | null>(null);
@@ -107,7 +109,23 @@ export function useHookProcessOps(
const messages = KIND_MESSAGES[kind];
setBanner(messages.start(pid));
try {
const result = await action();
const result = await runAction(
{
title: messages.start(pid),
detail: `PID ${pid}`,
successTitle: messages.ok(pid),
successDetail: `PID ${pid}`,
errorTitle: `${kind === 'load' ? '加载' : kind === 'unload' ? '卸载' : '刷新'}失败`,
resultError: (outcome) => (
kind === 'unload'
&& outcome.process?.status === 'connecting'
&& outcome.process.error
? outcome.process.error
: null
),
},
action,
);
if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) {
setUnloadFailedAlert({ pid, error: result.process.error });
setBanner(`进程 ${pid} 卸载失败`);
@@ -124,7 +142,7 @@ export function useHookProcessOps(
scheduleBannerClear();
}
},
[setKind, scheduleBannerClear],
[setKind, scheduleBannerClear, runAction],
);
const load = useCallback(
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import type { OneBotConfig, QQInfo } from '@/types';
import { useApi } from '@/lib/api';
@@ -50,6 +51,7 @@ export function useOneBotInstanceConfig(
options: UseOneBotInstanceConfigOptions,
): UseOneBotInstanceConfig {
const api = useApi();
const { runAction } = useActionFeedback();
const { selectedUin, onSelectedUinChange } = options;
const [config, setConfigState] = useState<OneBotConfig | null>(null);
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
@@ -152,8 +154,35 @@ export function useOneBotInstanceConfig(
setSaveStatus('保存中...');
setSaveStatusTone('saving');
try {
const result = await api.config.save(uin, target);
const result = await runAction(
{
title: '正在保存账号配置',
detail: `账号 ${uin}`,
successTitle: '账号配置已更新',
successDetail: (saved) => (
!saved.online
? '配置已保存,将在账号下次连接时应用'
: saved.applied
? '配置已保存并完成热重载'
: '配置已保存'
),
errorTitle: '账号配置更新失败',
resultError: (saved) => {
if (!saved.saved) return saved.message || '服务器未确认配置已保存';
if (saved.online && !saved.applied) {
return `配置已保存,但热重载失败${saved.errors[0]?.message ? `:${saved.errors[0].message}` : ''}`;
}
return null;
},
},
() => api.config.save(uin, target),
);
if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) return;
if (!result.saved) {
setSaveStatus(`保存失败:${result.message || '服务器未确认配置已保存'}`);
setSaveStatusTone('error');
return;
}
setSavedSnapshot(JSON.stringify(result.config));
if (editRevisionRef.current === editRevision) {
setConfigState(result.config);
@@ -182,7 +211,7 @@ export function useOneBotInstanceConfig(
scheduleStatusClear(uin, generation);
}
}
}, [api, selectedUin, config, scheduleStatusClear]);
}, [api, selectedUin, config, scheduleStatusClear, runAction]);
return {
selectedUin,
+5 -1
View File
@@ -94,9 +94,13 @@ export function AppLayout() {
const refreshUpdate = useCallback(async (force = false) => {
try {
setUpdateInfo(await api.update.check(force));
const next = await api.update.check(force);
setUpdateInfo(next);
return next;
} catch (e) {
console.error('update-check', e);
if (force) throw e;
return null;
}
}, [api]);
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
actionErrorMessage,
publishActionResult,
scheduleActionNoticeDismiss,
} from '../src/contexts/ActionFeedbackContext';
describe('action feedback error details', () => {
it('preserves the real Error message', () => {
expect(actionErrorMessage(new Error('证书校验失败'))).toBe('证书校验失败');
});
it('preserves a non-empty string rejection', () => {
expect(actionErrorMessage('保存被拒绝')).toBe('保存被拒绝');
});
it('makes an unknown rejection observable', () => {
expect(actionErrorMessage({ code: 'E_UNKNOWN' })).toBe('未知错误');
});
});
describe('action feedback result publishing', () => {
it('publishes a superseded action result without replacing the active surface', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
publishActionResult(false, updateCurrentActivity, publishNotice);
expect(updateCurrentActivity).not.toHaveBeenCalled();
expect(publishNotice).toHaveBeenCalledOnce();
});
it('updates and publishes the current action result', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
publishActionResult(true, updateCurrentActivity, publishNotice);
expect(updateCurrentActivity).toHaveBeenCalledOnce();
expect(publishNotice).toHaveBeenCalledOnce();
});
});
describe('action feedback auto-dismiss', () => {
afterEach(() => {
vi.useRealTimers();
});
it('dismisses a completed notice after its visible countdown', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
scheduleActionNoticeDismiss(dismiss);
vi.advanceTimersByTime(4_999);
expect(dismiss).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(dismiss).toHaveBeenCalledOnce();
});
it('cancels dismissal when the notice unmounts early', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
const cancel = scheduleActionNoticeDismiss(dismiss);
cancel();
vi.runAllTimers();
expect(dismiss).not.toHaveBeenCalled();
});
});