runtime + host: the theme engine (theme documents, choice catalog, page runtime, fonts; native theme state)

The site-independent theme engine moves from wayBetter for X into the framework:
- runtime/themeSpec.ts: theme document types, the schema's defaults (BASE_*), sanitizing,
  import, overrides, ensureContrast, font roles/stacks, font choices, backgrounds.
- runtime/themeChoice.ts: ThemeChoice and createThemeCatalog(builtins) (normalize, base,
  resolve, palette, all), choiceForId, serializeChoice.
- runtime/themeRuntime.ts: installThemeRuntime(win, site) (live CSS over the site's rules,
  --wb-* vars, site color mode, first-frame snapshot), collectRules, resolvedFonts.
- runtime/fonts.ts: bundled fonts and owner-downloaded Google Fonts from bytes.
- themeApi exports hexToRgb, mix and MONO_FAMILIES (one copy: themeTokens and themeSpec use them).
- host theme.rs: ThemeChoice/ThemeScopes over a site's ThemeSite (envelope checks against
  theme.schema.json, which theme a tab shows, page color, delivery script).
This commit is contained in:
CRTkafa 2026-09-29 13:07:59 +07:00
parent 3a4c7c9831
commit 5c93b78704
9 changed files with 1542 additions and 14 deletions

View file

@ -19,6 +19,8 @@
//! - [`i18n`]: the strings native UI and site tabs get in the owner's language (validated data), OS locale.
//! - [`backup`]: the settings backup envelope, secret scrubbing and the plugin/account sections.
//! - [`sync`]: encrypted settings sync through a folder the owner syncs (Argon2id + XChaCha20-Poly1305).
//! - [`theme`]: the owner's theme choice and account/pane themes (envelope checks, which theme a tab
//! shows, its page color and delivery script) over a site's built-in themes.
//! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated).
//! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file.
//! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits).
@ -57,6 +59,7 @@ pub mod store;
pub mod sync;
pub mod tabs;
pub mod testkit;
pub mod theme;
pub mod update;
pub mod workspaces;

View file

@ -0,0 +1,410 @@
//! The owner's theme state as native code keeps it: the theme choice (a theme id, an accent, the
//! panel's per-group overrides and the owner's imported theme documents; `x-theme.v2.json` style
//! app data) and which theme each site tab shows ([`ThemeScopes`]: a pane's own theme, else its
//! account profile's, else the global one). The same rules run in the shell
//! (`waybetter/packages/runtime/src/themeChoice.ts`, `shell/src/frame/themeScopes.ts`).
//!
//! Theme documents are declarative JSON (`theme.schema.json` in the `waybetter` package) that the page
//! runtime sanitizes field by field (`runtime/src/themeSpec.ts`: hex colors, clamped numbers, fixed
//! enums, font names matching a strict pattern, `data:image/*` backgrounds). Here only the envelope is
//! checked against the schema's own rules (ids, names, sizes, override groups), so nothing unbounded
//! is persisted or evaluated in every site tab. What differs per site is its built-in themes
//! ([`ThemeSite`]).
use crate::site::SiteSpec;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::BTreeMap;
/// A site's built-in themes. The first preset is the site's own look (the default choice).
#[derive(Clone, Copy, Debug)]
pub struct ThemeSite {
/// Built-in theme ids the page runtime knows (the site's `BUILTIN_THEMES`), its own look first.
pub presets: &'static [&'static str],
/// The page color (`colors.page`, else `colors.bg`) of every built-in theme with colors of its
/// own: a tab webview's native background before the page paints. The site's own look has none.
pub page_colors: &'static [(&'static str, &'static str)],
}
impl ThemeSite {
/// The site's own look (`presets[0]`).
pub fn own(&self) -> &'static str {
self.presets.first().copied().unwrap_or("site")
}
}
/// At most this many imported/user themes are kept (`MAX_USER_THEMES` in themeChoice.ts).
pub const MAX_THEMES: usize = 24;
/// One theme document (a background image is a `data:` URL inside it).
pub const MAX_THEME_BYTES: usize = 1_200_000;
/// The whole persisted theme state, all themes included.
pub const MAX_TOTAL_BYTES: usize = 4_000_000;
/// Theme names: 1-60 characters (`theme.schema.json` `name`).
pub const MAX_NAME_CHARS: usize = 60;
/// Override groups the panel may change on top of a theme.
pub const OVERRIDE_KEYS: [&str; 7] = ["font", "shape", "layout", "background", "effects", "colors", "css"];
/// 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.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ThemeChoice {
pub preset: String,
#[serde(default)]
pub accent: Option<String>,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub overrides: Map<String, Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub themes: Vec<Value>,
}
/// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`).
pub fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// A six-digit `#rrggbb` color.
pub fn valid_hex(value: &str) -> bool {
value.len() == 7 && value.starts_with('#') && value.as_bytes()[1..].iter().all(u8::is_ascii_hexdigit)
}
fn doc_id(theme: &Value) -> Option<&str> {
theme.get("id").and_then(Value::as_str)
}
impl ThemeChoice {
/// The site's own look, nothing customized.
pub fn default_for(site: &ThemeSite) -> Self {
Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new() }
}
pub fn validate(&self, site: &ThemeSite) -> Result<(), String> {
if let Some(accent) = &self.accent {
if !valid_hex(accent) {
return Err("VALIDATION: accent must use six-digit hex".into());
}
}
if self.themes.len() > MAX_THEMES {
return Err("VALIDATION: too many themes".into());
}
let mut ids: Vec<&str> = Vec::new();
for theme in &self.themes {
let object = theme.as_object().ok_or("VALIDATION: a theme must be an object")?;
let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: a theme needs an id")?;
if !valid_id(id) || site.presets.contains(&id) || ids.contains(&id) {
return Err("VALIDATION: theme ids are unique lowercase slugs".into());
}
let name = object.get("name").and_then(Value::as_str).ok_or("VALIDATION: a theme needs a name")?;
if name.trim().is_empty() || name.chars().count() > MAX_NAME_CHARS {
return Err("VALIDATION: theme names are 1-60 characters".into());
}
if serde_json::to_vec(theme).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_THEME_BYTES {
return Err("VALIDATION: theme is too large".into());
}
ids.push(id);
}
if !site.presets.contains(&self.preset.as_str()) && !ids.contains(&self.preset.as_str()) {
return Err("VALIDATION: unknown theme preset".into());
}
for (key, value) in &self.overrides {
if !OVERRIDE_KEYS.contains(&key.as_str()) || !value.is_object() {
return Err("VALIDATION: unknown theme override".into());
}
}
if serde_json::to_vec(self).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_TOTAL_BYTES {
return Err("VALIDATION: theme data is too large".into());
}
Ok(())
}
/// 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.
pub fn is_default(&self, site: &ThemeSite) -> bool {
self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty()
}
/// Nothing worth persisting: the site's own look and no imported themes.
pub fn is_empty(&self, site: &ThemeSite) -> bool {
self.is_default(site) && self.themes.is_empty()
}
/// Whether `id` names a theme this state knows (built-in or imported).
pub fn knows(&self, site: &ThemeSite, id: &str) -> bool {
site.presets.contains(&id) || self.themes.iter().any(|theme| doc_id(theme) == Some(id))
}
/// The state a tab gets when it shows theme `id`: this state itself for the global theme, else
/// that theme document without the global customizations. Only the document shown is sent.
pub fn for_theme(&self, site: &ThemeSite, id: &str) -> ThemeChoice {
let base = if id == self.preset || !self.knows(site, id) {
self.clone()
} else {
ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone() }
};
let preset = base.preset.clone();
let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect();
ThemeChoice { themes, ..base }
}
/// Google Fonts families (`font.roles.*` with `"source": "google"`) the shown theme uses in the
/// site's page, from its document and the global overrides. Names are checked again when read from disk.
pub fn google_fonts(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let doc = self.themes.iter().find(|theme| doc_id(theme) == Some(self.preset.as_str()));
let mut collect = |font: Option<&Value>| {
let Some(roles) = font.and_then(|font| font.get("roles")).and_then(Value::as_object) else { return };
for (role, spec) in roles {
if role == "chrome" || spec.get("source").and_then(Value::as_str) != Some("google") {
continue;
}
if let Some(family) = spec.get("family").and_then(|family| family.get(0)).and_then(Value::as_str) {
if crate::gfonts::valid_family(family) && !out.iter().any(|seen| seen == family) && out.len() < 8 {
out.push(family.to_owned());
}
}
}
};
collect(doc.and_then(|doc| doc.get("font")));
collect(self.overrides.get("font"));
out
}
/// The color the shown theme paints the site's page with, as RGB: the tab webview's native
/// background, so a new tab, a navigation or a pane growing during a drag never shows the
/// WebView's white before the page paints. `None` for the site's own look (the site picks it).
pub fn page_color(&self, site: &ThemeSite) -> Option<(u8, u8, u8)> {
let colors_of = |value: Option<&Value>| {
let colors = value?.get("colors")?;
["page", "bg"].iter().find_map(|key| colors.get(*key).and_then(Value::as_str).filter(|hex| valid_hex(hex)).map(str::to_owned))
};
let doc = self.themes.iter().find(|theme| doc_id(theme) == Some(self.preset.as_str()));
let base = match doc {
Some(doc) => colors_of(Some(doc)),
None => site.page_colors.iter().find(|(id, _)| *id == self.preset).map(|(_, hex)| (*hex).to_owned()),
}?;
// Color overrides apply only on top of a theme with colors of its own (like the runtime).
let hex = colors_of(Some(&Value::Object(self.overrides.clone()))).unwrap_or(base);
let channel = |at: usize| u8::from_str_radix(&hex[at..at + 2], 16).ok();
Some((channel(1)?, channel(3)?, channel(5)?))
}
/// Hands the theme to the page runtime (`<global>.theme.apply`), or leaves it for the runtime to
/// pick up at start (`__btTheme`); only in the top frame of the site's own origin.
pub fn script(&self, site: &ThemeSite, spec: &SiteSpec) -> Result<String, String> {
self.validate(site)?;
let json = serde_json::to_string(self).map_err(|_| "THEME: serialization failed")?;
Ok(format!(
"(()=>{{if(window.top!==window||location.origin!=='{origin}')return;const t={json};const BT=window.{global};if(BT&&BT.theme)BT.theme.apply(t);else window.__btTheme=t;}})();",
origin = spec.primary_origin(),
global = spec.runtime_global,
))
}
}
/// At most this many account profiles and panes carry a theme of their own.
pub const MAX_PROFILE_THEMES: usize = 32;
pub const MAX_PANE_THEMES: usize = 64;
/// Which theme each site tab gets: a pane's own theme, else its account profile's, else the global
/// one. `chrome` says whether wayBetter's own window follows the theme (`"theme"`) or keeps its own
/// style (`"own"`); only the shell reads it.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ThemeScopes {
#[serde(default = "chrome_default")]
pub chrome: String,
#[serde(default)]
pub profiles: BTreeMap<String, String>,
#[serde(default)]
pub panes: BTreeMap<String, String>,
}
impl Default for ThemeScopes {
fn default() -> Self {
Self { chrome: chrome_default(), profiles: BTreeMap::new(), panes: BTreeMap::new() }
}
}
fn chrome_default() -> String {
"theme".into()
}
impl ThemeScopes {
pub fn validate(&self) -> Result<(), String> {
if self.chrome != "theme" && self.chrome != "own" {
return Err("VALIDATION: chrome must be theme or own".into());
}
if self.profiles.len() > MAX_PROFILE_THEMES || self.panes.len() > MAX_PANE_THEMES {
return Err("VALIDATION: too many theme assignments".into());
}
for (profile, theme) in &self.profiles {
if !crate::profiles::valid_profile_id(profile) || !valid_id(theme) {
return Err("VALIDATION: invalid account theme".into());
}
}
for (tab, theme) in &self.panes {
if !crate::policy::valid_tab_id(tab) || !valid_id(theme) {
return Err("VALIDATION: invalid pane theme".into());
}
}
Ok(())
}
/// Nothing worth persisting.
pub fn is_default(&self) -> bool {
self.chrome == "theme" && self.profiles.is_empty() && self.panes.is_empty()
}
/// The theme id tab `tab` (in account `profile`) shows; unknown ids fall through to the next level.
pub fn theme_id<'a>(&'a self, site: &ThemeSite, global: &'a ThemeChoice, tab: &str, profile: Option<&str>) -> &'a str {
if let Some(id) = self.panes.get(tab).filter(|id| global.knows(site, id)) {
return id;
}
if let Some(id) = profile.and_then(|profile| self.profiles.get(profile)).filter(|id| global.knows(site, id)) {
return id;
}
&global.preset
}
/// The theme state for one site tab.
pub fn for_tab(&self, site: &ThemeSite, global: &ThemeChoice, tab: &str, profile: Option<&str>) -> ThemeChoice {
global.for_theme(site, self.theme_id(site, global, tab, profile))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
static SITE: ThemeSite = ThemeSite {
presets: &["site", "paper", "nord", "night-ink"],
page_colors: &[("paper", "#e9e2d3"), ("nord", "#232831"), ("night-ink", "#05060a")],
};
fn with(value: Value) -> Result<ThemeChoice, String> {
let theme: ThemeChoice = serde_json::from_value(value).map_err(|error| error.to_string())?;
theme.validate(&SITE).map(|()| theme)
}
#[test]
fn page_color_follows_the_shown_theme() {
let preset = |id: &str| ThemeChoice { preset: id.into(), ..ThemeChoice::default_for(&SITE) };
assert_eq!(preset("site").page_color(&SITE), None, "the site's own look: the site picks its palette");
assert_eq!(preset("nord").page_color(&SITE), Some((0x23, 0x28, 0x31)));
let overridden = ThemeChoice { overrides: json!({ "colors": { "page": "#102030" } }).as_object().unwrap().clone(), ..preset("nord") };
assert_eq!(overridden.page_color(&SITE), Some((0x10, 0x20, 0x30)));
let own_with_override = ThemeChoice { overrides: json!({ "colors": { "page": "#102030" } }).as_object().unwrap().clone(), ..preset("site") };
assert_eq!(own_with_override.page_color(&SITE), None, "the site's own look ignores color overrides");
let imported = ThemeChoice {
preset: "mine".into(),
themes: vec![json!({ "id": "mine", "name": "Mine", "colors": { "bg": "#abcdef", "page": "nope" } })],
..ThemeChoice::default_for(&SITE)
};
assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg");
}
#[test]
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();
assert!(!ok.is_default(&SITE));
let script = ok.script(&SITE, &crate::site::testing::SITE).unwrap();
assert!(script.contains(r#""preset":"mine""#));
assert!(script.starts_with("(()=>{if(window.top!==window||location.origin!=='https://x.com')return;"), "{script}");
assert!(script.contains("const BT=window.BetterTwttr;"));
assert!(with(json!({ "preset": "other", "themes": [{ "id": "mine", "name": "Mine" }] })).is_err(), "the selected theme must exist");
for id in ["Mine", "a b", "", "site", "night-ink", "</script>"] {
assert!(with(json!({ "preset": "site", "themes": [{ "id": id, "name": "n" }] })).is_err(), "accepted {id}");
}
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }, { "id": "a", "name": "B" }] })).is_err());
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "" }] })).is_err());
assert!(with(json!({ "preset": "site", "themes": ["css"] })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "script": {} } })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "css": { "text": "a { color: red }" } } })).is_ok(), "theme CSS override");
assert!(with(json!({ "preset": "site", "overrides": { "css": "a {}" } })).is_err(), "theme CSS must be an object");
assert!(with(json!({ "preset": "site", "overrides": { "font": "Comic Sans" } })).is_err());
let huge = "a".repeat(MAX_THEME_BYTES);
assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A", "css": huge }] })).is_err());
let many: Vec<Value> = (0..=MAX_THEMES).map(|i| json!({ "id": format!("t{i}"), "name": "T" })).collect();
assert!(with(json!({ "preset": "site", "themes": many })).is_err());
}
#[test]
fn tabs_get_pane_then_account_then_global_theme() {
let global = with(json!({ "preset": "mine", "accent": "#ff0000", "overrides": { "font": { "scale": 1.1 } },
"themes": [{ "id": "mine", "name": "Mine" }, { "id": "other", "name": "Other" }] })).unwrap();
let scopes: ThemeScopes = serde_json::from_value(json!({ "profiles": { "p1": "paper" }, "panes": { "t1": "other", "t2": "gone" } })).unwrap();
scopes.validate().unwrap();
assert_eq!(scopes.chrome, "theme");
assert_eq!(scopes.theme_id(&SITE, &global, "t1", Some("p1")), "other");
assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("p1")), "paper");
assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("default")), "mine");
assert_eq!(scopes.theme_id(&SITE, &global, "t3", None), "mine");
// The global theme keeps its customizations; another theme is sent bare and alone.
let same = scopes.for_tab(&SITE, &global, "t9", None);
assert_eq!((same.accent.as_deref(), same.overrides.len(), same.themes.len()), (Some("#ff0000"), 1, 1));
let other = scopes.for_tab(&SITE, &global, "t1", None);
assert_eq!((other.preset.as_str(), other.accent.as_deref(), other.overrides.len(), other.themes.len()), ("other", None, 0, 1));
other.validate(&SITE).unwrap();
let builtin = scopes.for_tab(&SITE, &global, "t5", Some("p1"));
assert_eq!((builtin.preset.as_str(), builtin.themes.len()), ("paper", 0));
builtin.validate(&SITE).unwrap();
}
#[test]
fn scopes_are_bounded_and_checked() {
let parse = |value: Value| serde_json::from_value::<ThemeScopes>(value).map_err(|e| e.to_string()).and_then(|s| s.validate().map(|()| s));
assert!(parse(json!({})).unwrap().is_default());
assert!(parse(json!({ "chrome": "own" })).is_ok());
assert!(parse(json!({ "chrome": "rainbow" })).is_err());
assert!(parse(json!({ "panes": { "t1": "Night Ink" } })).is_err(), "theme ids are slugs");
assert!(parse(json!({ "panes": { "../t": "paper" } })).is_err(), "tab ids are checked");
assert!(parse(json!({ "profiles": { "work": "paper" } })).is_err(), "profile ids are checked");
assert!(parse(json!({ "script": {} })).is_err(), "unknown fields");
let many: Map<String, Value> = (0..=MAX_PANE_THEMES).map(|i| (format!("t{i}"), json!("paper"))).collect();
assert!(parse(json!({ "panes": many })).is_err());
}
#[test]
fn google_fonts_come_from_the_shown_theme_only() {
let global = with(json!({ "preset": "mine", "overrides": { "font": { "roles": { "numbers": { "family": ["Space Mono"], "source": "google" } } } },
"themes": [
{ "id": "mine", "name": "Mine", "font": { "roles": {
"interface": { "family": ["Inter", "sans-serif"], "source": "google" },
"post": { "family": ["Georgia"] },
"chrome": { "family": ["Fraunces"], "source": "google" },
"heading": { "family": ["../../evil"], "source": "google" } } } },
{ "id": "other", "name": "Other", "font": { "roles": { "post": { "family": ["Lora"], "source": "google" } } } }
] })).unwrap();
// Chrome fonts are the shell's; invalid names are dropped; overrides count.
assert_eq!(global.google_fonts(), vec!["Inter".to_string(), "Space Mono".to_string()]);
assert_eq!(global.for_theme(&SITE, "other").google_fonts(), vec!["Lora".to_string()]);
assert!(global.for_theme(&SITE, "paper").google_fonts().is_empty());
}
#[test]
fn default_and_empty() {
let own = ThemeChoice::default_for(&SITE);
assert!(own.is_default(&SITE) && own.is_empty(&SITE));
assert_eq!(own.preset, "site");
let kept = with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }] })).unwrap();
assert!(kept.is_default(&SITE) && !kept.is_empty(&SITE));
}
/// The envelope checks are the theme file's JSON Schema (`waybetter/theme.schema.json`).
#[test]
fn envelope_rules_are_the_schema_rules() {
let schema: Value = serde_json::from_str(include_str!("../../../packages/waybetter/theme.schema.json")).unwrap();
let properties = schema["properties"].as_object().unwrap();
assert_eq!(schema["properties"]["id"]["pattern"], "^[a-z0-9-]{1,40}$");
assert_eq!(schema["properties"]["name"]["maxLength"], MAX_NAME_CHARS);
for group in OVERRIDE_KEYS {
assert!(properties.contains_key(group), "{group} is a theme document group");
}
assert_eq!(schema["required"], json!(["name"]));
let long = "a".repeat(41);
for (id, ok) in [("a", true), ("night-ink-2", true), ("A", false), ("a_b", false), (long.as_str(), false)] {
assert_eq!(valid_id(id), ok, "{id}");
}
}
}

View file

@ -0,0 +1,73 @@
// Theme fonts in a site's page. Sites usually block remote and `data:` font URLs (CSP `font-src`),
// but a FontFace built from bytes performs no fetch, so bundled families (Geist and Geist Mono: the
// app embeds their woff2 files in its page runtime) are registered only when a theme uses them, and
// Google Fonts the owner downloaded arrive as bytes from native code (`provideFonts`).
import { BUNDLED_FONTS } from './themeSpec.ts';
/** Unicode ranges of the Latin and Latin Extended subsets (@fontsource file names `latin`, `latin-ext`). */
export const LATIN_RANGE = 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD';
export const LATIN_EXT_RANGE = 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF';
/** A bundled family's files: base64 woff2 (variable, weights 100-900) with the unicode range each covers. */
export type BundledFontFiles = Record<string, Array<[base64: string, unicodeRange: string]>>;
const loaded = new WeakMap<Document, Set<string>>();
const log = (family: string, error: unknown) => console.error(`[wayBetter] font ${family} failed`, error);
/** Registers the bundled families `names` (BUNDLED_FONTS) from `files`, once per document. */
export function loadBundledFonts(doc: Document, names: string[], files: BundledFontFiles): void {
let done = loaded.get(doc);
if (!done) loaded.set(doc, done = new Set());
for (const name of names) {
const faces = files[name];
const family = BUNDLED_FONTS[name];
if (!faces || !family || done.has(name)) continue;
done.add(name);
for (const [base64, unicodeRange] of faces) {
const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0));
const face = new FontFace(family, bytes.buffer, { weight: '100 900', style: 'normal', unicodeRange, display: 'swap' });
doc.fonts.add(face);
face.load().catch(error => log(name, error));
}
}
}
/**
* Google Fonts the owner downloaded: native code validates and caches the woff2 files and hands
* their bytes to site tabs whose theme uses them. The page never requests a font; each family is
* registered once per document (again only when its bytes change, e.g. after picking other weights).
*/
export type ProvidedFont = { family: string; faces: Array<{ weight: [number, number]; unicodeRange: string | null; data: string }> };
const provided = new WeakMap<Document, Map<string, string>>();
const FAMILY = /^[A-Za-z0-9][A-Za-z0-9 ]{0,47}$/;
/** Registers the provided families (validated again; at most 8 families of 24 faces); returns the families added. */
export function provideFonts(doc: Document, fonts: unknown): string[] {
const added: string[] = [];
if (!Array.isArray(fonts)) return added;
let known = provided.get(doc);
if (!known) provided.set(doc, known = new Map());
for (const font of fonts.slice(0, 8) as ProvidedFont[]) {
if (!font || typeof font.family !== 'string' || !FAMILY.test(font.family) || !Array.isArray(font.faces)) continue;
const key = font.faces.map(face => `${face?.weight}|${typeof face?.data === 'string' ? face.data.length : 0}`).join(',');
if (known.get(font.family) === key) continue;
// Other weights of a family replace its earlier faces.
for (const face of [...doc.fonts]) if ((face as FontFace).family.replace(/"/g, '') === font.family && (face as FontFace & { wbGoogle?: boolean }).wbGoogle) doc.fonts.delete(face as FontFace);
known.set(font.family, key);
for (const face of font.faces.slice(0, 24)) {
if (!face || typeof face.data !== 'string' || !Array.isArray(face.weight)) continue;
try {
const bytes = Uint8Array.from(atob(face.data), char => char.charCodeAt(0));
const [min, max] = face.weight.map(Number) as [number, number];
const descriptors: FontFaceDescriptors = { weight: min === max ? String(min) : `${min} ${max}`, style: 'normal', display: 'swap' };
if (typeof face.unicodeRange === 'string' && /^[U+0-9A-Fa-f?, -]{1,4000}$/.test(face.unicodeRange)) descriptors.unicodeRange = face.unicodeRange;
const fontFace = Object.assign(new FontFace(font.family, bytes.buffer, descriptors), { wbGoogle: true });
doc.fonts.add(fontFace);
fontFace.load().catch(error => log(font.family, error));
} catch (error) { log(font.family, error); }
}
added.push(font.family);
}
return added;
}

View file

@ -73,7 +73,9 @@ export type ResolvedFont = {
inherited: boolean;
};
export type ResolvedFonts = Record<FontRoleName, ResolvedFont>;
export const MONO_FONT = 'ui-monospace, "Cascadia Mono", "SF Mono", Consolas, Menlo, monospace';
/** Monospaced families, in order: what a `mono` role that inherits (or a source without fonts) gets. */
export const MONO_FAMILIES = ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'];
export const MONO_FONT = MONO_FAMILIES.map(name => (/^(ui-monospace|monospace)$/.test(name) ? name : `"${name}"`)).join(', ');
/** What a site adapter provides: the current resolved theme and change notifications. */
export type ThemeSource = {
@ -95,14 +97,15 @@ export const FALLBACK_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, Helv
const HEX = /^#[0-9a-f]{6}$/i;
function channels(hex: string): [number, number, number] {
/** `#rrggbb` → [r, g, b]. */
export function hexToRgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
/** WCAG relative luminance of `#rrggbb`. */
export function relativeLuminance(hex: string): number {
const [r, g, b] = channels(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
const [r, g, b] = hexToRgb(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
@ -130,8 +133,9 @@ export function toHex(value: string | null | undefined): string | null {
return `#${[match[1], match[2], match[3]].map(v => Math.min(255, Number(v)).toString(16).padStart(2, '0')).join('')}`;
}
function mixHex(a: string, b: string, t: number): string {
const [x, y] = [channels(a), channels(b)];
/** `a` moved toward `b` by `t` (0–1), per channel. */
export function mix(a: string, b: string, t: number): string {
const [x, y] = [hexToRgb(a), hexToRgb(b)];
return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, '0')).join('')}`;
}
@ -143,10 +147,10 @@ export function themeFromColors(bg: string, text: string, accent: string, extra:
const dark = relativeLuminance(bg) < relativeLuminance(text);
const colors: ResolvedColors = {
bg, text, accent,
surface: mixHex(bg, text, dark ? 0.05 : 0.03),
elevated: mixHex(bg, text, dark ? 0.1 : 0.07),
border: mixHex(bg, text, dark ? 0.2 : 0.15),
muted: mixHex(bg, text, 0.62),
surface: mix(bg, text, dark ? 0.05 : 0.03),
elevated: mix(bg, text, dark ? 0.1 : 0.07),
border: mix(bg, text, dark ? 0.2 : 0.15),
muted: mix(bg, text, 0.62),
onAccent: readableOn(accent),
inverse: text,
onInverse: bg,

View file

@ -0,0 +1,79 @@
// The owner's theme choice: which theme document is on (a built-in one or an imported one), the
// panel's customizations on top of it and an accent override. Native code persists it and hands it
// to every site tab; the shell's theme store and the panel edit it. A site brings its built-in
// themes (`createThemeCatalog(builtins)`; the first one is the site's own look, the default). Pure.
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[] };
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
export const MAX_USER_THEMES = 24;
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css'] as const;
export type ThemeCatalog = {
/** The site's built-in themes; the first is its own look (and the default choice). */
builtins: readonly ThemeSpec[];
/** Nothing chosen: the first built-in theme, no customizations. */
defaultChoice: ThemeChoice;
/** Any JSON to a valid choice (imported themes sanitized, bounded and deduplicated; unknown ids fall back). */
normalize(input: unknown): ThemeChoice;
/** The theme document a choice refers to (built-in or imported), before overrides. */
base(choice: ThemeChoice): ThemeSpec;
/** The effective theme: the selected document with the panel's overrides and accent, legible. */
resolve(choice: ThemeChoice): ThemeSpec;
/** The effective palette: the theme's colors (or none for the site's own) with the accent override applied. */
palette(choice: ThemeChoice): Partial<Palette> | null;
/** Every theme that can be picked: the built-in ones, then the choice's imported ones. */
all(choice: ThemeChoice): ThemeSpec[];
};
export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog {
if (!builtins.length) throw new Error('wayBetter themes: a site needs at least one built-in theme (its own look)');
const first = builtins[0]!;
const defaultChoice: ThemeChoice = { preset: first.id, accent: null, overrides: {}, themes: [] };
const isBuiltin = (id: unknown) => builtins.some(item => item.id === id);
function normalize(input: unknown): ThemeChoice {
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
const themes: ThemeSpec[] = [];
if (Array.isArray(source.themes)) {
for (const raw of source.themes.slice(0, MAX_USER_THEMES)) {
const theme = sanitizeSpec(raw);
if (!isBuiltin(theme.id) && !themes.some(item => item.id === theme.id)) themes.push(theme);
}
}
const known = (id: unknown) => typeof id === 'string' && (isBuiltin(id) || themes.some(item => item.id === id));
const preset = known(source.preset) ? source.preset as string : first.id;
const accent = isHex(source.accent) ? source.accent.toLowerCase() : null;
const overrides: ThemeOverrides = {};
const rawOverrides = source.overrides && typeof source.overrides === 'object' ? source.overrides as Record<string, unknown> : {};
for (const key of OVERRIDE_GROUPS) {
const value = rawOverrides[key];
if (value && typeof value === 'object' && !Array.isArray(value)) (overrides as Record<string, unknown>)[key] = value;
}
return { preset, accent, overrides, themes };
}
const base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first;
const resolve = (choice: ThemeChoice) => applyOverrides(base(choice), choice.overrides, choice.accent);
function palette(choice: ThemeChoice): Partial<Palette> | null {
const theme = resolve(choice);
if (theme.colors) return theme.colors;
return choice.accent ? { accent: choice.accent } : null;
}
const all = (choice: ThemeChoice) => [...builtins, ...choice.themes];
return { builtins, defaultChoice, normalize, base, resolve, palette, all };
}
/** 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 {
return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes };
}
/** The shape persisted natively: empty groups are dropped so "no override" stays unambiguous. */
export function serializeChoice(choice: ThemeChoice) {
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 } : {}) };
}

View file

@ -0,0 +1,243 @@
// The theme engine in a site's page: keeps one `<style>` with the theme's CSS in sync while the site
// adds its own rules (React apps insert them lazily), exposes the resolved theme as `--wb-*` custom
// properties for plugins and the UI kit, follows the site's own color mode, and paints the last
// theme from the page's first frame (a snapshot in the page's storage). What the CSS is comes from
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
/** A style rule as the engine reads it (CSSStyleRule, or a plain object in tests). */
export type RuleLike = { selectorText: string; style: { getPropertyValue(name: string): string; length?: number } };
/** The font roles as the plugin API reports them in a site's page; an inheriting interface uses `siteStack` (the site's own font). */
export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts {
const roles = resolveFontRoles(font, siteStack);
return Object.fromEntries(FONT_ROLE_NAMES.map(role => {
const { stack, weight, size, tracking, tabular, inherited } = roles[role];
return [role, { stack, weight, size, tracking, tabular, inherited }];
})) as ResolvedFonts;
}
/** Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s. */
export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleLike[] {
const rules: RuleLike[] = [];
const walk = (list: CSSRuleList) => {
for (const rule of Array.from(list)) {
if ('selectorText' in rule && 'style' in rule) rules.push(rule as unknown as RuleLike);
else if ('cssRules' in rule && !('selectorText' in rule)) walk((rule as CSSGroupingRule).cssRules);
}
};
for (const sheet of Array.from(doc.styleSheets)) {
if (own && sheet.ownerNode === own) continue;
try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ }
}
return rules;
}
function ruleCount(doc: Document): number {
let count = 0;
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
return count;
}
/**
* The last theme CSS a tab showed, kept in the page's own storage so the next document paints it
* from its first frame: native code only hands the theme over once the page has finished loading,
* and the live CSS needs the site's rules, which it inserts while it renders. sessionStorage is per
* tab and survives reloads and navigations; localStorage (smaller cap: the site uses it too) is per
* account and covers a tab's first document.
*/
export type ThemeSnapshot = { key: string; choice: unknown; css: string };
const SNAPSHOT_KEY = 'wb:theme-snapshot';
export const SNAPSHOT_SESSION_MAX = 1_000_000;
export const SNAPSHOT_LOCAL_MAX = 200_000;
export type SnapshotStores = { session?: Storage | null; local?: Storage | null };
function stores(win: Window): SnapshotStores {
const get = (name: 'sessionStorage' | 'localStorage') => { try { return win[name]; } catch { return null; } };
return { session: get('sessionStorage'), local: get('localStorage') };
}
export function readSnapshot({ session, local }: SnapshotStores): ThemeSnapshot | null {
for (const store of [session, local]) {
try {
const value = JSON.parse(store?.getItem(SNAPSHOT_KEY) || 'null') as Partial<ThemeSnapshot> | null;
if (value && typeof value.key === 'string' && typeof value.css === 'string' && value.css && value.choice) return value as ThemeSnapshot;
} catch { /* Missing, blocked or foreign data: no snapshot. */ }
}
return null;
}
/** Stores `snapshot` (null clears it: the site's own look needs none), each store within its cap. */
export function writeSnapshot({ session, local }: SnapshotStores, snapshot: ThemeSnapshot | null) {
const json = snapshot ? JSON.stringify(snapshot) : '';
for (const [store, max] of [[session, SNAPSHOT_SESSION_MAX], [local, SNAPSHOT_LOCAL_MAX]] as const) {
try {
if (json && json.length <= max) store?.setItem(SNAPSHOT_KEY, json);
else store?.removeItem(SNAPSHOT_KEY);
} catch { /* Quota or blocked storage: the next document just starts unthemed. */ }
}
}
/** What the engine needs to know about a site. `Mode` is the site's own color mode (X: light, dim, dark). */
export type ThemeRuntimeSite<Mode extends string = string> = {
/** The site's built-in themes (themeChoice.ts). */
catalog: ThemeCatalog;
/** The mode before the page has a body. */
initialMode: Mode;
/** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */
readMode(win: Window): Mode;
/** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>): string;
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
siteVars?: readonly string[];
/** Id of the theme's `<style>` (default `wb-theme-css`). */
styleId?: string;
/** Name in console errors. */
name?: string;
};
export type ThemeHandle<Mode extends string = string> = {
apply(choice: unknown): void;
current(): ThemeChoice;
theme(): ThemeSpec;
/** The site's color mode the theme was last rendered for. */
mode(): Mode;
/** The active theme as values for plugins (`api.theme.current()`). */
resolved(): ResolvedTheme;
/** Calls `listener` after the theme or the site's color mode changes. */
onChange(listener: () => void): () => void;
};
export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
const VARS_ID = 'wb-theme-vars';
/** Keeps the site's page in the owner's theme (see the top of this file). */
export function installThemeRuntime<Mode extends string>(win: Window, site: ThemeRuntimeSite<Mode>, options: ThemeRuntimeOptions = {}): ThemeHandle<Mode> {
const doc = win.document;
const name = site.name ?? 'wayBetter';
const styleId = site.styleId ?? 'wb-theme-css';
const { catalog } = site;
// Document start (no <html> yet): the snapshot as an adopted sheet paints with the site's first
// frame. It stays while the live CSS is for the same theme and site mode, and goes when they differ.
const storage = stores(win);
const snapshot = readSnapshot(storage);
let early: CSSStyleSheet | null = null;
if (snapshot) {
try {
const Sheet = (win as Window & typeof globalThis).CSSStyleSheet;
early = new Sheet();
early.replaceSync(snapshot.css);
doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, early];
} catch { early = null; }
}
const dropEarly = () => {
if (!early) return;
const sheet = early;
early = null;
try { doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(item => item !== sheet); } catch { /* Never break the site. */ }
};
let savedCss = snapshot?.css ?? '';
let choice = catalog.defaultChoice;
let theme = catalog.resolve(choice);
let lastKey = '';
let timer: ReturnType<typeof setInterval> | null = null;
const active = () => !isNeutral(theme) || !!choice.accent;
let mode: Mode = site.initialMode;
let resolved: ResolvedTheme = site.resolved(choice, mode);
let resolvedKey = themeKey(resolved);
const listeners = new Set<() => void>();
const readMode = () => (doc.body ? site.readMode(win) : mode);
/** `--wb-*` on :root for plugin CSS, and a change notice when anything visible changed. */
const syncResolved = () => {
if (doc.body) mode = readMode();
resolved = site.resolved(choice, mode);
const key = themeKey(resolved);
let vars = doc.getElementById(VARS_ID) as HTMLStyleElement | null;
if (!vars?.isConnected) {
vars = doc.createElement('style');
vars.id = VARS_ID;
(doc.head || doc.documentElement).appendChild(vars);
}
const css = themeVarsCss(resolved);
if (vars.textContent !== css) vars.textContent = css;
if (key === resolvedKey) return;
resolvedKey = key;
for (const listener of [...listeners]) {
try { listener(); } catch (error) { console.error(`[${name}] theme listener failed`, error); }
}
};
let modeObserver: MutationObserver | null = null;
const watchMode = () => {
if (modeObserver || !doc.body) return;
// Sites repaint the body when their own display setting changes (X: Default / Dim / Lights out).
const Observer = (win as Window & typeof globalThis).MutationObserver ?? globalThis.MutationObserver;
if (!Observer) return;
modeObserver = new Observer(() => { try { if (readMode() !== mode) syncResolved(); } catch { /* Never break the site. */ } });
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] });
};
const render = (force = false) => {
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); lastKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!doc.body) return;
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
if (early && snapshot?.key !== snapshotKey) dropEarly();
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0)}`;
if (!force && key === lastKey) return;
lastKey = key;
if (!style) { style = doc.createElement('style'); style.id = styleId; }
// The site's own values, not the ones our previous render overrode (switching themes re-reads them).
if (style.sheet) style.sheet.disabled = true;
const vars: Record<string, string> = {};
if (site.siteVars?.length) {
const rootStyle = win.getComputedStyle(doc.documentElement);
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
}
if (style.sheet) style.sheet.disabled = false;
const css = site.css(collectRules(doc, style), choice, mode, vars);
if (style.textContent !== css) style.textContent = css;
// Last in <head> so equal-specificity `!important` rules win over the site's.
if (style.parentNode !== doc.head || doc.head.lastElementChild !== style) (doc.head || doc.documentElement).appendChild(style);
const full = `${themeVarsCss(resolved)}\n${css}`;
if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
};
const handle: ThemeHandle<Mode> = {
apply(input) {
choice = catalog.normalize(input);
theme = catalog.resolve(choice);
const fonts = bundledFontsUsed(theme);
if (fonts.length) { try { options.loadFonts?.(fonts); } catch (error) { console.error(`[${name}] theme fonts failed`, error); } }
if (active()) {
if (!timer) timer = setInterval(() => { try { render(); } catch { /* Never break the site. */ } }, 1200);
} else if (timer) { clearInterval(timer); timer = null; }
try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); }
win.dispatchEvent(new CustomEvent('wb-theme'));
},
current: () => choice,
theme: () => theme,
mode: () => mode,
resolved: () => {
if (doc.body && readMode() !== mode) syncResolved();
return resolved;
},
onChange(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
};
// The snapshot's theme until native code hands over the current one (usually the same): the
// live CSS then already renders at DOMContentLoaded instead of after the page finished loading.
if (snapshot) { try { handle.apply(snapshot.choice); } catch { /* Never break the site. */ } }
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', () => render(true), { once: true });
// `--wb-*` exist from the start (the site's own palette until a theme is applied), for plugins and the UI kit.
else if (doc.body) { try { watchMode(); syncResolved(); } catch { /* Never break the site. */ } }
return handle;
}

View file

@ -0,0 +1,521 @@
// Theme documents: a wayBetter theme is a JSON document (like a BetterDiscord theme, but data instead
// of a stylesheet) describing colors, type, shape, density, layout, background and motion; the format
// is `theme.schema.json` in the `waybetter` package. This module is the document side of the theme
// engine: types, the schema's defaults, sanitizing, import, panel overrides, legibility, font roles
// and stacks, and page backgrounds. Pure, so it runs in the page runtime, the settings previews and
// the tests. What a theme does to one site's page (its selectors, its palette) is the site's
// (themeRuntime.ts takes a site adapter).
//
// Safety: a theme is sanitized field by field before it becomes CSS. Colors are six-digit hex,
// numbers are clamped, enums are fixed, font names match a strict pattern, background images are
// `data:image/*;base64` only, and CSS is built from those values (never concatenated from raw
// strings). The single escape hatch is `css`, which is the same trust level as the owner's own
// Custom CSS and is shown as such when a theme is imported.
//
// Fonts: sites usually block remote and `data:` fonts (CSP `font-src`), so a theme may name installed
// system fonts, "Geist" / "Geist Mono" (bundled and registered from bytes: `FontFace(ArrayBuffer)` is
// not a fetch), or Google Fonts families the owner downloaded (`source: "google"`, fonts.ts).
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
import { deriveColors } from './themeTokens.ts';
export { FONT_ROLE_NAMES } from './themeApi.ts';
export type { FontRoleName } from './themeApi.ts';
export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' | 'accent';
/** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */
export type ButtonRole = 'inverse' | 'onInverse';
export type Palette = Record<Role, string> & Partial<Record<ButtonRole, string>>;
/** `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`. */
export type ThemeColors = Palette & { page?: string };
export type Density = 'compact' | 'default' | 'comfortable';
export type AvatarShape = 'circle' | 'rounded' | 'square';
export type Pattern = 'dots' | 'grid' | 'diagonal' | 'scanlines' | 'paper' | 'clouds';
export type Background =
| { kind: 'none' }
| { kind: 'gradient'; from: string; to: string; angle: number; glow?: string }
| { kind: 'pattern'; pattern: Pattern; ink: string; opacity: number; size: number }
| { kind: 'image'; url: string; fit: 'cover' | 'tile'; dim: number };
/**
* One role's font (roles: themeApi.ts `FONT_ROLE_NAMES`). `family` is a font stack; empty keeps the
* inherited family and only changes the rest. `source: "google"` says the first family comes from
* Google Fonts (downloaded once, asked first when a theme is imported, loaded from bytes). `weight`
* (100-900), `size` (0.75-1.5, relative to the site's size), `tracking` (em) and `tabular` figures
* are optional; the interface role takes only `family`/`source` (its size, weights and tracking are
* `scale`, `weight`, `bold` and `tracking` of the whole theme).
*/
export type FontRoleSpec = { family: string[]; source?: 'google'; weight?: number; size?: number; tracking?: number; tabular?: boolean };
export type FontRole = 'inherit' | FontRoleSpec;
export type FontRoles = Record<FontRoleName, FontRole>;
export type FontSpec = {
/**
* Interface font stack (replaces the site's own font everywhere). Empty keeps the site's.
* Shorthand kept for older theme files and older apps: it always equals `roles.interface`'s family.
*/
family: string[];
/** Post text stack (e.g. a serif reading face); shorthand of `roles.post`'s family. */
tweet: string[];
/** Which font goes where. Every role inherits from `interface` unless it says otherwise. */
roles: FontRoles;
/** Multiplies the site's pixel font sizes (0.85-1.2). */
scale: number;
/** Regular weight (300-500) and bold weight (500-800) that replace the site's 400/700. */
weight: number;
bold: number;
/** Letter spacing in em (-0.03-0.06). */
tracking: number;
/** Line height multiplier for post text (0 keeps the site's). */
leading: number;
};
export type ShapeSpec = { radius: number; button: number; avatar: AvatarShape };
export type LayoutSpec = { column: number; sidebar: number; density: Density; cards: boolean; frame: boolean };
export type EffectsSpec = { motion: number; hover: 'none' | 'tint' | 'lift' | 'glow'; shadow: 'none' | 'soft' | 'deep'; crt: boolean };
export type ThemeSpec = {
id: string;
name: string;
description: string;
author: string;
version: 1;
/** Which way the theme leans; used for scrollbars/form controls and previews. */
mode: 'light' | 'dark' | 'auto';
/** null keeps the site's own colors (X: Default / Dim / Lights out). */
colors: ThemeColors | null;
font: FontSpec;
shape: ShapeSpec;
layout: LayoutSpec;
background: Background;
effects: EffectsSpec;
/** Free-form CSS appended last (owner-trusted, like Custom CSS). */
css: string;
};
/** Panel overrides: any group may be partially overridden on top of the selected theme. */
export type ThemeOverrides = {
colors?: Partial<ThemeColors>;
/** `roles` is merged role by role (a named role replaces that role only). */
font?: Partial<Omit<FontSpec, 'roles'>> & { roles?: Partial<FontRoles> };
shape?: Partial<ShapeSpec>;
layout?: Partial<LayoutSpec>;
background?: Background;
effects?: Partial<EffectsSpec>;
/** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */
css?: { text: string };
};
// ---------------------------------------------------------------------------------------------
// The schema's defaults: a theme that sets nothing changes nothing (the site keeps its own geometry;
// a site's structure CSS only emits rules where a theme differs from these).
export const BASE_SHAPE: ShapeSpec = { radius: 16, button: 9999, avatar: 'circle' };
export const INHERIT_ROLES: FontRoles = { interface: 'inherit', post: 'inherit', heading: 'inherit', numbers: 'inherit', mono: 'inherit', chrome: 'inherit', dialog: 'inherit' };
/** A font spec from the interface/post stacks alone (every other role inherits). */
export const withRoles = (font: Omit<FontSpec, 'roles'>): FontSpec => ({
...font,
roles: { ...INHERIT_ROLES, ...(font.family.length ? { interface: { family: font.family } } : {}), ...(font.tweet.length ? { post: { family: font.tweet } } : {}) },
});
export const BASE_FONT: FontSpec = withRoles({ family: [], tweet: [], scale: 1, weight: 400, bold: 700, tracking: 0, leading: 0 });
export const BASE_LAYOUT: LayoutSpec = { column: 600, sidebar: 350, density: 'default', cards: false, frame: false };
export const BASE_EFFECTS: EffectsSpec = { motion: 0, hover: 'none', shadow: 'none', crt: false };
/** The system UI stack themes put after their own sans-serif families. */
export const SYSTEM_SANS = ['Segoe UI', '-apple-system', 'BlinkMacSystemFont', 'system-ui', 'sans-serif'];
// ---------------------------------------------------------------------------------------------
// Colors and contrast (luminance and ratios: themeApi.ts)
export const isHex = (value: unknown): value is string => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value);
/** `#rrggbb` + alpha as `rgba()`. */
export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`;
/** Moves `color` toward black or white until it reaches `ratio` against every surface. */
function reach(color: string, surfaces: string[], ratio: number): string {
const worst = (c: string) => Math.min(...surfaces.map(s => contrastRatio(c, s)));
if (worst(color) >= ratio) return color;
const lightSurfaces = surfaces.reduce((sum, s) => sum + relativeLuminance(s), 0) / surfaces.length > 0.18;
const pole = lightSurfaces ? '#000000' : '#ffffff';
for (let t = 0.04; t <= 1; t += 0.04) {
const next = mix(color, pole, t);
if (worst(next) >= ratio) return next;
}
return pole;
}
/**
* Guarantees legibility for any palette (built-in, imported or overridden): text, secondary text
* and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled
* button keeps a readable label and stands out from the page (3:1).
*/
export function ensureContrast<T extends Palette & { page?: string }>(colors: T): T {
const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])];
const out = { ...colors };
out.text = reach(colors.text, surfaces, 7);
out.muted = reach(colors.muted, surfaces, 4.5);
// Links live inside the columns, never on the page canvas.
out.accent = reach(colors.accent, [colors.bg, colors.surface, colors.elevated], 4.5);
const inverse = colors.inverse ?? out.text;
const onInverse = colors.onInverse ?? colors.bg;
out.inverse = reach(inverse, [colors.bg], 3);
out.onInverse = reach(onInverse, [out.inverse], 4.5);
return out;
}
// ---------------------------------------------------------------------------------------------
// Sanitizing
const GENERIC_FONTS = new Set(['system-ui', 'sans-serif', 'serif', 'monospace', 'cursive', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', '-apple-system', 'BlinkMacSystemFont']);
const FONT_NAME = /^[A-Za-z0-9][A-Za-z0-9 .\-]{0,47}$/;
const DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif|avif);base64,[A-Za-z0-9+/]+={0,2}$/;
export const MAX_IMAGE_CHARS = 1_100_000;
export const MAX_CSS_CHARS = 60_000;
const PATTERNS: Pattern[] = ['dots', 'grid', 'diagonal', 'scanlines', 'paper', 'clouds'];
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const num = (value: unknown, min: number, max: number, fallback: number) => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
const pick = <T extends string>(value: unknown, options: readonly T[], fallback: T): T => options.includes(value as T) ? value as T : fallback;
const text = (value: unknown, max: number, fallback = '') => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, max) : fallback;
export function sanitizeFonts(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.filter((name): name is string => typeof name === 'string' && (GENERIC_FONTS.has(name) || FONT_NAME.test(name))).slice(0, 8);
}
/** A theme needs its background, text and accent; any other role it leaves out is derived from the
* base structure (themeTokens.ts `deriveColors`), so every theme has the same proportions. */
function sanitizeColors(value: unknown): ThemeColors | null {
const source = obj(value);
if (!(['bg', 'text', 'accent'] as const).every(role => isHex(source[role]))) return null;
const named = Object.fromEntries((['bg', 'surface', 'elevated', 'border', 'text', 'muted', 'accent'] as Role[])
.filter(role => isHex(source[role])).map(role => [role, (source[role] as string).toLowerCase()]));
const colors = deriveColors(named as { bg: string; text: string; accent: string }) as ThemeColors;
for (const role of ['inverse', 'onInverse', 'page'] as const) if (isHex(source[role])) colors[role] = (source[role] as string).toLowerCase();
return colors;
}
export function sanitizeBackground(value: unknown): Background {
const source = obj(value);
if (source.kind === 'gradient' && isHex(source.from) && isHex(source.to)) {
return { kind: 'gradient', from: source.from.toLowerCase(), to: source.to.toLowerCase(), angle: Math.round(num(source.angle, 0, 360, 180)), ...(isHex(source.glow) ? { glow: source.glow.toLowerCase() } : {}) };
}
if (source.kind === 'pattern' && isHex(source.ink)) {
return { kind: 'pattern', pattern: pick(source.pattern, PATTERNS, 'dots'), ink: source.ink.toLowerCase(), opacity: num(source.opacity, 0, 0.6, 0.1), size: Math.round(num(source.size, 2, 400, 24)) };
}
if (source.kind === 'image' && typeof source.url === 'string' && source.url.length <= MAX_IMAGE_CHARS && DATA_IMAGE.test(source.url)) {
return { kind: 'image', url: source.url, fit: pick(source.fit, ['cover', 'tile'] as const, 'cover'), dim: num(source.dim, 0.35, 0.95, 0.6) };
}
return { kind: 'none' };
}
/** Bounds of a role's own settings (the JSON Schema says the same; tested). */
export const ROLE_LIMITS = { weight: [100, 900], size: [0.75, 1.5], tracking: [-0.05, 0.1] } as const;
/** One role from JSON: "inherit", or a stack with optional extras (clamped; unknown keys dropped). */
export function sanitizeFontRole(value: unknown, role: FontRoleName): FontRole {
if (value === 'inherit' || value === null || value === undefined) return 'inherit';
const source = obj(value);
if (!Object.keys(source).length) return 'inherit';
const family = sanitizeFonts(source.family);
const out: FontRoleSpec = { family };
if (source.source === 'google' && family.length && !GENERIC_FONTS.has(family[0]!)) out.source = 'google';
if (role !== 'interface') {
if (typeof source.weight === 'number' && Number.isFinite(source.weight)) out.weight = Math.round(num(source.weight, ...ROLE_LIMITS.weight, 400));
if (typeof source.size === 'number' && Number.isFinite(source.size)) out.size = +num(source.size, ...ROLE_LIMITS.size, 1).toFixed(3);
if (typeof source.tracking === 'number' && Number.isFinite(source.tracking)) out.tracking = +num(source.tracking, ...ROLE_LIMITS.tracking, 0).toFixed(4);
if (source.tabular === true) out.tabular = true;
}
// A role that changes nothing is the same as inheriting.
return Object.keys(out).length === 1 && !family.length ? 'inherit' : out;
}
const roleFamily = (role: FontRole): string[] => role === 'inherit' ? [] : role.family;
/** A role with a new family, keeping its other settings (and its Google source only for the same font). */
export function withFamily(role: FontRole, family: string[], source?: 'google'): FontRole {
const rest = role === 'inherit' ? {} : { ...role };
delete (rest as Partial<FontRoleSpec>).source;
delete (rest as Partial<FontRoleSpec>).family;
const next: FontRoleSpec = { ...rest, family, ...(source && family.length ? { source } : {}) };
return Object.keys(next).length === 1 && !family.length ? 'inherit' : next;
}
/**
* The roles of a font group from JSON over `base`: `roles.<name>` wins; the legacy shorthand
* (`family` → interface, `tweet` → post) applies when that role is not named, so theme files and
* saved customizations from before font roles keep working.
*/
function sanitizeRoles(source: Record<string, unknown>, base: FontSpec): FontRoles {
const named = obj(source.roles);
const roles = { ...base.roles };
for (const role of FONT_ROLE_NAMES) if (role in named) roles[role] = sanitizeFontRole(named[role], role);
if (!('interface' in named) && 'family' in source) roles.interface = withFamily(base.roles.interface, sanitizeFonts(source.family), sameFirst(source.family, base.roles.interface));
if (!('post' in named) && 'tweet' in source) roles.post = withFamily(base.roles.post, sanitizeFonts(source.tweet), sameFirst(source.tweet, base.roles.post));
return roles;
}
/** Keeps a role's Google source when the shorthand still names the same first family. */
function sameFirst(stack: unknown, role: FontRole): 'google' | undefined {
return role !== 'inherit' && role.source === 'google' && Array.isArray(stack) && stack[0] === role.family[0] ? 'google' : undefined;
}
function sanitizeFont(value: unknown, base: FontSpec): FontSpec {
const source = obj(value);
const roles = sanitizeRoles(source, base);
return {
family: roleFamily(roles.interface),
tweet: roleFamily(roles.post),
roles,
scale: num(source.scale, 0.85, 1.2, base.scale),
weight: Math.round(num(source.weight, 300, 500, base.weight)),
bold: Math.round(num(source.bold, 500, 800, base.bold)),
tracking: num(source.tracking, -0.03, 0.06, base.tracking),
leading: source.leading === 0 ? 0 : num(source.leading, 1.2, 1.8, base.leading),
};
}
const sanitizeShape = (value: unknown, base: ShapeSpec): ShapeSpec => {
const source = obj(value);
return { radius: Math.round(num(source.radius, 0, 28, base.radius)), button: Math.round(num(source.button, 0, 9999, base.button)), avatar: pick(source.avatar, ['circle', 'rounded', 'square'] as const, base.avatar) };
};
const sanitizeLayout = (value: unknown, base: LayoutSpec): LayoutSpec => {
const source = obj(value);
return {
column: Math.round(num(source.column, 520, 820, base.column)), sidebar: Math.round(num(source.sidebar, 290, 400, base.sidebar)),
density: pick(source.density, ['compact', 'default', 'comfortable'] as const, base.density),
cards: typeof source.cards === 'boolean' ? source.cards : base.cards, frame: typeof source.frame === 'boolean' ? source.frame : base.frame,
};
};
const sanitizeEffects = (value: unknown, base: EffectsSpec): EffectsSpec => {
const source = obj(value);
return {
motion: Math.round(num(source.motion, 0, 400, base.motion)), hover: pick(source.hover, ['none', 'tint', 'lift', 'glow'] as const, base.hover),
shadow: pick(source.shadow, ['none', 'soft', 'deep'] as const, base.shadow), crt: typeof source.crt === 'boolean' ? source.crt : base.crt,
};
};
export const slug = (value: string) => value.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'theme';
/** Any JSON to a complete, safe theme. Missing groups fall back to the schema's defaults. */
export function sanitizeSpec(input: unknown): ThemeSpec {
const source = obj(input);
const name = text(source.name, 60) || 'Untitled theme';
const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : slug(name);
return {
id, name, description: text(source.description, 200), author: text(source.author, 60), version: 1,
mode: pick(source.mode, ['light', 'dark', 'auto'] as const, 'auto'),
colors: sanitizeColors(source.colors),
font: sanitizeFont(source.font, BASE_FONT),
shape: sanitizeShape(source.shape, BASE_SHAPE),
layout: sanitizeLayout(source.layout, BASE_LAYOUT),
background: sanitizeBackground(source.background),
effects: sanitizeEffects(source.effects, BASE_EFFECTS),
css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '',
};
}
/** Parses an imported file; errors are human-readable. */
export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } {
let raw: unknown;
try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; }
const source = obj(raw);
if (typeof source.name !== 'string' || !source.name.trim()) return { error: 'A theme needs a "name".' };
const theme = sanitizeSpec(raw);
const warnings: string[] = [];
if (source.colors !== undefined && source.colors !== null && !theme.colors) warnings.push('Colors were ignored: bg, text and accent must be #rrggbb (the other roles are derived when missing).');
if (theme.css) warnings.push('Contains custom CSS, which runs inside the site like your own Custom CSS.');
if (source.background && theme.background.kind === 'none' && obj(source.background).kind !== 'none') warnings.push('The background was ignored (images must be data:image/png, jpeg, webp, gif or avif, up to about 800 KB).');
if (theme.colors) {
const fixed = ensureContrast(theme.colors);
if (fixed.text !== theme.colors.text || fixed.muted !== theme.colors.muted || fixed.accent !== theme.colors.accent) warnings.push('Some text colors were adjusted to stay readable.');
}
return { theme, warnings };
}
/** Applies panel overrides (and an accent) on top of a theme. Colors are then made legible. */
export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {}, accent: string | null = null): ThemeSpec {
const o = obj(overrides) as ThemeOverrides;
let colors = theme.colors ? { ...theme.colors, ...Object.fromEntries(Object.entries(obj(o.colors)).filter(([, v]) => isHex(v))) } as ThemeColors : null;
if (colors && accent) colors = { ...colors, accent, ...(theme.colors?.inverse === theme.colors?.accent ? { inverse: accent } : {}) };
return {
...theme,
colors: colors ? ensureContrast(colors) : null,
// Missing keys fall back to the theme's own; the legacy `family`/`tweet` shorthand still overrides.
font: o.font ? sanitizeFont(o.font, theme.font) : theme.font,
shape: o.shape ? sanitizeShape({ ...theme.shape, ...o.shape }, theme.shape) : theme.shape,
layout: o.layout ? sanitizeLayout({ ...theme.layout, ...o.layout }, theme.layout) : theme.layout,
background: o.background ? sanitizeBackground(o.background) : theme.background,
effects: o.effects ? sanitizeEffects({ ...theme.effects, ...o.effects }, theme.effects) : theme.effects,
css: o.css && typeof o.css.text === 'string' ? o.css.text.slice(0, MAX_CSS_CHARS) : theme.css,
};
}
/** True when a theme changes nothing about the site (the site's own look without overrides). */
export function isNeutral(theme: ThemeSpec): boolean {
return !theme.colors && JSON.stringify([theme.font, theme.shape, theme.layout, theme.effects]) === JSON.stringify([BASE_FONT, BASE_SHAPE, BASE_LAYOUT, BASE_EFFECTS])
&& theme.background.kind === 'none' && !theme.css;
}
// ---------------------------------------------------------------------------------------------
// Fonts
/** Bundled families and the names they are registered under (shell: @fontsource; site pages: FontFace, fonts.ts). */
export const BUNDLED_FONTS: Record<string, string> = { 'Geist': 'Geist Variable', 'Geist Mono': 'Geist Mono Variable' };
export function fontStack(names: string[]): string {
const out: string[] = [];
for (const name of names) {
const real = BUNDLED_FONTS[name];
if (real) out.push(`"${real}"`);
out.push(GENERIC_FONTS.has(name) ? name : `"${name}"`);
}
// Emoji and CJK keep working whatever the theme names.
return [...new Set(out), '"Segoe UI Emoji"', '"Apple Color Emoji"', 'sans-serif'].join(', ');
}
/** Roles that are drawn inside the site's page (chrome is wayBetter's own window). */
export const PAGE_ROLES: FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'dialog'];
const rolesUsing = (theme: ThemeSpec, roles: readonly FontRoleName[]) => roles.flatMap(role => roleFamily(theme.font.roles[role]));
/** Bundled families (Geist, Geist Mono) a theme names in the site's page. */
export const bundledFontsUsed = (theme: ThemeSpec, roles: readonly FontRoleName[] = PAGE_ROLES) => {
const names = new Set(rolesUsing(theme, roles));
return Object.keys(BUNDLED_FONTS).filter(name => names.has(name));
};
/** Google Fonts families a theme uses (`source: "google"`), for the given roles. */
export function googleFontsUsed(theme: ThemeSpec, roles: readonly FontRoleName[] = FONT_ROLE_NAMES): string[] {
const out = new Set<string>();
for (const role of roles) {
const spec = theme.font.roles[role];
if (spec !== 'inherit' && spec.source === 'google' && spec.family[0]) out.add(spec.family[0]);
}
return [...out];
}
/** A role resolved to what is drawn: the stack actually used and its settings. */
export type ResolvedFontRole = {
/** CSS `font-family`. */
stack: string;
/** The families of that stack (empty when it is the site's or app's own font). */
family: string[];
/** True when the family comes from another role (or the site/app default). */
inherited: boolean;
/** A Google Fonts family the stack starts with. */
google: string | null;
weight: number | null;
size: number;
tracking: number | null;
tabular: boolean;
};
export type ResolvedFontRoles = Record<FontRoleName, ResolvedFontRole>;
/**
* Every role resolved. `site` is the stack an inheriting interface uses: the site's own font in its
* page, wayBetter's own UI font in the shell. Every other role inherits the interface, except that an
* inheriting `mono` keeps a monospaced stack (`mono`: themeApi.ts `MONO_FAMILIES`, code rarely suits
* an interface font).
*/
export function resolveFontRoles(font: FontSpec, site: string, mono = fontStack(MONO_FAMILIES)): ResolvedFontRoles {
const base = font.roles.interface;
const baseFamily = roleFamily(base);
const root: ResolvedFontRole = {
stack: baseFamily.length ? fontStack(baseFamily) : site, family: baseFamily, inherited: !baseFamily.length,
google: base !== 'inherit' && base.source === 'google' ? baseFamily[0] ?? null : null,
weight: null, size: 1, tracking: null, tabular: false,
};
const out = { interface: root } as ResolvedFontRoles;
for (const role of FONT_ROLE_NAMES) {
if (role === 'interface') continue;
const spec = font.roles[role];
const own = roleFamily(spec);
const from = own.length
? { stack: fontStack(own), family: own, inherited: false, google: spec !== 'inherit' && spec.source === 'google' ? own[0]! : null }
: role === 'mono' ? { stack: mono, family: [] as string[], inherited: true, google: null }
: { stack: root.stack, family: root.family, inherited: true, google: root.google };
out[role] = {
...from,
weight: spec === 'inherit' ? null : spec.weight ?? null,
size: spec === 'inherit' ? 1 : spec.size ?? 1,
tracking: spec === 'inherit' ? null : spec.tracking ?? null,
tabular: spec !== 'inherit' && !!spec.tabular,
};
}
return out;
}
/**
* A named font stack offered by the panel's pickers. `key` names its translated label
* (`wb.fonts.choice.*`); `label` is the English one. A site adds its own font first (X: "X's Chirp",
* an empty family that keeps the site's type).
*/
export type FontChoice = { id: string; label: string; key?: string; family: string[] };
/** Font choices offered by the panel; any installed family can also be named in theme JSON. */
export const FONT_CHOICES: FontChoice[] = [
{ id: 'geist', label: 'Geist', family: ['Geist', ...SYSTEM_SANS] },
{ id: 'geist-mono', label: 'Geist Mono', family: ['Geist Mono', 'Cascadia Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] },
{ id: 'system', label: 'System UI', key: 'wb.fonts.choice.system', family: SYSTEM_SANS },
{ id: 'helvetica', label: 'Helvetica / Arial', family: ['Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif'] },
{ id: 'humanist', label: 'Humanist (Segoe, Avenir)', key: 'wb.fonts.choice.humanist', family: ['Avenir Next', 'Segoe UI Variable Text', 'Segoe UI', 'sans-serif'] },
{ id: 'rounded', label: 'Rounded', key: 'wb.fonts.choice.rounded', family: ['ui-rounded', 'SF Pro Rounded', 'Nunito', 'Bahnschrift', 'Segoe UI', 'sans-serif'] },
{ id: 'serif', label: 'Serif (Charter, Georgia)', key: 'wb.fonts.choice.serif', family: ['Charter', 'Iowan Old Style', 'Georgia', 'Cambria', 'serif'] },
{ id: 'mono', label: 'System mono', key: 'wb.fonts.choice.mono', family: ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] },
];
/** The choice whose stack is exactly `family` in `choices`, or `custom`. */
export const fontChoiceOf = (family: string[], choices: readonly FontChoice[] = FONT_CHOICES) => choices.find(choice => choice.family.join('|') === family.join('|'))?.id ?? 'custom';
// ---------------------------------------------------------------------------------------------
// Backgrounds
const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
/**
* The site's page background. A site's `<html>` and `<body>` are often one viewport tall while the
* content overflows them (X's timeline), so a background painted on both had `<body>` paint its own
* copy over its box, which scrolls away: after a partial scroll the gradient/glow showed only below a hard seam. Now
* `<html>` holds the plain page color, `<body>` is transparent (beating, by specificity, the
* palette's `html,body{background-color}` and its `[style^="background-color: …"]` remap of the
* inline color X puts on `<body>`) and every layer sits on one viewport-sized fixed
* layer behind all of the page (`z-index:-1` in the root stacking context), with no `fixed` attachments.
*/
export function pageBackgroundCss(background: Background, page: string): string[] {
const out = [`html:root{background:${page} !important}`, `html:root body{background:transparent !important}`];
if (background.kind !== 'none') {
out.push(`html:root::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;contain:strict;background:${backgroundLayers(background, page, false)}}`);
}
return out;
}
/**
* CSS `background` layers for the page canvas (behind the site's columns). `attach` keeps the `fixed`
* attachments for a box that scrolls (the Theme Builder preview); the site's page gets the layers without
* them, on one viewport-sized fixed layer (`pageBackgroundCss`).
*/
export function backgroundLayers(background: Background, page: string, attach = true): string {
const fixed = attach ? ' fixed' : '';
switch (background.kind) {
case 'gradient': {
const glow = background.glow ? `radial-gradient(1200px 600px at 50% -10%, ${rgba(background.glow, 0.55)}, transparent 70%), ` : '';
return `${glow}linear-gradient(${background.angle}deg, ${background.from}, ${background.to})${fixed}, ${page}`;
}
case 'pattern': {
const { ink, opacity: a, size: s } = background;
const c = rgba(ink, a);
switch (background.pattern) {
case 'dots': return `radial-gradient(${c} 1px, transparent 1.6px) 0 0 / ${s}px ${s}px, ${page}`;
case 'grid': return `linear-gradient(${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, linear-gradient(90deg, ${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, ${page}`;
case 'diagonal': return `repeating-linear-gradient(135deg, ${c} 0 1px, transparent 1px ${s}px), ${page}`;
case 'scanlines': return `repeating-linear-gradient(0deg, ${c} 0 1px, transparent 1px ${s}px), radial-gradient(ellipse at 50% 40%, ${rgba(ink, a * 1.6)}, transparent 70%)${fixed}, ${page}`;
case 'paper': return `${svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${s}"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="3" stitchTiles="stitch"/><feColorMatrix values="0 0 0 0 ${hexToRgb(ink).map(v => (v / 255).toFixed(3)).join(' 0 0 0 0 ')} 0 0 0 ${(a * 2.2).toFixed(3)} 0"/></filter><rect width="100%" height="100%" filter="url(#n)"/></svg>`)} 0 0 / ${s}px ${s}px, ${page}`;
case 'clouds': return [
`radial-gradient(${s}px ${Math.round(s * 0.42)}px at 12% 22%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 1.3)}px ${Math.round(s * 0.5)}px at 86% 12%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 1.1)}px ${Math.round(s * 0.4)}px at 78% 70%, ${c}, transparent 70%)${fixed}`,
`radial-gradient(${Math.round(s * 0.9)}px ${Math.round(s * 0.36)}px at 18% 82%, ${c}, transparent 70%)${fixed}`,
`linear-gradient(180deg, ${mix(page, '#ffffff', 0.25)}, ${page} 60%)${fixed}`, page,
].join(', ');
}
return page;
}
case 'image': {
const scrim = `linear-gradient(${rgba(page, background.dim)}, ${rgba(page, background.dim)})${fixed}`;
return background.fit === 'tile' ? `${scrim}, url("${background.url}") 0 0 / auto repeat, ${page}` : `${scrim}, url("${background.url}") center / cover no-repeat${fixed}, ${page}`;
}
default: return page;
}
}

View file

@ -9,11 +9,7 @@
// Pure: runs in the page runtime, the settings previews and the tests. The site adapter supplies the
// source palettes (`SourceAxis`, one per site mode); e.g. X's Default/Dim/Lights out.
/** `#rrggbb` → [r, g, b] (local, so themeSpec.ts can import this module without a cycle). */
function hexToRgb(hex: string): Rgb {
const n = parseInt(hex.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
import { hexToRgb } from './themeApi.ts';
export type Oklab = [number, number, number];
type Rgb = [number, number, number];

View file

@ -0,0 +1,199 @@
// The theme engine's site-independent parts: theme documents (sanitizing, import, roles, legibility),
// the choice catalog and the first-frame snapshot. Site behavior (X's palette remap and structure
// CSS) is tested in the app.
import assert from 'node:assert/strict';
import test from 'node:test';
import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts';
import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts';
import { SNAPSHOT_LOCAL_MAX, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
import {
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral,
pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec,
} from '../src/themeSpec.ts';
const own: ThemeSpec = { id: 'site', name: 'Site', description: '', author: '', version: 1, mode: 'auto', colors: null, font: BASE_FONT, shape: BASE_SHAPE, layout: BASE_LAYOUT, background: { kind: 'none' }, effects: BASE_EFFECTS, css: '' };
const night: ThemeSpec = sanitizeSpec({ id: 'night', name: 'Night', colors: { bg: '#07080c', text: '#eef0f7', accent: '#5b8cff' }, font: { family: ['Geist', 'system-ui'] } });
test('sanitizeSpec drops anything that could escape into CSS', () => {
const hostile = sanitizeSpec({
id: 'Bad Id!', name: ' Evil\u0000 theme ',
colors: { bg: 'red', surface: '#000', elevated: '#000000', border: '#000000', text: '#ffffff', muted: '#999999', accent: '#1d9bf0' },
font: { family: ['Inter;}body{display:none', 'Geist', 'x"y', 'serif'], scale: 9, weight: 'bold', leading: 99 },
shape: { radius: -4, button: 'pill', avatar: 'star' },
layout: { column: 99999, density: 'tiny', cards: 'yes' },
background: { kind: 'image', url: 'https://evil.test/a.png' },
effects: { motion: 1e9, hover: 'explode' },
});
assert.equal(hostile.id, 'evil-theme');
assert.equal(hostile.name, 'Evil theme');
assert.equal(hostile.colors, null);
assert.deepEqual(hostile.font.family, ['Geist', 'serif']);
assert.equal(hostile.font.scale, 1.2);
assert.equal(hostile.font.leading, 1.8);
assert.deepEqual(hostile.shape, { radius: 0, button: 9999, avatar: 'circle' });
assert.equal(hostile.layout.column, 820);
assert.equal(hostile.layout.density, 'default');
assert.equal(hostile.layout.cards, false);
assert.deepEqual(hostile.background, { kind: 'none' });
assert.equal(hostile.effects.motion, 400);
assert.equal(hostile.effects.hover, 'none');
for (const url of ['data:image/svg+xml;base64,PHN2Zz4=', 'data:text/html;base64,AAAA', 'data:image/png;base64,AA)A', 'javascript:alert(1)']) {
assert.deepEqual(sanitizeSpec({ name: 'a', background: { kind: 'image', url } }).background, { kind: 'none' }, url);
}
assert.equal(sanitizeSpec({ name: 'a', background: { kind: 'image', url: 'data:image/png;base64,iVBORw0KGgo=' } }).background.kind, 'image');
// The schema's defaults change nothing.
assert.ok(isNeutral(own));
assert.ok(!isNeutral(night));
});
test('parseThemeJson explains what it rejected or changed', () => {
assert.deepEqual(parseThemeJson('{nope'), { error: 'This file is not valid JSON.' });
assert.deepEqual(parseThemeJson('{"id":"a"}'), { error: 'A theme needs a "name".' });
const parsed = parseThemeJson(JSON.stringify({ name: 'Mine', css: 'a{}', colors: { bg: 'red' } }));
assert.ok('theme' in parsed);
if ('theme' in parsed) {
assert.equal(parsed.theme.id, 'mine');
assert.equal(parsed.warnings.length, 2);
}
});
test('a palette from three colors, then legibility: any accent stays readable on every surface', () => {
assert.ok(night.colors && night.colors.surface && night.colors.border, 'derived roles are filled in');
for (const accent of ['#1d9bf0', '#ffffff', '#000000', '#fffe00']) {
const c = applyOverrides(night, {}, accent).colors!;
for (const surface of [c.bg, c.surface, c.elevated]) assert.ok(contrastRatio(c.accent, surface) >= 4.5, accent);
assert.ok(contrastRatio(c.onInverse!, c.inverse!) >= 4.5, `${accent} button`);
}
const bad = ensureContrast({ bg: '#888888', surface: '#8a8a8a', elevated: '#909090', border: '#999999', text: '#777777', muted: '#7a7a7a', accent: '#8888ff' });
for (const role of ['text', 'muted', 'accent'] as const) assert.ok(contrastRatio(bad[role], '#909090') >= 4.5, role);
});
test('old theme files migrate and roles win over the shorthand', () => {
const old = sanitizeSpec({ name: 'Old', font: { family: ['Georgia', 'serif'], tweet: ['Charter'] } });
assert.deepEqual(old.font.roles.interface, { family: ['Georgia', 'serif'] });
assert.deepEqual(old.font.roles.post, { family: ['Charter'] });
assert.deepEqual(old.font, withRoles({ ...BASE_FONT, family: ['Georgia', 'serif'], tweet: ['Charter'] }));
const doc = { name: 'New', font: { family: ['Arial'], roles: { interface: { family: ['Inter', 'sans-serif'], source: 'google' }, numbers: { family: [], tabular: true, weight: 650 } } } };
const theme = sanitizeSpec(doc);
assert.deepEqual(theme.font.family, ['Inter', 'sans-serif']);
assert.deepEqual(theme.font.roles.numbers, { family: [], weight: 650, tabular: true });
assert.deepEqual(sanitizeSpec(JSON.parse(JSON.stringify(theme))), theme);
});
test('role sanitizing: clamps, drops unknown keys and unsafe names, interface takes only a family', () => {
const theme = sanitizeSpec({ name: 't', font: { roles: {
interface: { family: ['Inter'], weight: 900, size: 2 },
post: { family: ['Lora', '</style><script>'], weight: 5000, size: 9, tracking: -1, tabular: 'yes', script: 'x' },
heading: { family: ['serif'], source: 'google' },
numbers: {},
mono: 'monospace',
chrome: { family: ['Space Grotesk'], source: 'evil' },
nope: { family: ['Inter'] },
} } });
assert.deepEqual(theme.font.roles.interface, { family: ['Inter'] });
assert.deepEqual(theme.font.roles.post, { family: ['Lora'], weight: ROLE_LIMITS.weight[1], size: ROLE_LIMITS.size[1], tracking: ROLE_LIMITS.tracking[0] });
assert.deepEqual(theme.font.roles.heading, { family: ['serif'] }, 'a generic family is never a Google font');
assert.equal(theme.font.roles.numbers, 'inherit');
assert.equal(theme.font.roles.mono, 'inherit');
assert.deepEqual(theme.font.roles.chrome, { family: ['Space Grotesk'] });
assert.equal('nope' in theme.font.roles, false);
assert.deepEqual(withFamily({ family: ['Inter'], source: 'google', weight: 600 }, ['Georgia']), { family: ['Georgia'], weight: 600 });
assert.equal(withFamily({ family: ['Inter'] }, []), 'inherit');
});
test('font roles resolve: inherit the interface (the site font when it inherits), mono keeps a monospaced stack', () => {
const site = 'SiteSans, sans-serif';
const roles = resolveFontRoles(own.font, site);
for (const role of FONT_ROLE_NAMES) assert.equal(roles[role].inherited, true, role);
assert.equal(roles.interface.stack, site);
assert.equal(roles.post.stack, site);
assert.match(roles.mono.stack, /Cascadia Mono/);
const reported = resolvedFonts(night.font, site);
assert.equal(reported.interface.stack, fontStack(['Geist', 'system-ui']));
assert.equal(reported.interface.inherited, false);
assert.match(fontStack(['Geist']), /^"Geist Variable", "Geist"/, 'bundled families use their registered name first');
assert.match(MONO_FONT, /^"Cascadia Mono"/);
assert.equal(fontChoiceOf(FONT_CHOICES.find(choice => choice.id === 'serif')!.family), 'serif');
assert.equal(fontChoiceOf(['Nope']), 'custom');
});
test('backgrounds are values, painted on one fixed layer behind the page', () => {
const css = pageBackgroundCss({ kind: 'pattern', pattern: 'dots', ink: '#ffffff', opacity: 0.2, size: 20 }, '#000000').join('\n');
assert.match(css, /html:root::before\{[^}]*position:fixed/);
assert.match(css, /html:root body\{background:transparent !important\}/);
assert.doesNotMatch(backgroundLayers({ kind: 'gradient', from: '#000000', to: '#111111', angle: 90 }, '#000000', false), /fixed/);
assert.match(backgroundLayers({ kind: 'gradient', from: '#000000', to: '#111111', angle: 90 }, '#000000'), / fixed/);
});
test('a site catalog: the first built-in is the default; imported themes are kept, bounded and never shadow a built-in', () => {
const catalog = createThemeCatalog([own, night]);
assert.deepEqual(catalog.defaultChoice, { preset: 'site', accent: null, overrides: {}, themes: [] });
const many = Array.from({ length: MAX_USER_THEMES + 5 }, (_, n) => ({ id: `mine-${n}`, name: `Mine ${n}` }));
const choice = catalog.normalize({ preset: 'mine-3', accent: '#FF0000', themes: [{ id: 'night', name: 'Fake night' }, ...many], overrides: { font: { scale: 1.1 }, nope: { a: 1 }, css: 'x' } });
assert.equal(choice.themes.length, MAX_USER_THEMES - 1, 'the shadowing theme is dropped, the rest capped');
assert.equal(choice.preset, 'mine-3');
assert.equal(choice.accent, '#ff0000');
assert.deepEqual(Object.keys(choice.overrides), ['font']);
assert.equal(catalog.normalize({ preset: 'gone' }).preset, 'site');
assert.equal(catalog.base({ ...choice, preset: 'night' }).name, 'Night');
assert.equal(catalog.resolve({ ...choice, preset: 'site' }).font.scale, 1.1);
assert.deepEqual(catalog.palette({ ...catalog.defaultChoice, accent: '#00ff00' }), { accent: '#00ff00' });
assert.equal(catalog.palette(catalog.defaultChoice), null);
assert.equal(catalog.all(choice).length, 2 + choice.themes.length);
assert.equal(choiceForId(choice, choice.preset), choice);
assert.deepEqual(choiceForId(choice, 'night'), { preset: 'night', accent: null, overrides: {}, themes: choice.themes });
assert.deepEqual(serializeChoice({ ...catalog.defaultChoice, overrides: { font: {} } }), { preset: 'site', accent: null });
assert.throws(() => createThemeCatalog([]));
});
// ---- First-frame snapshot ----------------------------------------------------------------------
class MemoryStorage {
data = new Map<string, string>();
quota = Infinity;
getItem(key: string) { return this.data.get(key) ?? null; }
setItem(key: string, value: string) { if (value.length > this.quota) throw new Error('QuotaExceededError'); this.data.set(key, value); }
removeItem(key: string) { this.data.delete(key); }
}
const storages = () => {
const session = new MemoryStorage();
const local = new MemoryStorage();
return { session, local, stores: { session: session as unknown as Storage, local: local as unknown as Storage } };
};
const snap = (css: string, preset = 'nord'): ThemeSnapshot => ({ key: `{"preset":"${preset}"}|dark`, choice: { preset }, css });
const presetOf = (snapshot: ThemeSnapshot | null) => (snapshot?.choice as { preset: string } | undefined)?.preset;
test('the tab\'s own snapshot wins over the account-wide one', () => {
const { stores } = storages();
writeSnapshot(stores, snap('html{background:#2e3440 !important}'));
assert.equal(presetOf(readSnapshot(stores)), 'nord');
// Another tab of the account showed a different theme later: only localStorage changes.
stores.local!.setItem('wb:theme-snapshot', JSON.stringify(snap('html{background:#282a36 !important}', 'dracula')));
assert.equal(presetOf(readSnapshot(stores)), 'nord');
// A new tab (empty sessionStorage) falls back to the account's last theme.
assert.equal(presetOf(readSnapshot({ session: null, local: stores.local })), 'dracula');
});
test('the site\'s own look clears the snapshot', () => {
const { stores, session, local } = storages();
writeSnapshot(stores, snap('a{}'));
writeSnapshot(stores, null);
assert.equal(session.data.size + local.data.size, 0);
assert.equal(readSnapshot(stores), null);
});
test('big snapshots stay out of the site\'s localStorage; quota errors never throw', () => {
const { stores, session, local } = storages();
writeSnapshot(stores, snap('x'.repeat(SNAPSHOT_LOCAL_MAX + 10)));
assert.equal(session.data.size, 1, 'the tab keeps it for reloads');
assert.equal(local.data.size, 0, 'too big to share the site\'s localStorage quota');
session.quota = 10;
assert.doesNotThrow(() => writeSnapshot(stores, snap('y'.repeat(100))));
});
test('garbage in storage is no snapshot', () => {
const { stores } = storages();
stores.session!.setItem('wb:theme-snapshot', '{not json');
stores.local!.setItem('wb:theme-snapshot', JSON.stringify({ key: 1, css: 'a{}' }));
assert.equal(readSnapshot(stores), null);
});