Icon packs are the owner's pick: the theme choice carries it, Appearance offers it

- ThemeChoice gains an optional icons field (absent: follow the theme's pack; site: the site's
  own icons; else a pack id), validated natively as a slug (waybetter-host theme.rs, with a
  test) and kept by per-theme choices; variants is an override group natively too.
- Appearance: an Icons row (Follow the theme / the site's own icons / the site's packs) when the
  site lists packs; English words in the catalog.
- The chrome's glyphs follow the owner's pick as well as the theme's suggestion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CRTkafa 2026-10-01 04:19:55 +07:00
parent e88339bda6
commit 8a0ab6d3a1
8 changed files with 50 additions and 12 deletions

View file

@ -42,7 +42,7 @@ pub const MAX_TOTAL_BYTES: usize = 4_000_000;
/// Theme names: 1-60 characters (`theme.schema.json` `name`). /// Theme names: 1-60 characters (`theme.schema.json` `name`).
pub const MAX_NAME_CHARS: usize = 60; pub const MAX_NAME_CHARS: usize = 60;
/// Override groups the panel may change on top of a theme. /// Override groups the panel may change on top of a theme.
pub const OVERRIDE_KEYS: [&str; 7] = ["font", "shape", "layout", "background", "effects", "colors", "css"]; pub const OVERRIDE_KEYS: [&str; 8] = ["font", "shape", "layout", "background", "effects", "colors", "css", "variants"];
/// The theme applied to the site's tabs: a theme id (built-in or one of `themes`), an optional /// The theme applied to the site's tabs: a theme id (built-in or one of `themes`), an optional
/// accent, per-group overrides from the panel and the owner's imported theme documents. /// accent, per-group overrides from the panel and the owner's imported theme documents.
@ -56,6 +56,10 @@ pub struct ThemeChoice {
pub overrides: Map<String, Value>, pub overrides: Map<String, Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub themes: Vec<Value>, pub themes: Vec<Value>,
/// The owner's icon pack: absent follows the theme's suggestion, `site` keeps the site's own icons,
/// otherwise a pack id (theme engine v2). A slug; an unknown pack falls back to the site's icons in the page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icons: Option<String>,
} }
/// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`). /// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`).
@ -75,7 +79,7 @@ fn doc_id(theme: &Value) -> Option<&str> {
impl ThemeChoice { impl ThemeChoice {
/// The site's own look, nothing customized. /// The site's own look, nothing customized.
pub fn default_for(site: &ThemeSite) -> Self { pub fn default_for(site: &ThemeSite) -> Self {
Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new() } Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new(), icons: None }
} }
pub fn validate(&self, site: &ThemeSite) -> Result<(), String> { pub fn validate(&self, site: &ThemeSite) -> Result<(), String> {
@ -84,6 +88,11 @@ impl ThemeChoice {
return Err("VALIDATION: accent must use six-digit hex".into()); return Err("VALIDATION: accent must use six-digit hex".into());
} }
} }
if let Some(icons) = &self.icons {
if !valid_id(icons) {
return Err("VALIDATION: an icon pack id is a lowercase slug".into());
}
}
if self.themes.len() > MAX_THEMES { if self.themes.len() > MAX_THEMES {
return Err("VALIDATION: too many themes".into()); return Err("VALIDATION: too many themes".into());
} }
@ -120,7 +129,7 @@ impl ThemeChoice {
/// True when the site keeps its own look (nothing to apply). Imported themes are kept in the /// True when the site keeps its own look (nothing to apply). Imported themes are kept in the
/// file even while the site's own look is selected, so this only looks at what is applied. /// file even while the site's own look is selected, so this only looks at what is applied.
pub fn is_default(&self, site: &ThemeSite) -> bool { pub fn is_default(&self, site: &ThemeSite) -> bool {
self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty() self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty() && self.icons.is_none()
} }
/// Nothing worth persisting: the site's own look and no imported themes. /// Nothing worth persisting: the site's own look and no imported themes.
@ -139,7 +148,7 @@ impl ThemeChoice {
let base = if id == self.preset || !self.knows(site, id) { let base = if id == self.preset || !self.knows(site, id) {
self.clone() self.clone()
} else { } else {
ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone() } ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone(), icons: self.icons.clone() }
}; };
let preset = base.preset.clone(); let preset = base.preset.clone();
let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect(); let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect();
@ -304,6 +313,16 @@ mod tests {
assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg"); assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg");
} }
#[test]
fn icon_choice_is_a_slug_and_counts_as_a_choice() {
let picked = with(json!({ "preset": "site", "icons": "wb-pixel" })).unwrap();
assert_eq!(picked.icons.as_deref(), Some("wb-pixel"));
assert!(!picked.is_default(&SITE), "an icon pick is applied even on the site's own look");
assert!(with(json!({ "preset": "site", "icons": "Bad Pack!" })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "variants": { "nav": "top" } } })).is_ok(), "layout variants are an override group");
assert_eq!(picked.for_theme(&SITE, "nord").icons.as_deref(), Some("wb-pixel"), "the icon pick is global");
}
#[test] #[test]
fn user_themes_and_overrides_are_bounded() { fn user_themes_and_overrides_are_bounded() {
let ok = with(json!({ "preset": "mine", "themes": [{ "id": "mine", "name": "Mine", "colors": null }], "overrides": { "font": { "scale": 1.1 } } })).unwrap(); let ok = with(json!({ "preset": "mine", "themes": [{ "id": "mine", "name": "Mine", "colors": null }], "overrides": { "font": { "scale": 1.1 } } })).unwrap();

View file

@ -5,8 +5,11 @@
import { applyOverrides, isHex, sanitizeSpec, type Palette, type ThemeOverrides, type ThemeSpec } from './themeSpec.ts'; import { applyOverrides, isHex, sanitizeSpec, type Palette, type ThemeOverrides, type ThemeSpec } from './themeSpec.ts';
/** What is persisted natively and handed to the page runtime. */ /**
export type ThemeChoice = { preset: string; accent: string | null; overrides: ThemeOverrides; themes: ThemeSpec[] }; * What is persisted natively and handed to the page runtime. `icons` is the owner's icon pack (theme
* engine v2): absent follows the theme's suggestion, `site` keeps the site's own icons, else a pack id.
*/
export type ThemeChoice = { preset: string; accent: string | null; overrides: ThemeOverrides; themes: ThemeSpec[]; icons?: string };
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */ /** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
export const MAX_USER_THEMES = 24; export const MAX_USER_THEMES = 24;
@ -53,7 +56,8 @@ export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog
const value = rawOverrides[key]; const value = rawOverrides[key];
if (value && typeof value === 'object' && !Array.isArray(value)) (overrides as Record<string, unknown>)[key] = value; if (value && typeof value === 'object' && !Array.isArray(value)) (overrides as Record<string, unknown>)[key] = value;
} }
return { preset, accent, overrides, themes }; const icons = typeof source.icons === 'string' && /^[a-z0-9-]{1,40}$/.test(source.icons) && source.icons !== 'theme' ? source.icons : undefined;
return { preset, accent, overrides, themes, ...(icons ? { icons } : {}) };
} }
const base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first; const base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first;
@ -69,11 +73,11 @@ export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog
/** The choice a tab's theme id stands for (themeScopes: account and pane themes): the global choice itself, or that theme without customizations. */ /** The choice a tab's theme id stands for (themeScopes: account and pane themes): the global choice itself, or that theme without customizations. */
export function choiceForId(global: ThemeChoice, id: string): ThemeChoice { export function choiceForId(global: ThemeChoice, id: string): ThemeChoice {
return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes }; return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes, ...(global.icons ? { icons: global.icons } : {}) };
} }
/** The shape persisted natively: empty groups are dropped so "no override" stays unambiguous. */ /** The shape persisted natively: empty groups are dropped so "no override" stays unambiguous. */
export function serializeChoice(choice: ThemeChoice) { export function serializeChoice(choice: ThemeChoice) {
const overrides = Object.fromEntries(Object.entries(choice.overrides).filter(([, value]) => value && Object.keys(value).length)); const overrides = Object.fromEntries(Object.entries(choice.overrides).filter(([, value]) => value && Object.keys(value).length));
return { preset: choice.preset, accent: choice.accent, ...(Object.keys(overrides).length ? { overrides } : {}), ...(choice.themes.length ? { themes: choice.themes } : {}) }; return { preset: choice.preset, accent: choice.accent, ...(Object.keys(overrides).length ? { overrides } : {}), ...(choice.themes.length ? { themes: choice.themes } : {}), ...(choice.icons ? { icons: choice.icons } : {}) };
} }

View file

@ -205,7 +205,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
let theme = catalog.resolve(choice); let theme = catalog.resolve(choice);
let lastKey = ''; let lastKey = '';
let timer: ReturnType<typeof setInterval> | null = null; let timer: ReturnType<typeof setInterval> | null = null;
const active = () => !isNeutral(theme) || !!choice.accent; const active = () => !isNeutral(theme) || !!choice.accent || !!choice.icons;
let mode: Mode = site.initialMode; let mode: Mode = site.initialMode;
let resolved: ResolvedTheme = site.resolved(choice, mode); let resolved: ResolvedTheme = site.resolved(choice, mode);
let resolvedKey = themeKey(resolved); let resolvedKey = themeKey(resolved);

View file

@ -45,7 +45,7 @@ export type ThemeAdapter<Choice = unknown, Spec extends ThemeDoc = ThemeDoc> = {
/** The chrome's colors and fonts for a theme. */ /** The chrome's colors and fonts for a theme. */
chrome(spec: Spec): ChromeTheme; chrome(spec: Spec): ChromeTheme;
/** The icon pack a theme suggests for the chrome (theme engine v2); absent: the frame's own glyphs. */ /** The icon pack a theme suggests for the chrome (theme engine v2); absent: the frame's own glyphs. */
iconPack?(spec: Spec): IconPack | null; iconPack?(spec: Spec, choice?: Choice): IconPack | null;
/** Three swatch colors for menus (page, text, accent, on the theme's surface and border). */ /** Three swatch colors for menus (page, text, accent, on the theme's surface and border). */
dots(spec: Spec): { page: string; bg: string; border: string; text: string; accent: string }; dots(spec: Spec): { page: string; bg: string; border: string; text: string; accent: string };
}; };
@ -208,7 +208,7 @@ export function createThemeStore<Choice, Spec extends ThemeDoc>(adapter: ThemeAd
chromeFontsFor(global); chromeFontsFor(global);
const vars = chromeVars(adapter.chrome(global), own); const vars = chromeVars(adapter.chrome(global), own);
setVars(document.documentElement, vars); setVars(document.documentElement, vars);
try { setChromeIconPack(own ? null : adapter.iconPack?.(global) ?? null); } catch { setChromeIconPack(null); } try { setChromeIconPack(own ? null : adapter.iconPack?.(global, state.choice) ?? null); } catch { setChromeIconPack(null); }
// The next start paints these from its first frame (boot.ts); an editor's draft is not kept. // The next start paints these from its first frame (boot.ts); an editor's draft is not kept.
if (!state.preview) { try { localStorage.setItem(BOOT_CACHE_KEY, JSON.stringify(vars)); } catch { /* Best effort. */ } } if (!state.preview) { try { localStorage.setItem(BOOT_CACHE_KEY, JSON.stringify(vars)); } catch { /* Best effort. */ } }
syncGroups(); syncGroups();

View file

@ -206,6 +206,11 @@ export function Appearance({ notify }: { notify: Notify }) {
<Row label={t('wb.appearance.accent')} hint={t('wb.appearance.accentHint')} keywords="color colour highlight link" wide> <Row label={t('wb.appearance.accent')} hint={t('wb.appearance.accentHint')} keywords="color colour highlight link" wide>
<ColorField label={t('wb.appearance.accentColor')} value={choice.accent} swatches={[...themes.accents]} autoLabel={t('wb.appearance.theme')} onChange={accent => void update({ ...choice, accent })}/> <ColorField label={t('wb.appearance.accentColor')} value={choice.accent} swatches={[...themes.accents]} autoLabel={t('wb.appearance.theme')} onChange={accent => void update({ ...choice, accent })}/>
</Row> </Row>
{themes.iconPacks?.length ? <Row label={t('wb.appearance.icons')} hint={t('wb.appearance.iconsHint')} keywords="icon pack glyphs symbols pixel">
<Select label={t('wb.appearance.icons')} value={choice.icons ?? 'theme'} width={220}
onChange={icons => void update({ ...choice, icons: icons === 'theme' ? undefined : icons })}
options={[{ value: 'theme', label: t('wb.appearance.icons.theme') }, { value: 'site', label: t('wb.appearance.icons.site') }, ...themes.iconPacks.map(pack => ({ value: pack.id, label: pack.name }))]}/>
</Row> : null}
<Row label={t('wb.appearance.fonts')} hint={t('wb.appearance.fontsHint')} <Row label={t('wb.appearance.fonts')} hint={t('wb.appearance.fontsHint')}
keywords="typeface typography family font google fonts post text heading numbers code interface window dialogs" wide> keywords="typeface typography family font google fonts post text heading numbers code interface window dialogs" wide>
<FontRoles font={effective.font} onRole={setRole} compact/> <FontRoles font={effective.font} onRole={setRole} compact/>

View file

@ -7,6 +7,10 @@ export const PANEL_MESSAGES = {
'wb.appearance.accent': 'Accent', 'wb.appearance.accent': 'Accent',
'wb.appearance.accentColor': 'Accent color', 'wb.appearance.accentColor': 'Accent color',
'wb.appearance.accentHint': 'Links, the active tab, focus rings and filled buttons.', 'wb.appearance.accentHint': 'Links, the active tab, focus rings and filled buttons.',
'wb.appearance.icons': 'Icons',
'wb.appearance.iconsHint': 'The icons of the site and of this window. A theme may suggest a pack; your pick wins.',
'wb.appearance.icons.theme': 'Follow the theme',
'wb.appearance.icons.site': 'The site\'s own icons',
'wb.appearance.accountTheme': 'Account theme · {name}', 'wb.appearance.accountTheme': 'Account theme · {name}',
'wb.appearance.accountsHint': 'Every pane of an account shows its theme unless the pane has its own.', 'wb.appearance.accountsHint': 'Every pane of an account shows its theme unless the pane has its own.',
'wb.appearance.appTheme': 'App theme · {name}', 'wb.appearance.appTheme': 'App theme · {name}',

View file

@ -80,6 +80,8 @@ export type PanelThemes = {
baseSwatches?: { bg: string[]; text: string[]; accent: string[] }; baseSwatches?: { bg: string[]; text: string[]; accent: string[] };
/** File name suffix of an exported theme (default `.theme.json`). */ /** File name suffix of an exported theme (default `.theme.json`). */
fileSuffix?: string; fileSuffix?: string;
/** Icon packs the owner can pick in Appearance (theme engine v2); absent: no Icons row. */
iconPacks?: ReadonlyArray<{ id: string; name: string; description?: string }>;
/** The builder's chrome preview: tab titles and the address chip. */ /** The builder's chrome preview: tab titles and the address chip. */
chromePreview?: { tabs: [string, string, string]; chip: string; page: string }; chromePreview?: { tabs: [string, string, string]; chip: string; page: string };
/** /**

View file

@ -400,6 +400,10 @@
"wb.appearance.accent": "Accent", "wb.appearance.accent": "Accent",
"wb.appearance.accentColor": "Accent color", "wb.appearance.accentColor": "Accent color",
"wb.appearance.accentHint": "Links, the active tab, focus rings and filled buttons.", "wb.appearance.accentHint": "Links, the active tab, focus rings and filled buttons.",
"wb.appearance.icons": "Icons",
"wb.appearance.iconsHint": "The icons of the site and of this window. A theme may suggest a pack; your pick wins.",
"wb.appearance.icons.theme": "Follow the theme",
"wb.appearance.icons.site": "The site's own icons",
"wb.appearance.accountTheme": "Account theme · {name}", "wb.appearance.accountTheme": "Account theme · {name}",
"wb.appearance.accountsHint": "Every pane of an account shows its theme unless the pane has its own.", "wb.appearance.accountsHint": "Every pane of an account shows its theme unless the pane has its own.",
"wb.appearance.appTheme": "App theme · {name}", "wb.appearance.appTheme": "App theme · {name}",