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

+3
View File
@@ -0,0 +1,3 @@
{
"webuiPort": 8080
}
+3 -3
View File
@@ -9,7 +9,7 @@ const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
webuiPort: 8080,
webuiPort: 5099,
};
export function loadRuntimeConfig(): RuntimeConfig {
@@ -22,7 +22,7 @@ export function loadRuntimeConfig(): RuntimeConfig {
}
const normalized: RuntimeConfig = {
webuiPort: normalizePort(loaded.webuiPort ?? 8080, 8080),
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
};
if (
@@ -43,7 +43,7 @@ function tryLoadRuntimeConfig(): RuntimeConfig | null {
if (!isObject(parsed)) return null;
return {
webuiPort: normalizePort(parsed.webuiPort ?? 8080, 8080),
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
};
} catch {
return null;
+5 -2
View File
@@ -20,11 +20,14 @@ async function main() {
bridgeManager.bind(ntqq);
oneBotManager.bind(bridgeManager);
if (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) {
if (
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
log.info('WebUI is enabled, starting...');
const { initWebUI } = await import('./webui/server');
initWebUI(runtimeConfig.webuiPort || 8080, oneBotManager, hookManager);
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
+161
View File
@@ -0,0 +1,161 @@
import fs from 'fs';
import path from 'path';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
const CONFIG_DIR = 'config';
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
const SCRYPT_KEYLEN = 64;
const SCRYPT_N = 16384; // cost
const SCRYPT_R = 8;
const SCRYPT_P = 1;
export interface WebuiAuthState {
passwordHash: string; // hex
passwordSalt: string; // hex
mustChangePassword: boolean;
generatedAt: string;
updatedAt: string;
}
export interface PasswordRule {
id: string;
label: string;
test: (pwd: string) => boolean;
}
export const PASSWORD_RULES: PasswordRule[] = [
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
];
export function evaluatePasswordRules(password: string): { id: string; label: string; met: boolean }[] {
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, met: r.test(password) }));
}
export function isStrongPassword(password: string): boolean {
return PASSWORD_RULES.every((r) => r.test(password));
}
function hashPassword(password: string, salt: Buffer): Buffer {
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
}
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function isValidState(value: unknown): value is WebuiAuthState {
if (!value || typeof value !== 'object') return false;
const v = value as Record<string, unknown>;
return (
typeof v.passwordHash === 'string' &&
typeof v.passwordSalt === 'string' &&
typeof v.mustChangePassword === 'boolean' &&
/^[0-9a-f]+$/i.test(v.passwordHash) &&
/^[0-9a-f]+$/i.test(v.passwordSalt)
);
}
function generateInitialState(initialPassword: string): WebuiAuthState {
const salt = randomBytes(16);
const hash = hashPassword(initialPassword, salt);
const now = new Date().toISOString();
return {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: true,
generatedAt: now,
updatedAt: now,
};
}
function atomicWrite(state: WebuiAuthState): void {
ensureConfigDir();
const tmp = WEBUI_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
// chmod again in case the file already existed with looser perms
try {
fs.chmodSync(tmp, 0o600);
} catch {
/* ignore */
}
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
}
export class WebuiAuth {
private state: WebuiAuthState;
private initialPlain: string | null;
private constructor(state: WebuiAuthState, initialPlain: string | null) {
this.state = state;
this.initialPlain = initialPlain;
}
static load(): WebuiAuth {
ensureConfigDir();
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
try {
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (isValidState(parsed)) {
return new WebuiAuth(parsed, null);
}
} catch {
/* fallthrough — regenerate */
}
}
const initialPassword = randomBytes(8).toString('hex');
const state = generateInitialState(initialPassword);
atomicWrite(state);
return new WebuiAuth(state, initialPassword);
}
/** Returns the auto-generated initial password if this is a fresh install, else null. */
takeInitialPassword(): string | null {
const p = this.initialPlain;
this.initialPlain = null;
return p;
}
mustChangePassword(): boolean {
return this.state.mustChangePassword;
}
verify(password: string): boolean {
if (typeof password !== 'string' || password.length === 0) return false;
try {
const salt = Buffer.from(this.state.passwordSalt, 'hex');
const expected = Buffer.from(this.state.passwordHash, 'hex');
const got = hashPassword(password, salt);
if (got.length !== expected.length) return false;
return timingSafeEqual(got, expected);
} catch {
return false;
}
}
/**
* Update password atomically. Throws if the new password fails strength rules.
* After success, mustChangePassword=false and the file is rewritten on disk.
*/
setPassword(newPassword: string): void {
if (!isStrongPassword(newPassword)) {
throw new Error('密码不符合强度要求');
}
const salt = randomBytes(16);
const hash = hashPassword(newPassword, salt);
const next: WebuiAuthState = {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: false,
generatedAt: this.state.generatedAt,
updatedAt: new Date().toISOString(),
};
atomicWrite(next);
this.state = next;
}
}
+42
View File
@@ -0,0 +1,42 @@
import net from 'net';
/**
* Probe whether a TCP port is bindable on the given host.
* Resolves to true when bind+listen succeed.
*/
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
const finalize = (ok: boolean) => {
if (settled) return;
settled = true;
try {
server.close(() => resolve(ok));
} catch {
resolve(ok);
}
};
server.once('error', () => finalize(false));
server.once('listening', () => finalize(true));
try {
server.listen(port, host);
} catch {
finalize(false);
}
});
}
/**
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
}
+292 -66
View File
@@ -8,29 +8,52 @@ import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
import type { OneBotConfig } from '../onebot/types';
import type { HookManager } from '../hook/hook-manager';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import os from 'os';
import { exec } from 'child_process';
import { promisify } from 'util';
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
import { findAvailablePort } from './port';
const execAsync = promisify(exec);
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Session token store: token -> expiry timestamp (24h)
const sessionTokens = new Map<string, number>();
interface SessionInfo {
expiresAt: number;
mustChangePassword: boolean;
}
// Login attempt tracker: ip -> { count, resetAt }
const sessionTokens = new Map<string, SessionInfo>();
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; // 15 minutes
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
// Endpoints that an auth-required-but-must-change-password session can still hit.
const MUST_CHANGE_ALLOWLIST = new Set([
'/api/status',
'/api/auth/state',
'/api/auth/check-strength',
'/api/auth/change-password',
'/api/logout',
]);
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
const UIN_REGEX = /^\d{5,12}$/;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
function purgeExpiredTokens() {
const now = Date.now();
for (const [token, expiry] of sessionTokens) {
if (now > expiry) sessionTokens.delete(token);
for (const [token, info] of sessionTokens) {
if (now > info.expiresAt) sessionTokens.delete(token);
}
}
@@ -42,90 +65,162 @@ async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentTy
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
headers: {
'User-Agent': 'SnowLuma WebUI',
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
},
});
if (!response.ok) {
throw new Error(`avatar upstream responded with ${response.status}`);
}
if (!response.ok) throw new Error(`avatar upstream responded with ${response.status}`);
const contentType = response.headers.get('content-type') || 'image/jpeg';
const body = new Uint8Array(await response.arrayBuffer());
return { body, contentType };
}
export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hookManager?: HookManager) {
export async function initWebUI(
desiredPort: number = 5099,
oneBotManager: OneBotManager,
hookManager?: HookManager,
): Promise<{ port: number }> {
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (initialPassword) {
log.info('=========================================');
log.info('WebUI 安全认证(首次启动,已生成临时密码)');
log.info('默认用户: admin');
log.info('临时密码: %s', initialPassword);
log.info('请使用该密码登录后立即设置强密码(≥10 位、含大小写、特殊符号、不含空格)');
log.info('=========================================');
} else if (auth.mustChangePassword()) {
log.warn('WebUI 仍未完成强制改密,登录后须立即修改密码。');
}
const app = new Hono();
// Generate random password (printed once at startup)
const randomPassword = randomBytes(8).toString('hex');
log.info(`=========================================`);
log.info(`WebUI 安全认证`);
log.info(`默认用户: admin`);
log.info(`临时密码: ${randomPassword}`);
log.info(`=========================================`);
// API Auth middleware
// ─── Auth middleware ─────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
if (c.req.path === '/api/login') {
return next();
}
const reqPath = c.req.path;
if (reqPath === '/api/login') return next();
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = c.req.query('token') ?? '';
const token = bearerToken || queryToken;
if (!token) {
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
}
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
purgeExpiredTokens();
const expiry = sessionTokens.get(token);
if (!expiry || Date.now() > expiry) {
const info = sessionTokens.get(token);
if (!info || Date.now() > info.expiresAt) {
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
}
if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) {
return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403);
}
c.set('sessionToken' as never, token);
await next();
});
// Login Endpoint with rate limiting
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
const ip = getClientIp(c.req.raw);
const now = Date.now();
const attempt = loginAttempts.get(ip);
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
const waitSec = Math.ceil((attempt.resetAt - now) / 1000);
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
let body: { password?: unknown };
try {
const { password } = await c.req.json();
if (password === randomPassword) {
loginAttempts.delete(ip);
purgeExpiredTokens();
const token = randomBytes(32).toString('hex');
sessionTokens.set(token, now + TOKEN_TTL_MS);
return c.json({ success: true, token });
}
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
}
loginAttempts.delete(ip);
purgeExpiredTokens();
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
return c.json({ success: true, token, mustChangePassword: mustChange });
});
app.post('/api/logout', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
if (token) sessionTokens.delete(token);
return c.json({ success: true });
});
app.get('/api/auth/state', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
const info = token ? sessionTokens.get(token) : undefined;
return c.json({
mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(),
});
});
app.post('/api/auth/check-strength', async (c) => {
let body: { password?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ rules: evaluatePasswordRules(''), valid: false });
}
const pwd = typeof body.password === 'string' ? body.password : '';
return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) });
});
app.post('/api/auth/change-password', async (c) => {
let body: { oldPassword?: unknown; newPassword?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : '';
const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '';
if (!auth.verify(oldPassword)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
if (!isStrongPassword(newPassword)) {
return c.json(
{ success: false, message: '新密码不符合强度要求', rules: evaluatePasswordRules(newPassword) },
400,
);
}
if (oldPassword === newPassword) {
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
}
try {
auth.setPassword(newPassword);
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400);
}
// Invalidate all other sessions; current keeps but loses must-change flag.
const currentToken = c.get('sessionToken' as never) as string | undefined;
for (const [tok, info] of sessionTokens) {
if (tok === currentToken) {
info.mustChangePassword = false;
sessionTokens.set(tok, info);
} else {
sessionTokens.delete(tok);
}
}
log.info('WebUI 密码已更新(强制改密流程完成)');
return c.json({ success: true });
});
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
app.get('/avatar/:uin', async (c) => {
const uin = c.req.param('uin');
if (!/^\d{5,12}$/.test(uin)) {
return c.text('invalid uin', 400);
}
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
const now = Date.now();
let cached = avatarCache.get(uin);
@@ -139,7 +234,6 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
if (!cached) return c.text('avatar unavailable', 502);
}
}
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
@@ -148,17 +242,123 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
});
});
// API Routes
app.get('/api/status', (c) => {
return c.json({ status: 'running' });
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
// Host system info
let lastCpuTimes: { idle: number; total: number }[] | null = null;
function sampleCpuLoad(): number[] {
const cpus = os.cpus();
const current = cpus.map((cpu) => {
const t = cpu.times;
const total = t.user + t.nice + t.sys + t.idle + t.irq;
return { idle: t.idle, total };
});
if (!lastCpuTimes || lastCpuTimes.length !== current.length) {
lastCpuTimes = current;
return current.map(() => 0);
}
const usage = current.map((cur, i) => {
const prev = lastCpuTimes![i];
const totalDiff = cur.total - prev.total;
const idleDiff = cur.idle - prev.idle;
if (totalDiff <= 0) return 0;
return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100));
});
lastCpuTimes = current;
return usage;
}
let cachedGpu: { name: string; vendor: string }[] | null = null;
let gpuFetchedAt = 0;
async function detectGpus(): Promise<{ name: string; vendor: string }[]> {
const now = Date.now();
if (cachedGpu && now - gpuFetchedAt < 60_000) return cachedGpu;
const platform = os.platform();
const result: { name: string; vendor: string }[] = [];
try {
if (platform === 'win32') {
const { stdout } = await execAsync('wmic path win32_VideoController get Name /value', {
timeout: 4000,
windowsHide: true,
});
for (const line of stdout.split(/\r?\n/)) {
const m = line.match(/^Name=(.+)$/);
if (m && m[1].trim()) result.push({ name: m[1].trim(), vendor: '' });
}
} else if (platform === 'linux') {
try {
const { stdout } = await execAsync('lspci -mm | grep -Ei "vga|3d|display"', { timeout: 4000 });
for (const line of stdout.split(/\r?\n/)) {
const parts = line.match(/"([^"]+)"\s+"([^"]+)"\s+"([^"]+)"/);
if (parts) result.push({ vendor: parts[2], name: parts[3] });
}
} catch {
try {
const { stdout } = await execAsync('nvidia-smi --query-gpu=name --format=csv,noheader', { timeout: 4000 });
for (const line of stdout.split(/\r?\n/)) {
if (line.trim()) result.push({ name: line.trim(), vendor: 'NVIDIA' });
}
} catch {
/* ignore */
}
}
} else if (platform === 'darwin') {
const { stdout } = await execAsync('system_profiler SPDisplaysDataType -json', { timeout: 5000 });
try {
const json = JSON.parse(stdout);
const list = json.SPDisplaysDataType ?? [];
for (const item of list) {
if (item._name) result.push({ name: item._name, vendor: item.spdisplays_vendor ?? '' });
}
} catch {
/* ignore */
}
}
} catch {
/* best-effort */
}
cachedGpu = result;
gpuFetchedAt = now;
return result;
}
app.get('/api/system', async (c) => {
const cpus = os.cpus();
const usage = sampleCpuLoad();
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const gpus = await detectGpus().catch(() => []);
return c.json({
hostname: os.hostname(),
platform: os.platform(),
arch: os.arch(),
release: os.release(),
uptime: os.uptime(),
processUptime: process.uptime(),
nodeVersion: process.version,
cpu: {
model: cpus[0]?.model ?? 'unknown',
cores: cpus.length,
speedMHz: cpus[0]?.speed ?? 0,
loadAvg: os.loadavg(),
perCore: usage,
average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0,
},
memory: {
total: totalMem,
free: freeMem,
used: usedMem,
usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0,
},
gpus,
});
});
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
const list = instances.map(inst => ({
uin: inst.uin,
nickname: inst.qqInfo.nickname
}));
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.qqInfo.nickname }));
return c.json({ list });
});
@@ -185,16 +385,16 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
try {
controller.close();
} catch {
/* ignore */
}
});
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
Connection: 'keep-alive',
},
});
});
@@ -211,7 +411,7 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
app.post('/api/processes/:pid/load', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0) {
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
@@ -225,7 +425,7 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
app.post('/api/processes/:pid/unload', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0) {
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
@@ -238,6 +438,7 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
const config = loadOneBotConfig(uin);
return c.json({ config });
});
@@ -245,7 +446,8 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
app.post('/api/config/:uin', async (c) => {
try {
const uin = c.req.param('uin');
const body = await c.req.json() as OneBotConfig;
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
const body = (await c.req.json()) as OneBotConfig;
saveOneBotConfig(uin, body);
const reloaded = oneBotManager.reloadConfig(uin);
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
@@ -259,14 +461,38 @@ export function initWebUI(port: number = 8080, oneBotManager: OneBotManager, hoo
}
});
// Serve static files generated by the React frontend
const staticRoot = path.join(__dirname, 'client');
// ─── Static frontend ─────────────────────────────────────────────────────
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
const staticRoot = path.resolve(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
serve({
fetch: app.fetch,
port
}, (info) => {
log.info(`WebUI server is listening on http://localhost:${info.port}`);
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/')) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8');
return c.html(html);
}
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
});
const finalPort = await findAvailablePort(desiredPort);
if (finalPort !== desiredPort) {
log.warn('端口 %d 已被占用,已自动改用 %d', desiredPort, finalPort);
}
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort }, (info) => {
log.info(`WebUI 服务监听 http://localhost:${info.port}`);
resolve();
});
});
return { port: finalPort };
}
+5 -2
View File
@@ -35,13 +35,16 @@ const runtimeDistFiles = ['package.json',
];
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node}` – NTQQ hook (Windows-only).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
const nativeFiles = [
`websocket-${targetTriple}.node`,
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),
...(targetPlatform === 'linux'
? [`snowluma-${targetTriple}.node`, `snowluma-${targetTriple}.so`]
: []),
];
// Fail fast if any expected native binary is missing from packages/runtime/native/.
+42 -1
View File
@@ -84,5 +84,46 @@ function loadAddon(): NativeAddon {
return mod.exports as unknown as NativeAddon;
}
const addon: NativeAddon = loadAddon();
// Local-only escape hatch: when SNOWLUMA_DEV_NO_NATIVE=1 is set, we return a
// stub addon that lets the process boot (so the WebUI / HTTP API can run on
// platforms without a prebuilt binary, e.g. darwin-arm64 dev machines). Any
// actual WebSocket parsing/serialization call will throw at use-time. This
// branch never triggers for normal users because the env var is opt-in.
function createStubAddon(reason: string): NativeAddon {
const fail = (): never => {
throw new Error(
`[snowluma/websocket] native addon is stubbed (${reason}). ` +
`Set SNOWLUMA_DEV_NO_NATIVE=0 (or unset) and provide the prebuilt binary to enable WebSocket I/O.`,
);
};
class StubParser {
constructor(_options: ParserOptions) {}
push(_chunk: Buffer): ParseResult {
return fail();
}
}
// eslint-disable-next-line no-console
console.warn(
`[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`,
);
return {
Parser: StubParser as unknown as NativeAddon['Parser'],
buildFrame: fail as unknown as NativeAddon['buildFrame'],
computeAcceptKey: fail as unknown as NativeAddon['computeAcceptKey'],
};
}
function tryLoad(): NativeAddon {
const devSkip = process.env.SNOWLUMA_DEV_NO_NATIVE === '1';
try {
return loadAddon();
} catch (err) {
if (devSkip) {
return createStubAddon((err as Error).message);
}
throw err;
}
}
const addon: NativeAddon = tryLoad();
export default addon;
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
+4 -3
View File
@@ -2,9 +2,10 @@
<html lang="zh-CN" class="light" data-theme="light">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SnowLuma</title>
<link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0ea5e9" />
<title>SnowLuma 控制台</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&display=swap" rel="stylesheet" />
+12 -6
View File
@@ -11,14 +11,21 @@
"preview": "vite preview"
},
"dependencies": {
"@heroui/react": "^3.0.2",
"@heroui/styles": "^3.0.2",
"@radix-ui/react-alert-dialog": "^1.1.7",
"@radix-ui/react-dialog": "^1.1.7",
"@radix-ui/react-label": "^2.1.3",
"@radix-ui/react-scroll-area": "^1.2.4",
"@radix-ui/react-separator": "^1.1.3",
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"framer-motion": "^12.38.0",
"lucide-react": "^1.8.0",
"lucide-react": "^0.469.0",
"motion": "^12.0.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"tailwind-merge": "^3.5.0"
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.2.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -31,7 +38,6 @@
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"sass": "^1.99.0",
"tailwindcss": "^4.2.2",
"typescript": "catalog:",
"typescript-eslint": "^8.58.2",
-469
View File
@@ -1,469 +0,0 @@
.layout {
display: flex;
height: 100vh;
width: 100%;
}
.sidebar {
width: 240px;
background: var(--bg-sidebar);
border-right: 1px solid var(--border-subtle);
display: flex;
flex-direction: column;
padding: 24px 0 0 0;
transition: background-color 0.3s;
}
.brand {
padding: 0 24px;
margin-bottom: 32px;
}
.brand h1 {
font-size: 1.3rem;
font-weight: 600;
color: var(--text-main);
background: linear-gradient(90deg, var(--color-primary), #818cf8);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
}
.nav-menu {
flex: 1;
padding: 0 16px;
display: flex;
flex-direction: column;
gap: 4px;
}
.nav-item {
padding: 10px 16px;
border-radius: var(--radius-md);
cursor: pointer;
color: var(--text-muted);
font-size: 0.9rem;
transition: all 0.2s;
}
.nav-item:hover {
background: var(--bg-hover);
color: var(--text-main);
}
.nav-item.active {
background: var(--color-primary);
color: #fff;
font-weight: 500;
}
.sidebar-footer {
padding: 16px;
border-top: 1px solid var(--border-subtle);
display: flex;
flex-direction: column;
gap: 8px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8px 16px;
border-radius: var(--radius-md);
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s;
outline: none;
font-family: inherit;
}
.btn-primary {
background: var(--color-primary);
color: #fff;
}
.btn-primary:hover {
background: var(--color-primary-hover);
}
.btn-ghost {
background: transparent;
color: var(--text-muted);
}
.btn-ghost:hover {
background: var(--bg-hover);
color: var(--text-main);
}
.btn-outline {
background: transparent;
border-color: var(--border-subtle);
color: var(--text-muted);
}
.btn-outline:hover {
background: var(--bg-hover);
color: var(--text-main);
}
.btn-danger {
background: transparent;
border-color: var(--border-subtle);
color: var(--color-danger);
}
.btn-danger:hover {
background: var(--color-danger);
border-color: var(--color-danger);
color: #fff;
}
.btn-icon {
padding: 4px;
width: 28px;
height: 28px;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--bg-body);
}
.header {
height: 60px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 32px;
background: var(--bg-card);
border-bottom: 1px solid var(--border-subtle);
}
.search-input {
background: var(--bg-input);
border: 1px solid var(--border-subtle);
padding: 8px 14px;
border-radius: var(--radius-sm);
color: var(--text-main);
width: 260px;
font-size: 0.85rem;
transition: border-color 0.2s;
}
.search-input:focus {
border-color: var(--color-primary);
}
.header-right {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.85rem;
color: var(--text-muted);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--text-muted);
}
.status-dot.on { background: #10b981; }
.status-dot.off { background: var(--color-danger); }
.main-scroll {
flex: 1;
overflow-y: auto;
padding: 32px;
}
.card {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
padding: 24px;
}
.overview-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 20px;
}
.overview-card {
display: flex;
flex-direction: column;
gap: 12px;
}
.card-label {
font-size: 0.85rem;
color: var(--text-muted);
}
.card-value {
font-size: 2rem;
font-weight: 600;
color: var(--text-main);
}
.status-ok {
color: #10b981;
}
/* Config Layout */
.config-layout {
display: flex;
gap: 24px;
align-items: flex-start;
}
.list-pane {
width: 280px;
padding: 16px;
}
.pane-title {
font-size: 0.95rem;
color: var(--text-main);
margin-bottom: 16px;
font-weight: 600;
}
.qq-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.qq-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px;
border-radius: var(--radius-md);
cursor: pointer;
transition: background 0.2s;
border: 1px solid transparent;
}
.qq-item:hover {
background: var(--bg-hover);
}
.qq-item.active {
background: var(--bg-hover);
border-color: var(--border-active);
}
.qq-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background: linear-gradient(135deg, var(--color-primary), #818cf8);
}
.qq-info {
display: flex;
flex-direction: column;
}
.qq-nik {
font-size: 0.9rem;
font-weight: 500;
color: var(--text-main);
}
.qq-uin {
font-size: 0.75rem;
color: var(--text-muted);
}
.editor-pane {
flex: 1;
min-height: 500px;
padding: 32px;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: var(--text-muted);
font-size: 0.9rem;
opacity: 0.7;
}
.empty-icon {
font-size: 2rem;
margin-bottom: 12px;
}
.editor-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 32px;
border-bottom: 1px solid var(--border-subtle);
padding-bottom: 16px;
}
.editor-title h2 {
font-size: 1.25rem;
color: var(--text-main);
margin-bottom: 4px;
}
.editor-subtitle {
font-size: 0.85rem;
color: var(--text-muted);
font-family: monospace;
}
.editor-actions {
display: flex;
align-items: center;
gap: 16px;
}
.save-status {
font-size: 0.85rem;
color: var(--text-muted);
}
.save-status.ok { color: #10b981; }
.cfg-section {
margin-bottom: 32px;
}
.cfg-section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.cfg-section-header h4 {
font-size: 1rem;
color: var(--text-main);
font-weight: 600;
}
.cfg-section-body {
display: flex;
flex-direction: column;
gap: 16px;
}
.endpoint-row {
display: flex;
align-items: center;
gap: 16px;
background: var(--bg-input);
border: 1px solid var(--border-subtle);
padding: 16px;
border-radius: var(--radius-md);
}
.input-group {
display: flex;
flex-direction: column;
gap: 8px;
flex: 1;
}
.input-group label {
font-size: 0.8rem;
color: var(--text-muted);
}
.input-group input {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
padding: 8px 12px;
border-radius: var(--radius-sm);
color: var(--text-main);
font-family: monospace;
font-size: 0.85rem;
transition: border-color 0.2s;
outline: none;
}
.input-group input:focus {
border-color: var(--border-focus);
}
.endpoint-actions {
display: flex;
align-items: center;
margin-top: 24px;
}
.text-muted {
color: var(--text-muted);
font-size: 0.85rem;
}
/* Login Screen Override */
.login-screen {
position: fixed;
inset: 0;
z-index: 1000;
background: var(--bg-body);
display: flex;
justify-content: center;
align-items: center;
}
.login-card {
width: 380px;
display: flex;
flex-direction: column;
align-items: center;
padding: 40px;
}
.login-title {
font-size: 1.5rem;
color: var(--text-main);
margin-bottom: 12px;
background: linear-gradient(90deg, var(--color-primary), #818cf8);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
.login-desc {
font-size: 0.85rem;
color: var(--text-muted);
text-align: center;
margin-bottom: 32px;
}
.login-form {
width: 100%;
display: flex;
flex-direction: column;
gap: 20px;
}
.login-submit-btn {
width: 100%;
padding: 10px;
}
.login-error {
color: var(--color-danger);
font-size: 0.8rem;
text-align: center;
}
-2
View File
@@ -1,2 +0,0 @@
// Token layer only — component styles live in Tailwind classes inside TSX
@use './styles/variables';
+287 -170
View File
@@ -1,231 +1,348 @@
import { useState, useEffect } from 'react';
import { ThemeProvider } from './contexts/ThemeContext';
import { MainLayout } from './components/layout/MainLayout';
import { LoginPage } from './components/pages/LoginPage';
import { OverviewPage } from './components/pages/OverviewPage';
import { ConfigPage } from './components/pages/ConfigPage';
import { LogsPage } from './components/pages/LogsPage';
import type { QQInfo, OneBotConfig, HookProcessInfo } from './types';
import { useCallback, useEffect, useRef, useState } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
import { LoginPage } from '@/components/pages/login-page';
import { MainLayout } from '@/components/layout/main-layout';
import { OverviewPage } from '@/components/pages/overview-page';
import { ConfigPage } from '@/components/pages/config-page';
import { LogsPage } from '@/components/pages/logs-page';
import { SettingsPage } from '@/components/pages/settings-page';
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
import type { Page } from '@/components/layout/sidebar';
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
const fetchApi = async (url: string, options: RequestInit = {}) => {
const token = localStorage.getItem('snowluma_token');
const headers = new Headers(options.headers || {});
if (token) headers.set('Authorization', `Bearer ${token}`);
return fetch(url, { ...options, headers });
};
const TOKEN_KEY = 'snowluma_token';
function App() {
const [status, setStatus] = useState('连接中');
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(
import.meta.env.VITE_SKIP_AUTH === 'true' ? true : null
function readToken() {
return localStorage.getItem(TOKEN_KEY) || '';
}
export default function App() {
return (
<ThemeProvider>
<AppInner />
</ThemeProvider>
);
const [activePage, setActivePage] = useState<'总览' | '配置' | '日志'>('总览');
}
function AppInner() {
const { pollInterval } = useTheme();
const [authChecked, setAuthChecked] = useState(false);
const [authed, setAuthed] = useState(false);
const [mustChange, setMustChange] = useState(false);
const [status, setStatus] = useState('未连接');
const [active, setActive] = useState<Page>('overview');
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState('');
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const [config, setConfig] = useState<OneBotConfig | null>(null);
const [saveStatus, setSaveStatus] = useState('');
function checkStatus() {
fetchApi('/api/status')
.then(async (res) => {
if (res.status === 401) { setIsAuthenticated(false); setStatus('需要认证'); return; }
if (res.ok) {
setIsAuthenticated(true);
const data = await res.json();
setStatus(data.status === 'running' ? '已连接' : '已断开');
fetchQqList();
fetchProcesses();
return;
}
// Any other non-ok status (502, 500, etc.)
setIsAuthenticated(false);
setStatus('已断开');
})
.catch(() => { setStatus('已断开'); setIsAuthenticated(false); });
}
const tokenRef = useRef(readToken());
useEffect(() => {
if (import.meta.env.VITE_SKIP_AUTH !== 'true') checkStatus();
// ---------- API helpers ----------
const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => {
const headers: Record<string, string> = {
...(options.headers as Record<string, string> | undefined),
};
if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`;
if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...options, headers });
if (res.status === 401) {
tokenRef.current = '';
localStorage.removeItem(TOKEN_KEY);
setAuthed(false);
setStatus('未授权');
}
return res;
}, []);
useEffect(() => {
if (isAuthenticated !== true) return;
fetchQqList();
fetchProcesses();
const timer = window.setInterval(() => {
fetchQqList();
fetchProcesses();
}, 3000);
return () => window.clearInterval(timer);
}, [isAuthenticated]);
// ---------- Polling ----------
const refreshQqList = useCallback(async () => {
try {
const res = await fetchApi('/api/qq-list');
if (!res.ok) return;
const data = await res.json();
setQqList(data.list || []);
} catch (e) {
console.error('qq-list', e);
}
}, [fetchApi]);
const handleLogin = async (password: string) => {
const refreshProcesses = useCallback(async () => {
try {
const res = await fetchApi('/api/processes');
if (!res.ok) return;
const data = await res.json();
setProcessList(data.list || []);
} catch (e) {
console.error('processes', e);
}
}, [fetchApi]);
const refreshSystem = useCallback(async () => {
try {
const res = await fetchApi('/api/system');
if (!res.ok) return;
const data = (await res.json()) as SystemInfo;
setSystemInfo(data);
} catch (e) {
console.error('system', e);
}
}, [fetchApi]);
const checkStatus = useCallback(async () => {
try {
const res = await fetchApi('/api/status');
if (res.ok) {
setAuthed(true);
setStatus('已连接');
return true;
}
setStatus('未连接');
return false;
} catch {
setStatus('未连接');
return false;
}
}, [fetchApi]);
useEffect(() => {
(async () => {
if (tokenRef.current) {
const ok = await checkStatus();
if (ok) {
// Existing session may still need to change password.
try {
const r = await fetchApi('/api/auth/state');
if (r.ok) {
const d = await r.json();
setMustChange(!!d.mustChangePassword);
}
} catch { /* ignore */ }
}
}
setAuthChecked(true);
})();
}, [checkStatus, fetchApi]);
useEffect(() => {
if (!authed || mustChange) return;
if (pollInterval <= 0) return;
let cancelled = false;
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
};
tick();
const interval = setInterval(tick, pollInterval);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
// Auto-select first uin when navigating to config
useEffect(() => {
if (active !== 'config') return;
if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin);
}, [active, qqList, selectedUin]);
// Load config when selectedUin changes
useEffect(() => {
if (!selectedUin) {
setConfig(null);
return;
}
let cancelled = false;
(async () => {
try {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
if (!res.ok) return;
const data = await res.json();
if (cancelled) return;
setConfig({
httpServers: data.httpServers || [],
httpPostEndpoints: data.httpPostEndpoints || [],
wsServers: data.wsServers || [],
wsClients: data.wsClients || [],
musicSignUrl: data.musicSignUrl,
});
} catch (e) {
console.error('load-config', e);
}
})();
return () => {
cancelled = true;
};
}, [selectedUin, fetchApi]);
// ---------- Actions ----------
const handleLogin = useCallback(async (password: string) => {
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
const data = await res.json();
if (res.ok && data.success) {
localStorage.setItem('snowluma_token', data.token);
setIsAuthenticated(true);
checkStatus();
return { success: true };
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { success: false, error: data.message || data.error || '令牌错误' };
}
return { success: false, error: '认证失败,请检查控制台日志' };
} catch {
return { success: false, error: '内部错误,请检查后端运行状态' };
const data = await res.json();
const token = data.token as string;
localStorage.setItem(TOKEN_KEY, token);
tokenRef.current = token;
setMustChange(!!data.mustChangePassword);
const ok = await checkStatus();
return ok ? { success: true } : { success: false, error: '校验失败' };
} catch (e) {
return { success: false, error: (e as Error).message || '网络错误' };
}
};
}, [checkStatus]);
const handleLogout = () => {
localStorage.removeItem('snowluma_token');
setIsAuthenticated(false);
setStatus('需要认证');
const handleLogout = useCallback(async () => {
try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ }
localStorage.removeItem(TOKEN_KEY);
tokenRef.current = '';
setAuthed(false);
setMustChange(false);
setStatus('未连接');
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setSelectedUin(null);
setConfig(null);
};
}, [fetchApi]);
async function fetchQqList() {
try {
const res = await fetchApi('/api/qq-list');
if (res.ok) { const data = await res.json(); setQqList(data.list || []); }
} catch (err) { console.error(err); }
}
async function fetchProcesses() {
try {
const res = await fetchApi('/api/processes');
if (res.ok) { const data = await res.json(); setProcessList(data.list || []); }
} catch (err) { console.error(err); }
}
const loadProcess = async (pid: number) => {
const handleLoadProcess = useCallback(async (pid: number) => {
setProcessLoadingPid(pid);
setProcessActionStatus('正在手动映射加载 SnowLuma...');
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try {
const res = await fetchApi(`/api/processes/${pid}/load`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
setProcessActionStatus(res.ok && data.success ? '已开始监听登录状态' : data.message || '加载失败');
await fetchProcesses();
await fetchQqList();
} catch {
setProcessActionStatus('网络错误,加载失败');
if (!res.ok) throw new Error(data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`加载失败:${(e as Error).message}`);
} finally {
setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 3000);
setTimeout(() => setProcessActionStatus(''), 4000);
}
};
}, [fetchApi, refreshProcesses]);
const unloadProcess = async (pid: number) => {
const handleUnloadProcess = useCallback(async (pid: number) => {
setProcessUnloadingPid(pid);
setProcessActionStatus('正在卸载 SnowLuma...');
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try {
const res = await fetchApi(`/api/processes/${pid}/unload`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
setProcessActionStatus(res.ok && data.success ? '已卸载 SnowLuma' : data.message || '卸载失败');
await fetchProcesses();
await fetchQqList();
} catch {
setProcessActionStatus('网络错误,卸载失败');
if (!res.ok) throw new Error(data.error || '卸载失败');
setProcessActionStatus(`已从进程 ${pid} 卸载`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
} finally {
setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 3000);
setTimeout(() => setProcessActionStatus(''), 4000);
}
};
}, [fetchApi, refreshProcesses]);
const loadConfig = async (uin: string) => {
setSelectedUin(uin);
setSaveStatus('');
setConfig(null);
try {
const res = await fetchApi(`/api/config/${uin}`);
if (res.ok) { const data = await res.json(); setConfig(data.config); }
} catch (err) { console.error(err); }
};
const saveConfig = async () => {
const handleSaveConfig = useCallback(async () => {
if (!selectedUin || !config) return;
setSaveStatus('保存中...');
try {
const res = await fetchApi(`/api/config/${selectedUin}`, {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
});
setSaveStatus(res.ok ? '保存成功' : '保存出错');
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '保存失败');
setSaveStatus('保存成功');
} catch (e) {
setSaveStatus(`保存失败:${(e as Error).message}`);
} finally {
setTimeout(() => setSaveStatus(''), 3000);
} catch {
setSaveStatus('网络错误');
}
};
}, [selectedUin, config, fetchApi]);
// Loading state
if (isAuthenticated === null) {
// ---------- Render ----------
if (!authChecked) {
return (
<div className="h-screen flex items-center justify-center" style={{ background: 'var(--bg-body)' }}>
<div className="size-5 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--border-subtle)', borderTopColor: 'var(--accent)' }} />
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
初始化中…
</div>
);
}
// Login
if (isAuthenticated === false) {
return (
<ThemeProvider>
<LoginPage onLogin={handleLogin} />
</ThemeProvider>
);
}
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 };
};
// Main app
return (
<ThemeProvider>
<MainLayout activePage={activePage} onNavigate={setActivePage} status={status} onLogout={handleLogout}>
{activePage === '总览' && (
<OverviewPage
qqList={qqList}
status={status}
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processActionStatus={processActionStatus}
onRefreshProcesses={fetchProcesses}
onLoadProcess={loadProcess}
onUnloadProcess={unloadProcess}
/>
)}
{activePage === '配置' && (
<ConfigPage
qqList={qqList}
selectedUin={selectedUin}
config={config}
saveStatus={saveStatus}
onSelectAccount={loadConfig}
onSave={saveConfig}
onConfigChange={setConfig}
/>
)}
{activePage === '日志' && (
<LogsPage fetchApi={fetchApi} />
)}
</MainLayout>
</ThemeProvider>
<TooltipProvider delayDuration={150}>
{!authed ? (
<LoginPage onLogin={handleLogin} />
) : mustChange ? (
<ChangePasswordPage
forced
checkStrength={checkStrength}
submit={submitPwd}
onSuccess={() => setMustChange(false)}
/>
) : (
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
{active === 'overview' && (
<OverviewPage
qqList={qqList}
status={status}
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processActionStatus={processActionStatus}
systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess}
/>
)}
{active === 'config' && (
<ConfigPage
qqList={qqList}
selectedUin={selectedUin}
config={config}
saveStatus={saveStatus}
onSelectAccount={setSelectedUin}
onSave={handleSaveConfig}
onConfigChange={setConfig}
/>
)}
{active === 'logs' && <LogsPage fetchApi={fetchApi} />}
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
</MainLayout>
)}
</TooltipProvider>
);
}
export default App;
@@ -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 };
+136 -12
View File
@@ -1,27 +1,118 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
export type ThemeMode = 'light' | 'dark' | 'system';
export type AccentColor = 'sky' | 'blue' | 'violet' | 'rose' | 'emerald' | 'amber' | 'orange';
export type Density = 'cozy' | 'compact';
export interface AccentSpec {
id: AccentColor;
label: string;
swatch: string;
light: { primary: string; ring: string; sidebarPrimary: string; sidebarRing: string };
dark: { primary: string; ring: string; sidebarPrimary: string; sidebarRing: string };
}
export const ACCENTS: AccentSpec[] = [
{ id: 'sky', label: '天蓝', swatch: '#38bdf8',
light: { primary: 'oklch(68.5% 0.155 230)', ring: 'oklch(68.5% 0.155 230)', sidebarPrimary: 'oklch(68.5% 0.155 230)', sidebarRing: 'oklch(68.5% 0.155 230)' },
dark: { primary: 'oklch(75% 0.14 230)', ring: 'oklch(75% 0.14 230)', sidebarPrimary: 'oklch(75% 0.14 230)', sidebarRing: 'oklch(75% 0.14 230)' } },
{ id: 'blue', label: '靛蓝', swatch: '#3b82f6',
light: { primary: 'oklch(60% 0.18 258)', ring: 'oklch(60% 0.18 258)', sidebarPrimary: 'oklch(60% 0.18 258)', sidebarRing: 'oklch(60% 0.18 258)' },
dark: { primary: 'oklch(70% 0.16 258)', ring: 'oklch(70% 0.16 258)', sidebarPrimary: 'oklch(70% 0.16 258)', sidebarRing: 'oklch(70% 0.16 258)' } },
{ id: 'violet', label: '紫罗兰', swatch: '#8b5cf6',
light: { primary: 'oklch(60% 0.2 290)', ring: 'oklch(60% 0.2 290)', sidebarPrimary: 'oklch(60% 0.2 290)', sidebarRing: 'oklch(60% 0.2 290)' },
dark: { primary: 'oklch(72% 0.17 290)', ring: 'oklch(72% 0.17 290)', sidebarPrimary: 'oklch(72% 0.17 290)', sidebarRing: 'oklch(72% 0.17 290)' } },
{ id: 'rose', label: '玫瑰', swatch: '#f43f5e',
light: { primary: 'oklch(63% 0.21 18)', ring: 'oklch(63% 0.21 18)', sidebarPrimary: 'oklch(63% 0.21 18)', sidebarRing: 'oklch(63% 0.21 18)' },
dark: { primary: 'oklch(72% 0.18 18)', ring: 'oklch(72% 0.18 18)', sidebarPrimary: 'oklch(72% 0.18 18)', sidebarRing: 'oklch(72% 0.18 18)' } },
{ id: 'emerald', label: '翡翠', swatch: '#10b981',
light: { primary: 'oklch(64% 0.16 162)', ring: 'oklch(64% 0.16 162)', sidebarPrimary: 'oklch(64% 0.16 162)', sidebarRing: 'oklch(64% 0.16 162)' },
dark: { primary: 'oklch(74% 0.15 162)', ring: 'oklch(74% 0.15 162)', sidebarPrimary: 'oklch(74% 0.15 162)', sidebarRing: 'oklch(74% 0.15 162)' } },
{ id: 'amber', label: '琥珀', swatch: '#f59e0b',
light: { primary: 'oklch(72% 0.17 70)', ring: 'oklch(72% 0.17 70)', sidebarPrimary: 'oklch(72% 0.17 70)', sidebarRing: 'oklch(72% 0.17 70)' },
dark: { primary: 'oklch(78% 0.16 70)', ring: 'oklch(78% 0.16 70)', sidebarPrimary: 'oklch(78% 0.16 70)', sidebarRing: 'oklch(78% 0.16 70)' } },
{ id: 'orange', label: '夕橙', swatch: '#f97316',
light: { primary: 'oklch(67% 0.2 45)', ring: 'oklch(67% 0.2 45)', sidebarPrimary: 'oklch(67% 0.2 45)', sidebarRing: 'oklch(67% 0.2 45)' },
dark: { primary: 'oklch(74% 0.18 45)', ring: 'oklch(74% 0.18 45)', sidebarPrimary: 'oklch(74% 0.18 45)', sidebarRing: 'oklch(74% 0.18 45)' } },
];
export const RADIUS_OPTIONS = [
{ value: 0.375, label: '紧凑' },
{ value: 0.5, label: '默认' },
{ value: 0.75, label: '舒适' },
{ value: 1.0, label: '圆润' },
] as const;
export const POLL_INTERVAL_OPTIONS = [
{ value: 1000, label: '1 秒(实时)' },
{ value: 3000, label: '3 秒(默认)' },
{ value: 5000, label: '5 秒(节能)' },
{ value: 10000, label: '10 秒(省电)' },
{ value: 0, label: '已暂停' },
] as const;
interface ThemeContextValue {
mode: ThemeMode;
resolved: 'light' | 'dark';
setMode: (mode: ThemeMode) => void;
accent: AccentColor;
setAccent: (a: AccentColor) => void;
radius: number;
setRadius: (r: number) => void;
density: Density;
setDensity: (d: Density) => void;
pollInterval: number;
setPollInterval: (ms: number) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
const LS = {
mode: 'snowluma_theme',
accent: 'snowluma_accent',
radius: 'snowluma_radius',
density: 'snowluma_density',
poll: 'snowluma_poll_interval',
};
function getSystemTheme(): 'light' | 'dark' {
if (typeof window === 'undefined') return 'light';
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function readAccent(): AccentColor {
const v = localStorage.getItem(LS.accent);
if (v && ACCENTS.some((a) => a.id === v)) return v as AccentColor;
return 'sky';
}
function readRadius(): number {
const v = Number(localStorage.getItem(LS.radius));
if (Number.isFinite(v) && v > 0 && v <= 2) return v;
return 0.75;
}
function readDensity(): Density {
return localStorage.getItem(LS.density) === 'compact' ? 'compact' : 'cozy';
}
function readPoll(): number {
const raw = localStorage.getItem(LS.poll);
if (raw === null) return 3000;
const v = Number(raw);
if (Number.isFinite(v) && v >= 0 && v <= 60_000) return v;
return 3000;
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [mode, setModeState] = useState<ThemeMode>(() => {
const saved = localStorage.getItem('snowluma_theme') as ThemeMode | null;
const saved = localStorage.getItem(LS.mode) as ThemeMode | null;
if (saved === 'light' || saved === 'dark' || saved === 'system') return saved;
return 'system';
});
const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme);
const [accent, setAccentState] = useState<AccentColor>(readAccent);
const [radius, setRadiusState] = useState<number>(readRadius);
const [density, setDensityState] = useState<Density>(readDensity);
const [pollInterval, setPollIntervalState] = useState<number>(readPoll);
useEffect(() => {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
@@ -34,21 +125,54 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const root = document.documentElement;
root.className = resolved;
root.classList.remove('light', 'dark');
root.classList.add(resolved);
root.setAttribute('data-theme', resolved);
root.style.colorScheme = resolved;
}, [resolved]);
const setMode = (m: ThemeMode) => {
setModeState(m);
localStorage.setItem('snowluma_theme', m);
};
useEffect(() => {
document.documentElement.setAttribute('data-density', density);
}, [density]);
return (
<ThemeContext value={{ mode, resolved, setMode }}>
{children}
</ThemeContext>
useEffect(() => {
const styleId = 'snowluma-theme-overrides';
let el = document.getElementById(styleId) as HTMLStyleElement | null;
if (!el) {
el = document.createElement('style');
el.id = styleId;
document.head.appendChild(el);
}
const spec = ACCENTS.find((a) => a.id === accent) ?? ACCENTS[0];
el.textContent = `
:root {
--radius: ${radius}rem;
--primary: ${spec.light.primary};
--ring: ${spec.light.ring};
--sidebar-primary: ${spec.light.sidebarPrimary};
--sidebar-ring: ${spec.light.sidebarRing};
}
.dark {
--primary: ${spec.dark.primary};
--ring: ${spec.dark.ring};
--sidebar-primary: ${spec.dark.sidebarPrimary};
--sidebar-ring: ${spec.dark.sidebarRing};
}
`.trim();
}, [accent, radius]);
const setMode = (m: ThemeMode) => { setModeState(m); localStorage.setItem(LS.mode, m); };
const setAccent = (a: AccentColor) => { setAccentState(a); localStorage.setItem(LS.accent, a); };
const setRadius = (r: number) => { setRadiusState(r); localStorage.setItem(LS.radius, String(r)); };
const setDensity = (d: Density) => { setDensityState(d); localStorage.setItem(LS.density, d); };
const setPollInterval = (ms: number) => { setPollIntervalState(ms); localStorage.setItem(LS.poll, String(ms)); };
const value = useMemo<ThemeContextValue>(
() => ({ mode, resolved, setMode, accent, setAccent, radius, setRadius, density, setDensity, pollInterval, setPollInterval }),
[mode, resolved, accent, radius, density, pollInterval],
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
@@ -0,0 +1,18 @@
import { useEffect, useState } from 'react';
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => {
if (typeof window === 'undefined') return false;
return window.matchMedia(query).matches;
});
useEffect(() => {
const mq = window.matchMedia(query);
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
setMatches(mq.matches);
mq.addEventListener('change', handler);
return () => mq.removeEventListener('change', handler);
}, [query]);
return matches;
}
+154 -68
View File
@@ -1,78 +1,164 @@
@import "tailwindcss";
@import "tw-animate-css";
/* ── Global Reset & Base ── */
@custom-variant dark (&:where(.dark, .dark *));
/* ──────────────────────────────────────────────
Theme tokens (sky-blue accent)
────────────────────────────────────────────── */
:root {
color-scheme: light dark;
--radius: 0.75rem;
--background: oklch(99% 0.004 240);
--foreground: oklch(20% 0.03 250);
--card: oklch(100% 0 0);
--card-foreground: oklch(20% 0.03 250);
--popover: oklch(100% 0 0);
--popover-foreground: oklch(20% 0.03 250);
/* sky-500 */
--primary: oklch(68.5% 0.155 230);
--primary-foreground: oklch(99% 0.005 240);
--secondary: oklch(96% 0.012 240);
--secondary-foreground: oklch(25% 0.03 250);
--muted: oklch(96% 0.012 240);
--muted-foreground: oklch(50% 0.02 250);
--accent: oklch(94% 0.03 230);
--accent-foreground: oklch(35% 0.07 230);
--destructive: oklch(60% 0.22 27);
--destructive-foreground: oklch(99% 0.005 240);
--success: oklch(70% 0.15 160);
--warning: oklch(78% 0.16 80);
--border: oklch(92% 0.01 240);
--input: oklch(94% 0.012 240);
--ring: oklch(68.5% 0.155 230);
--sidebar: oklch(98% 0.006 240);
--sidebar-foreground: oklch(25% 0.03 250);
--sidebar-primary: oklch(68.5% 0.155 230);
--sidebar-primary-foreground: oklch(99% 0.005 240);
--sidebar-accent: oklch(94% 0.025 230);
--sidebar-accent-foreground: oklch(35% 0.08 230);
--sidebar-border: oklch(92% 0.01 240);
--sidebar-ring: oklch(68.5% 0.155 230);
}
/* ── HeroUI Avatar base ── */
.avatar {
position: relative;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: 9999px;
flex-shrink: 0;
}
.avatar__image {
width: 100%;
height: 100%;
object-fit: cover;
aspect-ratio: 1 / 1;
}
.avatar__fallback {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
.dark {
--background: oklch(16% 0.02 250);
--foreground: oklch(96% 0.01 240);
--card: oklch(20% 0.025 250);
--card-foreground: oklch(96% 0.01 240);
--popover: oklch(20% 0.025 250);
--popover-foreground: oklch(96% 0.01 240);
--primary: oklch(75% 0.14 230);
--primary-foreground: oklch(15% 0.02 250);
--secondary: oklch(25% 0.025 250);
--secondary-foreground: oklch(96% 0.01 240);
--muted: oklch(24% 0.02 250);
--muted-foreground: oklch(68% 0.02 240);
--accent: oklch(28% 0.05 230);
--accent-foreground: oklch(85% 0.1 230);
--destructive: oklch(62% 0.2 27);
--destructive-foreground: oklch(98% 0.005 240);
--success: oklch(72% 0.15 160);
--warning: oklch(80% 0.16 80);
--border: oklch(28% 0.02 250);
--input: oklch(26% 0.02 250);
--ring: oklch(75% 0.14 230);
--sidebar: oklch(18% 0.022 250);
--sidebar-foreground: oklch(92% 0.01 240);
--sidebar-primary: oklch(75% 0.14 230);
--sidebar-primary-foreground: oklch(15% 0.02 250);
--sidebar-accent: oklch(28% 0.05 230);
--sidebar-accent-foreground: oklch(85% 0.1 230);
--sidebar-border: oklch(26% 0.02 250);
--sidebar-ring: oklch(75% 0.14 230);
}
body {
margin: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif;
line-height: 1.5;
color: var(--text-primary);
background-color: var(--bg-body);
transition: background-color 0.3s ease, color 0.3s ease;
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-success: var(--success);
--color-warning: var(--warning);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
}
#root {
width: 100%;
height: 100%;
@layer base {
* {
border-color: var(--border);
}
html, body, #root {
height: 100%;
}
body {
margin: 0;
background-color: var(--background);
color: var(--foreground);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
line-height: 1.5;
}
::selection {
background-color: color-mix(in oklab, var(--primary) 28%, transparent);
color: var(--foreground);
}
/* Density: compact tightens the global rhythm a touch. */
html[data-density="compact"] body {
font-size: 13.5px;
line-height: 1.45;
}
html[data-density="compact"] {
--tw-leading: 1.4;
}
}
* {
box-sizing: border-box;
}
h1, h2, h3, h4, p {
margin: 0;
}
/* ── Scrollbar ── */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
/* ── Selection ── */
::selection {
background: rgba(56, 189, 248, 0.25);
color: #f1f5f9;
}
+26
View File
@@ -0,0 +1,26 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatBytes(bytes: number, decimals = 1): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
const v = bytes / Math.pow(1024, i);
return `${v.toFixed(decimals)} ${units[i]}`;
}
export function formatUptime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds <= 0) return '0 秒';
const d = Math.floor(seconds / 86400);
const h = Math.floor((seconds % 86400) / 3600);
const m = Math.floor((seconds % 3600) / 60);
const parts: string[] = [];
if (d) parts.push(`${d} 天`);
if (h) parts.push(`${h} 时`);
if (m || (!d && !h)) parts.push(`${m} 分`);
return parts.join(' ');
}
+6 -7
View File
@@ -1,11 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './App.scss'
import App from './App.tsx'
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.tsx';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
</StrictMode>
);
-30
View File
@@ -1,30 +0,0 @@
// Responsive breakpoint mixins
@mixin sm {
@media (min-width: 640px) { @content; }
}
@mixin md {
@media (min-width: 768px) { @content; }
}
@mixin lg {
@media (min-width: 1024px) { @content; }
}
// Flex shortcuts
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin flex-between {
display: flex;
align-items: center;
justify-content: space-between;
}
@mixin flex-col {
display: flex;
flex-direction: column;
}
-103
View File
@@ -1,103 +0,0 @@
// SnowLuma – Refined dark-first glassmorphism design system
// Palette: deep navy base, cool slate surfaces, cyan/indigo accent pair
:root {
// Typography
--font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', ui-monospace, monospace;
// Radii
--radius-xs: 6px;
--radius-sm: 8px;
--radius-md: 12px;
--radius-lg: 16px;
--radius-xl: 20px;
--radius-2xl: 24px;
--radius-full: 9999px;
// Transitions
--transition-fast: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
--transition-base: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
--transition-smooth: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
// Dark theme (default)
:root,
[data-theme='dark'],
.dark {
--bg-body: #080b12;
--bg-surface: rgba(15, 19, 28, 0.85);
--bg-card: rgba(20, 26, 38, 0.7);
--bg-card-hover: rgba(28, 35, 50, 0.8);
--bg-input: rgba(12, 16, 24, 0.8);
--bg-hover: rgba(99, 179, 237, 0.06);
--bg-active: rgba(99, 179, 237, 0.12);
--border-subtle: rgba(255, 255, 255, 0.06);
--border-medium: rgba(255, 255, 255, 0.1);
--border-focus: rgba(56, 189, 248, 0.5);
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--text-tertiary: #475569;
--text-accent: #7dd3fc;
--accent: #38bdf8;
--accent-hover: #7dd3fc;
--accent-subtle: rgba(56, 189, 248, 0.1);
--accent-glow: rgba(56, 189, 248, 0.15);
--color-success: #34d399;
--color-warning: #fbbf24;
--color-danger: #f87171;
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.3);
--shadow-md: 0 8px 32px rgba(0, 0, 0, 0.4);
--shadow-lg: 0 24px 64px rgba(0, 0, 0, 0.5);
--shadow-glow: 0 0 40px rgba(56, 189, 248, 0.08);
--shadow-focus: 0 0 0 3px rgba(56, 189, 248, 0.2);
--glass-bg: rgba(15, 19, 28, 0.75);
--glass-border: rgba(255, 255, 255, 0.08);
--glass-highlight: rgba(255, 255, 255, 0.04);
}
// Light theme
[data-theme='light'],
.light {
--bg-body: #f8fafc;
--bg-surface: rgba(255, 255, 255, 0.85);
--bg-card: rgba(255, 255, 255, 0.9);
--bg-card-hover: rgba(248, 250, 252, 1);
--bg-input: rgba(241, 245, 249, 0.9);
--bg-hover: rgba(14, 165, 233, 0.05);
--bg-active: rgba(14, 165, 233, 0.1);
--border-subtle: rgba(0, 0, 0, 0.06);
--border-medium: rgba(0, 0, 0, 0.1);
--border-focus: rgba(14, 165, 233, 0.5);
--text-primary: #0f172a;
--text-secondary: #64748b;
--text-tertiary: #94a3b8;
--text-accent: #0284c7;
--accent: #0ea5e9;
--accent-hover: #0284c7;
--accent-subtle: rgba(14, 165, 233, 0.08);
--accent-glow: rgba(14, 165, 233, 0.1);
--color-success: #10b981;
--color-warning: #f59e0b;
--color-danger: #ef4444;
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.05);
--shadow-md: 0 8px 24px rgba(0, 0, 0, 0.08);
--shadow-lg: 0 16px 48px rgba(0, 0, 0, 0.1);
--shadow-glow: 0 0 40px rgba(14, 165, 233, 0.05);
--shadow-focus: 0 0 0 3px rgba(14, 165, 233, 0.15);
--glass-bg: rgba(255, 255, 255, 0.8);
--glass-border: rgba(255, 255, 255, 0.6);
--glass-highlight: rgba(255, 255, 255, 0.5);
}
@@ -1,402 +0,0 @@
// Config styles — now handled via Tailwind + CSS vars in components
&.active {
background: var(--color-primary-subtle);
border-color: var(--border-focus);
.qq-nik {
color: var(--color-primary);
}
}
}
.qq-avatar {
width: 38px;
height: 38px;
border-radius: 50%;
background: linear-gradient(135deg, var(--color-primary) 0%, #818cf8 100%);
flex-shrink: 0;
box-shadow: 0 2px 8px rgba(14, 165, 233, 0.28);
}
.qq-info {
@include flex-col;
gap: 2px;
}
.qq-nik {
font-size: 0.875rem;
font-weight: 600;
color: var(--text-main);
transition: color 0.15s;
}
.qq-uin {
font-size: 0.72rem;
color: var(--text-muted);
font-family: var(--font-mono);
}
// ---- Editor Pane ----
.editor-pane {
flex: 1;
min-height: 500px;
padding: 28px !important;
border-radius: var(--radius-lg) !important;
}
.empty-state {
@include flex-col;
@include flex-center;
height: 100%;
min-height: 380px;
color: var(--text-muted);
font-size: 0.875rem;
opacity: 0.5;
gap: 14px;
}
.editor-header {
@include flex-between;
align-items: flex-start;
margin-bottom: 24px;
padding-bottom: 20px;
border-bottom: 1px solid var(--border-subtle);
}
.editor-title {
h2 {
font-size: 1.1rem;
font-weight: 700;
color: var(--text-main);
margin-bottom: 6px;
letter-spacing: -0.01em;
}
}
.editor-subtitle {
font-size: 0.75rem;
color: var(--text-muted);
font-family: var(--font-mono);
background: var(--bg-input);
border: 1px solid var(--border-subtle);
padding: 2px 8px;
border-radius: var(--radius-xs);
display: inline-block;
}
.editor-actions {
display: flex;
align-items: center;
gap: 12px;
}
.save-status {
font-size: 0.8rem;
color: var(--text-muted);
padding: 4px 10px;
border-radius: var(--radius-xs);
background: var(--bg-input);
&.ok {
color: var(--color-success);
background: rgba(16, 185, 129, 0.1);
}
}
// ---- Config Sections ----
.editor-sections {
@include flex-col;
gap: 10px;
}
.cfg-section {
border-radius: var(--radius-md);
overflow: hidden;
border: 1px solid var(--border-subtle);
background: var(--bg-card);
}
.cfg-section-header {
@include flex-between;
padding: 13px 18px;
background: var(--bg-input);
border-bottom: 1px solid var(--border-subtle);
h4 {
font-size: 0.85rem;
color: var(--text-main);
font-weight: 600;
}
}
.cfg-section-body {
@include flex-col;
gap: 0;
.text-muted {
padding: 16px 18px;
font-size: 0.82rem;
}
}
.endpoint-row {
display: flex;
align-items: flex-end;
gap: 12px;
padding: 14px 18px;
border-top: 1px solid var(--border-subtle);
transition: background 0.15s;
&:hover {
background: var(--bg-hover);
}
}
.endpoint-actions {
display: flex;
align-items: center;
padding-bottom: 1px;
}
.input-group {
@include flex-col;
gap: 6px;
flex: 1;
label {
font-size: 0.73rem;
color: var(--text-muted);
font-weight: 600;
letter-spacing: 0.03em;
text-transform: uppercase;
}
input {
background: var(--bg-input);
border: 1.5px solid var(--border-subtle);
padding: 8px 12px;
border-radius: var(--radius-sm);
color: var(--text-main);
font-family: var(--font-sans);
font-size: 0.85rem;
transition: var(--transition-fast);
outline: none;
width: 100%;
&::placeholder {
color: var(--text-placeholder);
}
&:focus {
border-color: var(--border-focus);
box-shadow: var(--shadow-focus);
background: var(--bg-card-solid);
}
&[type='number'] {
font-family: var(--font-mono);
}
}
}
.card-label {
font-size: 0.85rem;
color: var(--text-muted);
}
.card-value {
font-size: 2rem;
font-weight: 600;
color: var(--text-main);
&.status-ok {
color: #10b981;
}
}
// ---- Config Layout ----
.config-layout {
display: flex;
gap: 24px;
align-items: flex-start;
}
.list-pane {
width: 280px;
padding: 16px;
}
.pane-title {
font-size: 0.95rem;
color: var(--text-main);
margin-bottom: 16px;
font-weight: 600;
}
.qq-list {
@include flex-col;
gap: 8px;
}
.qq-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px;
border-radius: var(--radius-md);
cursor: pointer;
transition: background 0.2s;
border: 1px solid transparent;
&:hover {
background: var(--bg-hover);
}
&.active {
background: var(--bg-hover);
border-color: var(--border-active);
}
}
.qq-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background: linear-gradient(135deg, var(--color-primary), #818cf8);
flex-shrink: 0;
}
.qq-info {
@include flex-col;
}
.qq-nik {
font-size: 0.9rem;
font-weight: 500;
color: var(--text-main);
}
.qq-uin {
font-size: 0.75rem;
color: var(--text-muted);
}
// ---- Editor Pane ----
.editor-pane {
flex: 1;
min-height: 500px;
padding: 32px;
}
.empty-state {
@include flex-col;
@include flex-center;
height: 100%;
color: var(--text-muted);
font-size: 0.9rem;
opacity: 0.7;
gap: 12px;
}
.editor-header {
@include flex-between;
align-items: flex-start;
margin-bottom: 32px;
border-bottom: 1px solid var(--border-subtle);
padding-bottom: 16px;
}
.editor-title {
h2 {
font-size: 1.25rem;
color: var(--text-main);
margin-bottom: 4px;
}
}
.editor-subtitle {
font-size: 0.85rem;
color: var(--text-muted);
font-family: monospace;
}
.editor-actions {
display: flex;
align-items: center;
gap: 16px;
}
.save-status {
font-size: 0.85rem;
color: var(--text-muted);
&.ok {
color: #10b981;
}
}
// ---- Config Sections ----
.cfg-section {
margin-bottom: 32px;
}
.cfg-section-header {
@include flex-between;
margin-bottom: 16px;
h4 {
font-size: 1rem;
color: var(--text-main);
font-weight: 600;
}
}
.cfg-section-body {
@include flex-col;
gap: 16px;
}
.endpoint-row {
display: flex;
align-items: center;
gap: 16px;
background: var(--bg-input);
border: 1px solid var(--border-subtle);
padding: 16px;
border-radius: var(--radius-md);
}
.endpoint-actions {
display: flex;
align-items: center;
margin-top: 24px;
}
.input-group {
@include flex-col;
gap: 8px;
flex: 1;
label {
font-size: 0.8rem;
color: var(--text-muted);
}
input {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
padding: 8px 12px;
border-radius: var(--radius-sm);
color: var(--text-main);
font-family: monospace;
font-size: 0.85rem;
transition: border-color 0.2s;
outline: none;
&:focus {
border-color: var(--border-focus);
}
}
}
@@ -1,61 +0,0 @@
// Layout styles — now handled via Tailwind + CSS vars in components
.sidebar-footer {
padding: 12px;
border-top: 1px solid var(--border-subtle);
@include flex-col;
gap: 4px;
}
// ---- Main Content ----
.content {
flex: 1;
@include flex-col;
overflow: hidden;
min-width: 0;
}
.header {
height: 64px;
flex-shrink: 0;
@include flex-between;
padding: 0 32px;
background: var(--glass-bg);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
border-bottom: 1px solid var(--glass-border);
box-shadow: var(--shadow-xs);
z-index: 5;
}
.header-right {
@include flex-center;
gap: 8px;
font-size: 0.8rem;
color: var(--text-muted);
font-weight: 500;
letter-spacing: 0.01em;
}
.main-scroll {
flex: 1;
overflow-y: auto;
padding: 28px 32px;
&::-webkit-scrollbar {
width: 5px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: var(--border-subtle);
border-radius: var(--radius-full);
&:hover {
background: var(--text-muted);
}
}
}
@@ -1,264 +0,0 @@
// Shared styles — now handled via Tailwind + CSS vars in components
color: #fff;
box-shadow: 0 2px 8px rgba(14, 165, 233, 0.28);
&:hover {
background: var(--color-primary-hover);
box-shadow: 0 4px 16px rgba(14, 165, 233, 0.38);
transform: translateY(-1px);
}
&:active {
transform: translateY(0);
}
}
.btn-ghost {
background: transparent;
color: var(--text-muted);
border-radius: var(--radius-md);
&:hover {
background: var(--bg-hover);
color: var(--text-main);
}
}
.btn-outline {
background: transparent;
border-color: var(--border-subtle);
color: var(--text-muted);
&:hover {
background: var(--bg-hover);
color: var(--text-main);
border-color: var(--border-active);
}
}
.btn-danger {
background: transparent;
border-color: var(--border-subtle);
color: var(--color-danger);
border-radius: var(--radius-sm);
&:hover {
background: var(--color-danger);
border-color: var(--color-danger);
color: #fff;
box-shadow: 0 2px 8px rgba(239, 68, 68, 0.28);
}
}
.btn-icon {
padding: 4px;
width: 28px;
height: 28px;
}
// ---- Login Screen ----
.login-screen {
position: fixed;
inset: 0;
z-index: 1000;
background: var(--bg-body);
background-image: var(--glass-body-gradient);
@include flex-center;
}
.login-card {
width: 400px;
@include flex-col;
align-items: center;
padding: 48px 40px;
border-radius: var(--radius-xl);
background: var(--bg-card);
backdrop-filter: blur(20px) saturate(1.8);
-webkit-backdrop-filter: blur(20px) saturate(1.8);
border: 1px solid var(--glass-border);
box-shadow: var(--shadow-lg);
}
.login-title {
font-size: 1.6rem;
font-weight: 700;
letter-spacing: -0.02em;
margin-bottom: 10px;
background: linear-gradient(135deg, var(--color-primary) 0%, #818cf8 100%);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
.login-desc {
font-size: 0.83rem;
color: var(--text-muted);
text-align: center;
line-height: 1.65;
margin-bottom: 32px;
}
.login-form {
width: 100%;
@include flex-col;
gap: 16px;
}
.login-submit-btn {
width: 100%;
padding: 10px;
}
.login-error {
color: var(--color-danger);
font-size: 0.8rem;
text-align: center;
padding: 8px 12px;
background: rgba(239, 68, 68, 0.08);
border-radius: var(--radius-sm);
}
// Search input (header)
.search-input {
background: var(--bg-input);
border: 1px solid var(--border-subtle);
padding: 8px 14px;
border-radius: var(--radius-sm);
color: var(--text-main);
width: 260px;
font-size: 0.85rem;
transition: border-color 0.2s;
outline: none;
&:focus {
border-color: var(--color-primary);
}
}
// Generic card
.card {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
padding: 24px;
}
// Muted helper
.text-muted {
color: var(--text-muted);
font-size: 0.85rem;
}
// ---- Shared Button System ----
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 16px;
border-radius: var(--radius-md);
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s;
outline: none;
font-family: inherit;
}
.btn-primary {
background: var(--color-primary);
color: #fff;
&:hover { background: var(--color-primary-hover); }
}
.btn-ghost {
background: transparent;
color: var(--text-muted);
&:hover {
background: var(--bg-hover);
color: var(--text-main);
}
}
.btn-outline {
background: transparent;
border-color: var(--border-subtle);
color: var(--text-muted);
&:hover {
background: var(--bg-hover);
color: var(--text-main);
}
}
.btn-danger {
background: transparent;
border-color: var(--border-subtle);
color: var(--color-danger);
&:hover {
background: var(--color-danger);
border-color: var(--color-danger);
color: #fff;
}
}
.btn-icon {
padding: 4px;
width: 28px;
height: 28px;
}
// ---- Login Screen ----
.login-screen {
position: fixed;
inset: 0;
z-index: 1000;
background: var(--bg-body);
@include flex-center;
}
.login-card {
width: 380px;
@include flex-col;
align-items: center;
padding: 40px;
}
.login-title {
font-size: 1.5rem;
margin-bottom: 12px;
background: linear-gradient(90deg, var(--color-primary), #818cf8);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
.login-desc {
font-size: 0.85rem;
color: var(--text-muted);
text-align: center;
margin-bottom: 32px;
}
.login-form {
width: 100%;
@include flex-col;
gap: 20px;
}
.login-submit-btn {
width: 100%;
padding: 10px;
}
.login-error {
color: var(--color-danger);
font-size: 0.8rem;
text-align: center;
}
-5
View File
@@ -1,5 +0,0 @@
@use 'variables';
@use 'mixins';
@use 'components/layout';
@use 'components/config';
@use 'components/shared';
+37
View File
@@ -1,3 +1,6 @@
export const APP_NAME = 'SnowLuma';
export const APP_VERSION = '0.1.0';
export interface QQInfo {
uin: string;
nickname: string;
@@ -55,3 +58,37 @@ export interface OneBotConfig {
wsClients: WsClientEndpoint[];
musicSignUrl?: string;
}
export interface SystemInfo {
hostname: string;
platform: string;
arch: string;
release: string;
uptime: number;
processUptime: number;
nodeVersion: string;
cpu: {
model: string;
cores: number;
speedMHz: number;
loadAvg: number[];
perCore: number[];
average: number;
};
memory: {
total: number;
free: number;
used: number;
usagePercent: number;
};
gpus: { name: string; vendor: string }[];
}
export interface LogEntry {
id: number;
time: string;
level: 'debug' | 'info' | 'success' | 'warn' | 'error';
scope: string;
message: string;
line: string;
}
+1
View File
@@ -11,6 +11,7 @@
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"paths": { "@/*": ["./src/*"] },
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
+15 -6
View File
@@ -1,20 +1,29 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [tailwindcss(), react()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
server: {
port: 5178,
strictPort: false,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
'/api': { target: 'http://localhost:5099', changeOrigin: true, ws: true },
'/avatar': { target: 'http://localhost:5099', changeOrigin: true },
},
},
build: {
// Emit into the monorepo-root dist/client so the bundled core can serve it via Hono.
outDir: '../../dist/client',
emptyOutDir: true
}
emptyOutDir: true,
},
});
+653 -1058
View File
File diff suppressed because it is too large. Load diff