feat(webui): appearance customization — theme/accent/background/fonts/a11y (phase 2)

Wires the Phase 1 store into a full appearance layer.

ThemeContext is rewritten to load/save UiAppearance from the server (with a
localStorage anti-flash cache + a one-time migration of the legacy per-browser
theme keys), apply ~12 dimensions to <html>, and theme the login page pre-auth.

New Settings controls (外观 / 数据与格式): free-hex accent (+ presets + apply
scope), dark intensity (soft / OLED black), sidebar style, background
(solid / gradient / uploaded image with opacity + blur), font presets, UI
scale, reduce-motion, high-contrast, default-collapsed sidebar, 12h/24h time
format (wired into logs + overview timestamps).

- index.html gains a pre-paint bootstrap script that applies the cached theme
  before the bundle mounts, eliminating the dark/OLED/scale FOUC.
- server saveUiConfig is now a section-level merge so appearance-only and
  layout-only saves never clobber each other.
- reduce-motion uses Framer MotionConfig; the background renders on a fixed
  layer revealed by transparent app roots; custom-accent hex and ui-scale are
  validated/clamped before use (localStorage-tamper hardening).

Verified across 2 adversarial review rounds (FOUC + CSS-injection + impure
state-updater + ref-staleness all fixed).
This commit is contained in:
DrSmoothl committed 2026-06-13 01:15:00 +08:00
1 parent 0b5087b410
commit ac1ffc46d3
9 files changed
+1028 -308

No files matched your search

@@ -6,6 +6,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { Sidebar } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
interface MainLayoutProps {
@@ -16,9 +17,16 @@ interface MainLayoutProps {
export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
const isMobile = !useMediaQuery('(min-width: 768px)');
const { appearance } = useTheme();
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
// An explicit per-browser toggle wins; otherwise fall back to the
// operator's `sidebarDefaultCollapsed` appearance preference.
const explicit = localStorage.getItem('snowluma_sidebar_collapsed');
if (explicit === '1') return true;
if (explicit === '0') return false;
return appearance.sidebarDefaultCollapsed;
});
const customBg = appearance.background.type !== 'none';
const [mobileOpen, setMobileOpen] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname });
@@ -27,7 +35,7 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
}, [collapsed]);
return (
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
<div className={cn('flex h-screen w-screen overflow-hidden text-foreground', customBg ? 'bg-transparent' : 'bg-background')}>
{/* Desktop sidebar */}
{!isMobile && (
<motion.aside
@@ -5,6 +5,8 @@ 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 { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
interface LoginPageProps {
@@ -12,6 +14,8 @@ interface LoginPageProps {
}
export function LoginPage({ onLogin }: LoginPageProps) {
const { appearance } = useTheme();
const customBg = appearance.background.type !== 'none';
const [password, setPassword] = useState('');
const [showPwd, setShowPwd] = useState(false);
const [error, setError] = useState('');
@@ -31,7 +35,7 @@ export function LoginPage({ onLogin }: LoginPageProps) {
};
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
<div className={cn('relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-8', customBg ? 'bg-transparent' : 'bg-background')}>
{/* Sky gradient backdrop */}
<div
className="pointer-events-none absolute inset-0"
@@ -10,6 +10,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry, LogLevel } from '@/types';
import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
const levelClass: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
@@ -22,15 +23,9 @@ const levelClass: Record<LogLevel, string> = {
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
/** Show a locale time when the backend sends an ISO timestamp (it does);
* fall back to the raw string otherwise so we never render "Invalid Date". */
function formatTime(t: string): string {
const d = new Date(t);
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
}
export function LogsPage() {
const api = useApi();
const { formatClock } = useTheme();
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
@@ -220,7 +215,7 @@ export function LogsPage() {
the full width instead of a ~40px column that breaks
every few characters. On sm+ it's the dense single row. */}
<div className="flex shrink-0 items-center gap-2">
<span className="shrink-0 text-muted-foreground tabular-nums">{formatTime(log.time)}</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(log.time)}</span>
<span className={cn('shrink-0 font-semibold sm:w-14', levelClass[log.level])}>
{log.level.toUpperCase()}
</span>
@@ -26,6 +26,7 @@ import type { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry }
import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
import { useTheme } from '@/contexts/ThemeContext';
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
@@ -390,13 +391,9 @@ function ConnectionsCard({ connections }: { connections: AccountConnections[] })
// ─────────────── recent alerts ───────────────
function alertClock(t: string): string {
const d = new Date(t);
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
}
function RecentAlertsCard() {
const api = useApi();
const { formatClock } = useTheme();
const [alerts, setAlerts] = useState<LogEntry[]>([]);
useEffect(() => {
@@ -446,7 +443,7 @@ function RecentAlertsCard() {
<div className="flex flex-col gap-1 font-mono text-[11px]">
{alerts.map((a) => (
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
<span className="shrink-0 text-muted-foreground tabular-nums">{alertClock(a.time)}</span>
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(a.time)}</span>
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
{a.level.toUpperCase()}
</span>
@@ -1,39 +1,41 @@
import { useState, type ReactNode } from 'react';
import { useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { Bug, Check, Download, ExternalLink, Github, Info, KeyRound, Loader2, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sparkles, Star, Sun, Tag } from 'lucide-react';
import {
Accessibility, Bug, Check, Clock, Download, ExternalLink, Github, Image as ImageIcon,
Info, KeyRound, Loader2, Monitor, Moon, Palette, RefreshCw, ShieldCheck,
Sparkles, Star, Sun, Tag, Upload, Trash2,
} 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 { ToggleSwitch } from '@/components/ui/toggle-switch';
import {
ACCENTS,
FONT_MONO_OPTIONS,
FONT_SANS_OPTIONS,
GRADIENT_OPTIONS,
POLL_INTERVAL_OPTIONS,
RADIUS_OPTIONS,
UI_SCALE,
useTheme,
type AccentColor,
type AccentScope,
type BackgroundType,
type DarkIntensity,
type Density,
type SidebarStyle,
type ThemeMode,
type TimeFormat,
} from '@/contexts/ThemeContext';
import { ChangePasswordDialog } from '@/components/change-password-dialog';
import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils';
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: '更小的字号与行距,单屏放更多内容' },
];
type SettingsTab = 'appearance' | 'data' | 'account' | 'about';
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
{ key: 'appearance', label: '外观', icon: Palette },
{ key: 'data', label: '数据刷新', icon: RefreshCw },
{ key: 'data', label: '数据与格式', icon: RefreshCw },
{ key: 'account', label: '账号安全', icon: ShieldCheck },
{ key: 'about', label: '关于', icon: Info },
];
@@ -89,178 +91,454 @@ function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsT
);
}
// ─────────────── shared little controls ───────────────
interface Opt<T> { value: T; label: string; icon?: typeof Sun }
function Segmented<T extends string | number>({
value, options, onChange,
}: { value: T; options: Opt<T>[]; onChange: (v: T) => void }) {
return (
<div className="flex flex-wrap gap-2">
{options.map((opt) => {
const active = value === opt.value;
const Icon = opt.icon;
return (
<button
key={String(opt.value)}
type="button"
onClick={() => onChange(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 && <Icon className="size-4" />}
{opt.label}
</button>
);
})}
</div>
);
}
function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-2">
<div>
<Label>{label}</Label>
{hint && <p className="mt-0.5 text-[11px] text-muted-foreground">{hint}</p>}
</div>
{children}
</div>
);
}
function ToggleRow({ label, hint, value, onChange }: { label: string; hint?: string; value: boolean; onChange: (v: boolean) => void }) {
return (
<div className="flex items-center justify-between gap-4">
<div className="min-w-0">
<p className="text-sm font-medium">{label}</p>
{hint && <p className="text-[11px] text-muted-foreground">{hint}</p>}
</div>
<ToggleSwitch value={value} onChange={onChange} ariaLabel={label} />
</div>
);
}
// ─────────────── 外观 ───────────────
const MODE_OPTIONS: Opt<ThemeMode>[] = [
{ value: 'light', label: '浅色', icon: Sun },
{ value: 'dark', label: '深色', icon: Moon },
{ value: 'system', label: '跟随系统', icon: Monitor },
];
const DARK_INTENSITY_OPTIONS: Opt<DarkIntensity>[] = [
{ value: 'soft', label: '柔和' },
{ value: 'black', label: '纯黑 (OLED)' },
];
const SCOPE_OPTIONS: Opt<AccentScope>[] = [
{ value: 'global', label: '全局' },
{ value: 'sidebar', label: '仅侧栏' },
];
const SIDEBAR_STYLE_OPTIONS: Opt<SidebarStyle>[] = [
{ value: 'follow', label: '跟随背景' },
{ value: 'panel', label: '浅色面板' },
{ value: 'accent', label: '强调色' },
];
const BG_TYPE_OPTIONS: Opt<BackgroundType>[] = [
{ value: 'none', label: '无' },
{ value: 'solid', label: '纯色' },
{ value: 'gradient', label: '渐变' },
{ value: 'image', label: '图片' },
];
const DENSITY_OPTIONS: Opt<Density>[] = [
{ value: 'cozy', label: '舒适' },
{ value: 'compact', label: '紧凑' },
];
function AppearancePanel() {
const { mode, setMode, accent, setAccent, radius, setRadius, density, setDensity } = useTheme();
const { appearance, setAppearance, uploadBackground, removeBackground } = useTheme();
const a = appearance;
return (
<div className="flex flex-col gap-5">
{/* 主题 */}
<Card>
<CardHeader>
<CardTitle>主题</CardTitle>
<CardDescription>明暗模式与深色风格。所有改动立即生效并保存到服务器,跨设备同步。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-6">
<Field label="显示模式">
<Segmented value={a.mode} options={MODE_OPTIONS} onChange={(mode) => setAppearance({ mode })} />
</Field>
<Separator />
<Field label="深色强度" hint="“纯黑”将深色背景压到接近纯黑,适合 OLED 屏幕(仅深色模式下可见)。">
<Segmented value={a.darkIntensity} options={DARK_INTENSITY_OPTIONS} onChange={(darkIntensity) => setAppearance({ darkIntensity })} />
</Field>
</CardContent>
</Card>
{/* 强调色 */}
<Card>
<CardHeader>
<CardTitle>强调色</CardTitle>
<CardDescription>按钮、链接与高亮使用的主色调。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-6">
<Field label="预设色">
<div className="flex flex-wrap items-center gap-2">
{ACCENTS.map((spec) => {
const active = a.accentMode === 'preset' && a.accentPreset === spec.id;
return (
<button
key={spec.id}
type="button"
onClick={() => setAppearance({ accentMode: 'preset', accentPreset: spec.id })}
title={spec.label}
aria-label={spec.label}
className={cn(
'relative flex size-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 && <Check className="size-4 text-white drop-shadow-sm" strokeWidth={3} />}
</button>
);
})}
{/* custom colour */}
<label
title="自定义颜色"
className={cn(
'relative flex size-9 cursor-pointer items-center justify-center overflow-hidden rounded-full border transition-transform hover:scale-105',
a.accentMode === 'custom' ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
)}
style={{ background: a.accentMode === 'custom' ? a.accentCustom : 'conic-gradient(from 0deg, #f43f5e, #f59e0b, #10b981, #0ea5e9, #8b5cf6, #f43f5e)' }}
>
<input
type="color"
value={a.accentCustom}
onChange={(e) => setAppearance({ accentMode: 'custom', accentCustom: e.target.value })}
className="absolute inset-0 cursor-pointer opacity-0"
aria-label="自定义强调色"
/>
{a.accentMode === 'custom' && <Check className="size-4 text-white drop-shadow-sm" strokeWidth={3} />}
</label>
</div>
</Field>
<Separator />
<Field label="应用范围" hint="“仅侧栏”时,按钮等全局元素保持默认蓝,强调色只染侧栏选中项。">
<Segmented value={a.accentScope} options={SCOPE_OPTIONS} onChange={(accentScope) => setAppearance({ accentScope })} />
</Field>
<Separator />
<Field label="侧栏样式">
<Segmented value={a.sidebarStyle} options={SIDEBAR_STYLE_OPTIONS} onChange={(sidebarStyle) => setAppearance({ sidebarStyle })} />
</Field>
</CardContent>
</Card>
{/* 背景 */}
<BackgroundCard appearance={a} setAppearance={setAppearance} uploadBackground={uploadBackground} removeBackground={removeBackground} />
{/* 排版与界面 */}
<Card>
<CardHeader>
<CardTitle>排版与界面</CardTitle>
<CardDescription>字体、圆角、缩放与密度。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-6">
<div className="grid gap-6 sm:grid-cols-2">
<Field label="界面字体">
<Segmented value={a.fontSans} options={FONT_SANS_OPTIONS.map((f) => ({ value: f.id, label: f.label }))} onChange={(fontSans) => setAppearance({ fontSans })} />
</Field>
<Field label="等宽字体" hint="用于日志与代码。">
<Segmented value={a.fontMono} options={FONT_MONO_OPTIONS.map((f) => ({ value: f.id, label: f.label }))} onChange={(fontMono) => setAppearance({ fontMono })} />
</Field>
</div>
<Separator />
<Field label="圆角">
<Segmented
value={a.radius}
options={RADIUS_OPTIONS.map((r) => ({ value: r.value, label: `${r.label}(${r.value}rem)` }))}
onChange={(radius) => setAppearance({ radius })}
/>
</Field>
<Separator />
<Field label={`界面缩放(${Math.round(a.uiScale * 100)}%)`} hint="整体放大或缩小界面,适合高分屏或视力需要。">
<div className="flex items-center gap-3">
<span className="text-[11px] text-muted-foreground tabular-nums">{Math.round(UI_SCALE.min * 100)}%</span>
<input
type="range"
min={UI_SCALE.min}
max={UI_SCALE.max}
step={UI_SCALE.step}
value={a.uiScale}
onChange={(e) => setAppearance({ uiScale: Number(e.target.value) })}
className="h-2 flex-1 cursor-pointer accent-primary"
aria-label="界面缩放"
/>
<span className="text-[11px] text-muted-foreground tabular-nums">{Math.round(UI_SCALE.max * 100)}%</span>
</div>
</Field>
<Separator />
<Field label="显示密度">
<Segmented value={a.density} options={DENSITY_OPTIONS} onChange={(density) => setAppearance({ density })} />
</Field>
</CardContent>
</Card>
{/* 无障碍与侧栏 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><Accessibility className="size-4 text-primary" /> 无障碍与侧栏</CardTitle>
<CardDescription>动效、对比度与侧栏默认状态。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<ToggleRow
label="减少动效"
hint="关闭页面切换、弹簧等装饰性动画,对低端设备与晕动敏感者更友好。"
value={a.reduceMotion}
onChange={(reduceMotion) => setAppearance({ reduceMotion })}
/>
<Separator />
<ToggleRow
label="高对比模式"
hint="加强边框与次要文字的对比度。"
value={a.highContrast}
onChange={(highContrast) => setAppearance({ highContrast })}
/>
<Separator />
<ToggleRow
label="侧栏默认折叠"
hint="新会话首次进入时侧栏默认收起(手动展开/收起后以手动选择为准)。"
value={a.sidebarDefaultCollapsed}
onChange={(sidebarDefaultCollapsed) => setAppearance({ sidebarDefaultCollapsed })}
/>
</CardContent>
</Card>
</div>
);
}
function BackgroundCard({
appearance: a, setAppearance, uploadBackground, removeBackground,
}: {
appearance: ReturnType<typeof useTheme>['appearance'];
setAppearance: ReturnType<typeof useTheme>['setAppearance'];
uploadBackground: ReturnType<typeof useTheme>['uploadBackground'];
removeBackground: ReturnType<typeof useTheme>['removeBackground'];
}) {
const fileRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
const onFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (fileRef.current) fileRef.current.value = '';
if (!file) return;
setUploading(true);
setErr(null);
try {
await uploadBackground(file);
} catch (ex) {
setErr(ex instanceof Error ? ex.message : '上传失败');
} finally {
setUploading(false);
}
};
const onRemove = async () => {
setBusy(true);
setErr(null);
try {
await removeBackground();
} catch {
setErr('删除失败');
} finally {
setBusy(false);
}
};
return (
<Card>
<CardHeader>
<CardTitle>外观</CardTitle>
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
<CardTitle className="flex items-center gap-2"><ImageIcon className="size-4 text-primary" /> 背景</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>
);
})}
<Field label="背景类型">
<Segmented value={a.background.type} options={BG_TYPE_OPTIONS} onChange={(type) => setAppearance({ background: { type } })} />
</Field>
{a.background.type === 'solid' && (
<Field label="背景颜色">
<div className="flex items-center gap-3">
<label className="relative size-10 cursor-pointer overflow-hidden rounded-lg border" style={{ backgroundColor: a.background.color }}>
<input
type="color"
value={a.background.color}
onChange={(e) => setAppearance({ background: { color: e.target.value } })}
className="absolute inset-0 cursor-pointer opacity-0"
aria-label="背景颜色"
/>
</label>
<span className="font-mono text-sm text-muted-foreground">{a.background.color}</span>
</div>
</Field>
)}
{a.background.type === 'gradient' && (
<Field label="渐变预设">
<div className="flex flex-wrap gap-2">
{GRADIENT_OPTIONS.map((g) => {
const active = a.background.gradient === g.id;
return (
<button
key={g.id}
type="button"
onClick={() => setAppearance({ background: { gradient: g.id } })}
title={g.label}
aria-label={g.label}
className={cn(
'h-12 w-20 rounded-lg border transition-transform cursor-pointer hover:scale-105',
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
)}
style={{ backgroundImage: g.css }}
/>
);
})}
</div>
</Field>
)}
{a.background.type === 'image' && (
<div className="flex flex-col gap-5">
<Field label="壁纸" hint="支持 PNG / JPEG / WebP,最大 5MB。">
<div className="flex flex-wrap items-center gap-3">
<input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp" onChange={onFile} className="hidden" />
<Button variant="outline" size="sm" onClick={() => fileRef.current?.click()} disabled={uploading}>
{uploading ? <Loader2 className="size-4 animate-spin" /> : <Upload className="size-4" />}
{a.background.hasImage ? '更换图片' : '上传图片'}
</Button>
{a.background.hasImage && (
<Button variant="ghost" size="sm" onClick={onRemove} disabled={busy} className="text-destructive hover:text-destructive">
<Trash2 className="size-4" /> 移除
</Button>
)}
</div>
</Field>
{a.background.hasImage && (
<>
<div className="overflow-hidden rounded-lg border">
<img
src={`/ui-asset/background?v=${a.background.imageVersion}`}
alt="背景预览"
className="h-32 w-full object-cover"
/>
</div>
<Field label={`遮罩强度(${Math.round(a.background.imageOpacity * 100)}%)`} hint="越高越能盖住壁纸、提升前景可读性。">
<input
type="range"
min={0}
max={1}
step={0.05}
value={a.background.imageOpacity}
onChange={(e) => setAppearance({ background: { imageOpacity: Number(e.target.value) } })}
className="h-2 w-full cursor-pointer accent-primary"
aria-label="遮罩强度"
/>
</Field>
<Field label={`模糊(${a.background.imageBlur}px)`}>
<input
type="range"
min={0}
max={40}
step={1}
value={a.background.imageBlur}
onChange={(e) => setAppearance({ background: { imageBlur: Number(e.target.value) } })}
className="h-2 w-full cursor-pointer accent-primary"
aria-label="背景模糊"
/>
</Field>
</>
)}
</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>
{err && <p className="text-[11px] text-destructive">{err}</p>}
</CardContent>
</Card>
);
}
// ─────────────── 数据刷新 ───────────────
// ─────────────── 数据与格式 ───────────────
const TIME_FORMAT_OPTIONS: Opt<TimeFormat>[] = [
{ value: '24h', label: '24 小时制' },
{ value: '12h', label: '12 小时制 (AM/PM)' },
];
function DataPanel() {
const { pollInterval, setPollInterval } = useTheme();
const { appearance, setAppearance } = useTheme();
return (
<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>
<div className="flex flex-col gap-5">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><RefreshCw className="size-4 text-primary" /> 数据刷新</CardTitle>
<CardDescription>总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
</CardHeader>
<CardContent>
<Field label="轮询间隔" hint={appearance.pollInterval === 0 ? '已暂停轮询' : `当前 ${appearance.pollInterval} 毫秒`}>
<Segmented
value={appearance.pollInterval}
options={POLL_INTERVAL_OPTIONS.map((o) => ({ value: o.value, label: o.label }))}
onChange={(pollInterval) => setAppearance({ pollInterval })}
/>
</Field>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><Clock className="size-4 text-primary" /> 时间格式</CardTitle>
<CardDescription>日志与告警等时间戳的显示方式。</CardDescription>
</CardHeader>
<CardContent>
<Field label="时制">
<Segmented value={appearance.timeFormat} options={TIME_FORMAT_OPTIONS} onChange={(timeFormat) => setAppearance({ timeFormat })} />
</Field>
</CardContent>
</Card>
</div>
);
}
+453 -112
View File
@@ -1,40 +1,50 @@
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { MotionConfig } from 'motion/react';
import type { ThemeMode, UiAppearance, UiBackground } from '@/types';
export type ThemeMode = 'light' | 'dark' | 'system';
// Re-export the appearance value types so consumers (settings page etc.) can
// import them straight from the context module.
export type {
AccentMode, AccentScope, BackgroundType, DarkIntensity, Density, SidebarStyle, ThemeMode, TimeFormat, UiAppearance,
} from '@/types';
/** A partial appearance update; `background` may itself be a partial patch. */
export type AppearancePatch = Partial<Omit<UiAppearance, 'background'>> & { background?: Partial<UiBackground> };
// ─── Frontend catalogues (the server stores only ids; the visuals live here) ───
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 };
light: { primary: string; ring: string };
dark: { primary: string; ring: 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)' } },
light: { primary: 'oklch(68.5% 0.155 230)', ring: 'oklch(68.5% 0.155 230)' },
dark: { primary: 'oklch(75% 0.14 230)', ring: '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)' } },
light: { primary: 'oklch(60% 0.18 258)', ring: 'oklch(60% 0.18 258)' },
dark: { primary: 'oklch(70% 0.16 258)', ring: '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)' } },
light: { primary: 'oklch(60% 0.2 290)', ring: 'oklch(60% 0.2 290)' },
dark: { primary: 'oklch(72% 0.17 290)', ring: '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)' } },
light: { primary: 'oklch(63% 0.21 18)', ring: 'oklch(63% 0.21 18)' },
dark: { primary: 'oklch(72% 0.18 18)', ring: '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)' } },
light: { primary: 'oklch(64% 0.16 162)', ring: 'oklch(64% 0.16 162)' },
dark: { primary: 'oklch(74% 0.15 162)', ring: '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)' } },
light: { primary: 'oklch(72% 0.17 70)', ring: 'oklch(72% 0.17 70)' },
dark: { primary: 'oklch(78% 0.16 70)', ring: '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)' } },
light: { primary: 'oklch(67% 0.2 45)', ring: 'oklch(67% 0.2 45)' },
dark: { primary: 'oklch(74% 0.18 45)', ring: 'oklch(74% 0.18 45)' } },
];
export const RADIUS_OPTIONS = [
@@ -52,68 +62,341 @@ export const POLL_INTERVAL_OPTIONS = [
{ value: 0, label: '已暂停' },
] as const;
export interface FontSpec { id: string; label: string; stack: string }
export const FONT_SANS_OPTIONS: FontSpec[] = [
{ id: 'default', label: '默认 (Inter)', stack: "'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif" },
{ id: 'system', label: '系统界面', stack: "system-ui, -apple-system, 'Segoe UI', 'Noto Sans SC', sans-serif" },
{ id: 'rounded', label: '圆润', stack: "'Varela Round', 'Quicksand', 'Noto Sans SC', system-ui, sans-serif" },
{ id: 'serif', label: '衬线', stack: "Georgia, 'Songti SC', 'Noto Serif SC', serif" },
];
export const FONT_MONO_OPTIONS: FontSpec[] = [
{ id: 'default', label: '默认 (JetBrains)', stack: "'JetBrains Mono', 'Fira Code', ui-monospace, monospace" },
{ id: 'system', label: '系统等宽', stack: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace" },
];
export interface GradientSpec { id: string; label: string; css: string }
export const GRADIENT_OPTIONS: GradientSpec[] = [
{ id: 'aurora', label: '极光', css: 'linear-gradient(135deg, #1e3a8a 0%, #0ea5e9 50%, #22d3ee 100%)' },
{ id: 'sunset', label: '日落', css: 'linear-gradient(135deg, #f97316 0%, #db2777 50%, #7c3aed 100%)' },
{ id: 'forest', label: '森野', css: 'linear-gradient(135deg, #064e3b 0%, #10b981 55%, #84cc16 100%)' },
{ id: 'dusk', label: '暮色', css: 'linear-gradient(160deg, #0f172a 0%, #334155 55%, #64748b 100%)' },
{ id: 'rose', label: '霞光', css: 'linear-gradient(135deg, #9f1239 0%, #fb7185 55%, #fda4af 100%)' },
];
export const UI_SCALE = { min: 0.9, max: 1.2, step: 0.05 } as const;
// ─── Defaults (mirror core/src/webui/ui-config.ts) ─────────────────────────
export const DEFAULT_APPEARANCE: UiAppearance = {
mode: 'system',
accentMode: 'preset',
accentPreset: 'sky',
accentCustom: '#38bdf8',
accentScope: 'global',
darkIntensity: 'soft',
sidebarStyle: 'follow',
background: { type: 'none', color: '#0ea5e9', gradient: 'none', imageOpacity: 0.15, imageBlur: 0, hasImage: false, imageMime: '', imageVersion: 0 },
fontSans: 'default',
fontMono: 'default',
uiScale: 1,
radius: 0.75,
density: 'cozy',
reduceMotion: false,
highContrast: false,
sidebarDefaultCollapsed: false,
timeFormat: '24h',
pollInterval: 3000,
};
const LS_CACHE = 'snowluma_ui_appearance';
const LS_MIGRATED = 'snowluma_ui_migrated';
const TOKEN_KEY = 'snowluma_token';
// ─── Colour helpers (custom hex accent → readable foreground) ──────────────
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
const m = hex.trim().replace('#', '');
if (m.length === 3) {
const r = parseInt(m[0] + m[0], 16), g = parseInt(m[1] + m[1], 16), b = parseInt(m[2] + m[2], 16);
return Number.isNaN(r + g + b) ? null : { r, g, b };
}
if (m.length === 6 || m.length === 8) {
const r = parseInt(m.slice(0, 2), 16), g = parseInt(m.slice(2, 4), 16), b = parseInt(m.slice(4, 6), 16);
return Number.isNaN(r + g + b) ? null : { r, g, b };
}
return null;
}
/** Pick black or white text for a given accent so labels stay legible. */
function readableForeground(hex: string): string {
const rgb = hexToRgb(hex);
if (!rgb) return '#ffffff';
// Relative luminance (sRGB approximation).
const lum = (0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b) / 255;
return lum > 0.6 ? '#0b0d12' : '#ffffff';
}
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
/** A hex colour safe to interpolate into CSS text, else the fallback. Guards
* the localStorage cache (writable by anyone with local access) from
* injecting arbitrary CSS through the accent <style> block. */
function safeHex(value: unknown, fallback: string): string {
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;
}
/** Lighten a hex colour toward white by `ratio` (0..1) for dark-mode accents. */
function lightenHex(hex: string, ratio: number): string {
const rgb = hexToRgb(hex);
if (!rgb) return hex;
const mix = (c: number) => Math.round(c + (255 - c) * ratio);
const to2 = (n: number) => n.toString(16).padStart(2, '0');
return `#${to2(mix(rgb.r))}${to2(mix(rgb.g))}${to2(mix(rgb.b))}`;
}
// ─── Apply appearance → DOM ────────────────────────────────────────────────
function accentVarsCss(a: UiAppearance): string {
if (a.accentMode === 'custom') {
const hex = safeHex(a.accentCustom, '#38bdf8');
const lightFg = readableForeground(hex);
// Dark mode: lighten the accent for contrast on dark surfaces, and pick
// the foreground from the *lightened* colour (a light accent needs dark text).
const darkHex = lightenHex(hex, 0.18);
const darkFg = readableForeground(darkHex);
const lightBlock = a.accentScope === 'global'
? `--primary:${hex};--primary-foreground:${lightFg};--ring:${hex};--sidebar-primary:${hex};--sidebar-primary-foreground:${lightFg};--sidebar-ring:${hex};`
: `--sidebar-primary:${hex};--sidebar-primary-foreground:${lightFg};--sidebar-ring:${hex};`;
const darkBlock = a.accentScope === 'global'
? `--primary:${darkHex};--primary-foreground:${darkFg};--ring:${darkHex};--sidebar-primary:${darkHex};--sidebar-primary-foreground:${darkFg};--sidebar-ring:${darkHex};`
: `--sidebar-primary:${darkHex};--sidebar-primary-foreground:${darkFg};--sidebar-ring:${darkHex};`;
return `:root{${lightBlock}}\n.dark{${darkBlock}}`;
}
const spec = ACCENTS.find((x) => x.id === a.accentPreset) ?? ACCENTS[0];
const light = a.accentScope === 'global'
? `--primary:${spec.light.primary};--ring:${spec.light.ring};--sidebar-primary:${spec.light.primary};--sidebar-ring:${spec.light.ring};`
: `--sidebar-primary:${spec.light.primary};--sidebar-ring:${spec.light.ring};`;
const dark = a.accentScope === 'global'
? `--primary:${spec.dark.primary};--ring:${spec.dark.ring};--sidebar-primary:${spec.dark.primary};--sidebar-ring:${spec.dark.ring};`
: `--sidebar-primary:${spec.dark.primary};--sidebar-ring:${spec.dark.ring};`;
// Presets keep the base token's primary-foreground (designed for these hues).
return `:root{${light}}\n.dark{${dark}}`;
}
function fontStack(options: FontSpec[], id: string): string {
return (options.find((f) => f.id === id) ?? options[0]).stack;
}
function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
const root = document.documentElement;
root.classList.remove('light', 'dark');
root.classList.add(resolved);
root.setAttribute('data-theme', resolved);
root.style.colorScheme = resolved;
root.setAttribute('data-density', a.density);
root.setAttribute('data-dark-intensity', a.darkIntensity);
root.setAttribute('data-sidebar-style', a.sidebarStyle);
root.setAttribute('data-contrast', a.highContrast ? 'high' : 'normal');
root.setAttribute('data-reduce-motion', a.reduceMotion ? '1' : '0');
// Mode-independent vars go inline on :root.
root.style.setProperty('--radius', `${a.radius}rem`);
root.style.setProperty('--font-sans', fontStack(FONT_SANS_OPTIONS, a.fontSans));
root.style.setProperty('--font-mono', fontStack(FONT_MONO_OPTIONS, a.fontMono));
// UI scale: scale the root font-size so all rem-based sizing tracks it.
// Clamp defensively (the localStorage cache is locally tamperable; the
// server already bounds this to 0.9..1.2 for its own values).
const scale = Math.min(2, Math.max(0.5, Number.isFinite(a.uiScale) ? a.uiScale : 1));
root.style.fontSize = `${Math.round(16 * scale * 100) / 100}px`;
// Accent differs by light/dark, so it needs a stylesheet with a `.dark` rule.
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);
}
el.textContent = accentVarsCss(a);
}
/** Manage the fixed full-viewport background layer behind the app. */
function applyBackgroundLayer(a: UiAppearance): void {
const id = 'snowluma-bg-layer';
let layer = document.getElementById(id) as HTMLDivElement | null;
const bg = a.background;
if (bg.type === 'none') {
if (layer) layer.style.display = 'none';
return;
}
if (!layer) {
layer = document.createElement('div');
layer.id = id;
layer.setAttribute('aria-hidden', 'true');
// Behind app content, ignores pointer events, fixed to the viewport.
layer.style.position = 'fixed';
layer.style.inset = '0';
layer.style.zIndex = '-1';
layer.style.pointerEvents = 'none';
layer.style.backgroundSize = 'cover';
layer.style.backgroundPosition = 'center';
layer.style.backgroundRepeat = 'no-repeat';
document.body.insertBefore(layer, document.body.firstChild);
}
layer.style.display = 'block';
layer.style.filter = '';
layer.style.transform = '';
if (bg.type === 'solid') {
layer.style.backgroundColor = bg.color;
layer.style.backgroundImage = 'none';
} else if (bg.type === 'gradient') {
const g = GRADIENT_OPTIONS.find((x) => x.id === bg.gradient) ?? GRADIENT_OPTIONS[0];
layer.style.backgroundColor = 'transparent';
layer.style.backgroundImage = g.css;
} else if (bg.type === 'image' && bg.hasImage) {
// Overlay (for readability) layered over the image; opacity 0..1 = how
// strongly the base background colour masks the wallpaper.
const overlay = `color-mix(in oklab, var(--background) ${Math.round(bg.imageOpacity * 100)}%, transparent)`;
layer.style.backgroundColor = 'transparent';
layer.style.backgroundImage = `linear-gradient(${overlay}, ${overlay}), url("/ui-asset/background?v=${bg.imageVersion}")`;
if (bg.imageBlur > 0) {
layer.style.filter = `blur(${bg.imageBlur}px)`;
// Scale up so the blurred edges don't reveal the viewport border.
layer.style.transform = 'scale(1.06)';
}
} else {
// type === 'image' but no image on disk → nothing to show.
layer.style.display = 'none';
}
}
// ─── Server transport (ThemeProvider sits outside ApiProvider, so it uses a
// direct fetch with the bearer token from localStorage) ─────────────────
function authToken(): string | null {
try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
}
async function fetchAppearance(): Promise<UiAppearance | null> {
try {
const res = await fetch('/api/ui/public');
if (!res.ok) return null;
const data = (await res.json()) as { appearance?: UiAppearance };
return data.appearance ?? null;
} catch {
return null;
}
}
async function persistAppearance(appearance: UiAppearance): Promise<void> {
const token = authToken();
if (!token) return; // pre-auth: local cache only (no settings UI exists there anyway)
try {
await fetch('/api/ui', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
// Section-level save: only `appearance`; the server preserves `layout`.
body: JSON.stringify({ appearance }),
});
} catch {
/* best-effort — the local cache already holds the change */
}
}
// ─── Migration of the pre-server-config localStorage theme ─────────────────
function readLegacyOverlay(): Partial<UiAppearance> | null {
try {
const out: Partial<UiAppearance> = {};
const mode = localStorage.getItem('snowluma_theme');
if (mode === 'light' || mode === 'dark' || mode === 'system') out.mode = mode;
const accent = localStorage.getItem('snowluma_accent');
if (accent && ACCENTS.some((a) => a.id === accent)) { out.accentMode = 'preset'; out.accentPreset = accent; }
const radius = Number(localStorage.getItem('snowluma_radius'));
if (Number.isFinite(radius) && radius > 0 && radius <= 2) out.radius = radius;
const density = localStorage.getItem('snowluma_density');
if (density === 'cozy' || density === 'compact') out.density = density;
const poll = Number(localStorage.getItem('snowluma_poll_interval'));
if (Number.isFinite(poll) && poll >= 0 && poll <= 60_000) out.pollInterval = poll;
return Object.keys(out).length > 0 ? out : null;
} catch {
return null;
}
}
function isPristine(a: UiAppearance): boolean {
const d = DEFAULT_APPEARANCE;
return a.mode === d.mode && a.accentMode === d.accentMode && a.accentPreset === d.accentPreset
&& a.radius === d.radius && a.density === d.density && a.pollInterval === d.pollInterval
&& a.background.type === 'none';
}
function readCache(): UiAppearance {
try {
const raw = localStorage.getItem(LS_CACHE);
if (!raw) return DEFAULT_APPEARANCE;
const parsed = JSON.parse(raw) as Partial<UiAppearance>;
// Shallow merge over defaults so a cache written by an older build still
// yields a complete object (the server is the real validator).
return { ...DEFAULT_APPEARANCE, ...parsed, background: { ...DEFAULT_APPEARANCE.background, ...parsed.background } };
} catch {
return DEFAULT_APPEARANCE;
}
}
function writeCache(a: UiAppearance): void {
try { localStorage.setItem(LS_CACHE, JSON.stringify(a)); } catch { /* quota / private mode */ }
}
// ─── Context ───────────────────────────────────────────────────────────────
interface ThemeContextValue {
mode: ThemeMode;
appearance: UiAppearance;
/** True once the first server load attempt has resolved. */
ready: boolean;
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;
/** Merge a partial appearance: applies instantly, caches, debounced-persists. */
setAppearance: (patch: AppearancePatch) => void;
/** Upload a wallpaper (PNG/JPEG/WebP, ≤5MB). Throws on failure. */
uploadBackground: (file: File) => Promise<void>;
/** Remove the wallpaper. */
removeBackground: () => Promise<void>;
/** Format a timestamp per the configured 12h/24h preference. */
formatClock: (input: string | number | Date) => string;
// ── back-compat conveniences ──
mode: ThemeMode;
setMode: (m: ThemeMode) => 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(LS.mode) as ThemeMode | null;
if (saved === 'light' || saved === 'dark' || saved === 'system') return saved;
return 'system';
});
const [appearance, setAppearanceState] = useState<UiAppearance>(readCache);
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);
const [ready, setReady] = useState(false);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Mirror of the latest appearance so the (pure) setAppearance can read the
// current value without an impure state-updater closure (StrictMode-safe).
// Synced via a layout effect (not during render) + written synchronously by
// the mutators themselves so consecutive calls in one tick still compose.
const appearanceRef = useRef(appearance);
const resolved: 'light' | 'dark' = appearance.mode === 'system' ? systemTheme : appearance.mode;
// Track the OS theme for `mode: 'system'`.
useEffect(() => {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const handler = (e: MediaQueryListEvent) => setSystemTheme(e.matches ? 'dark' : 'light');
@@ -121,61 +404,119 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
return () => mq.removeEventListener('change', handler);
}, []);
const resolved: 'light' | 'dark' = mode === 'system' ? systemTheme : mode;
// Initial server load (+ one-time legacy migration). Runs once.
useEffect(() => {
const root = document.documentElement;
root.classList.remove('light', 'dark');
root.classList.add(resolved);
root.setAttribute('data-theme', resolved);
root.style.colorScheme = resolved;
}, [resolved]);
let cancelled = false;
(async () => {
const server = await fetchAppearance();
if (cancelled) return;
let next = server ?? readCache();
useEffect(() => {
document.documentElement.setAttribute('data-density', density);
}, [density]);
if (!localStorage.getItem(LS_MIGRATED)) {
try { localStorage.setItem(LS_MIGRATED, '1'); } catch { /* ignore */ }
const legacy = readLegacyOverlay();
// Only migrate when the server has never been customized, so we don't
// clobber a look already set from another device.
if (legacy && server && isPristine(server)) {
next = { ...server, ...legacy, background: server.background };
void persistAppearance(next);
}
}
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);
setAppearanceState(next);
writeCache(next);
setReady(true);
})();
return () => { cancelled = true; };
}, []);
// Keep the mutator-facing ref in sync after any state change (init load,
// system-theme flip, upload/delete). Written in an effect, never during render.
useLayoutEffect(() => { appearanceRef.current = appearance; }, [appearance]);
// Apply to the DOM before paint (useLayoutEffect) so the post-mount
// application doesn't flash. The pre-mount flash is handled by the inline
// bootstrap script in index.html.
useLayoutEffect(() => { applyAppearance(appearance, resolved); }, [appearance, resolved]);
useLayoutEffect(() => { applyBackgroundLayer(appearance); }, [appearance]);
// Flush a pending debounced save on unmount (defensive — the provider lives
// at the app root and normally never unmounts).
useEffect(() => () => { if (saveTimer.current) clearTimeout(saveTimer.current); }, []);
const setAppearance = useCallback((patch: AppearancePatch) => {
const prev = appearanceRef.current;
const next: UiAppearance = {
...prev,
...patch,
background: patch.background ? { ...prev.background, ...patch.background } : prev.background,
};
appearanceRef.current = next;
setAppearanceState(next);
writeCache(next);
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => void persistAppearance(next), 400);
}, []);
const uploadBackground = useMemo(() => async (file: File) => {
const token = authToken();
if (!token) throw new Error('未登录');
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/ui/background', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form });
if (!res.ok) {
const e = (await res.json().catch(() => ({}))) as { message?: string };
throw new Error(e.message || '上传失败');
}
const 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 data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
}, []);
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 removeBackground = useMemo(() => async () => {
const token = authToken();
if (!token) throw new Error('未登录');
const res = await fetch('/api/ui/background', { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error('删除失败');
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
const ap = data.config?.appearance;
if (ap) { appearanceRef.current = ap; setAppearanceState(ap); writeCache(ap); }
}, []);
const value = useMemo<ThemeContextValue>(
() => ({ mode, resolved, setMode, accent, setAccent, radius, setRadius, density, setDensity, pollInterval, setPollInterval }),
[mode, resolved, accent, radius, density, pollInterval],
const formatClock = useMemo(() => (input: string | number | Date) => {
const d = input instanceof Date ? input : new Date(input);
if (Number.isNaN(d.getTime())) return String(input);
return d.toLocaleTimeString(undefined, {
hour12: appearance.timeFormat === '12h',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
}, [appearance.timeFormat]);
const value = useMemo<ThemeContextValue>(() => ({
appearance,
ready,
resolved,
setAppearance,
uploadBackground,
removeBackground,
formatClock,
mode: appearance.mode,
setMode: (m: ThemeMode) => setAppearance({ mode: m }),
pollInterval: appearance.pollInterval,
}), [appearance, ready, resolved, setAppearance, uploadBackground, removeBackground, formatClock]);
return (
<ThemeContext.Provider value={value}>
<MotionConfig reducedMotion={appearance.reduceMotion ? 'always' : 'user'}>
{children}
</MotionConfig>
</ThemeContext.Provider>
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
+55 -2
View File
@@ -153,12 +153,65 @@
background-color: color-mix(in oklab, var(--primary) 28%, transparent);
color: var(--foreground);
}
/* Density: compact tightens the global rhythm a touch. */
/* Density: compact tightens the global rhythm a touch. Use rem (not px) so
it still tracks the UI-scale root font-size. */
html[data-density="compact"] body {
font-size: 13.5px;
font-size: 0.84rem;
line-height: 1.45;
}
html[data-density="compact"] {
--tw-leading: 1.4;
}
}
/* ──────────────────────────────────────────────
Customization layers (driven by ThemeContext via
data-* attributes + CSS vars on <html>)
────────────────────────────────────────────── */
/* Dark intensity: "black" pushes the dark palette toward true black for
OLED screens. Only meaningful in dark mode. */
.dark[data-dark-intensity="black"] {
--background: oklch(0% 0 0);
--foreground: oklch(97% 0.01 240);
--card: oklch(13% 0.008 250);
--card-foreground: oklch(96% 0.01 240);
--popover: oklch(13% 0.008 250);
--popover-foreground: oklch(96% 0.01 240);
--secondary: oklch(17% 0.012 250);
--muted: oklch(15% 0.01 250);
--muted-foreground: oklch(66% 0.02 240);
--border: oklch(22% 0.012 250);
--input: oklch(19% 0.012 250);
--sidebar: oklch(5% 0.006 250);
--sidebar-border: oklch(20% 0.012 250);
}
/* Sidebar style: how distinct the sidebar surface is from the main canvas. */
html[data-sidebar-style="panel"] {
--sidebar: color-mix(in oklab, var(--card) 90%, var(--primary) 4%);
}
html[data-sidebar-style="accent"] {
--sidebar: color-mix(in oklab, var(--background) 76%, var(--primary) 24%);
--sidebar-foreground: color-mix(in oklab, var(--foreground) 85%, var(--primary));
--sidebar-border: color-mix(in oklab, var(--border) 60%, var(--primary) 40%);
}
/* High contrast: strengthen borders + dim-text contrast for legibility. */
html[data-contrast="high"] {
--border: color-mix(in oklab, var(--foreground) 55%, var(--border));
--input: color-mix(in oklab, var(--foreground) 45%, var(--input));
--muted-foreground: color-mix(in oklab, var(--foreground) 78%, var(--muted-foreground));
--sidebar-border: color-mix(in oklab, var(--foreground) 55%, var(--sidebar-border));
}
/* Reduce motion: a CSS fallback for non-Framer transitions/animations.
Framer Motion itself is handled by <MotionConfig reducedMotion>. */
html[data-reduce-motion="1"] *,
html[data-reduce-motion="1"] *::before,
html[data-reduce-motion="1"] *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}