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

@@ -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>
);
}