feat(webui): custom fonts + theme-variable override panel (B1)
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 <datalist> 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.
This commit is contained in:
4 files changed
+324
-10
No files matched your search
@@ -82,10 +82,14 @@ export interface UiAppearance {
|
|||||||
palette: Palette;
|
palette: Palette;
|
||||||
sidebarStyle: SidebarStyle;
|
sidebarStyle: SidebarStyle;
|
||||||
background: UiBackground;
|
background: UiBackground;
|
||||||
/** Sans font preset id (frontend catalogue). */
|
/** Sans font preset id (frontend catalogue); 'custom' uses `fontSansCustom`. */
|
||||||
fontSans: string;
|
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;
|
fontMono: string;
|
||||||
|
/** Free-form mono font-family stack, used when `fontMono === 'custom'`. */
|
||||||
|
fontMonoCustom: string;
|
||||||
/** Global UI scale, 0.9…1.2. */
|
/** Global UI scale, 0.9…1.2. */
|
||||||
uiScale: number;
|
uiScale: number;
|
||||||
/** Corner radius in rem, 0…2. */
|
/** Corner radius in rem, 0…2. */
|
||||||
@@ -107,6 +111,13 @@ export interface UiAppearance {
|
|||||||
* lock the operator out.
|
* lock the operator out.
|
||||||
*/
|
*/
|
||||||
customCss: string;
|
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<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UiLayoutItem {
|
export interface UiLayoutItem {
|
||||||
@@ -196,7 +207,9 @@ const DEFAULT_APPEARANCE: UiAppearance = {
|
|||||||
sidebarStyle: 'follow',
|
sidebarStyle: 'follow',
|
||||||
background: DEFAULT_BACKGROUND,
|
background: DEFAULT_BACKGROUND,
|
||||||
fontSans: 'default',
|
fontSans: 'default',
|
||||||
|
fontSansCustom: '',
|
||||||
fontMono: 'default',
|
fontMono: 'default',
|
||||||
|
fontMonoCustom: '',
|
||||||
uiScale: 1,
|
uiScale: 1,
|
||||||
radius: 0.75,
|
radius: 0.75,
|
||||||
density: 'cozy',
|
density: 'cozy',
|
||||||
@@ -207,6 +220,7 @@ const DEFAULT_APPEARANCE: UiAppearance = {
|
|||||||
timeFormat: '24h',
|
timeFormat: '24h',
|
||||||
pollInterval: 3000,
|
pollInterval: 3000,
|
||||||
customCss: '',
|
customCss: '',
|
||||||
|
cssVars: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
|
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
|
||||||
@@ -243,7 +257,7 @@ const DEFAULT_PAGES: UiPages = {
|
|||||||
export function defaultUiConfig(): UiConfig {
|
export function defaultUiConfig(): UiConfig {
|
||||||
return {
|
return {
|
||||||
version: UI_CONFIG_VERSION,
|
version: UI_CONFIG_VERSION,
|
||||||
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND } },
|
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND }, cssVars: {} },
|
||||||
layout: {
|
layout: {
|
||||||
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
|
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
|
||||||
navItems: DEFAULT_NAV_ITEMS.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;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A free-form font-family value (a single family or a comma-separated stack),
|
||||||
|
* safe to interpolate into `--font-sans: <value>;`. 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<string>([
|
||||||
|
'--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:
|
||||||
|
// <value>;` 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<string, string> {
|
||||||
|
if (!isObject(value)) return {};
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
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[] {
|
function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayoutItem[] {
|
||||||
if (!Array.isArray(value)) return fallback.map((i) => ({ ...i }));
|
if (!Array.isArray(value)) return fallback.map((i) => ({ ...i }));
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
@@ -404,7 +485,9 @@ export function normalizeAppearance(value: unknown, imageState: ServerImageState
|
|||||||
sidebarStyle: oneOf<SidebarStyle>(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle),
|
sidebarStyle: oneOf<SidebarStyle>(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle),
|
||||||
background: normalizeBackground(v.background, imageState),
|
background: normalizeBackground(v.background, imageState),
|
||||||
fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans),
|
fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans),
|
||||||
|
fontSansCustom: fontFamilyOr(v.fontSansCustom, DEFAULT_APPEARANCE.fontSansCustom),
|
||||||
fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono),
|
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),
|
uiScale: clampNum(v.uiScale, 0.9, 1.2, DEFAULT_APPEARANCE.uiScale),
|
||||||
radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius),
|
radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius),
|
||||||
density: oneOf<Density>(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density),
|
density: oneOf<Density>(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density),
|
||||||
@@ -415,6 +498,7 @@ export function normalizeAppearance(value: unknown, imageState: ServerImageState
|
|||||||
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
|
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
|
||||||
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
|
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
|
||||||
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
|
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
|
||||||
|
cssVars: normalizeCssVars(v.cssVars),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Slider } from '@/components/ui/slider';
|
|||||||
import {
|
import {
|
||||||
ACCENTS,
|
ACCENTS,
|
||||||
DEFAULT_APPEARANCE,
|
DEFAULT_APPEARANCE,
|
||||||
|
FONT_CUSTOM_ID,
|
||||||
FONT_MONO_OPTIONS,
|
FONT_MONO_OPTIONS,
|
||||||
FONT_SANS_OPTIONS,
|
FONT_SANS_OPTIONS,
|
||||||
GRADIENT_OPTIONS,
|
GRADIENT_OPTIONS,
|
||||||
@@ -25,6 +26,7 @@ import {
|
|||||||
type BackgroundType,
|
type BackgroundType,
|
||||||
type DarkIntensity,
|
type DarkIntensity,
|
||||||
type Density,
|
type Density,
|
||||||
|
type FontSpec,
|
||||||
type SidebarStyle,
|
type SidebarStyle,
|
||||||
type ThemeMode,
|
type ThemeMode,
|
||||||
type TimeFormat,
|
type TimeFormat,
|
||||||
@@ -356,10 +358,24 @@ function AppearancePanel() {
|
|||||||
|
|
||||||
<Group title="排版与界面" icon={Palette} description="字体、圆角、缩放与密度。">
|
<Group title="排版与界面" icon={Palette} description="字体、圆角、缩放与密度。">
|
||||||
<SettingRow label="界面字体" layout="stack">
|
<SettingRow label="界面字体" layout="stack">
|
||||||
<Segmented value={a.fontSans} options={FONT_SANS_OPTIONS.map((f) => ({ value: f.id, label: f.label }))} onChange={(fontSans) => setAppearance({ fontSans })} />
|
<FontField
|
||||||
|
value={a.fontSans}
|
||||||
|
custom={a.fontSansCustom}
|
||||||
|
presets={FONT_SANS_OPTIONS}
|
||||||
|
onChange={(fontSans) => setAppearance({ fontSans })}
|
||||||
|
onCustomChange={(fontSansCustom) => setAppearance({ fontSansCustom })}
|
||||||
|
placeholder="例如:LXGW WenKai, PingFang SC"
|
||||||
|
/>
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="等宽字体" hint="用于日志与代码。" layout="stack">
|
<SettingRow label="等宽字体" hint="用于日志与代码。" layout="stack">
|
||||||
<Segmented value={a.fontMono} options={FONT_MONO_OPTIONS.map((f) => ({ value: f.id, label: f.label }))} onChange={(fontMono) => setAppearance({ fontMono })} />
|
<FontField
|
||||||
|
value={a.fontMono}
|
||||||
|
custom={a.fontMonoCustom}
|
||||||
|
presets={FONT_MONO_OPTIONS}
|
||||||
|
onChange={(fontMono) => setAppearance({ fontMono })}
|
||||||
|
onCustomChange={(fontMonoCustom) => setAppearance({ fontMonoCustom })}
|
||||||
|
placeholder="例如:Cascadia Code, Sarasa Mono SC"
|
||||||
|
/>
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="圆角">
|
<SettingRow label="圆角">
|
||||||
<Segmented value={a.radius} options={RADIUS_OPTIONS.map((r) => ({ value: r.value, label: r.label }))} onChange={(radius) => setAppearance({ radius })} />
|
<Segmented value={a.radius} options={RADIUS_OPTIONS.map((r) => ({ value: r.value, label: r.label }))} onChange={(radius) => setAppearance({ radius })} />
|
||||||
@@ -384,6 +400,8 @@ function AppearancePanel() {
|
|||||||
</SettingRow>
|
</SettingRow>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
<ThemeVarsPanel cssVars={a.cssVars} onChange={(cssVars) => setAppearance({ cssVars })} />
|
||||||
|
|
||||||
<Group title="无障碍与侧栏" icon={Accessibility} description="动效、对比度与侧栏默认状态。">
|
<Group title="无障碍与侧栏" icon={Accessibility} description="动效、对比度与侧栏默认状态。">
|
||||||
<SettingRow label="减弱动效" hint="弱化页面切换、弹簧等装饰性动画(保留轻微淡入),对低端设备与晕动敏感者更友好。" layout="inline">
|
<SettingRow label="减弱动效" hint="弱化页面切换、弹簧等装饰性动画(保留轻微淡入),对低端设备与晕动敏感者更友好。" layout="inline">
|
||||||
<ToggleSwitch value={a.reduceMotion} onChange={(reduceMotion) => setAppearance({ reduceMotion })} ariaLabel="减弱动效" />
|
<ToggleSwitch value={a.reduceMotion} onChange={(reduceMotion) => 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 <datalist> 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<LocalFont[]> };
|
||||||
|
|
||||||
|
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<string[] | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const canQuery = typeof (window as FontQueryWindow).queryLocalFonts === 'function';
|
||||||
|
const isCustom = value === FONT_CUSTOM_ID;
|
||||||
|
|
||||||
|
const options: Opt<string>[] = [
|
||||||
|
...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 (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<Segmented value={value} options={options} onChange={onChange} />
|
||||||
|
{isCustom && (
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={custom}
|
||||||
|
list={canQuery ? listId : undefined}
|
||||||
|
onChange={(e) => 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 && (
|
||||||
|
<datalist id={listId}>
|
||||||
|
{fonts.map((f) => <option key={f} value={f} />)}
|
||||||
|
</datalist>
|
||||||
|
)}
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
{canQuery
|
||||||
|
? '可输入字体名称,或聚焦后从已安装字体中选择;找不到时回退到系统字体。'
|
||||||
|
: '输入已安装的字体名称(可写多个,用逗号分隔);找不到时回退到系统字体。'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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<string, string>; onChange: (next: Record<string, string>) => 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 (
|
||||||
|
<Group
|
||||||
|
title="主题微调"
|
||||||
|
icon={Palette}
|
||||||
|
description="逐个覆盖主题颜色变量,叠加在当前配色之上;未设置的保持配色默认值。登录页也会应用(安全:仅白名单变量与颜色值)。"
|
||||||
|
>
|
||||||
|
{CSS_VAR_FIELDS.map((f) => {
|
||||||
|
const override = cssVars[f.token];
|
||||||
|
return (
|
||||||
|
<SettingRow key={f.token} label={f.label} hint={<code className="font-mono text-[11px]">{f.token}</code>} layout="inline">
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
{override ? (
|
||||||
|
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{override}</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-[11px] text-muted-foreground">默认</span>
|
||||||
|
)}
|
||||||
|
<label
|
||||||
|
title="选择颜色"
|
||||||
|
className="relative size-7 cursor-pointer overflow-hidden rounded-md border"
|
||||||
|
style={override ? { backgroundColor: override } : { background: 'repeating-conic-gradient(#cbd5e1 0% 25%, #fff 0% 50%) 50% / 10px 10px' }}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
value={override || '#888888'}
|
||||||
|
onChange={(e) => set(f.token, e.target.value)}
|
||||||
|
className="absolute inset-0 cursor-pointer opacity-0"
|
||||||
|
aria-label={`${f.label}颜色`}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => clear(f.token)}
|
||||||
|
disabled={!override}
|
||||||
|
aria-label={`重置${f.label}`}
|
||||||
|
className="rounded-md p-1 text-muted-foreground transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 enabled:hover:text-destructive disabled:opacity-30"
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</SettingRow>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{count > 0 && (
|
||||||
|
<div className="flex items-center justify-between gap-4 px-5 py-3">
|
||||||
|
<span className="text-[11px] text-muted-foreground">已覆盖 {count} 个变量</span>
|
||||||
|
<Button variant="ghost" size="sm" onClick={() => onChange({})} className="text-destructive hover:text-destructive">
|
||||||
|
<RotateCcw className="size-4" /> 全部恢复默认
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─────────────── 数据与格式 ───────────────
|
// ─────────────── 数据与格式 ───────────────
|
||||||
|
|
||||||
const TIME_FORMAT_OPTIONS: Opt<TimeFormat>[] = [
|
const TIME_FORMAT_OPTIONS: Opt<TimeFormat>[] = [
|
||||||
|
|||||||
@@ -102,7 +102,9 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
|
|||||||
sidebarStyle: 'follow',
|
sidebarStyle: 'follow',
|
||||||
background: { type: 'none', color: '#0ea5e9', gradient: 'none', imageOpacity: 0.15, imageBlur: 0, hasImage: false, imageMime: '', imageVersion: 0 },
|
background: { type: 'none', color: '#0ea5e9', gradient: 'none', imageOpacity: 0.15, imageBlur: 0, hasImage: false, imageMime: '', imageVersion: 0 },
|
||||||
fontSans: 'default',
|
fontSans: 'default',
|
||||||
|
fontSansCustom: '',
|
||||||
fontMono: 'default',
|
fontMono: 'default',
|
||||||
|
fontMonoCustom: '',
|
||||||
uiScale: 1,
|
uiScale: 1,
|
||||||
radius: 0.75,
|
radius: 0.75,
|
||||||
density: 'cozy',
|
density: 'cozy',
|
||||||
@@ -113,8 +115,12 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
|
|||||||
timeFormat: '24h',
|
timeFormat: '24h',
|
||||||
pollInterval: 3000,
|
pollInterval: 3000,
|
||||||
customCss: '',
|
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_CACHE = 'snowluma_ui_appearance';
|
||||||
const LS_MIGRATED = 'snowluma_ui_migrated';
|
const LS_MIGRATED = 'snowluma_ui_migrated';
|
||||||
const TOKEN_KEY = 'snowluma_token';
|
const TOKEN_KEY = 'snowluma_token';
|
||||||
@@ -306,10 +312,50 @@ function paletteVarsCss(a: UiAppearance): string {
|
|||||||
return `${selector}{${body}}`;
|
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;
|
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<string>([
|
||||||
|
'--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 {
|
function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
|
|
||||||
@@ -334,8 +380,8 @@ function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
|
|||||||
|
|
||||||
// Mode-independent vars go inline on :root.
|
// Mode-independent vars go inline on :root.
|
||||||
root.style.setProperty('--radius', `${a.radius}rem`);
|
root.style.setProperty('--radius', `${a.radius}rem`);
|
||||||
root.style.setProperty('--font-sans', fontStack(FONT_SANS_OPTIONS, a.fontSans));
|
root.style.setProperty('--font-sans', resolveFontStack(FONT_SANS_OPTIONS, a.fontSans, a.fontSansCustom, 'system-ui, sans-serif'));
|
||||||
root.style.setProperty('--font-mono', fontStack(FONT_MONO_OPTIONS, a.fontMono));
|
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.
|
// UI scale: scale the root font-size so all rem-based sizing tracks it.
|
||||||
// Clamp defensively (the localStorage cache is locally tamperable; the
|
// Clamp defensively (the localStorage cache is locally tamperable; the
|
||||||
// server already bounds this to 0.9..1.2 for its own values).
|
// 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);
|
document.head.appendChild(el);
|
||||||
}
|
}
|
||||||
// Palette (base/surface tokens) first, then accent (--primary/--ring) — a
|
// Palette (base/surface tokens) first, then accent (--primary/--ring) — a
|
||||||
// disjoint var set, layered after so it composes with any flavor.
|
// disjoint var set, layered after so it composes with any flavor. The
|
||||||
el.textContent = `${paletteVarsCss(a)}\n${accentVarsCss(a)}`;
|
// 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
|
// Custom CSS — appended AFTER the accent block so it is the last style in
|
||||||
// <head> and can override anything. Skipped under ?safe-mode=1 (escape
|
// <head> and can override anything. Skipped under ?safe-mode=1 (escape
|
||||||
|
|||||||
@@ -202,7 +202,11 @@ export interface UiAppearance {
|
|||||||
sidebarStyle: SidebarStyle;
|
sidebarStyle: SidebarStyle;
|
||||||
background: UiBackground;
|
background: UiBackground;
|
||||||
fontSans: string;
|
fontSans: string;
|
||||||
|
/** Free-form sans font-family stack, used when `fontSans === 'custom'`. */
|
||||||
|
fontSansCustom: string;
|
||||||
fontMono: string;
|
fontMono: string;
|
||||||
|
/** Free-form mono font-family stack, used when `fontMono === 'custom'`. */
|
||||||
|
fontMonoCustom: string;
|
||||||
uiScale: number;
|
uiScale: number;
|
||||||
radius: number;
|
radius: number;
|
||||||
density: Density;
|
density: Density;
|
||||||
@@ -214,6 +218,8 @@ export interface UiAppearance {
|
|||||||
pollInterval: number;
|
pollInterval: number;
|
||||||
/** Operator custom CSS (applied post-auth only; stripped from /api/ui/public). */
|
/** Operator custom CSS (applied post-auth only; stripped from /api/ui/public). */
|
||||||
customCss: string;
|
customCss: string;
|
||||||
|
/** Theme-token overrides from the variable panel (whitelisted keys/values). */
|
||||||
|
cssVars: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UiLayoutItem {
|
export interface UiLayoutItem {
|
||||||
|
|||||||
Reference in new issue
Block a user