feat: add settings page and theme toggle component

- Implemented a new SettingsPage component for user preferences including appearance, behavior, and account security settings.
- Added a ThemeToggle component to switch between light, dark, and system modes.
- Created reusable UI components: AlertDialog, Avatar, Badge, Button, Card, Dialog, Input, Label, Progress, ScrollArea, Separator, Sheet, Skeleton, Tooltip.
- Introduced utility functions for class name merging and formatting bytes/uptime.
- Added a custom hook for media query handling
This commit is contained in:
DrSmoothl committed 2026-05-05 00:39:52 +08:00
1 parent f52a84d53f
commit 1426d7adb2
65 files changed
+4687 -4530

No files matched your search

@@ -0,0 +1,69 @@
import { useState, type ReactNode } from 'react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';
interface ConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description?: ReactNode;
confirmText?: string;
cancelText?: string;
destructive?: boolean;
onConfirm: () => void | Promise<void>;
}
export function ConfirmDialog({
open,
onOpenChange,
title,
description,
confirmText = '确认',
cancelText = '取消',
destructive = false,
onConfirm,
}: ConfirmDialogProps) {
const [busy, setBusy] = useState(false);
const handleConfirm = async () => {
setBusy(true);
try {
await onConfirm();
onOpenChange(false);
} finally {
setBusy(false);
}
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={busy}>{cancelText}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
void handleConfirm();
}}
className={cn(destructive && buttonVariants({ variant: 'destructive' }))}
disabled={busy}
>
{busy ? '处理中…' : confirmText}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -1,251 +0,0 @@
import type { ReactNode } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Activity, LayoutDashboard, Settings, Sparkles, Terminal } from 'lucide-react';
import { Sidebar } from './Sidebar';
import { useTheme } from '../../contexts/ThemeContext';
type Page = '总览' | '配置' | '日志';
interface MainLayoutProps {
activePage: Page;
onNavigate: (page: Page) => void;
status: string;
onLogout: () => void;
children: ReactNode;
}
const pageMeta: Record<Page, { title: string; subtitle: string; badge: string; icon: typeof LayoutDashboard }> = {
'总览': { title: '总览', subtitle: '查看当前接入的 QQ 账号及服务运行状态', badge: '控制台视图', icon: LayoutDashboard },
'配置': { title: '节点配置', subtitle: '管理 OneBot 协议端点与通信参数', badge: '协议编排', icon: Settings },
'日志': { title: '日志', subtitle: '查看后端运行日志与实时事件流', badge: 'SSE 实时流', icon: Terminal },
};
export function MainLayout({ activePage, onNavigate, status, onLogout, children }: MainLayoutProps) {
const meta = pageMeta[activePage];
const { resolved } = useTheme();
const dark = resolved === 'dark';
const PageIcon = meta.icon;
const runtimeLabel = status === '已连接' ? '运行中' : status;
return (
<div className="h-screen w-screen flex overflow-hidden font-(--font-sans)" style={{ background: 'var(--bg-body)' }}>
{/* Full-screen ambient gradient — matches login page */}
<div
className="pointer-events-none fixed inset-0"
style={{
background: dark
? 'linear-gradient(135deg, rgba(8,11,18,1) 0%, rgba(10,16,27,1) 42%, rgba(7,10,17,1) 100%)'
: 'linear-gradient(135deg, #f8fbff 0%, #eef6ff 45%, #f9fafc 100%)',
}}
/>
{/* Animated orbs */}
<div className="pointer-events-none fixed inset-0 overflow-hidden">
<motion.div
className="absolute -left-24 -top-24 h-[60vh] w-[60vh] rounded-full"
style={{
background: dark
? 'radial-gradient(circle, rgba(56,189,248,0.12) 0%, transparent 68%)'
: 'radial-gradient(circle, rgba(56,189,248,0.18) 0%, transparent 70%)',
filter: 'blur(42px)',
}}
animate={{ scale: [1, 1.08, 1] }}
transition={{ duration: 10, ease: 'easeInOut', repeat: Infinity }}
/>
<motion.div
className="absolute -right-16 -bottom-32 h-[50vh] w-[50vh] rounded-full"
style={{
background: dark
? 'radial-gradient(circle, rgba(129,140,248,0.10) 0%, transparent 68%)'
: 'radial-gradient(circle, rgba(129,140,248,0.14) 0%, transparent 70%)',
filter: 'blur(52px)',
}}
animate={{ scale: [1, 1.12, 1] }}
transition={{ duration: 12, ease: 'easeInOut', repeat: Infinity, delay: 0.8 }}
/>
</div>
{/* Sidebar */}
<Sidebar activePage={activePage} onNavigate={onNavigate} status={status} onLogout={onLogout} />
{/* Main content */}
<div className="flex-1 flex flex-col min-h-0 p-3 pl-0 z-10 relative">
<main
className="flex-1 overflow-y-auto rounded-2xl relative"
style={{
background: dark
? 'linear-gradient(135deg, rgba(8,13,22,0.72), rgba(14,20,32,0.82))'
: 'linear-gradient(135deg, rgba(255,255,255,0.68), rgba(255,255,255,0.85))',
border: '1px solid var(--glass-border)',
backdropFilter: 'blur(38px) saturate(1.35)',
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
boxShadow: dark
? '0 24px 80px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.05)'
: '0 20px 60px rgba(15,23,42,0.08), inset 0 1px 0 rgba(255,255,255,0.7)',
}}
>
{/* Top highlight */}
<div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/8 to-transparent rounded-t-2xl" />
{/* Grid texture overlay */}
<div
className="pointer-events-none absolute inset-0 rounded-2xl"
style={{
backgroundImage: dark
? 'linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px)'
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
backgroundSize: '36px 36px',
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.35), transparent 60%)',
}}
/>
{/* Accent glow in corner */}
<motion.div
className="pointer-events-none absolute right-[12%] top-[8%] h-32 w-32 rounded-full"
style={{
background: 'radial-gradient(circle, rgba(56,189,248,0.18), transparent 68%)',
filter: 'blur(20px)',
}}
animate={{ scale: [1, 1.15, 1], opacity: [0.6, 1, 0.6] }}
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
/>
<div className="relative w-full min-h-full px-4 py-4 sm:px-6 sm:py-6 xl:px-8 2xl:px-10 flex flex-col">
{/* Page header */}
<AnimatePresence mode="wait">
<motion.header
key={meta.title + '_header'}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.25 }}
className="mb-6"
>
<div
className="relative overflow-hidden rounded-[1.75rem] border px-4 py-4 sm:px-5 sm:py-5 xl:px-6"
style={{
background: dark
? 'linear-gradient(135deg, rgba(8,12,20,0.48), rgba(14,20,32,0.62))'
: 'linear-gradient(135deg, rgba(255,255,255,0.5), rgba(255,255,255,0.72))',
borderColor: 'var(--glass-border)',
boxShadow: dark
? '0 18px 48px rgba(0,0,0,0.26), inset 0 1px 0 rgba(255,255,255,0.04)'
: '0 14px 40px rgba(15,23,42,0.05), inset 0 1px 0 rgba(255,255,255,0.5)',
}}
>
<div
className="pointer-events-none absolute inset-0"
style={{
backgroundImage: dark
? 'linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px)'
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
backgroundSize: '34px 34px',
maskImage: 'linear-gradient(90deg, rgba(0,0,0,0.45), transparent 85%)',
}}
/>
<motion.div
className="pointer-events-none absolute -right-8 -top-10 h-28 w-28 rounded-full"
style={{
background: 'radial-gradient(circle, rgba(56,189,248,0.16), transparent 68%)',
filter: 'blur(18px)',
}}
animate={{ scale: [1, 1.12, 1], opacity: [0.45, 0.78, 0.45] }}
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
/>
<div className="relative flex items-center justify-between gap-6">
<div className="flex min-w-0 items-center gap-4">
{/* Icon */}
<div
className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border"
style={{
borderColor: 'color-mix(in srgb, var(--accent) 26%, transparent)',
background: dark
? 'linear-gradient(135deg, rgba(56,189,248,0.16), rgba(129,140,248,0.14))'
: 'linear-gradient(135deg, rgba(56,189,248,0.16), rgba(129,140,248,0.12))',
boxShadow: '0 8px 22px color-mix(in srgb, var(--accent) 16%, transparent)',
}}
>
<PageIcon size={20} strokeWidth={2.2} style={{ color: 'var(--accent)' }} />
</div>
{/* Title block */}
<div className="min-w-0">
<div className="flex items-center gap-2.5 flex-wrap">
<h1 className="text-xl font-bold tracking-[-0.03em]" style={{ color: 'var(--text-primary)' }}>
{meta.title}
</h1>
<span
className="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium"
style={{
color: 'var(--accent)',
background: 'var(--accent-subtle)',
border: '1px solid color-mix(in srgb, var(--accent) 22%, transparent)',
}}
>
<Sparkles size={10} className="mr-1" />
{meta.badge}
</span>
</div>
<p className="mt-0.5 text-sm" style={{ color: 'var(--text-secondary)' }}>
{meta.subtitle}
</p>
</div>
</div>
<motion.div
whileHover={{ y: -1.5 }}
className="hidden sm:flex shrink-0 overflow-hidden rounded-2xl border px-4 py-3 items-center gap-3"
style={{
borderColor: dark ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.82)',
background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.52)',
backdropFilter: 'blur(18px)',
WebkitBackdropFilter: 'blur(18px)',
}}
>
<Activity size={14} style={{ color: 'var(--accent)', flexShrink: 0 }} />
<div>
<div className="text-[11px] font-semibold uppercase tracking-widest mb-0.5" style={{ color: 'var(--text-tertiary)' }}>运行状态</div>
<div className="text-sm font-semibold" style={{ color: 'var(--accent)' }}>{runtimeLabel}</div>
</div>
</motion.div>
</div>
</div>
</motion.header>
</AnimatePresence>
{/* Page content */}
<div className="flex-1 flex flex-col">
<AnimatePresence mode="wait">
<motion.div
key={activePage}
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -12 }}
transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
className="flex-1"
>
{children}
</motion.div>
</AnimatePresence>
<motion.footer
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.08 }}
className="mt-8 flex items-center justify-center border-t pt-5 text-[11px] tracking-wide"
style={{
color: 'var(--text-tertiary)',
borderColor: 'var(--border-subtle)',
}}
>
&copy; {new Date().getFullYear()} SnowLuma. All rights reserved.
</motion.footer>
</div>
</div>
</main>
</div>
</div>
);
}
+77 -179
View File
@@ -1,193 +1,91 @@
import { LayoutDashboard, Settings, LogOut, Sun, Moon, Monitor, Terminal } from 'lucide-react';
import { Avatar } from '@heroui/react';
import { StatusBadge } from '../ui/StatusBadge';
import { motion } from 'framer-motion';
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion } from 'motion/react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
type Page = '总览' | '配置' | '日志';
export type Page = 'overview' | 'config' | 'logs' | 'settings';
export const NAV_ITEMS: { page: Page; label: string; icon: typeof LayoutDashboard; description: string }[] = [
{ page: 'overview', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
{ page: 'config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
{ page: 'logs', label: '日志', icon: Terminal, description: '实时事件流' },
{ page: 'settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
];
interface SidebarProps {
activePage: Page;
active: Page;
onNavigate: (page: Page) => void;
status: string;
onLogout: () => void;
collapsed?: boolean;
onItemClick?: () => void;
}
const navItems: { page: Page; label: string; icon: typeof LayoutDashboard }[] = [
{ page: '总览', label: '总览', icon: LayoutDashboard },
{ page: '配置', label: '配置', icon: Settings },
{ page: '日志', label: '日志', icon: Terminal },
];
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
{ mode: 'system', icon: Monitor, label: '跟随系统' },
{ mode: 'light', icon: Sun, label: '浅色' },
{ mode: 'dark', icon: Moon, label: '深色' },
];
export function Sidebar({ activePage, onNavigate, status, onLogout }: SidebarProps) {
const { resolved, mode, setMode } = useTheme();
const dark = resolved === 'dark';
export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: SidebarProps) {
return (
<aside
className="w-55 shrink-0 flex flex-col z-40 m-3 rounded-2xl overflow-hidden relative"
style={{
background: dark
? 'linear-gradient(135deg, rgba(8,13,22,0.78), rgba(14,20,32,0.88))'
: 'linear-gradient(135deg, rgba(255,255,255,0.72), rgba(255,255,255,0.9))',
border: '1px solid var(--glass-border)',
backdropFilter: 'blur(38px) saturate(1.35)',
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
boxShadow: dark
? '0 24px 80px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.05)'
: '0 20px 60px rgba(15,23,42,0.08), inset 0 1px 0 rgba(255,255,255,0.7)',
}}
>
{/* Top highlight */}
<div className="absolute inset-x-0 top-0 h-px bg-linear-to-r from-transparent via-white/8 to-transparent" />
{/* Grid texture overlay */}
<div
className="pointer-events-none absolute inset-0"
style={{
backgroundImage: dark
? 'linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px)'
: 'linear-gradient(90deg, rgba(15,23,42,0.03) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.03) 1px, transparent 1px)',
backgroundSize: '36px 36px',
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.3), transparent 70%)',
}}
/>
{/* Accent glow at top-left */}
<motion.div
className="pointer-events-none absolute -left-6 -top-6 h-24 w-24 rounded-full"
style={{
background: 'radial-gradient(circle, rgba(56,189,248,0.2), transparent 68%)',
filter: 'blur(14px)',
}}
animate={{ scale: [1, 1.15, 1], opacity: [0.5, 0.8, 0.5] }}
transition={{ duration: 7, ease: 'easeInOut', repeat: Infinity }}
/>
{/* Logo */}
<div className="relative h-16 px-5 flex items-center gap-2" style={{ borderBottom: '1px solid var(--border-subtle)' }}>
<div className="relative shrink-0">
<div
className="absolute -inset-1.5 rounded-full blur-lg"
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.2), rgba(129,140,248,0.18))' }}
/>
<div
className="relative rounded-full border p-0.5"
style={{
borderColor: 'var(--glass-border)',
background: dark ? 'rgba(8,12,19,0.7)' : 'rgba(255,255,255,0.8)',
}}
>
<Avatar
className="rounded-full"
style={{ width: 32, height: 32, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 }}
>
<Avatar.Image src="/logo.png" alt="SnowLuma" className="object-cover" />
<Avatar.Fallback>SL</Avatar.Fallback>
</Avatar>
</div>
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
{/* Brand */}
<div className={cn('flex h-16 items-center gap-3 border-b px-4', collapsed && 'justify-center px-2')}>
<div className="relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-primary/10 ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-7 object-contain" />
</div>
<span className="text-sm font-bold tracking-tight" style={{ color: 'var(--text-primary)' }}>
SnowLuma
</span>
{!collapsed && (
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-1.5">
<span className="text-sm font-bold tracking-tight">{APP_NAME}</span>
<span className="text-[10px] font-medium text-muted-foreground tabular-nums">v{APP_VERSION}</span>
</div>
<span className="text-[10px] text-muted-foreground">OneBot v11 控制台</span>
</div>
)}
</div>
{/* Navigation */}
<nav className="flex-1 px-3 pt-4 flex flex-col gap-1.5">
{navItems.map(({ page, label, icon: Icon }) => {
const isActive = activePage === page;
return (
<motion.button
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
key={page}
onClick={() => onNavigate(page)}
className="flex items-center gap-2.5 h-9 px-3 rounded-xl text-sm font-medium cursor-pointer relative overflow-hidden"
style={{
color: isActive ? 'var(--accent)' : 'var(--text-secondary)',
background: isActive ? 'var(--accent-subtle)' : 'transparent',
transition: 'var(--transition-fast)',
}}
onMouseEnter={e => { if (!isActive) (e.currentTarget.style.background = 'var(--bg-hover)'); }}
onMouseLeave={e => { if (!isActive) (e.currentTarget.style.background = 'transparent'); }}
>
{isActive && (
<motion.div
layoutId="sidebarActive"
className="absolute inset-0 rounded-xl"
style={{
background: 'var(--accent-subtle)',
border: '1px solid color-mix(in srgb, var(--accent) 24%, transparent)',
boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06)',
}}
initial={false}
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
/>
)}
<Icon
size={16}
strokeWidth={isActive ? 2.2 : 1.8}
className="relative z-10 shrink-0"
style={{ color: isActive ? 'var(--accent)' : undefined }}
/>
<span className="relative z-10">{label}</span>
</motion.button>
);
})}
</nav>
{/* Nav */}
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{NAV_ITEMS.map(({ page, label, icon: Icon, description }) => {
const isActive = active === page;
return (
<button
key={page}
type="button"
title={collapsed ? label : undefined}
onClick={() => {
onNavigate(page);
onItemClick?.();
}}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground'
)}
>
{isActive && (
<motion.span
layoutId="sidebar-active-pill"
className="absolute inset-0 rounded-lg bg-sidebar-accent ring-1 ring-primary/20"
transition={{ type: 'spring', stiffness: 380, damping: 32 }}
/>
)}
<Icon className={cn('relative z-10 size-4 shrink-0', isActive && 'text-primary')} />
{!collapsed && (
<span className="relative z-10 flex min-w-0 flex-1 flex-col items-start">
<span className="truncate leading-tight">{label}</span>
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</button>
);
})}
</nav>
</ScrollArea>
{/* Bottom */}
<div className="relative p-3 flex flex-col gap-2" style={{ borderTop: '1px solid var(--border-subtle)' }}>
<div className="flex items-center justify-between px-1">
<StatusBadge status={status} />
<div className="flex items-center gap-0.5">
{THEME_OPTIONS.map(({ mode: m, icon: Icon, label }) => {
const active = mode === m;
return (
<button
key={m}
title={label}
onClick={() => setMode(m)}
className="relative flex size-7 cursor-pointer items-center justify-center rounded-lg transition-colors duration-200"
style={{ color: active ? 'var(--accent)' : 'var(--text-tertiary)' }}
>
{active && (
<motion.div
layoutId="sidebar-theme-pill"
className="absolute inset-0 rounded-lg"
style={{ background: 'var(--accent-subtle)' }}
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
/>
)}
<Icon size={13} className="relative z-10" />
</button>
);
})}
</div>
</div>
<motion.button
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
onClick={onLogout}
className="flex items-center justify-center gap-2 h-8 rounded-lg text-xs font-medium cursor-pointer"
style={{
color: 'var(--text-tertiary)',
border: '1px solid var(--border-subtle)',
transition: 'var(--transition-fast)',
}}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.borderColor = 'rgba(248,113,113,0.2)'; e.currentTarget.style.background = 'rgba(248,113,113,0.06)'; }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-tertiary)'; e.currentTarget.style.borderColor = 'var(--border-subtle)'; e.currentTarget.style.background = 'transparent'; }}
>
<LogOut size={13} strokeWidth={2} />
登出
</motion.button>
<Separator />
<div className={cn('px-4 py-3 text-[10px] text-muted-foreground', collapsed && 'text-center px-2')}>
{collapsed ? '©' : `© ${new Date().getFullYear()} SnowLuma`}
</div>
</aside>
</div>
);
}
@@ -1,27 +0,0 @@
import { Moon, Sun } from 'lucide-react';
import { useTheme } from '../../contexts/ThemeContext';
interface TopBarProps {
title: string;
subtitle?: string;
}
export function TopBar({ title, subtitle }: TopBarProps) {
const { resolved, mode, setMode } = useTheme();
const cycleTheme = () => setMode(mode === 'system' ? 'light' : mode === 'light' ? 'dark' : 'system');
return (
<header className="h-14 shrink-0 flex items-center justify-between px-6 border-b border-zinc-200/60 dark:border-white/6 bg-white/60 dark:bg-zinc-900/60 backdrop-blur-xl">
<div>
<h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 tracking-tight">{title}</h1>
{subtitle && <p className="text-xs text-zinc-400 dark:text-zinc-500 mt-0.5">{subtitle}</p>}
</div>
<button
onClick={cycleTheme}
className="size-8 flex items-center justify-center rounded-lg text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-white/8 transition-all duration-150 cursor-pointer"
>
{resolved === 'light' ? <Moon size={16} /> : <Sun size={16} />}
</button>
</header>
);
}
@@ -0,0 +1,88 @@
import { useEffect, useState, type ReactNode } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { Sheet, SheetContent } from '@/components/ui/sheet';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sidebar, type Page } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query';
import { cn } from '@/lib/utils';
interface MainLayoutProps {
active: Page;
onNavigate: (page: Page) => void;
status: string;
onLogout: () => void;
children: ReactNode;
}
export function MainLayout({ active, onNavigate, status, onLogout, children }: MainLayoutProps) {
const isMobile = !useMediaQuery('(min-width: 768px)');
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
});
const [mobileOpen, setMobileOpen] = useState(false);
useEffect(() => {
localStorage.setItem('snowluma_sidebar_collapsed', collapsed ? '1' : '0');
}, [collapsed]);
return (
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
{/* Desktop sidebar */}
{!isMobile && (
<motion.aside
initial={false}
animate={{ width: collapsed ? 64 : 248 }}
transition={{ type: 'spring', stiffness: 280, damping: 32 }}
className="relative h-full shrink-0 border-r overflow-hidden"
>
<Sidebar active={active} onNavigate={onNavigate} collapsed={collapsed} />
</motion.aside>
)}
{/* Mobile sidebar in sheet */}
{isMobile && (
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
<Sidebar
active={active}
onNavigate={onNavigate}
onItemClick={() => setMobileOpen(false)}
/>
</SheetContent>
</Sheet>
)}
{/* Main column */}
<div className="flex min-w-0 flex-1 flex-col">
<TopBar
active={active}
status={status}
collapsed={collapsed}
onToggleCollapse={() => setCollapsed((v) => !v)}
onOpenMobile={() => setMobileOpen(true)}
onLogout={onLogout}
isMobile={isMobile}
/>
<main className={cn('flex min-h-0 flex-1 flex-col')}>
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
<AnimatePresence mode="wait">
<motion.div
key={active}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
transition={{ duration: 0.22, ease: [0.16, 1, 0.3, 1] }}
>
{children}
</motion.div>
</AnimatePresence>
</div>
</ScrollArea>
</main>
</div>
</div>
);
}
@@ -0,0 +1,108 @@
import { useState } from 'react';
import { LogOut, Menu, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ThemeToggle } from '@/components/theme-toggle';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import { NAV_ITEMS } from '@/components/layout/sidebar';
interface TopBarProps {
active: Page;
status: string;
collapsed: boolean;
onToggleCollapse: () => void;
onOpenMobile: () => void;
onLogout: () => void;
isMobile: boolean;
}
export function TopBar({
active,
status,
collapsed,
onToggleCollapse,
onOpenMobile,
onLogout,
isMobile,
}: TopBarProps) {
const [confirmLogout, setConfirmLogout] = useState(false);
const meta = NAV_ITEMS.find((n) => n.page === active);
const PageIcon = meta?.icon;
const online = status === '已连接';
return (
<header className="sticky top-0 z-30 flex h-16 shrink-0 items-center gap-2 border-b bg-background/55 px-3 backdrop-blur-xl backdrop-saturate-150 supports-[backdrop-filter]:bg-background/45 sm:px-4">
{/* Collapse toggle (desktop) / menu (mobile) */}
{isMobile ? (
<Button variant="ghost" size="icon-sm" onClick={onOpenMobile} aria-label="打开菜单">
<Menu className="size-4" />
</Button>
) : (
<Button
variant="ghost"
size="icon-sm"
onClick={onToggleCollapse}
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
>
{collapsed ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />}
</Button>
)}
<div className="mx-1 h-6 w-px bg-border" />
{/* Page title */}
<AnimatePresence mode="wait">
<motion.div
key={active}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 8 }}
transition={{ duration: 0.18 }}
className="flex min-w-0 items-center gap-2"
>
{PageIcon && <PageIcon className="size-4 text-primary" />}
<h1 className="truncate text-sm font-semibold tracking-tight">{meta?.label}</h1>
<span className="hidden sm:inline truncate text-xs text-muted-foreground">{meta?.description}</span>
</motion.div>
</AnimatePresence>
<div className="ml-auto flex items-center gap-2">
<Badge
variant={online ? 'success' : 'destructive'}
className="hidden sm:inline-flex gap-1.5"
>
<span
className={`size-1.5 rounded-full ${online ? 'bg-success' : 'bg-destructive'} ${online ? 'animate-pulse' : ''}`}
/>
{status}
</Badge>
<ThemeToggle />
<Button
variant="ghost"
size="icon-sm"
onClick={() => setConfirmLogout(true)}
aria-label="登出"
title="登出"
className="text-muted-foreground hover:text-destructive"
>
<LogOut className="size-4" />
</Button>
</div>
<ConfirmDialog
open={confirmLogout}
onOpenChange={setConfirmLogout}
title="确认登出?"
description="登出后将清除当前会话令牌,您需要重新输入访问密码才能进入控制台。"
confirmText="登出"
destructive
onConfirm={onLogout}
/>
</header>
);
}
@@ -1,214 +0,0 @@
import { MousePointerClick } from 'lucide-react';
import { motion } from 'framer-motion';
import { SectionCard } from '../ui/SectionCard';
import { EndpointRow } from '../ui/EndpointRow';
import { FieldInput } from '../ui/FieldInput';
import { useTheme } from '../../contexts/ThemeContext';
import type { QQInfo, OneBotConfig } from '../../types';
interface ConfigPageProps {
qqList: QQInfo[];
selectedUin: string | null;
config: OneBotConfig | null;
saveStatus: string;
onSelectAccount: (uin: string) => void;
onSave: () => void;
onConfigChange: (config: OneBotConfig) => void;
}
function qqAvatarUrl(uin: string): string {
return `/avatar/${encodeURIComponent(uin)}`;
}
export function ConfigPage({
qqList, selectedUin, config, saveStatus,
onSelectAccount, onSave, onConfigChange,
}: ConfigPageProps) {
const { resolved } = useTheme();
const dark = resolved === 'dark';
return (
<div className="flex flex-col gap-4 xl:flex-row xl:items-start">
{/* Account list panel */}
<div className="w-full shrink-0 xl:sticky xl:top-0 xl:w-60 2xl:w-64">
<div
className="rounded-xl overflow-hidden"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: dark
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
}}
>
<div className="px-4 pt-4 pb-2">
<span className="text-[11px] font-semibold uppercase tracking-widest" style={{ color: 'var(--text-secondary)' }}>
在线连接
</span>
</div>
<div className="px-2 pb-3 flex flex-col gap-0.5 sm:grid sm:grid-cols-2 sm:gap-1.5 xl:flex">
{qqList.length === 0 ? (
<p className="text-xs text-center py-6" style={{ color: 'var(--text-tertiary)' }}>暂无在线会话</p>
) : qqList.map(q => {
const isActive = selectedUin === q.uin;
return (
<motion.button
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
key={q.uin}
onClick={() => onSelectAccount(q.uin)}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-left cursor-pointer"
style={{
background: isActive ? 'var(--accent-subtle)' : 'transparent',
transition: 'var(--transition-fast)',
}}
>
<div
className="size-7 rounded-md flex items-center justify-center text-white text-[11px] font-bold shrink-0 overflow-hidden"
style={{
background: isActive
? 'linear-gradient(135deg, var(--accent), #818cf8)'
: 'var(--bg-input)',
color: isActive ? '#fff' : 'var(--text-secondary)',
}}
>
<img
src={qqAvatarUrl(q.uin)}
alt={q.nickname || q.uin}
className="size-full object-cover"
referrerPolicy="no-referrer"
/>
</div>
<div className="min-w-0 flex-1">
<div
className="text-sm font-medium truncate"
style={{ color: isActive ? 'var(--accent)' : 'var(--text-primary)' }}
>
{q.nickname}
</div>
<div
className="text-[11px] truncate"
style={{ color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
>
{q.uin}
</div>
</div>
</motion.button>
);
})}
</div>
</div>
</div>
{/* Editor panel */}
<div className="flex-1 min-w-0">
{!selectedUin ? (
<div className="flex flex-col items-center justify-center h-64 gap-3">
<MousePointerClick size={28} strokeWidth={1.2} style={{ color: 'var(--text-tertiary)', opacity: 0.5 }} />
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>在左栏选择会话以配置通信节点</p>
</div>
) : !config ? (
<div className="space-y-4 animate-pulse">
<div className="h-8 rounded-lg w-48" style={{ background: 'var(--bg-card)' }} />
<div className="h-32 rounded-xl" style={{ background: 'var(--bg-card)' }} />
<div className="h-32 rounded-xl" style={{ background: 'var(--bg-card)' }} />
</div>
) : (
<div className="space-y-4">
{/* Header */}
<div className="flex items-start justify-between">
<div>
<h2 className="text-base font-semibold tracking-tight" style={{ color: 'var(--text-primary)' }}>
OneBot 协议端点
</h2>
<code
className="text-xs mt-1 block"
style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
>
UIN {selectedUin}
</code>
</div>
<div className="flex items-center gap-2.5">
{saveStatus && (
<span
className="text-xs font-medium px-2.5 py-1 rounded-full"
style={{
color: saveStatus === '保存成功' ? 'var(--color-success)' : saveStatus === '保存中...' ? 'var(--text-secondary)' : 'var(--color-danger)',
background: saveStatus === '保存成功' ? 'rgba(52,211,153,0.1)' : saveStatus === '保存中...' ? 'var(--bg-card)' : 'rgba(248,113,113,0.1)',
border: `1px solid ${saveStatus === '保存成功' ? 'rgba(52,211,153,0.2)' : saveStatus === '保存中...' ? 'var(--border-subtle)' : 'rgba(248,113,113,0.2)'}`,
}}
>
{saveStatus}
</span>
)}
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onSave}
className="h-8 px-4 rounded-lg text-white text-xs font-medium cursor-pointer"
style={{
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
boxShadow: '0 2px 12px var(--accent-glow)',
transition: 'var(--transition-fast)',
}}
>
保存设定
</motion.button>
</div>
</div>
{/* HTTP Servers */}
<SectionCard title="HTTP 服务监听" onAdd={() => { const c = { ...config }; c.httpServers = [...c.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}>
{config.httpServers.length === 0 ? null : config.httpServers.map((s, idx) => (
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.httpServers = c.httpServers.filter((_, i) => i !== idx); onConfigChange(c); }}>
<FieldInput label="端口" value={s.port} isNum flex="w-28" onChange={v => { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} />
<FieldInput label="授权 Token" placeholder="不填则无密码" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.httpServers = c.httpServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
</EndpointRow>
))}
</SectionCard>
{/* HTTP Post */}
<SectionCard title="HTTP Post 推送端点" onAdd={() => { const c = { ...config }; c.httpPostEndpoints = [...c.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }]; onConfigChange(c); }}>
{config.httpPostEndpoints.length === 0 ? null : config.httpPostEndpoints.map((s, idx) => (
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.filter((_, i) => i !== idx); onConfigChange(c); }}>
<FieldInput label="目标 URL" placeholder="http://..." grow value={s.url || ''} onChange={v => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} />
<FieldInput label="授权 Token" placeholder="可选" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.httpPostEndpoints = c.httpPostEndpoints.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
</EndpointRow>
))}
</SectionCard>
{/* WS Servers */}
<SectionCard title="WebSocket 服务监听" onAdd={() => { const c = { ...config }; c.wsServers = [...c.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }]; onConfigChange(c); }}>
{config.wsServers.length === 0 ? null : config.wsServers.map((s, idx) => (
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.wsServers = c.wsServers.filter((_, i) => i !== idx); onConfigChange(c); }}>
<FieldInput label="端口" value={s.port} isNum flex="w-28" onChange={v => { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, port: v as number } : item); onConfigChange(c); }} />
<FieldInput label="授权 Token" placeholder="不填则无密码" value={s.accessToken || ''} onChange={v => { const c = { ...config }; c.wsServers = c.wsServers.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
</EndpointRow>
))}
</SectionCard>
{/* WS Clients */}
<SectionCard title="WebSocket 客户端(反向连出)" onAdd={() => { const c = { ...config }; c.wsClients = [...c.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }]; onConfigChange(c); }}>
{config.wsClients.length === 0 ? null : config.wsClients.map((c2, idx) => (
<EndpointRow key={idx} onRemove={() => { const c = { ...config }; c.wsClients = c.wsClients.filter((_, i) => i !== idx); onConfigChange(c); }}>
<FieldInput label="目标 URL" placeholder="ws://..." grow value={c2.url || ''} onChange={v => { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, url: v as string } : item); onConfigChange(c); }} />
<FieldInput label="授权 Token" placeholder="可选" value={c2.accessToken || ''} onChange={v => { const c = { ...config }; c.wsClients = c.wsClients.map((item, i) => i === idx ? { ...item, accessToken: v as string } : item); onConfigChange(c); }} />
</EndpointRow>
))}
</SectionCard>
{/* Music Sign URL */}
<SectionCard title="音乐签名 URL" onAdd={() => {}}>
<div className="px-5 py-4">
<FieldInput label="签名服务地址" placeholder="留空则不启用" value={config.musicSignUrl || ''} onChange={v => onConfigChange({ ...config, musicSignUrl: (v as string) || undefined })} />
</div>
</SectionCard>
</div>
)}
</div>
</div>
);
}
@@ -1,473 +0,0 @@
import { useState, useMemo, useRef, useCallback } from 'react';
import { Avatar } from '@heroui/react';
import { Sun, Moon, Monitor, Eye, EyeOff, ArrowRight, KeyRound } from 'lucide-react';
import { motion, AnimatePresence, useMotionValue, useSpring, useTransform } from 'framer-motion';
import { useTheme, type ThemeMode } from '../../contexts/ThemeContext';
interface LoginPageProps {
onLogin: (password: string) => Promise<{ success: boolean; error?: string }>;
}
const THEME_OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
{ mode: 'system', icon: Monitor, label: '跟随系统' },
{ mode: 'light', icon: Sun, label: '浅色' },
{ mode: 'dark', icon: Moon, label: '深色' },
];
const SPARKLES = Array.from({ length: 12 }, (_, i) => ({
id: i,
x: (i * 31 + 9) % 100,
y: (i * 47 + 13) % 100,
size: 2 + (i % 2),
delay: (i * 0.35) % 4,
duration: 3.5 + (i % 3),
}));
const BRAND_TAGS = ['OneBot v11', '多账号', '实时面板'];
export function LoginPage({ onLogin }: LoginPageProps) {
const [password, setPassword] = useState('');
const [showPwd, setShowPwd] = useState(false);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [shakeKey, setShakeKey] = useState(0);
const { mode, resolved, setMode } = useTheme();
const containerRef = useRef<HTMLDivElement>(null);
const logoSrc = useMemo(() => '/logo.png', []);
const mouseX = useMotionValue(0);
const mouseY = useMotionValue(0);
const smoothX = useSpring(mouseX, { stiffness: 60, damping: 20 });
const smoothY = useSpring(mouseY, { stiffness: 60, damping: 20 });
const shellRotateX = useTransform(smoothY, [-0.5, 0.5], [4, -4]);
const shellRotateY = useTransform(smoothX, [-0.5, 0.5], [-5, 5]);
const orb1X = useTransform(smoothX, [-0.5, 0.5], [-45, 45]);
const orb1Y = useTransform(smoothY, [-0.5, 0.5], [-28, 28]);
const orb2X = useTransform(smoothX, [-0.5, 0.5], [35, -35]);
const orb2Y = useTransform(smoothY, [-0.5, 0.5], [30, -30]);
const accentX = useTransform(smoothX, [-0.5, 0.5], [-16, 16]);
const accentY = useTransform(smoothY, [-0.5, 0.5], [-12, 12]);
const handleMouseMove = useCallback((e: React.MouseEvent) => {
const rect = containerRef.current?.getBoundingClientRect();
if (!rect) return;
mouseX.set((e.clientX - rect.left) / rect.width - 0.5);
mouseY.set((e.clientY - rect.top) / rect.height - 0.5);
}, [mouseX, mouseY]);
const handleMouseLeave = useCallback(() => {
mouseX.set(0);
mouseY.set(0);
}, [mouseX, mouseY]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
const result = await onLogin(password);
setLoading(false);
if (!result.success && result.error) {
setError(result.error);
setShakeKey(k => k + 1);
}
};
const darkMode = resolved === 'dark';
return (
<div
ref={containerRef}
className="relative min-h-screen overflow-hidden"
style={{ background: 'var(--bg-body)' }}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<div
className="pointer-events-none absolute inset-0"
style={{
background: darkMode
? 'linear-gradient(135deg, rgba(8,11,18,1) 0%, rgba(10,16,27,1) 42%, rgba(7,10,17,1) 100%)'
: 'linear-gradient(135deg, #f8fbff 0%, #eef6ff 45%, #f9fafc 100%)',
}}
/>
<div className="pointer-events-none absolute inset-0 overflow-hidden">
{SPARKLES.map(s => (
<motion.div
key={s.id}
className="absolute rounded-full"
style={{
width: s.size,
height: s.size,
left: `${s.x}%`,
top: `${s.y}%`,
background: darkMode
? `rgba(${s.id % 2 === 0 ? '56,189,248' : '129,140,248'},0.38)`
: `rgba(${s.id % 2 === 0 ? '14,165,233' : '99,102,241'},0.26)`,
}}
animate={{ y: [0, -16, 0], opacity: [0.18, 0.55, 0.18], scale: [1, 1.25, 1] }}
transition={{ duration: s.duration, delay: s.delay, ease: 'easeInOut', repeat: Infinity }}
/>
))}
<motion.div
className="absolute -left-24 -top-24 h-120 w-120 rounded-full"
style={{
x: orb1X,
y: orb1Y,
background: darkMode
? 'radial-gradient(circle, rgba(56,189,248,0.16) 0%, transparent 68%)'
: 'radial-gradient(circle, rgba(56,189,248,0.22) 0%, transparent 70%)',
filter: 'blur(42px)',
}}
animate={{ scale: [1, 1.08, 1] }}
transition={{ duration: 10, ease: 'easeInOut', repeat: Infinity }}
/>
<motion.div
className="absolute -right-16 -bottom-32 h-112 w-md rounded-full"
style={{
x: orb2X,
y: orb2Y,
background: darkMode
? 'radial-gradient(circle, rgba(129,140,248,0.14) 0%, transparent 68%)'
: 'radial-gradient(circle, rgba(129,140,248,0.16) 0%, transparent 70%)',
filter: 'blur(52px)',
}}
animate={{ scale: [1, 1.12, 1] }}
transition={{ duration: 12, ease: 'easeInOut', repeat: Infinity, delay: 0.8 }}
/>
</div>
<div className="relative z-10 flex min-h-screen items-center justify-center px-5 py-10 sm:px-8 lg:px-12">
<motion.div
initial={{ opacity: 0, y: 24, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.55, ease: [0.16, 1, 0.3, 1] }}
style={{ rotateX: shellRotateX, rotateY: shellRotateY, transformPerspective: 1200 }}
className="relative w-full max-w-6xl"
>
<div
className="absolute -inset-5 -z-10 rounded-4xl blur-3xl"
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.12), rgba(129,140,248,0.14), rgba(34,211,238,0.08))' }}
/>
<div
className="relative overflow-hidden rounded-4xl border"
style={{
background: darkMode
? 'linear-gradient(135deg, rgba(8,13,22,0.78), rgba(14,20,32,0.88))'
: 'linear-gradient(135deg, rgba(255,255,255,0.72), rgba(255,255,255,0.9))',
borderColor: 'var(--glass-border)',
backdropFilter: 'blur(38px) saturate(1.35)',
WebkitBackdropFilter: 'blur(38px) saturate(1.35)',
boxShadow: darkMode
? '0 38px 120px rgba(0,0,0,0.55), inset 0 1px 0 rgba(255,255,255,0.05)'
: '0 32px 90px rgba(15,23,42,0.12), inset 0 1px 0 rgba(255,255,255,0.7)',
}}
>
<div
className="absolute inset-0"
style={{
backgroundImage: darkMode
? 'linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px), linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px)'
: 'linear-gradient(90deg, rgba(15,23,42,0.04) 1px, transparent 1px), linear-gradient(rgba(15,23,42,0.04) 1px, transparent 1px)',
backgroundSize: '36px 36px',
maskImage: 'linear-gradient(180deg, rgba(0,0,0,0.45), transparent 82%)',
}}
/>
<motion.div
className="pointer-events-none absolute right-[18%] top-[14%] h-28 w-28 rounded-full"
style={{
x: accentX,
y: accentY,
background: 'radial-gradient(circle, rgba(56,189,248,0.28), transparent 68%)',
filter: 'blur(18px)',
}}
animate={{ scale: [1, 1.12, 1] }}
transition={{ duration: 6, ease: 'easeInOut', repeat: Infinity }}
/>
<div className="relative grid min-h-168 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]">
<div className="relative flex flex-col justify-center gap-12 p-6 sm:p-10 lg:p-14 xl:p-16">
<div className="max-w-2xl">
<motion.div
initial={{ opacity: 0, y: 14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.45, delay: 0.08 }}
className="flex items-center gap-4"
>
<motion.div whileHover={{ scale: 1.03 }} className="relative shrink-0">
<div
className="absolute -inset-2 rounded-full blur-xl"
style={{ background: 'linear-gradient(135deg, rgba(56,189,248,0.25), rgba(129,140,248,0.22))' }}
/>
<div
className="relative rounded-full border p-1"
style={{
borderColor: 'var(--glass-border)',
background: darkMode ? 'rgba(8,12,19,0.7)' : 'rgba(255,255,255,0.8)',
}}
>
<Avatar
className="size-16 rounded-full"
style={{ width: 64, height: 64, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 }}
>
<Avatar.Image src={logoSrc} alt="SnowLuma" className="object-cover" />
<Avatar.Fallback>SL</Avatar.Fallback>
</Avatar>
</div>
</motion.div>
<div>
<div className="text-sm font-medium" style={{ color: 'var(--accent)' }}>
SnowLuma 控制台
</div>
<h1
className="mt-1 text-4xl font-semibold tracking-[-0.04em] sm:text-5xl"
style={{ color: 'var(--text-primary)' }}
>
SnowLuma
</h1>
</div>
</motion.div>
<motion.p
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.45, delay: 0.16 }}
className="mt-8 max-w-xl text-base leading-8"
style={{ color: 'var(--text-secondary)' }}
>
基于 OneBot v11 标准实现的高性能 QQ 协议网关。
</motion.p>
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.45, delay: 0.22 }}
className="mt-8 flex flex-wrap gap-2"
>
{BRAND_TAGS.map(tag => (
<span
key={tag}
className="rounded-full px-3.5 py-1.5 text-xs font-medium"
style={{
color: 'var(--accent)',
background: 'var(--accent-subtle)',
border: '1px solid color-mix(in srgb, var(--accent) 30%, transparent)',
}}
>
{tag}
</span>
))}
</motion.div>
</div>
<div className="absolute bottom-6 left-6 sm:bottom-10 sm:left-10 lg:bottom-14 lg:left-14 xl:bottom-16 xl:left-16 pointer-events-none">
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.6, delay: 0.4 }}
className="text-[11px] tracking-wide"
style={{ color: 'var(--text-tertiary)' }}
>
&copy; {new Date().getFullYear()} SnowLuma. All rights reserved.
</motion.p>
</div>
</div>
<div
className="relative flex items-center px-5 pb-5 pt-0 sm:px-8 sm:pb-8 lg:border-l lg:px-12 lg:py-12"
style={{ borderColor: 'var(--glass-border)' }}
>
<motion.div
initial={{ opacity: 0, x: 18 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5, delay: 0.18 }}
className="relative w-full max-w-md mx-auto rounded-[1.75rem] p-7 sm:p-8 overflow-hidden"
style={{
background: darkMode ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: darkMode
? '0 24px 64px rgba(0,0,0,0.4), inset 0 1px 1px rgba(255,255,255,0.08)'
: '0 24px 54px rgba(15,23,42,0.06), inset 0 1px 1px rgba(255,255,255,0.6)',
border: '1px solid',
borderColor: darkMode ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.8)',
}}
>
{/* Subtle animated background glow for the card */}
<motion.div
className="absolute -top-32 -right-32 w-64 h-64 rounded-full pointer-events-none z-0"
style={{
background: 'var(--accent)',
opacity: 0.15,
filter: 'blur(60px)'
}}
animate={{ scale: [1, 1.2, 1], opacity: [0.1, 0.2, 0.1] }}
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
/>
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-xs font-medium uppercase tracking-widest" style={{ color: 'var(--accent)' }}>
安全登录
</div>
{/* <h2 className="mt-1 text-2xl font-semibold tracking-[-0.03em]" style={{ color: 'var(--text-primary)' }}>
验证访问令牌
</h2> */}
</div>
<div className="flex items-center gap-0.5">
{THEME_OPTIONS.map(({ mode: m, icon: Icon, label }) => {
const active = mode === m;
return (
<button
key={m}
title={label}
onClick={() => setMode(m)}
className="relative flex size-8 cursor-pointer items-center justify-center rounded-xl transition-colors duration-200"
style={{ color: active ? 'var(--accent)' : 'var(--text-tertiary)' }}
>
{active && (
<motion.div
layoutId="theme-pill"
className="absolute inset-0 rounded-xl"
style={{ background: 'var(--accent-subtle)' }}
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
/>
)}
<Icon size={14} className="relative z-10" />
</button>
);
})}
</div>
</div>
<motion.form
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.45, delay: 0.26 }}
onSubmit={handleSubmit}
className="relative z-10 mt-6 flex flex-col gap-5"
>
<motion.div
key={shakeKey}
className="relative flex items-center justify-between overflow-hidden rounded-2xl"
style={{
background: darkMode ? 'rgba(0,0,0,0.2)' : 'rgba(255,255,255,0.6)',
boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.05)',
border: '1px solid',
borderColor: darkMode ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.04)',
transition: 'all 0.3s ease',
}}
whileFocus={{ borderColor: 'var(--accent)', boxShadow: '0 0 0 2px var(--accent-subtle)' }}
animate={shakeKey > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
transition={{ duration: 0.45, ease: 'easeInOut' }}
>
<div className="flex h-14 flex-1 items-center px-4">
<div
className="mr-3 shrink-0"
style={{ color: 'var(--text-tertiary)', transition: 'color 0.3s' }}
>
<KeyRound size={16} />
</div>
<input
type={showPwd ? 'text' : 'password'}
placeholder="输入访问令牌"
value={password}
onChange={e => setPassword(e.target.value)}
autoFocus
className="h-full w-full bg-transparent text-sm font-medium outline-none placeholder:font-normal"
style={{
color: 'var(--text-primary)',
}}
onFocus={e => {
const icon = e.target.previousElementSibling as HTMLElement;
if (icon) icon.style.color = 'var(--accent)';
}}
onBlur={e => {
const icon = e.target.previousElementSibling as HTMLElement;
if (icon) icon.style.color = 'var(--text-tertiary)';
}}
/>
</div>
<button
type="button"
tabIndex={-1}
onClick={() => setShowPwd(v => !v)}
className="flex h-14 w-12 shrink-0 cursor-pointer items-center justify-center transition-colors hover:bg-black/5 dark:hover:bg-white/5"
style={{ color: 'var(--text-tertiary)' }}
>
{showPwd ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
</motion.div>
<AnimatePresence>
{error && (
<motion.p
key="err"
initial={{ opacity: 0, y: -6, scale: 0.97 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -4, scale: 0.97 }}
transition={{ duration: 0.2 }}
className="rounded-2xl px-4 py-3 text-center text-xs"
style={{
color: 'var(--color-danger)',
background: 'rgba(248,113,113,0.08)',
border: '1px solid rgba(248,113,113,0.18)',
}}
>
{error}
</motion.p>
)}
</AnimatePresence>
<motion.button
whileHover={{ scale: 1.015, borderColor: 'var(--accent)', color: 'var(--accent)' }}
whileTap={{ scale: 0.985 }}
type="submit"
disabled={loading}
className="relative mt-2 flex h-13 cursor-pointer items-center justify-center overflow-hidden rounded-2xl text-sm font-medium disabled:cursor-not-allowed disabled:opacity-75"
style={{
background: darkMode ? 'rgba(255, 255, 255, 0.04)' : 'rgba(0, 0, 0, 0.02)',
border: '1px solid',
borderColor: darkMode ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.06)',
color: 'var(--text-primary)',
transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
}}
>
<span className="relative z-10 flex items-center justify-center gap-2 tracking-wide">
{loading ? (
<>
<motion.span
animate={{ rotate: 360 }}
transition={{ duration: 0.8, ease: 'linear', repeat: Infinity }}
className="inline-block size-4 rounded-full border-2 border-t-transparent"
style={{ borderColor: 'currentColor', borderTopColor: 'transparent' }}
/>
验证中…
</>
) : (
<>
进入控制台
<ArrowRight size={16} strokeWidth={2} />
</>
)}
</span>
</motion.button>
</motion.form>
</motion.div>
</div>
</div>
</div>
</motion.div>
</div>
</div>
);
}
@@ -1,132 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { RefreshCw, Terminal } from 'lucide-react';
import { motion } from 'framer-motion';
import { useTheme } from '../../contexts/ThemeContext';
interface LogEntry {
id: number;
time: string;
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
scope: string;
message: string;
line: string;
}
interface LogsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
}
const levelColor: Record<LogEntry['level'], string> = {
debug: 'var(--text-tertiary)',
info: 'var(--accent)',
success: 'var(--color-success)',
warn: '#f59e0b',
error: 'var(--color-danger)',
};
export function LogsPage({ fetchApi }: LogsPageProps) {
const { resolved } = useTheme();
const dark = resolved === 'dark';
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const endRef = useRef<HTMLDivElement | null>(null);
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
async function loadLogs() {
const res = await fetchApi('/api/logs?limit=500');
if (!res.ok) return;
const data = await res.json();
setLogs(data.list || []);
}
useEffect(() => {
loadLogs().catch(console.error);
}, []);
useEffect(() => {
if (!token) return;
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
const source = new EventSource(url);
source.onopen = () => setStreamStatus('实时连接');
source.onerror = () => setStreamStatus('重连中');
source.onmessage = event => {
try {
const entry = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in entry) return;
setLogs(prev => [...prev.filter(item => item.id !== entry.id), entry].slice(-500));
} catch {
}
};
return () => source.close();
}, [token]);
useEffect(() => {
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs]);
return (
<div className="flex min-h-0 flex-1 flex-col gap-4">
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
className="rounded-xl p-4"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
}}
>
<div className="mb-4 flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<div
className="flex size-9 items-center justify-center rounded-lg"
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
>
<Terminal size={17} strokeWidth={2} />
</div>
<div>
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>运行日志</h2>
<p className="mt-0.5 text-xs" style={{ color: 'var(--text-secondary)' }}>{streamStatus} · 最近 {logs.length} 条</p>
</div>
</div>
<button
onClick={() => loadLogs().catch(console.error)}
className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-3 text-xs font-medium"
style={{
color: 'var(--text-secondary)',
border: '1px solid var(--border-subtle)',
background: 'transparent',
}}
>
<RefreshCw size={13} />
刷新
</button>
</div>
<div
className="h-[58vh] overflow-auto rounded-xl p-3 text-xs"
style={{
background: dark ? 'rgba(0,0,0,0.22)' : 'rgba(255,255,255,0.42)',
border: '1px solid var(--border-subtle)',
fontFamily: 'var(--font-mono)',
}}
>
{logs.length === 0 ? (
<div className="flex h-full items-center justify-center" style={{ color: 'var(--text-tertiary)' }}>暂无日志</div>
) : logs.map(log => (
<div key={log.id} className="flex gap-2 whitespace-pre-wrap py-0.5 leading-5">
<span className="shrink-0" style={{ color: 'var(--text-tertiary)' }}>{new Date(log.time).toLocaleTimeString()}</span>
<span className="w-14 shrink-0 font-semibold" style={{ color: levelColor[log.level] }}>{log.level.toUpperCase()}</span>
<span className="w-24 shrink-0 truncate" style={{ color: 'var(--text-secondary)' }}>[{log.scope}]</span>
<span style={{ color: 'var(--text-primary)' }}>{log.message}</span>
</div>
))}
<div ref={endRef} />
</div>
</motion.div>
</div>
);
}
@@ -1,307 +0,0 @@
import { Users, Activity, Cpu, RefreshCw, Loader2, CheckCircle2, AlertCircle, Unplug } from 'lucide-react';
import { motion } from 'framer-motion';
import { StatCard } from '../ui/StatCard';
import { useTheme } from '../../contexts/ThemeContext';
import type { QQInfo, HookProcessInfo } from '../../types';
interface OverviewPageProps {
qqList: QQInfo[];
status: string;
processList: HookProcessInfo[];
processLoadingPid: number | null;
processUnloadingPid: number | null;
processActionStatus: string;
onRefreshProcesses: () => void;
onLoadProcess: (pid: number) => void;
onUnloadProcess: (pid: number) => void;
}
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
loading: '加载中',
loaded: '等待登录',
online: '已在线',
error: '错误',
disconnected: '已断开',
};
function processStatusColor(status: HookProcessInfo['status']): string {
if (status === 'online') return 'var(--color-success)';
if (status === 'error' || status === 'disconnected') return 'var(--color-danger)';
if (status === 'loading' || status === 'loaded') return 'var(--accent)';
return 'var(--text-secondary)';
}
function qqAvatarUrl(uin: string): string {
return `/avatar/${encodeURIComponent(uin)}`;
}
export function OverviewPage({
qqList,
status,
processList,
processLoadingPid,
processUnloadingPid,
processActionStatus,
onRefreshProcesses,
onLoadProcess,
onUnloadProcess,
}: OverviewPageProps) {
const { resolved } = useTheme();
const dark = resolved === 'dark';
return (
<div className="space-y-8">
{/* Stat cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard
label="接入账号"
value={String(qqList.length)}
icon={<Users size={18} strokeWidth={2} />}
/>
<StatCard
label="服务状态"
value={status === '已连接' ? '运行中' : status}
icon={<Activity size={18} strokeWidth={2} />}
accent={status === '已连接' ? 'success' : 'danger'}
/>
</div>
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05, duration: 0.3 }}
className="rounded-xl p-4"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: dark
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
}}
>
<div className="flex items-center justify-between gap-3 mb-4">
<div className="flex items-center gap-2">
<div
className="size-9 rounded-lg flex items-center justify-center"
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
>
<Cpu size={17} strokeWidth={2} />
</div>
<div>
<h2 className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>
选择 QQ 进程
</h2>
<p className="text-xs mt-0.5" style={{ color: 'var(--text-secondary)' }}>
加载 SnowLuma 后会监听登录状态,登录成功后自动接入原有 OneBot 流程
</p>
</div>
</div>
<button
onClick={onRefreshProcesses}
className="h-8 px-3 rounded-lg text-xs font-medium inline-flex items-center gap-1.5 cursor-pointer"
style={{
color: 'var(--text-secondary)',
border: '1px solid var(--border-subtle)',
background: 'transparent',
}}
>
<RefreshCw size={13} />
刷新
</button>
</div>
{processActionStatus && (
<div
className="mb-3 rounded-lg px-3 py-2 text-xs"
style={{
color: 'var(--accent)',
background: 'var(--accent-subtle)',
border: '1px solid color-mix(in srgb, var(--accent) 20%, transparent)',
}}
>
{processActionStatus}
</div>
)}
{processList.length > 0 ? (
<div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const busy = loading || unloading;
const online = proc.status === 'online';
const canUnload = proc.injected || proc.status === 'loaded' || online || proc.status === 'disconnected';
const disabled = busy;
const actionLabel = canUnload
? unloading ? '卸载中' : '卸载'
: loading ? '加载中' : '加载';
const action = canUnload ? () => onUnloadProcess(proc.pid) : () => onLoadProcess(proc.pid);
return (
<motion.div
key={proc.pid}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.08 + idx * 0.03, duration: 0.22 }}
className="flex items-center gap-3 rounded-xl p-3 overflow-hidden"
style={{
background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.46)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
}}
>
<div
className="size-10 rounded-lg flex items-center justify-center shrink-0"
style={{ background: 'var(--accent-subtle)', color: 'var(--accent)' }}
>
{online ? <CheckCircle2 size={18} /> : proc.status === 'error' ? <AlertCircle size={18} /> : <Cpu size={18} />}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 min-w-0">
<span className="text-sm font-semibold truncate" style={{ color: 'var(--text-primary)' }}>
{proc.name || 'QQ.exe'}
</span>
<span
className="text-[11px] px-1.5 py-0.5 rounded-md shrink-0"
style={{
color: processStatusColor(proc.status),
background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.6)',
}}
>
{processStatusLabel[proc.status]}
</span>
</div>
<div className="text-xs mt-0.5 truncate" style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)' }}>
PID {proc.pid}{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
</div>
{proc.path && (
<div className="text-[11px] mt-0.5 truncate" title={proc.path} style={{ color: 'var(--text-tertiary)' }}>
{proc.path}
</div>
)}
{proc.error && (
<div className="text-[11px] mt-1 truncate" title={proc.error} style={{ color: 'var(--color-danger)' }}>
{proc.error}
</div>
)}
</div>
<button
onClick={action}
disabled={disabled}
className="h-8 px-3 rounded-lg text-xs font-semibold inline-flex items-center gap-1.5 shrink-0"
style={{
color: disabled ? 'var(--text-tertiary)' : canUnload ? 'var(--color-danger)' : 'white',
background: disabled ? 'var(--bg-hover)' : canUnload ? 'rgba(248,113,113,0.08)' : 'linear-gradient(135deg, var(--accent), #818cf8)',
cursor: disabled ? 'default' : 'pointer',
border: canUnload ? '1px solid rgba(248,113,113,0.2)' : '1px solid transparent',
boxShadow: disabled || canUnload ? 'none' : '0 8px 18px var(--accent-glow)',
}}
>
{busy && <Loader2 size={13} className="animate-spin" />}
{!busy && canUnload && <Unplug size={13} />}
{actionLabel}
</button>
</motion.div>
);
})}
</div>
) : (
<div
className="flex flex-col items-center justify-center py-10 rounded-xl gap-2"
style={{
border: '1px dashed',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.08)',
}}
>
<Cpu size={30} strokeWidth={1.5} style={{ color: 'var(--text-tertiary)' }} />
<p className="text-sm font-medium" style={{ color: 'var(--text-secondary)' }}>未检测到可加载 QQ 主进程</p>
</div>
)}
</motion.div>
{/* Account list */}
{qqList.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1, duration: 0.3 }}
>
<h2 className="text-sm font-semibold mb-4" style={{ color: 'var(--text-primary)' }}>
在线会话
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3">
{qqList.map((q, idx) => (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 + idx * 0.04, duration: 0.25 }}
whileHover={{ y: -2 }}
key={q.uin}
className="flex items-center gap-3 p-4 rounded-xl cursor-default group overflow-hidden"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: dark
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
transition: 'var(--transition-base)',
}}
>
<div
className="size-10 rounded-lg flex items-center justify-center text-white text-sm font-bold shrink-0 overflow-hidden"
style={{
background: 'linear-gradient(135deg, var(--accent), #818cf8)',
boxShadow: '0 0 12px var(--accent-glow)',
}}
>
<img
src={qqAvatarUrl(q.uin)}
alt={q.nickname || q.uin}
className="size-full object-cover"
referrerPolicy="no-referrer"
/>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold truncate" style={{ color: 'var(--text-primary)' }}>
{q.nickname}
</div>
<div
className="text-xs mt-0.5 truncate"
style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' }}
>
{q.uin}
</div>
</div>
<span
className="size-2 rounded-full shrink-0 animate-pulse"
style={{ background: 'var(--color-success)', boxShadow: '0 0 8px rgba(52,211,153,0.5)' }}
/>
</motion.div>
))}
</div>
</motion.div>
)}
{qqList.length === 0 && (
<motion.div
initial={{ opacity: 0 }} animate={{ opacity: 1 }}
className="flex flex-col items-center justify-center py-16 rounded-xl gap-3"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px dashed',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.08)',
}}
>
<Users size={36} strokeWidth={1.5} style={{ color: 'var(--text-tertiary)' }} />
<p className="text-sm font-medium" style={{ color: 'var(--text-secondary)' }}>暂无在线会话</p>
</motion.div>
)}
</div>
);
}
@@ -0,0 +1,303 @@
import { useEffect, useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ThemeToggle } from '@/components/theme-toggle';
import { cn } from '@/lib/utils';
export interface PasswordRule {
id: string;
label: string;
ok: boolean;
}
interface ChangePasswordPageProps {
/** When true, this is the forced first-time change flow. */
forced?: boolean;
/** Heading shown above the form. */
title?: string;
/** Subheading. */
description?: string;
/** Sends `{ password }` and returns the rule list + valid flag. */
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
/** Called after a successful submit. */
onSuccess: () => void;
/** Called when user cancels (only available when not forced). */
onCancel?: () => void;
}
export function ChangePasswordPage({
forced = false,
title,
description,
checkStrength,
submit,
onSuccess,
onCancel,
}: ChangePasswordPageProps) {
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showOld, setShowOld] = useState(false);
const [showNew, setShowNew] = useState(false);
const [rules, setRules] = useState<PasswordRule[]>([]);
const [valid, setValid] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState('');
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
const canSubmit =
!submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword;
// Debounce the strength check so we don't slam the API on every keystroke.
useEffect(() => {
let cancelled = false;
const handle = window.setTimeout(async () => {
try {
const res = await checkStrength(newPassword);
if (cancelled) return;
setRules(res.rules);
setValid(res.valid);
} catch {
/* ignore – the form will just stay disabled */
}
}, 180);
return () => {
cancelled = true;
window.clearTimeout(handle);
};
}, [newPassword, checkStrength]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!canSubmit) return;
setSubmitting(true);
setError('');
try {
const res = await submit(oldPassword, newPassword);
if (res.success) {
onSuccess();
} else {
setError(res.message || '修改失败');
}
} catch (err) {
setError(err instanceof Error ? err.message : '网络错误');
} finally {
setSubmitting(false);
}
};
const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码');
const computedDescription =
description ??
(forced
? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。'
: '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。');
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
}}
/>
<motion.div
aria-hidden
className="pointer-events-none absolute -left-24 top-24 size-72 rounded-full bg-primary/15 blur-3xl"
animate={{ scale: [1, 1.08, 1] }}
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
/>
<div className="absolute right-4 top-4">
<ThemeToggle />
</div>
<motion.div
initial={{ opacity: 0, y: 16, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
className="relative z-10 w-full max-w-lg"
>
<Card className="border-primary/15 shadow-xl">
<CardContent className="p-7 sm:p-9">
<div className="flex items-start gap-3">
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
{forced ? (
<ShieldAlert className="size-6 text-primary" />
) : (
<KeyRound className="size-6 text-primary" />
)}
</div>
<div className="min-w-0">
<h1 className="text-lg font-semibold tracking-tight">{computedTitle}</h1>
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{computedDescription}</p>
</div>
</div>
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="old">当前密码</Label>
<div className="relative">
<Input
id="old"
type={showOld ? 'text' : 'password'}
autoComplete="current-password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
placeholder="输入当前访问密码"
className="h-10 pr-10 text-sm"
/>
<button
type="button"
onClick={() => setShowOld((v) => !v)}
aria-label={showOld ? '隐藏密码' : '显示密码'}
tabIndex={-1}
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
>
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</button>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="new">新密码</Label>
<div className="relative">
<Input
id="new"
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="设置新的强密码"
className="h-10 pr-10 text-sm"
/>
<button
type="button"
onClick={() => setShowNew((v) => !v)}
aria-label={showNew ? '隐藏密码' : '显示密码'}
tabIndex={-1}
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
>
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</button>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="confirm">确认新密码</Label>
<Input
id="confirm"
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="再次输入新密码"
className="h-10 text-sm"
/>
{confirmPassword.length > 0 && !confirmMatches && (
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
)}
</div>
<RuleList rules={rules} />
<AnimatePresence>
{error && (
<motion.p
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
>
{error}
</motion.p>
)}
</AnimatePresence>
<div className="flex items-center gap-2">
{!forced && onCancel && (
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
取消
</Button>
)}
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
{submitting ? (
<>
<Loader2 className="size-4 animate-spin" /> 提交中…
</>
) : (
'保存新密码'
)}
</Button>
</div>
</form>
</CardContent>
</Card>
</motion.div>
</div>
);
}
function RuleList({ rules }: { rules: PasswordRule[] }) {
// Initial empty state: show a placeholder set so the user knows the rules
// exist even before any input.
const display = useMemo<PasswordRule[]>(() => {
if (rules.length > 0) return rules;
return [
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
{ id: 'no-space', label: '不得包含空格', ok: false },
];
}, [rules]);
return (
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
{display.map((rule) => (
<li key={rule.id} className="flex items-center gap-2">
<motion.span
initial={false}
animate={{
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
scale: rule.ok ? [1, 1.18, 1] : 1,
}}
transition={{ duration: 0.25 }}
className={cn(
'flex size-4 items-center justify-center rounded-full border',
)}
>
<AnimatePresence>
{rule.ok && (
<motion.span
key="check"
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.4 }}
transition={{ duration: 0.18 }}
>
<Check className="size-3 text-primary" strokeWidth={3} />
</motion.span>
)}
</AnimatePresence>
</motion.span>
<motion.span
initial={false}
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
transition={{ duration: 0.2 }}
className="text-xs"
>
{rule.label}
</motion.span>
</li>
))}
</ul>
);
}
@@ -0,0 +1,434 @@
import { useState } from 'react';
import { motion } from 'motion/react';
import { MousePointerClick, Plus, Save, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type {
HttpPostEndpoint,
HttpServerEndpoint,
OneBotConfig,
QQInfo,
WsClientEndpoint,
WsServerEndpoint,
} from '@/types';
interface ConfigPageProps {
qqList: QQInfo[];
selectedUin: string | null;
config: OneBotConfig | null;
saveStatus: string;
onSelectAccount: (uin: string) => void;
onSave: () => Promise<void> | void;
onConfigChange: (config: OneBotConfig) => void;
}
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
function Field({
label,
value,
onChange,
placeholder,
type = 'text',
className,
}: {
label: string;
value: string | number | undefined;
onChange: (v: string) => void;
placeholder?: string;
type?: 'text' | 'number' | 'url';
className?: string;
}) {
return (
<div className={cn('flex flex-col gap-1.5', className)}>
<Label>{label}</Label>
<Input
type={type}
value={value ?? ''}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
/>
</div>
);
}
interface SectionProps {
title: string;
description?: string;
onAdd?: () => void;
children: React.ReactNode;
count?: number;
}
function Section({ title, description, onAdd, children, count }: SectionProps) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
<div className="min-w-0">
<div className="flex items-center gap-2">
<CardTitle className="text-sm">{title}</CardTitle>
{typeof count === 'number' && <Badge variant="secondary">{count}</Badge>}
</div>
{description && <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>}
</div>
{onAdd && (
<Button size="sm" variant="outline" onClick={onAdd}>
<Plus className="size-3.5" /> 添加
</Button>
)}
</CardHeader>
<CardContent className="flex flex-col gap-3 pt-0">{children}</CardContent>
</Card>
);
}
function EndpointRow({ children, onRemove }: { children: React.ReactNode; onRemove?: () => void }) {
return (
<motion.div
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18 }}
className="flex flex-col gap-3 rounded-lg border bg-card/40 p-3 sm:flex-row sm:items-end"
>
<div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-end">{children}</div>
{onRemove && (
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
aria-label="删除"
className="self-end text-muted-foreground hover:text-destructive"
>
<Trash2 className="size-4" />
</Button>
)}
</motion.div>
);
}
export function ConfigPage({
qqList,
selectedUin,
config,
saveStatus,
onSelectAccount,
onSave,
onConfigChange,
}: ConfigPageProps) {
const [confirmSave, setConfirmSave] = useState(false);
const update = (next: OneBotConfig) => onConfigChange(next);
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
{/* Account list */}
<Card className="lg:sticky lg:top-2 lg:self-start">
<CardHeader>
<CardTitle className="text-sm">在线连接</CardTitle>
</CardHeader>
<CardContent className="pt-0">
{qqList.length === 0 ? (
<p className="py-6 text-center text-xs text-muted-foreground">暂无在线会话</p>
) : (
<ScrollArea className="max-h-[60vh]" viewportClassName="[&>div]:!block">
<div className="grid grid-cols-2 gap-1.5 lg:grid-cols-1">
{qqList.map((q) => {
const isActive = selectedUin === q.uin;
return (
<motion.button
key={q.uin}
type="button"
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
onClick={() => onSelectAccount(q.uin)}
className={cn(
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
)}
>
<Avatar size={28}>
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<div
className={cn('truncate text-sm font-medium', isActive ? 'text-primary' : 'text-foreground')}
>
{q.nickname}
</div>
<div className="truncate font-mono text-[10px] text-muted-foreground tabular-nums">{q.uin}</div>
</div>
</motion.button>
);
})}
</div>
</ScrollArea>
)}
</CardContent>
</Card>
{/* Editor */}
<div className="min-w-0">
{!selectedUin ? (
<div className="flex h-64 flex-col items-center justify-center gap-2 rounded-lg border border-dashed text-muted-foreground">
<MousePointerClick className="size-7" strokeWidth={1.5} />
<p className="text-sm">请在左栏选择会话以配置通信节点</p>
</div>
) : !config ? (
<div className="space-y-3">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-32" />
<Skeleton className="h-32" />
</div>
) : (
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="text-base font-semibold tracking-tight">OneBot 协议端点</h2>
<code className="mt-0.5 block font-mono text-xs text-muted-foreground tabular-nums">UIN {selectedUin}</code>
</div>
<div className="flex items-center gap-2">
{saveStatus && (
<span
className={cn(
'rounded-full border px-2.5 py-1 text-[11px] font-medium',
saveStatus === '保存成功' && 'border-success/30 bg-success/10 text-success',
saveStatus === '保存中...' && 'border-border bg-muted text-muted-foreground',
saveStatus !== '保存成功' && saveStatus !== '保存中...' && 'border-destructive/30 bg-destructive/10 text-destructive'
)}
>
{saveStatus}
</span>
)}
<Button onClick={() => setConfirmSave(true)} size="sm">
<Save className="size-3.5" /> 保存设定
</Button>
</div>
</div>
{/* HTTP Servers */}
<Section
title="HTTP 服务监听"
description="开放 HTTP API,OneBot 客户端可主动发起请求"
count={config.httpServers.length}
onAdd={() => update({ ...config, httpServers: [...config.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }] })}
>
{config.httpServers.length === 0 ? (
<EmptyHint label="暂无 HTTP 服务" />
) : (
config.httpServers.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, httpServers: config.httpServers.filter((_, i) => i !== idx) })}
>
<Field
label="端口"
type="number"
value={s.port}
onChange={(v) =>
update({
...config,
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as HttpServerEndpoint[],
})
}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={s.accessToken}
onChange={(v) =>
update({
...config,
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="flex-1"
/>
</EndpointRow>
))
)}
</Section>
{/* HTTP Post */}
<Section
title="HTTP Post 推送"
description="向远端 URL 主动推送事件"
count={config.httpPostEndpoints.length}
onAdd={() => update({ ...config, httpPostEndpoints: [...config.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }] })}
>
{config.httpPostEndpoints.length === 0 ? (
<EmptyHint label="暂无 HTTP 推送目标" />
) : (
config.httpPostEndpoints.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() =>
update({ ...config, httpPostEndpoints: config.httpPostEndpoints.filter((_, i) => i !== idx) })
}
>
<Field
label="目标 URL"
type="url"
placeholder="http://..."
value={s.url}
onChange={(v) =>
update({
...config,
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, url: v } : it)) as HttpPostEndpoint[],
})
}
className="flex-1"
/>
<Field
label="授权 Token"
placeholder="可选"
value={s.accessToken}
onChange={(v) =>
update({
...config,
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="sm:w-64"
/>
</EndpointRow>
))
)}
</Section>
{/* WS Servers */}
<Section
title="WebSocket 服务监听"
description="开放 WS 服务,客户端可建立持久连接"
count={config.wsServers.length}
onAdd={() => update({ ...config, wsServers: [...config.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }] })}
>
{config.wsServers.length === 0 ? (
<EmptyHint label="暂无 WS 服务" />
) : (
config.wsServers.map((s, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, wsServers: config.wsServers.filter((_, i) => i !== idx) })}
>
<Field
label="端口"
type="number"
value={s.port}
onChange={(v) =>
update({
...config,
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as WsServerEndpoint[],
})
}
className="sm:w-32"
/>
<Field
label="授权 Token"
placeholder="不填则无密码"
value={s.accessToken}
onChange={(v) =>
update({
...config,
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="flex-1"
/>
</EndpointRow>
))
)}
</Section>
{/* WS Clients */}
<Section
title="WebSocket 反向连出"
description="主动连接到外部 WS 服务器(reverse-ws)"
count={config.wsClients.length}
onAdd={() =>
update({
...config,
wsClients: [...config.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }],
})
}
>
{config.wsClients.length === 0 ? (
<EmptyHint label="暂无反向 WS 客户端" />
) : (
config.wsClients.map((c, idx) => (
<EndpointRow
key={idx}
onRemove={() => update({ ...config, wsClients: config.wsClients.filter((_, i) => i !== idx) })}
>
<Field
label="目标 URL"
type="url"
placeholder="ws://..."
value={c.url}
onChange={(v) =>
update({
...config,
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, url: v } : it)) as WsClientEndpoint[],
})
}
className="flex-1"
/>
<Field
label="授权 Token"
placeholder="可选"
value={c.accessToken}
onChange={(v) =>
update({
...config,
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
})
}
className="sm:w-64"
/>
</EndpointRow>
))
)}
</Section>
<Section title="音乐签名 URL" description="用于生成音乐卡片签名(可选)">
<Field
label="签名服务地址"
type="url"
placeholder="留空则不启用"
value={config.musicSignUrl}
onChange={(v) => update({ ...config, musicSignUrl: v || undefined })}
/>
</Section>
</div>
)}
</div>
<ConfirmDialog
open={confirmSave}
onOpenChange={setConfirmSave}
title="保存配置变更?"
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
confirmText="保存"
onConfirm={onSave}
/>
</div>
);
}
function EmptyHint({ label }: { label: string }) {
return (
<div className="rounded-md border border-dashed py-6 text-center text-xs text-muted-foreground">{label}</div>
);
}
@@ -0,0 +1,135 @@
import { useState } from 'react';
import { motion } from 'motion/react';
import { ArrowRight, Eye, EyeOff, KeyRound } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ThemeToggle } from '@/components/theme-toggle';
import { APP_NAME, APP_VERSION } from '@/types';
interface LoginPageProps {
onLogin: (password: string) => Promise<{ success: boolean; error?: string }>;
}
export function LoginPage({ onLogin }: LoginPageProps) {
const [password, setPassword] = useState('');
const [showPwd, setShowPwd] = useState(false);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [shake, setShake] = useState(0);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
const result = await onLogin(password);
setLoading(false);
if (!result.success) {
setError(result.error || '登录失败');
setShake((k) => k + 1);
}
};
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
{/* Sky gradient backdrop */}
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
}}
/>
<motion.div
aria-hidden
className="pointer-events-none absolute -left-24 top-24 size-72 rounded-full bg-primary/15 blur-3xl"
animate={{ scale: [1, 1.08, 1] }}
transition={{ duration: 8, repeat: Infinity, ease: 'easeInOut' }}
/>
<motion.div
aria-hidden
className="pointer-events-none absolute -right-16 bottom-10 size-80 rounded-full bg-primary/10 blur-3xl"
animate={{ scale: [1, 1.12, 1] }}
transition={{ duration: 10, repeat: Infinity, ease: 'easeInOut', delay: 0.6 }}
/>
<div className="absolute right-4 top-4">
<ThemeToggle />
</div>
<motion.div
initial={{ opacity: 0, y: 16, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
className="relative z-10 w-full max-w-md"
>
<Card className="border-primary/15 shadow-xl">
<CardContent className="p-7 sm:p-9">
<div className="flex items-center gap-3">
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-9 object-contain" />
</div>
<div>
<div className="flex items-baseline gap-2">
<span className="text-xl font-bold tracking-tight">{APP_NAME}</span>
<span className="text-[11px] text-muted-foreground tabular-nums">v{APP_VERSION}</span>
</div>
<p className="text-xs text-muted-foreground">OneBot v11 协议网关 · 安全登录</p>
</div>
</div>
<form onSubmit={handleSubmit} className="mt-7 flex flex-col gap-4">
<motion.div
key={shake}
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
transition={{ duration: 0.4 }}
className="relative"
>
<KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
type={showPwd ? 'text' : 'password'}
placeholder="输入访问令牌"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoFocus
className="h-11 pl-9 pr-10 text-sm"
/>
<button
type="button"
onClick={() => setShowPwd((v) => !v)}
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
tabIndex={-1}
aria-label={showPwd ? '隐藏密码' : '显示密码'}
>
{showPwd ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</button>
</motion.div>
{error && (
<motion.p
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
>
{error}
</motion.p>
)}
<Button type="submit" disabled={loading || !password} className="h-11">
{loading ? '验证中…' : (
<>
进入控制台 <ArrowRight className="size-4" />
</>
)}
</Button>
</form>
<p className="mt-6 text-center text-[11px] text-muted-foreground">
© {new Date().getFullYear()} SnowLuma. All rights reserved.
</p>
</CardContent>
</Card>
</motion.div>
</div>
);
}
@@ -0,0 +1,199 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry } from '@/types';
interface LogsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
}
const levelClass: Record<LogEntry['level'], string> = {
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
warn: 'text-warning',
error: 'text-destructive',
};
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
export function LogsPage({ fetchApi }: LogsPageProps) {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
const [filter, setFilter] = useState('');
const [enabledLevels, setEnabledLevels] = useState<Set<LogEntry['level']>>(new Set(LEVELS));
const [confirmClear, setConfirmClear] = useState(false);
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
async function loadLogs() {
const res = await fetchApi('/api/logs?limit=500');
if (!res.ok) return;
const data = await res.json();
setLogs(data.list || []);
}
useEffect(() => {
loadLogs().catch(console.error);
}, []);
useEffect(() => {
if (!token) return;
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
const source = new EventSource(url);
source.onopen = () => setStreamStatus('实时');
source.onerror = () => setStreamStatus('重连中');
source.onmessage = (event) => {
try {
const entry = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in entry) return;
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
} catch {
// ignore
}
};
return () => source.close();
}, [token]);
useEffect(() => {
if (paused) return;
endRef.current?.scrollIntoView({ block: 'end' });
}, [logs, paused]);
const filtered = useMemo(() => {
const f = filter.trim().toLowerCase();
return logs.filter((l) => {
if (!enabledLevels.has(l.level)) return false;
if (!f) return true;
return (
l.message.toLowerCase().includes(f) ||
l.scope.toLowerCase().includes(f) ||
l.level.toLowerCase().includes(f)
);
});
}, [logs, filter, enabledLevels]);
const toggleLevel = (lv: LogEntry['level']) => {
setEnabledLevels((prev) => {
const next = new Set(prev);
if (next.has(lv)) next.delete(lv);
else next.add(lv);
return next;
});
};
return (
<Card className="flex h-[calc(100vh-7rem)] min-h-[480px] flex-col">
<CardHeader className="flex flex-col gap-3 space-y-0 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="flex items-center gap-2">
运行日志
<Badge variant={streamStatus === '实时' ? 'success' : 'secondary'}>{streamStatus}</Badge>
</CardTitle>
<CardDescription>
最近 {filtered.length} / {logs.length} 条 · 通过 SSE 推送
</CardDescription>
</div>
<div className="flex flex-wrap items-center gap-2">
<Input
placeholder="搜索消息 / 模块 / 级别"
value={filter}
onChange={(e) => setFilter(e.target.value)}
className="h-8 w-48"
/>
<Button variant="outline" size="sm" onClick={() => setPaused((v) => !v)}>
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
{paused ? '继续' : '暂停'}
</Button>
<Button variant="outline" size="sm" onClick={() => loadLogs().catch(console.error)}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setConfirmClear(true)}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="size-3.5" /> 清空视图
</Button>
</div>
</CardHeader>
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
{LEVELS.map((lv) => {
const active = enabledLevels.has(lv);
return (
<button
key={lv}
type="button"
onClick={() => toggleLevel(lv)}
className={cn(
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer',
active
? cn('border-transparent', levelClass[lv], 'bg-muted')
: 'border-border text-muted-foreground/60 line-through'
)}
>
{lv.toUpperCase()}
</button>
);
})}
</div>
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
<ScrollArea
className="flex-1 min-h-0"
viewportClassName="[&>div]:!block"
>
<div ref={viewportRef} className="font-mono text-xs">
{filtered.length === 0 ? (
<div className="flex h-40 items-center justify-center text-muted-foreground">暂无日志</div>
) : (
filtered.map((log) => (
<motion.div
key={log.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.12 }}
className="flex gap-2 whitespace-pre-wrap px-3 py-0.5 leading-5 hover:bg-accent/30"
>
<span className="shrink-0 text-muted-foreground tabular-nums">
{new Date(log.time).toLocaleTimeString()}
</span>
<span className={cn('w-14 shrink-0 font-semibold', levelClass[log.level])}>
{log.level.toUpperCase()}
</span>
<span className="w-28 shrink-0 truncate text-muted-foreground">[{log.scope}]</span>
<span className="break-all">{log.message}</span>
</motion.div>
))
)}
<div ref={endRef} />
</div>
</ScrollArea>
</div>
</CardContent>
<ConfirmDialog
open={confirmClear}
onOpenChange={setConfirmClear}
title="清空当前日志视图?"
description="此操作仅清空浏览器视图中的日志,不会影响服务端的日志缓冲区。"
confirmText="清空"
destructive
onConfirm={() => setLogs([])}
/>
</Card>
);
}
@@ -0,0 +1,421 @@
import { useEffect, useState } from 'react';
import { motion } from 'motion/react';
import {
Activity,
AlertCircle,
CheckCircle2,
Cpu,
HardDrive,
Loader2,
MemoryStick,
MonitorCog,
RefreshCw,
Server,
Unplug,
Users,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
interface OverviewPageProps {
qqList: QQInfo[];
status: string;
processList: HookProcessInfo[];
processLoadingPid: number | null;
processUnloadingPid: number | null;
processActionStatus: string;
systemInfo: SystemInfo | null;
onRefreshProcesses: () => void;
onRefreshSystem: () => void;
onLoadProcess: (pid: number) => Promise<void> | void;
onUnloadProcess: (pid: number) => Promise<void> | void;
}
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
loading: '加载中',
loaded: '等待登录',
online: '已在线',
error: '错误',
disconnected: '已断开',
};
function processBadgeVariant(status: HookProcessInfo['status']) {
if (status === 'online') return 'success' as const;
if (status === 'error' || status === 'disconnected') return 'destructive' as const;
if (status === 'loading' || status === 'loaded') return 'default' as const;
return 'secondary' as const;
}
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
}
function StatTile({
icon,
label,
value,
subtext,
accent = false,
}: {
icon: React.ReactNode;
label: string;
value: React.ReactNode;
subtext?: React.ReactNode;
accent?: boolean;
}) {
return (
<Card className="overflow-hidden">
<CardContent className="flex items-center gap-3 p-4">
<div
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-xl',
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
)}
>
{icon}
</div>
<div className="min-w-0 flex-1">
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div>
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>}
</div>
</CardContent>
</Card>
);
}
export function OverviewPage({
qqList,
status,
processList,
processLoadingPid,
processUnloadingPid,
processActionStatus,
systemInfo,
onRefreshProcesses,
onRefreshSystem,
onLoadProcess,
onUnloadProcess,
}: OverviewPageProps) {
const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string }
| null
>(null);
// Lightweight tick to refresh "uptime" pretty-print every 30s
const [, force] = useState(0);
useEffect(() => {
const t = setInterval(() => force((v) => v + 1), 30_000);
return () => clearInterval(t);
}, []);
const online = status === '已连接';
return (
<div className="flex flex-col gap-6">
{/* Top stats */}
<div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4">
<StatTile
icon={<Activity className="size-5" />}
label="服务状态"
value={online ? '运行中' : status}
subtext={online ? '已连接到后端' : '请检查后端进程'}
accent={online}
/>
<StatTile
icon={<Users className="size-5" />}
label="在线账号"
value={qqList.length}
subtext={`已接入 ${qqList.length} 个会话`}
/>
<StatTile
icon={<Server className="size-5" />}
label="主机名"
value={systemInfo?.hostname ?? '—'}
subtext={systemInfo ? `${systemInfo.platform} · ${systemInfo.arch}` : '加载中'}
/>
<StatTile
icon={<MonitorCog className="size-5" />}
label="系统运行"
value={systemInfo ? formatUptime(systemInfo.uptime) : '—'}
subtext={systemInfo ? `进程 ${formatUptime(systemInfo.processUptime)}` : undefined}
/>
</div>
{/* System metrics */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle>主机资源</CardTitle>
<CardDescription>
{systemInfo
? `${systemInfo.cpu.model.trim()} · ${systemInfo.cpu.cores} 核 · Node ${systemInfo.nodeVersion}`
: '正在采集主机信息…'}
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshSystem}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-3">
{/* CPU */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<Cpu className="size-4 text-primary" />
<span className="text-sm font-semibold">CPU 使用率</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.cpu.average.toFixed(1)}%` : '—'}
</span>
</div>
<Progress value={systemInfo?.cpu.average ?? 0} />
<p className="mt-2 text-[11px] text-muted-foreground">
负载: {systemInfo ? systemInfo.cpu.loadAvg.map((v) => v.toFixed(2)).join(' / ') : '—'}
</p>
{systemInfo && systemInfo.cpu.perCore.length > 0 && (
<div className="mt-3 grid grid-cols-8 gap-1">
{systemInfo.cpu.perCore.map((p, i) => (
<div
key={i}
title={`Core ${i}: ${p.toFixed(1)}%`}
className="h-6 rounded-sm bg-muted overflow-hidden flex items-end"
>
<div
className="w-full bg-primary/70 transition-[height] duration-500"
style={{ height: `${Math.max(4, p)}%` }}
/>
</div>
))}
</div>
)}
</div>
{/* Memory */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-2">
<MemoryStick className="size-4 text-primary" />
<span className="text-sm font-semibold">内存使用</span>
</div>
<span className="text-sm font-semibold tabular-nums text-primary">
{systemInfo ? `${systemInfo.memory.usagePercent.toFixed(1)}%` : '—'}
</span>
</div>
<Progress value={systemInfo?.memory.usagePercent ?? 0} />
<div className="mt-3 flex items-center justify-between text-[11px] text-muted-foreground tabular-nums">
<span>已用 {systemInfo ? formatBytes(systemInfo.memory.used) : '—'}</span>
<span>共 {systemInfo ? formatBytes(systemInfo.memory.total) : '—'}</span>
</div>
</div>
{/* GPU */}
<div className="rounded-lg border bg-card/40 p-4">
<div className="mb-2 flex items-center gap-2">
<HardDrive className="size-4 text-primary" />
<span className="text-sm font-semibold">显示适配器</span>
</div>
{!systemInfo ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
) : systemInfo.gpus.length === 0 ? (
<p className="text-xs text-muted-foreground">未检测到 GPU 信息</p>
) : (
<ul className="space-y-1.5">
{systemInfo.gpus.map((g, i) => (
<li key={i} className="rounded-md bg-background/60 px-2 py-1.5 text-xs">
<div className="truncate font-medium" title={g.name}>{g.name}</div>
{g.vendor && <div className="text-[10px] text-muted-foreground">{g.vendor}</div>}
</li>
))}
</ul>
)}
</div>
</CardContent>
</Card>
{/* QQ Processes */}
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<div>
<CardTitle>QQ 进程</CardTitle>
<CardDescription>
加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshProcesses}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
<CardContent>
{processActionStatus && (
<motion.div
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
className="mb-3 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-primary"
>
{processActionStatus}
</motion.div>
)}
{processList.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Cpu className="size-7" strokeWidth={1.5} />
<p className="text-sm">未检测到可加载 QQ 主进程</p>
</div>
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const busy = loading || unloading;
const isOnline = proc.status === 'online';
const canUnload =
proc.injected || proc.status === 'loaded' || isOnline || proc.status === 'disconnected';
return (
<motion.div
key={proc.pid}
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.03 + idx * 0.025, duration: 0.22 }}
className="flex items-center gap-3 rounded-lg border bg-card/50 p-3"
>
<div
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-lg',
isOnline
? 'bg-success/15 text-success'
: proc.status === 'error'
? 'bg-destructive/15 text-destructive'
: 'bg-primary/10 text-primary'
)}
>
{isOnline ? (
<CheckCircle2 className="size-5" />
) : proc.status === 'error' ? (
<AlertCircle className="size-5" />
) : (
<Cpu className="size-5" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-semibold">{proc.name || 'QQ.exe'}</span>
<Badge variant={processBadgeVariant(proc.status)}>{processStatusLabel[proc.status]}</Badge>
</div>
<div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground tabular-nums">
PID {proc.pid}
{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
</div>
{proc.path && (
<div className="truncate text-[11px] text-muted-foreground/80" title={proc.path}>
{proc.path}
</div>
)}
{proc.error && (
<div className="mt-0.5 truncate text-[11px] text-destructive" title={proc.error}>
{proc.error}
</div>
)}
</div>
<Button
size="sm"
variant={canUnload ? 'outline' : 'default'}
disabled={busy}
onClick={() =>
setConfirm({
kind: canUnload ? 'unload' : 'load',
pid: proc.pid,
name: proc.name || `PID ${proc.pid}`,
})
}
className={cn(
'shrink-0',
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
)}
>
{busy && <Loader2 className="size-3.5 animate-spin" />}
{!busy && canUnload && <Unplug className="size-3.5" />}
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
</Button>
</motion.div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* Online accounts */}
<Card>
<CardHeader>
<CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription>
</CardHeader>
<CardContent>
{qqList.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Users className="size-7" strokeWidth={1.5} />
<p className="text-sm">暂无在线会话</p>
</div>
) : (
<ScrollArea className="max-h-[420px]" viewportClassName="[&>div]:!block">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
{qqList.map((q, idx) => (
<motion.div
key={q.uin}
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.03 + idx * 0.04, duration: 0.22 }}
whileHover={{ y: -2 }}
className="flex items-center gap-3 rounded-lg border bg-card/40 p-3"
>
<Avatar size={40}>
<AvatarImage src={qqAvatarUrl(q.uin)} alt={q.nickname || q.uin} />
<AvatarFallback>{(q.nickname || q.uin).slice(0, 2)}</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{q.nickname}</div>
<div className="truncate font-mono text-[11px] text-muted-foreground tabular-nums">{q.uin}</div>
</div>
<span className="size-2 shrink-0 animate-pulse rounded-full bg-success shadow-[0_0_8px_color-mix(in_oklab,var(--success)_60%,transparent)]" />
</motion.div>
))}
</div>
</ScrollArea>
)}
</CardContent>
</Card>
<ConfirmDialog
open={!!confirm}
onOpenChange={(o) => !o && setConfirm(null)}
title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'}
description={
confirm
? confirm.kind === 'unload'
? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。`
: `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。`
: ''
}
confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'}
destructive={confirm?.kind === 'unload'}
onConfirm={async () => {
if (!confirm) return;
if (confirm.kind === 'unload') await onUnloadProcess(confirm.pid);
else await onLoadProcess(confirm.pid);
}}
/>
</div>
);
}
@@ -0,0 +1,285 @@
import { useState } from 'react';
import { motion } from 'motion/react';
import { Check, KeyRound, Loader2, Monitor, Moon, Sun } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import {
ACCENTS,
POLL_INTERVAL_OPTIONS,
RADIUS_OPTIONS,
useTheme,
type AccentColor,
type Density,
type ThemeMode,
} from '@/contexts/ThemeContext';
import {
ChangePasswordPage,
type PasswordRule,
} from '@/components/pages/change-password-page';
import { cn } from '@/lib/utils';
interface SettingsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
/** Called after successful logout (e.g. all-sessions invalidated). */
onLogout: () => void;
}
const MODE_OPTIONS: { value: ThemeMode; label: string; icon: typeof Sun }[] = [
{ value: 'light', label: '浅色', icon: Sun },
{ value: 'dark', label: '深色', icon: Moon },
{ value: 'system', label: '跟随系统', icon: Monitor },
];
const DENSITY_OPTIONS: { value: Density; label: string; description: string }[] = [
{ value: 'cozy', label: '舒适', description: '默认间距,阅读更轻松' },
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
];
export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
const {
mode, setMode,
accent, setAccent,
radius, setRadius,
density, setDensity,
pollInterval, setPollInterval,
} = useTheme();
const [showChangePwd, setShowChangePwd] = useState(false);
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
const checkStrength = async (password: string) => {
const res = await fetchApi('/api/auth/check-strength', {
method: 'POST',
body: JSON.stringify({ password }),
});
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
return { rules: data.rules ?? [], valid: !!data.valid };
};
const submitPwd = async (oldPassword: string, newPassword: string) => {
const res = await fetchApi('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ oldPassword, newPassword }),
});
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
return { success: !!data.success, message: data.message };
};
if (showChangePwd) {
return (
<ChangePasswordPage
forced={false}
checkStrength={checkStrength}
submit={submitPwd}
onSuccess={() => {
setShowChangePwd(false);
setPwdSavedAt(Date.now());
}}
onCancel={() => setShowChangePwd(false)}
/>
);
}
return (
<div className="flex flex-col gap-6">
{/* Appearance */}
<Card>
<CardHeader>
<CardTitle>外观</CardTitle>
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-6">
{/* Mode */}
<div className="flex flex-col gap-2">
<Label>显示模式</Label>
<div className="flex flex-wrap gap-2">
{MODE_OPTIONS.map((opt) => {
const Icon = opt.icon;
const active = mode === opt.value;
return (
<button
key={opt.value}
type="button"
onClick={() => setMode(opt.value)}
className={cn(
'flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors cursor-pointer',
active
? 'border-primary bg-primary/10 text-primary'
: 'border-border bg-background hover:bg-accent/40',
)}
>
<Icon className="size-4" />
{opt.label}
</button>
);
})}
</div>
</div>
<Separator />
{/* Accent color */}
<div className="flex flex-col gap-2">
<Label>强调色</Label>
<div className="flex flex-wrap gap-2">
{ACCENTS.map((spec) => {
const active = accent === spec.id;
return (
<button
key={spec.id}
type="button"
onClick={() => setAccent(spec.id as AccentColor)}
title={spec.label}
aria-label={spec.label}
className={cn(
'group relative flex h-9 w-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
)}
style={{ backgroundColor: spec.swatch }}
>
{active && (
<motion.span
initial={{ scale: 0.4, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="text-white drop-shadow-sm"
>
<Check className="size-4" strokeWidth={3} />
</motion.span>
)}
</button>
);
})}
</div>
<p className="text-[11px] text-muted-foreground">当前:{ACCENTS.find((a) => a.id === accent)?.label}</p>
</div>
<Separator />
{/* Radius */}
<div className="flex flex-col gap-2">
<Label>圆角</Label>
<div className="flex flex-wrap gap-2">
{RADIUS_OPTIONS.map((opt) => {
const active = Math.abs(radius - opt.value) < 1e-6;
return (
<button
key={opt.value}
type="button"
onClick={() => setRadius(opt.value)}
className={cn(
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
active
? 'border-primary bg-primary/10 text-primary'
: 'border-border bg-background hover:bg-accent/40',
)}
style={{ borderRadius: `${opt.value}rem` }}
>
{opt.label}({opt.value}rem)
</button>
);
})}
</div>
</div>
<Separator />
{/* Density */}
<div className="flex flex-col gap-2">
<Label>显示密度</Label>
<div className="grid gap-2 sm:grid-cols-2">
{DENSITY_OPTIONS.map((opt) => {
const active = density === opt.value;
return (
<button
key={opt.value}
type="button"
onClick={() => setDensity(opt.value)}
className={cn(
'flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors cursor-pointer',
active
? 'border-primary bg-primary/10'
: 'border-border bg-background hover:bg-accent/40',
)}
>
<span className="text-sm font-medium">{opt.label}</span>
<span className="text-[11px] text-muted-foreground">{opt.description}</span>
</button>
);
})}
</div>
</div>
</CardContent>
</Card>
{/* Behavior */}
<Card>
<CardHeader>
<CardTitle>数据刷新</CardTitle>
<CardDescription>控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-2">
<Label>轮询间隔</Label>
<div className="flex flex-wrap gap-2">
{POLL_INTERVAL_OPTIONS.map((opt) => {
const active = pollInterval === opt.value;
return (
<button
key={opt.value}
type="button"
onClick={() => setPollInterval(opt.value)}
className={cn(
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
active
? 'border-primary bg-primary/10 text-primary'
: 'border-border bg-background hover:bg-accent/40',
)}
>
{opt.label}
</button>
);
})}
</div>
<p className="text-[11px] text-muted-foreground">当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}</p>
</div>
</CardContent>
</Card>
{/* Account */}
<Card>
<CardHeader>
<CardTitle>账号安全</CardTitle>
<CardDescription>WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<Button
variant="outline"
onClick={() => setShowChangePwd(true)}
className="w-fit"
>
<KeyRound className="size-4" />
修改访问密码
</Button>
{pwdSavedAt && (
<span className="text-[11px] text-success">
密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。
</span>
)}
<Separator />
<div>
<p className="text-sm font-medium">退出登录</p>
<p className="mt-1 text-[11px] text-muted-foreground">立即清除当前浏览器的会话令牌。</p>
<Button variant="ghost" onClick={onLogout} className="mt-2 text-destructive hover:text-destructive">
<Loader2 className="size-4 hidden" />
退出登录
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,48 @@
import { Monitor, Moon, Sun } from 'lucide-react';
import { motion } from 'motion/react';
import { useTheme, type ThemeMode } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
const OPTIONS: { mode: ThemeMode; icon: typeof Sun; label: string }[] = [
{ mode: 'system', icon: Monitor, label: '跟随系统' },
{ mode: 'light', icon: Sun, label: '浅色' },
{ mode: 'dark', icon: Moon, label: '深色' },
];
export function ThemeToggle({ className }: { className?: string }) {
const { mode, setMode } = useTheme();
return (
<div
className={cn(
'relative inline-flex items-center gap-0.5 rounded-full border bg-card/60 p-0.5 shadow-xs',
className
)}
>
{OPTIONS.map(({ mode: m, icon: Icon, label }) => {
const active = mode === m;
return (
<button
key={m}
type="button"
title={label}
aria-label={label}
onClick={() => setMode(m)}
className={cn(
'relative flex size-7 items-center justify-center rounded-full transition-colors cursor-pointer',
active ? 'text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
)}
>
{active && (
<motion.span
layoutId="theme-toggle-pill"
className="absolute inset-0 rounded-full bg-primary"
transition={{ type: 'spring', stiffness: 380, damping: 30 }}
/>
)}
<Icon className="relative z-10 size-3.5" />
</button>
);
})}
</div>
);
}
@@ -1,30 +0,0 @@
import type { ReactNode } from 'react';
import { X } from 'lucide-react';
import { motion } from 'framer-motion';
interface EndpointRowProps {
onRemove: () => void;
children: ReactNode;
}
export function EndpointRow({ onRemove, children }: EndpointRowProps) {
return (
<div
className="flex items-end gap-3 px-5 py-4"
style={{ borderBottom: '1px solid var(--border-subtle)', transition: 'var(--transition-fast)' }}
>
{children}
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={onRemove}
className="size-7 shrink-0 flex items-center justify-center rounded-lg cursor-pointer mb-0.5"
style={{ color: 'var(--text-tertiary)', transition: 'var(--transition-fast)' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'rgba(248,113,113,0.08)'; }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-tertiary)'; e.currentTarget.style.background = 'transparent'; }}
>
<X size={14} />
</motion.button>
</div>
);
}
@@ -1,34 +0,0 @@
interface FieldInputProps {
label: string;
placeholder?: string;
value?: string | number;
isNum?: boolean;
flex?: string;
grow?: boolean;
onChange: (v: string | number) => void;
}
export function FieldInput({ label, placeholder, value, isNum, flex, grow, onChange }: FieldInputProps) {
return (
<div className={`flex flex-col gap-1.5 ${grow ? 'flex-1' : flex || ''}`}>
<label className="text-xs font-medium pl-0.5" style={{ color: 'var(--text-secondary)' }}>{label}</label>
<input
type={isNum ? 'number' : 'text'}
placeholder={placeholder}
value={value ?? ''}
onChange={e => onChange(isNum ? (parseInt(e.target.value) || 0) : e.target.value)}
className="h-9 px-3 rounded-lg text-sm outline-none"
style={{
background: 'rgba(0,0,0,0.12)',
border: '1px solid var(--border-subtle)',
boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.05)',
color: 'var(--text-primary)',
transition: 'all 0.3s ease',
...(isNum ? { fontVariantNumeric: 'tabular-nums', fontFamily: 'var(--font-mono, monospace)' } : {}),
}}
onFocus={e => { e.target.style.borderColor = 'var(--border-focus)'; e.target.style.boxShadow = '0 0 0 2px var(--accent-subtle)'; }}
onBlur={e => { e.target.style.borderColor = 'var(--border-subtle)'; e.target.style.boxShadow = 'inset 0 2px 4px rgba(0,0,0,0.05)'; }}
/>
</div>
);
}
@@ -1,55 +0,0 @@
import type { ReactNode } from 'react';
import { Plus } from 'lucide-react';
import { motion } from 'framer-motion';
import { useTheme } from '../../contexts/ThemeContext';
interface SectionCardProps {
title: string;
onAdd: () => void;
children: ReactNode;
}
export function SectionCard({ title, onAdd, children }: SectionCardProps) {
const { resolved } = useTheme();
const dark = resolved === 'dark';
return (
<div
className="rounded-xl overflow-hidden relative"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: dark
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
transition: 'var(--transition-base)',
}}
>
{/* Header */}
<div
className="flex items-center justify-between px-5 py-3"
style={{ borderBottom: '1px solid var(--border-subtle)' }}
>
<h3 className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>{title}</h3>
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={onAdd}
className="size-7 flex items-center justify-center rounded-lg cursor-pointer"
style={{ color: 'var(--text-secondary)', transition: 'var(--transition-fast)' }}
>
<Plus size={14} />
</motion.button>
</div>
{/* Body */}
<div>
{!children ? (
<p className="text-xs px-5 py-6 text-center" style={{ color: 'var(--text-tertiary)' }}>未配置,点击 + 新增</p>
) : children}
</div>
</div>
);
}
@@ -1,61 +0,0 @@
import type { ReactNode } from 'react';
import { motion } from 'framer-motion';
import { useTheme } from '../../contexts/ThemeContext';
interface StatCardProps {
label: string;
value: string;
icon?: ReactNode;
accent?: 'default' | 'success' | 'warning' | 'danger';
}
const accentColors: Record<string, { icon: string; value: string; glow: string }> = {
default: { icon: 'var(--accent)', value: 'var(--text-primary)', glow: 'var(--accent-glow)' },
success: { icon: 'var(--color-success)', value: 'var(--color-success)', glow: 'rgba(52,211,153,0.1)' },
warning: { icon: 'var(--color-warning)', value: 'var(--color-warning)', glow: 'rgba(251,191,36,0.1)' },
danger: { icon: 'var(--color-danger)', value: 'var(--color-danger)', glow: 'rgba(248,113,113,0.1)' },
};
export function StatCard({ label, value, icon, accent = 'default' }: StatCardProps) {
const colors = accentColors[accent];
const { resolved } = useTheme();
const dark = resolved === 'dark';
return (
<motion.div
whileHover={{ y: -2 }}
transition={{ duration: 0.2 }}
className="relative rounded-xl p-5 group overflow-hidden"
style={{
background: dark ? 'rgba(8,12,19,0.4)' : 'rgba(255,255,255,0.4)',
border: '1px solid',
borderColor: dark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.8)',
backdropFilter: 'blur(32px) saturate(1.2)',
WebkitBackdropFilter: 'blur(32px) saturate(1.2)',
boxShadow: dark
? '0 8px 32px rgba(0,0,0,0.3), inset 0 1px 1px rgba(255,255,255,0.06)'
: '0 8px 24px rgba(15,23,42,0.04), inset 0 1px 1px rgba(255,255,255,0.5)',
transition: 'var(--transition-base)',
}}
>
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-medium uppercase tracking-wider" style={{ color: 'var(--text-secondary)' }}>
{label}
</span>
{icon && (
<div
className="size-8 rounded-lg flex items-center justify-center"
style={{ background: colors.glow, color: colors.icon }}
>
{icon}
</div>
)}
</div>
<div
className="text-2xl font-bold tracking-tight"
style={{ color: colors.value, fontVariantNumeric: 'tabular-nums' }}
>
{value}
</div>
</motion.div>
);
}
@@ -1,27 +0,0 @@
interface StatusBadgeProps {
status: string;
}
export function StatusBadge({ status }: StatusBadgeProps) {
const isOnline = status === '已连接';
const isConnecting = status === '连接中';
const dotColor = isOnline
? 'var(--color-success)'
: isConnecting
? 'var(--color-warning)'
: 'var(--text-tertiary)';
return (
<span
className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-medium"
style={{ color: dotColor, background: `color-mix(in srgb, ${dotColor} 10%, transparent)`, border: `1px solid color-mix(in srgb, ${dotColor} 20%, transparent)` }}
>
<span
className={`size-1.5 rounded-full shrink-0 ${isOnline ? 'animate-pulse' : ''}`}
style={{ background: dotColor }}
/>
{status}
</span>
);
}
@@ -0,0 +1,97 @@
import * as React from 'react';
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
import { cn } from '@/lib/utils';
import { buttonVariants } from '@/components/ui/button';
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
AlertDialogOverlay.displayName = 'AlertDialogOverlay';
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = 'AlertDialogContent';
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
);
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
);
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold', className)} {...props} />
));
AlertDialogTitle.displayName = 'AlertDialogTitle';
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
));
AlertDialogDescription.displayName = 'AlertDialogDescription';
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = 'AlertDialogAction';
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel ref={ref} className={cn(buttonVariants({ variant: 'outline' }), 'mt-0', className)} {...props} />
));
AlertDialogCancel.displayName = 'AlertDialogCancel';
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
@@ -0,0 +1,44 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
interface AvatarProps extends React.HTMLAttributes<HTMLDivElement> {
size?: number;
}
const Avatar = React.forwardRef<HTMLDivElement, AvatarProps>(
({ className, size = 36, style, ...props }, ref) => (
<div
ref={ref}
className={cn('relative inline-flex shrink-0 overflow-hidden rounded-full bg-muted', className)}
style={{ width: size, height: size, ...style }}
{...props}
/>
)
);
Avatar.displayName = 'Avatar';
const AvatarImage = React.forwardRef<HTMLImageElement, React.ImgHTMLAttributes<HTMLImageElement>>(
({ className, alt = '', ...props }, ref) => (
<img
ref={ref}
alt={alt}
className={cn('aspect-square size-full object-cover', className)}
referrerPolicy="no-referrer"
{...props}
/>
)
);
AvatarImage.displayName = 'AvatarImage';
const AvatarFallback = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>(
({ className, ...props }, ref) => (
<span
ref={ref}
className={cn('flex size-full items-center justify-center bg-muted text-xs font-medium text-muted-foreground', className)}
{...props}
/>
)
);
AvatarFallback.displayName = 'AvatarFallback';
export { Avatar, AvatarImage, AvatarFallback };
@@ -0,0 +1,28 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors',
{
variants: {
variant: {
default: 'border-transparent bg-primary/15 text-primary',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive/15 text-destructive',
success: 'border-transparent bg-success/15 text-success',
warning: 'border-transparent bg-warning/15 text-warning',
outline: 'border-border text-foreground',
},
},
defaultVariants: { variant: 'default' },
}
);
export interface BadgeProps extends React.HTMLAttributes<HTMLSpanElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <span className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };
@@ -0,0 +1,42 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring cursor-pointer",
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95',
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline: 'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-6',
icon: 'size-9',
'icon-sm': 'size-8',
},
},
defaultVariants: { variant: 'default', size: 'default' },
}
);
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return <Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />;
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };
+50
View File
@@ -0,0 +1,50 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('rounded-xl border bg-card text-card-foreground shadow-sm', className)}
{...props}
/>
)
);
Card.displayName = 'Card';
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex flex-col gap-1.5 p-5', className)} {...props} />
)
);
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('font-semibold tracking-tight text-base', className)} {...props} />
)
);
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
)
);
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-5 pt-0', className)} {...props} />
)
);
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center p-5 pt-0', className)} {...props} />
)
);
CardFooter.displayName = 'CardFooter';
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter };
@@ -0,0 +1,89 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = 'DialogOverlay';
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { showClose?: boolean }
>(({ className, children, showClose = true, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
className
)}
{...props}
>
{children}
{showClose && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring cursor-pointer">
<X className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = 'DialogContent';
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
);
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col-reverse sm:flex-row sm:justify-end gap-2', className)} {...props} />
);
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold leading-none tracking-tight', className)} {...props} />
));
DialogTitle.displayName = 'DialogTitle';
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
));
DialogDescription.displayName = 'DialogDescription';
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
@@ -0,0 +1,24 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, type, ...props }, ref) => (
<input
type={type}
ref={ref}
className={cn(
'flex h-9 w-full min-w-0 rounded-md border border-border bg-transparent px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none',
'file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium',
'placeholder:text-muted-foreground',
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
'disabled:cursor-not-allowed disabled:opacity-50',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20',
className
)}
{...props}
/>
)
);
Input.displayName = 'Input';
export { Input };
@@ -0,0 +1,17 @@
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cn } from '@/lib/utils';
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn('text-xs font-medium leading-none text-muted-foreground select-none', className)}
{...props}
/>
));
Label.displayName = 'Label';
export { Label };
@@ -0,0 +1,32 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
value?: number;
indicatorClassName?: string;
}
const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
({ className, value = 0, indicatorClassName, ...props }, ref) => {
const clamped = Math.max(0, Math.min(100, value));
return (
<div
ref={ref}
role="progressbar"
aria-valuenow={clamped}
aria-valuemin={0}
aria-valuemax={100}
className={cn('relative h-2 w-full overflow-hidden rounded-full bg-muted', className)}
{...props}
>
<div
className={cn('h-full rounded-full bg-primary transition-[width] duration-500 ease-out', indicatorClassName)}
style={{ width: `${clamped}%` }}
/>
</div>
);
}
);
Progress.displayName = 'Progress';
export { Progress };
@@ -0,0 +1,49 @@
import * as React from 'react';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import { cn } from '@/lib/utils';
interface ScrollAreaProps extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
viewportClassName?: string;
}
const ScrollArea = React.forwardRef<React.ElementRef<typeof ScrollAreaPrimitive.Root>, ScrollAreaProps>(
({ className, children, viewportClassName, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
className={cn('size-full rounded-[inherit] [&>div]:!block', viewportClassName)}
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollBar orientation="horizontal" />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
);
ScrollArea.displayName = 'ScrollArea';
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = 'vertical', ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
'flex touch-none select-none p-0.5 transition-colors',
orientation === 'vertical' && 'h-full w-2 border-l border-l-transparent',
orientation === 'horizontal' && 'h-2 w-full flex-col border-t border-t-transparent',
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border hover:bg-muted-foreground/40 transition-colors" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = 'ScrollBar';
export { ScrollArea, ScrollBar };
@@ -0,0 +1,23 @@
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '@/lib/utils';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
className
)}
{...props}
/>
));
Separator.displayName = 'Separator';
export { Separator };
@@ -0,0 +1,66 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
const SheetClose = DialogPrimitive.Close;
const SheetPortal = DialogPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
SheetOverlay.displayName = 'SheetOverlay';
const sheetVariants = cva(
'fixed z-50 gap-4 bg-card p-0 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 outline-none',
{
variants: {
side: {
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
left: 'inset-y-0 left-0 h-full w-3/4 max-w-xs border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
right: 'inset-y-0 right-0 h-full w-3/4 max-w-xs border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',
},
},
defaultVariants: { side: 'right' },
}
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
VariantProps<typeof sheetVariants> {
showClose?: boolean;
}
const SheetContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>, SheetContentProps>(
({ side = 'right', className, children, showClose = true, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<DialogPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
{showClose && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none cursor-pointer">
<X className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</SheetPortal>
)
);
SheetContent.displayName = 'SheetContent';
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay };
@@ -0,0 +1,8 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn('animate-pulse rounded-md bg-muted', className)} {...props} />;
}
export { Skeleton };
@@ -0,0 +1,28 @@
import * as React from 'react';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { cn } from '@/lib/utils';
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 6, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 overflow-hidden rounded-md border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-md',
'data-[state=delayed-open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=delayed-open]:fade-in-0',
className
)}
{...props}
/>
</TooltipPrimitive.Portal>
));
TooltipContent.displayName = 'TooltipContent';
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };