From 5b07f518cc6f13aab83d456cd1dc262ffd653446 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 16 Jun 2026 14:04:59 +0800 Subject: [PATCH] feat(webui): custom fonts + theme-variable override panel (B1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds two appearance customizations from the WebUI plan's B1 batch: - Custom fonts: new `fontSansCustom`/`fontMonoCustom` free-form family fields (mirroring accent's preset/custom dual-field). A "自定义" segment reveals a text input; on Chromium it gets a native of installed fonts via `queryLocalFonts()`, feature-detected with a silent fallback to a plain text box on Firefox/Safari/mobile. No font-file uploads. - Theme-variable panel: new `cssVars` map lets the operator override individual theme tokens (background/foreground/primary/…) with colour pickers, layered last over palette+accent. Both keys (token whitelist) and values (hex/named/functional colour) are validated, so — unlike customCss — this stays safe to serve to the unauthenticated login page. Server `normalizeAppearance` gains `fontFamilyOr` (rejects control chars/injection) and `normalizeCssVars` (whitelist keys + colour-only values, total over corrupt input). Client `ThemeContext` re-validates defensively (the localStorage cache is locally tamperable) before injecting into CSS. Tests for the new normalizers land with the B4 batch. --- packages/core/src/webui/ui-config.ts | 90 ++++++++- .../src/components/pages/settings-page.tsx | 181 +++++++++++++++++- packages/webui/src/contexts/ThemeContext.tsx | 57 +++++- packages/webui/src/types.ts | 6 + 4 files changed, 324 insertions(+), 10 deletions(-) diff --git a/packages/core/src/webui/ui-config.ts b/packages/core/src/webui/ui-config.ts index 00d9b3eb..79c85eab 100644 --- a/packages/core/src/webui/ui-config.ts +++ b/packages/core/src/webui/ui-config.ts @@ -82,10 +82,14 @@ export interface UiAppearance { palette: Palette; sidebarStyle: SidebarStyle; background: UiBackground; - /** Sans font preset id (frontend catalogue). */ + /** Sans font preset id (frontend catalogue); 'custom' uses `fontSansCustom`. */ fontSans: string; - /** Mono font preset id (frontend catalogue). */ + /** Free-form sans font-family stack, used when `fontSans === 'custom'`. */ + fontSansCustom: string; + /** Mono font preset id (frontend catalogue); 'custom' uses `fontMonoCustom`. */ fontMono: string; + /** Free-form mono font-family stack, used when `fontMono === 'custom'`. */ + fontMonoCustom: string; /** Global UI scale, 0.9…1.2. */ uiScale: number; /** Corner radius in rem, 0…2. */ @@ -107,6 +111,13 @@ export interface UiAppearance { * lock the operator out. */ customCss: string; + /** + * Theme-token overrides from the variable panel. Keys are restricted to a + * fixed whitelist of `--token` names and values to colours / lengths, so + * (unlike `customCss`) this is safe to serve to the unauthenticated login + * page — `normalizeAppearance` drops unknown keys and invalid values. + */ + cssVars: Record; } export interface UiLayoutItem { @@ -196,7 +207,9 @@ const DEFAULT_APPEARANCE: UiAppearance = { sidebarStyle: 'follow', background: DEFAULT_BACKGROUND, fontSans: 'default', + fontSansCustom: '', fontMono: 'default', + fontMonoCustom: '', uiScale: 1, radius: 0.75, density: 'cozy', @@ -207,6 +220,7 @@ const DEFAULT_APPEARANCE: UiAppearance = { timeFormat: '24h', pollInterval: 3000, customCss: '', + cssVars: {}, }; const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [ @@ -243,7 +257,7 @@ const DEFAULT_PAGES: UiPages = { export function defaultUiConfig(): UiConfig { return { version: UI_CONFIG_VERSION, - appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND } }, + appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND }, cssVars: {} }, layout: { overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })), navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })), @@ -302,6 +316,73 @@ function idOr(value: unknown, fallback: string, maxLen = 64): string { return v; } +/** + * A free-form font-family value (a single family or a comma-separated stack), + * safe to interpolate into `--font-sans: ;`. Allows letters (incl. CJK), + * digits, spaces and the punctuation real font names use, but refuses anything + * that could break out of the declaration (`;`, `{`, `}`, control chars, etc.). + * Empty / over-long / invalid → fallback ('' = "no custom family set"). + */ +const FONT_FAMILY_RE = /^[\p{L}\p{N}\s,'"._-]+$/u; +function fontFamilyOr(value: unknown, fallback: string, maxLen = 200): string { + if (typeof value !== 'string') return fallback; + const v = value.trim(); + if (v.length === 0) return ''; // explicitly cleared + if (v.length > maxLen || !FONT_FAMILY_RE.test(v)) return fallback; + return v; +} + +// ─── cssVars (theme-token override panel) ────────────────────────────────── +// Both the keys (which `--token` may be set) and the values (colour / length) +// are whitelisted so the result is safe to serve to the UNAUTHENTICATED login +// page — it shares the trust level of palette/accent, not of `customCss`. + +/** The `--token` names the variable panel is allowed to override. Kept in sync + * with the surface/accent tokens `ThemeContext` actually injects. */ +const CSS_VAR_WHITELIST = new Set([ + '--background', '--foreground', + '--card', '--card-foreground', + '--popover', '--popover-foreground', + '--primary', '--primary-foreground', + '--secondary', '--secondary-foreground', + '--muted', '--muted-foreground', + '--accent', '--accent-foreground', + '--destructive', '--destructive-foreground', + '--success', '--warning', + '--border', '--input', '--ring', + '--sidebar', '--sidebar-foreground', + '--sidebar-primary', '--sidebar-primary-foreground', + '--sidebar-accent', '--sidebar-accent-foreground', + '--sidebar-border', '--sidebar-ring', +]); + +// A CSS colour value, restricted to forms that cannot break out of a `--token: +// ;` declaration. Hex, a named colour, or a single balanced functional +// notation (rgb/hsl/oklch/… and color-mix) over a safe char set — crucially no +// `;`, `{`, `}`, `:` or angle brackets are permitted anywhere. +const CSS_HEX_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; +const CSS_NAMED_RE = /^[a-zA-Z]{1,24}$/; +const CSS_FUNC_RE = /^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\([a-zA-Z0-9.,%/\s#-]{1,120}\)$/; +function cssColorOrNull(value: unknown): string | null { + if (typeof value !== 'string') return null; + const v = value.trim(); + if (v.length === 0 || v.length > 128) return null; + if (CSS_HEX_RE.test(v) || CSS_NAMED_RE.test(v) || CSS_FUNC_RE.test(v)) return v; + return null; +} + +/** Keep only whitelisted token keys with valid colour values; drop the rest. */ +function normalizeCssVars(value: unknown): Record { + if (!isObject(value)) return {}; + const out: Record = {}; + for (const key of Object.keys(value)) { + if (!CSS_VAR_WHITELIST.has(key)) continue; + const color = cssColorOrNull(value[key]); + if (color) out[key] = color; + } + return out; +} + function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayoutItem[] { if (!Array.isArray(value)) return fallback.map((i) => ({ ...i })); const seen = new Set(); @@ -404,7 +485,9 @@ export function normalizeAppearance(value: unknown, imageState: ServerImageState sidebarStyle: oneOf(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle), background: normalizeBackground(v.background, imageState), fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans), + fontSansCustom: fontFamilyOr(v.fontSansCustom, DEFAULT_APPEARANCE.fontSansCustom), fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono), + fontMonoCustom: fontFamilyOr(v.fontMonoCustom, DEFAULT_APPEARANCE.fontMonoCustom), uiScale: clampNum(v.uiScale, 0.9, 1.2, DEFAULT_APPEARANCE.uiScale), radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius), density: oneOf(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density), @@ -415,6 +498,7 @@ export function normalizeAppearance(value: unknown, imageState: ServerImageState timeFormat: oneOf(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat), pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval), customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss, + cssVars: normalizeCssVars(v.cssVars), }; } diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 7c3a8106..6de5794b 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -12,6 +12,7 @@ import { Slider } from '@/components/ui/slider'; import { ACCENTS, DEFAULT_APPEARANCE, + FONT_CUSTOM_ID, FONT_MONO_OPTIONS, FONT_SANS_OPTIONS, GRADIENT_OPTIONS, @@ -25,6 +26,7 @@ import { type BackgroundType, type DarkIntensity, type Density, + type FontSpec, type SidebarStyle, type ThemeMode, type TimeFormat, @@ -356,10 +358,24 @@ function AppearancePanel() { - ({ value: f.id, label: f.label }))} onChange={(fontSans) => setAppearance({ fontSans })} /> + setAppearance({ fontSans })} + onCustomChange={(fontSansCustom) => setAppearance({ fontSansCustom })} + placeholder="例如:LXGW WenKai, PingFang SC" + /> - ({ value: f.id, label: f.label }))} onChange={(fontMono) => setAppearance({ fontMono })} /> + setAppearance({ fontMono })} + onCustomChange={(fontMonoCustom) => setAppearance({ fontMonoCustom })} + placeholder="例如:Cascadia Code, Sarasa Mono SC" + /> ({ value: r.value, label: r.label }))} onChange={(radius) => setAppearance({ radius })} /> @@ -384,6 +400,8 @@ function AppearancePanel() { + setAppearance({ cssVars })} /> + setAppearance({ reduceMotion })} ariaLabel="减弱动效" /> @@ -543,6 +561,165 @@ function BackgroundCard({ ); } +// A font selector: preset segments + a "自定义" segment that reveals a +// free-form family input. On Chromium (where `queryLocalFonts` exists) the +// input gets a native populated with the user's installed fonts; +// everywhere else it stays a plain text box (feature-detect, silent fallback). +type LocalFont = { family: string }; +type FontQueryWindow = Window & { queryLocalFonts?: () => Promise }; + +function FontField({ + value, custom, presets, onChange, onCustomChange, placeholder, +}: { + value: string; + custom: string; + presets: FontSpec[]; + onChange: (id: string) => void; + onCustomChange: (family: string) => void; + placeholder: string; +}) { + const listId = useId(); + const [fonts, setFonts] = useState(null); + const [loading, setLoading] = useState(false); + const canQuery = typeof (window as FontQueryWindow).queryLocalFonts === 'function'; + const isCustom = value === FONT_CUSTOM_ID; + + const options: Opt[] = [ + ...presets.map((f) => ({ value: f.id, label: f.label })), + { value: FONT_CUSTOM_ID, label: '自定义' }, + ]; + + // Lazily enumerate local fonts the first time the field is focused. A denied + // permission (or any failure) just leaves the plain text box — no error UI. + const loadFonts = async () => { + if (fonts !== null || loading || !canQuery) return; + setLoading(true); + try { + const arr = await (window as FontQueryWindow).queryLocalFonts!(); + setFonts(Array.from(new Set(arr.map((f) => f.family))).sort((x, y) => x.localeCompare(y))); + } catch { + setFonts([]); + } finally { + setLoading(false); + } + }; + + return ( +
+ + {isCustom && ( +
+ onCustomChange(e.target.value)} + onFocus={loadFonts} + placeholder={placeholder} + spellCheck={false} + autoComplete="off" + style={custom ? { fontFamily: custom } : undefined} + className="w-full rounded-lg border bg-card/40 px-3 py-2 text-sm outline-none focus:border-primary" + /> + {canQuery && fonts && fonts.length > 0 && ( + + {fonts.map((f) => + )} +

+ {canQuery + ? '可输入字体名称,或聚焦后从已安装字体中选择;找不到时回退到系统字体。' + : '输入已安装的字体名称(可写多个,用逗号分隔);找不到时回退到系统字体。'} +

+
+ )} +
+ ); +} + +// Curated subset of the cssVars whitelist surfaced as colour pickers. The +// server accepts the full token set; this is just the operator-friendly view. +const CSS_VAR_FIELDS: { token: string; label: string }[] = [ + { token: '--background', label: '页面背景' }, + { token: '--foreground', label: '主文字' }, + { token: '--card', label: '卡片背景' }, + { token: '--primary', label: '主色调' }, + { token: '--muted-foreground', label: '次要文字' }, + { token: '--border', label: '边框' }, + { token: '--sidebar', label: '侧栏背景' }, + { token: '--destructive', label: '危险 / 错误' }, + { token: '--success', label: '成功' }, + { token: '--warning', label: '警告' }, +]; + +// The variable panel: per-token colour overrides layered over the active +// palette/accent. Each override is a single hex value (validated server-side); +// an unset token falls through to the theme default. +function ThemeVarsPanel({ + cssVars, onChange, +}: { cssVars: Record; onChange: (next: Record) => void }) { + const set = (token: string, hex: string) => onChange({ ...cssVars, [token]: hex }); + const clear = (token: string) => { + const next = { ...cssVars }; + delete next[token]; + onChange(next); + }; + const count = CSS_VAR_FIELDS.filter((f) => cssVars[f.token]).length; + + return ( + + {CSS_VAR_FIELDS.map((f) => { + const override = cssVars[f.token]; + return ( + {f.token}} layout="inline"> +
+ {override ? ( + {override} + ) : ( + 默认 + )} + + +
+
+ ); + })} + {count > 0 && ( +
+ 已覆盖 {count} 个变量 + +
+ )} +
+ ); +} + // ─────────────── 数据与格式 ─────────────── const TIME_FORMAT_OPTIONS: Opt[] = [ diff --git a/packages/webui/src/contexts/ThemeContext.tsx b/packages/webui/src/contexts/ThemeContext.tsx index 64dd7d65..4d8caa90 100644 --- a/packages/webui/src/contexts/ThemeContext.tsx +++ b/packages/webui/src/contexts/ThemeContext.tsx @@ -102,7 +102,9 @@ export const DEFAULT_APPEARANCE: UiAppearance = { sidebarStyle: 'follow', background: { type: 'none', color: '#0ea5e9', gradient: 'none', imageOpacity: 0.15, imageBlur: 0, hasImage: false, imageMime: '', imageVersion: 0 }, fontSans: 'default', + fontSansCustom: '', fontMono: 'default', + fontMonoCustom: '', uiScale: 1, radius: 0.75, density: 'cozy', @@ -113,8 +115,12 @@ export const DEFAULT_APPEARANCE: UiAppearance = { timeFormat: '24h', pollInterval: 3000, customCss: '', + cssVars: {}, }; +/** The sentinel `fontSans`/`fontMono` id selecting the free-form custom family. */ +export const FONT_CUSTOM_ID = 'custom'; + const LS_CACHE = 'snowluma_ui_appearance'; const LS_MIGRATED = 'snowluma_ui_migrated'; const TOKEN_KEY = 'snowluma_token'; @@ -306,10 +312,50 @@ function paletteVarsCss(a: UiAppearance): string { return `${selector}{${body}}`; } -function fontStack(options: FontSpec[], id: string): string { +// Guards the locally-tamperable cache from injecting arbitrary CSS through the +// `--font-sans`/`--font-mono` declaration. Mirrors the server's fontFamilyOr. +const FONT_FAMILY_RE = /^[\p{L}\p{N}\s,'"._-]+$/u; +function safeFontFamily(value: string): string | null { + const v = value.trim(); + if (v.length === 0 || v.length > 200 || !FONT_FAMILY_RE.test(v)) return null; + return v; +} + +/** Resolve the active font stack: a preset's stack, or — when `id === 'custom'` + * and the free-form family is valid — that family with a generic fallback + * appended (so a missing font still degrades gracefully). */ +function resolveFontStack(options: FontSpec[], id: string, custom: string, generic: string): string { + if (id === FONT_CUSTOM_ID) { + const fam = safeFontFamily(custom); + if (fam) return `${fam}, ${generic}`; + return options[0].stack; // 'custom' selected but empty/invalid → default preset + } return (options.find((f) => f.id === id) ?? options[0]).stack; } +/** Build the `:root{ --token: value; … }` block from whitelisted cssVar + * overrides. Re-validates keys/values defensively (the cache is tamperable; + * the server is the real validator). Applied last so it wins over palette. */ +const CSS_VAR_WHITELIST = new Set([ + '--background', '--foreground', '--card', '--card-foreground', + '--popover', '--popover-foreground', '--primary', '--primary-foreground', + '--secondary', '--secondary-foreground', '--muted', '--muted-foreground', + '--accent', '--accent-foreground', '--destructive', '--destructive-foreground', + '--success', '--warning', '--border', '--input', '--ring', + '--sidebar', '--sidebar-foreground', '--sidebar-primary', '--sidebar-primary-foreground', + '--sidebar-accent', '--sidebar-accent-foreground', '--sidebar-border', '--sidebar-ring', +]); +const CSS_COLOR_RE = /^(?:#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|[a-zA-Z]{1,24}|(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\([a-zA-Z0-9.,%/\s#-]{1,120}\))$/; +function cssVarsCss(a: UiAppearance): string { + const vars = a.cssVars; + if (!vars || typeof vars !== 'object') return ''; + const decls = Object.entries(vars) + .filter(([k, v]) => CSS_VAR_WHITELIST.has(k) && typeof v === 'string' && CSS_COLOR_RE.test(v.trim())) + .map(([k, v]) => `${k}:${v.trim()};`) + .join(''); + return decls ? `:root{${decls}}` : ''; +} + function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void { const root = document.documentElement; @@ -334,8 +380,8 @@ function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void { // 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)); + root.style.setProperty('--font-sans', resolveFontStack(FONT_SANS_OPTIONS, a.fontSans, a.fontSansCustom, 'system-ui, sans-serif')); + root.style.setProperty('--font-mono', resolveFontStack(FONT_MONO_OPTIONS, a.fontMono, a.fontMonoCustom, 'ui-monospace, monospace')); // 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). @@ -351,8 +397,9 @@ function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void { document.head.appendChild(el); } // Palette (base/surface tokens) first, then accent (--primary/--ring) — a - // disjoint var set, layered after so it composes with any flavor. - el.textContent = `${paletteVarsCss(a)}\n${accentVarsCss(a)}`; + // disjoint var set, layered after so it composes with any flavor. The + // operator's variable-panel overrides come last so they win over both. + el.textContent = `${paletteVarsCss(a)}\n${accentVarsCss(a)}\n${cssVarsCss(a)}`; // Custom CSS — appended AFTER the accent block so it is the last style in // and can override anything. Skipped under ?safe-mode=1 (escape diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 1c2d4d80..0279c384 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -202,7 +202,11 @@ export interface UiAppearance { sidebarStyle: SidebarStyle; background: UiBackground; fontSans: string; + /** Free-form sans font-family stack, used when `fontSans === 'custom'`. */ + fontSansCustom: string; fontMono: string; + /** Free-form mono font-family stack, used when `fontMono === 'custom'`. */ + fontMonoCustom: string; uiScale: number; radius: number; density: Density; @@ -214,6 +218,8 @@ export interface UiAppearance { pollInterval: number; /** Operator custom CSS (applied post-auth only; stripped from /api/ui/public). */ customCss: string; + /** Theme-token overrides from the variable panel (whitelisted keys/values). */ + cssVars: Record; } export interface UiLayoutItem {