feat(qbz-theme): add frontend-agnostic theme registry crate

Introduce the `qbz-theme` crate (ADR-006): pure Rust, no Slint/Tauri/heavy
deps, hand-rolled color + contrast math. It holds the scalable theming data
model the Slint migration consumes.

- `Rgba` + WCAG relative-luminance/contrast-ratio + an APCA Lc approximation
  (secondary a11y gate for P3 tests).
- `ThemeColors`: the complete token contract (surfaces incl. bg-hover, text,
  accent, danger/warning/success families, border-subtle/muted/strong,
  focus-ring, favorite, card-shadow, 24-tier alpha superset with polarity
  baked in).
- `ThemeId` enum (all 33 themes) with stable slugs, display names (proper-noun
  data, not i18n keys), Core/Dark/Light/Accessibility categories, and a
  luminance-derived light/dark flag. `default_theme_id()` = OLED.
- Registry materializes the 4 P1 themes (Dark/OLED/Tokyo Night/System-fallback)
  from src/app.css, preserving the legacy translucent alias values so the
  existing themes stay pixel-identical; derives the new token families.
- 22 unit tests (registry fully populated, default is OLED, legacy alpha
  aliases unchanged, slug roundtrip).

cc
This commit is contained in:
vicrodh committed 2026-06-20 14:49:53 -06:00
1 parent c5cb9dbbe0
commit ff5536a02e
8 files changed
+1018

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
//! Plain RGBA color + hand-rolled contrast math (WCAG 2.x + APCA approximation).
//!
//! No external color crate: the registry must compile and unit-test fast on its
//! own (ADR-006), so the few formulas we need live here.
/// 8-bit-per-channel color with straight (non-premultiplied) alpha.
///
/// `a == 255` is fully opaque, `a == 0` fully transparent. The Slint side maps
/// this 1:1 to `slint::Color::from_argb_u8(a, r, g, b)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rgba {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Rgba {
/// Opaque color from 8-bit channels.
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b, a: 255 }
}
/// Color with explicit alpha.
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
/// Parse `#rrggbb` / `rrggbb` / `#rrggbbaa` (case-insensitive). Returns
/// `None` on any malformed input. `const`-incompatible (loops), used only
/// in tests + as a convenience.
pub fn from_hex(s: &str) -> Option<Self> {
let h = s.strip_prefix('#').unwrap_or(s);
let bytes = h.as_bytes();
let hx = |hi: u8, lo: u8| -> Option<u8> {
let v = |c: u8| -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
};
Some(v(hi)? * 16 + v(lo)?)
};
match bytes.len() {
6 => Some(Self::rgb(
hx(bytes[0], bytes[1])?,
hx(bytes[2], bytes[3])?,
hx(bytes[4], bytes[5])?,
)),
8 => Some(Self::rgba(
hx(bytes[0], bytes[1])?,
hx(bytes[2], bytes[3])?,
hx(bytes[4], bytes[5])?,
hx(bytes[6], bytes[7])?,
)),
_ => None,
}
}
}
/// sRGB 0..=255 channel -> linear-light 0.0..=1.0 (WCAG 2.x transfer function).
fn srgb_to_linear(c: u8) -> f64 {
let cs = c as f64 / 255.0;
if cs <= 0.040_45 {
cs / 12.92
} else {
((cs + 0.055) / 1.055).powf(2.4)
}
}
/// WCAG 2.x relative luminance of an OPAQUE color (alpha ignored).
/// `Y = 0.2126 R + 0.7152 G + 0.0722 B` on linear channels.
pub fn relative_luminance(c: Rgba) -> f64 {
0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
}
/// WCAG 2.x contrast ratio between two opaque colors, in `[1.0, 21.0]`.
/// `(L_lighter + 0.05) / (L_darker + 0.05)`. Order-independent.
pub fn contrast_ratio(a: Rgba, b: Rgba) -> f64 {
let la = relative_luminance(a);
let lb = relative_luminance(b);
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
(hi + 0.05) / (lo + 0.05)
}
// --- APCA (Lc) approximation ------------------------------------------------
//
// A compact port of the APCA-W3 0.1.9 "Lc" contrast estimator. Sign convention:
// negative Lc = light text on a dark background, positive Lc = dark text on a
// light background. We only ever consume |Lc| against thresholds, so the sign is
// informational. This is an APPROXIMATION (the official lookup-table clamps and
// the soft-black/low-contrast roll-offs are reproduced); it is used as a
// secondary gate in a11y unit tests, never for production rendering.
const APCA_SRGB_R: f64 = 0.2126729;
const APCA_SRGB_G: f64 = 0.7151522;
const APCA_SRGB_B: f64 = 0.0721750;
const APCA_MAIN_TRC: f64 = 2.4;
const APCA_NORM_BG: f64 = 0.56;
const APCA_NORM_TXT: f64 = 0.57;
const APCA_REV_BG: f64 = 0.62;
const APCA_REV_TXT: f64 = 0.65;
const APCA_BLK_THRS: f64 = 0.022;
const APCA_BLK_CLMP: f64 = 1.414;
const APCA_SCALE: f64 = 1.14;
const APCA_LO_CLIP: f64 = 0.1;
const APCA_DELTA_Y_MIN: f64 = 0.0005;
fn apca_screen_y(c: Rgba) -> f64 {
let lin = |v: u8| (v as f64 / 255.0).powf(APCA_MAIN_TRC);
APCA_SRGB_R * lin(c.r) + APCA_SRGB_G * lin(c.g) + APCA_SRGB_B * lin(c.b)
}
fn apca_soft_clamp(mut y: f64) -> f64 {
if y < 0.0 {
y = 0.0;
}
if y < APCA_BLK_THRS {
y += (APCA_BLK_THRS - y).powf(APCA_BLK_CLMP);
}
y
}
/// APCA Lc estimate for `text` on `bg`. See module note on sign + accuracy.
pub fn apca_lc(text: Rgba, bg: Rgba) -> f64 {
let txt_y = apca_soft_clamp(apca_screen_y(text));
let bg_y = apca_soft_clamp(apca_screen_y(bg));
if (bg_y - txt_y).abs() < APCA_DELTA_Y_MIN {
return 0.0;
}
let out;
if bg_y > txt_y {
// Normal polarity: dark text on light bg -> positive Lc.
let c = (bg_y.powf(APCA_NORM_BG) - txt_y.powf(APCA_NORM_TXT)) * APCA_SCALE;
out = if c < APCA_LO_CLIP { 0.0 } else { c - APCA_LO_CLIP * 0.027 };
} else {
// Reverse polarity: light text on dark bg -> negative Lc.
let c = (bg_y.powf(APCA_REV_BG) - txt_y.powf(APCA_REV_TXT)) * APCA_SCALE;
out = if c > -APCA_LO_CLIP { 0.0 } else { c + APCA_LO_CLIP * 0.027 };
}
out * 100.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_roundtrip() {
assert_eq!(Rgba::from_hex("#0f0f0f"), Some(Rgba::rgb(15, 15, 15)));
assert_eq!(Rgba::from_hex("ffffff"), Some(Rgba::rgb(255, 255, 255)));
assert_eq!(Rgba::from_hex("#ffffff14"), Some(Rgba::rgba(255, 255, 255, 0x14)));
assert_eq!(Rgba::from_hex("nope"), None);
}
#[test]
fn black_white_contrast_is_21() {
let r = contrast_ratio(Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255));
assert!((r - 21.0).abs() < 0.01, "got {r}");
}
#[test]
fn contrast_is_symmetric_and_min_one() {
let a = Rgba::rgb(0x42, 0x85, 0xf4);
let b = Rgba::rgb(0x0f, 0x0f, 0x0f);
assert!((contrast_ratio(a, b) - contrast_ratio(b, a)).abs() < 1e-9);
assert!(contrast_ratio(a, a) >= 0.999);
}
#[test]
fn apca_sign_convention() {
// light text on dark bg -> negative
let lc = apca_lc(Rgba::rgb(255, 255, 255), Rgba::rgb(15, 15, 15));
assert!(lc < -60.0, "white on near-black should be strongly negative, got {lc}");
// dark text on light bg -> positive
let lc = apca_lc(Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255));
assert!(lc > 90.0, "black on white should be strongly positive, got {lc}");
}
}
+168
View File
@@ -0,0 +1,168 @@
//! The fully-materialized per-theme color set.
//!
//! Every theme row in the registry returns one of these with EVERY field
//! populated — there is no CSS cascade on the Slint side, so omissions in
//! `src/app.css` are resolved against `:root` (Dark) at registry-build time.
use crate::color::Rgba;
/// The 24 alpha tiers, in ascending percentage order. This is the SUPERSET of
/// the two Tauri alpha scales (cosmetic 20-tier + a11y 22-tier), per the
/// migration plan (A.3). Index into [`ThemeColors::alpha`] with [`AlphaTier`].
pub const ALPHA_PERCENTS: [u8; 24] = [
4, 5, 6, 8, 10, 12, 15, 18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,
];
/// Number of alpha tiers (= `ALPHA_PERCENTS.len()`).
pub const ALPHA_COUNT: usize = 24;
/// Map an alpha percentage to its `0xAA` byte (rounded). `pct * 255 / 100`.
pub const fn alpha_byte(pct: u8) -> u8 {
((pct as u16 * 255 + 50) / 100) as u8
}
/// Position of an alpha percentage within [`ALPHA_PERCENTS`], or `None`.
pub fn alpha_index(pct: u8) -> Option<usize> {
let mut i = 0;
while i < ALPHA_COUNT {
if ALPHA_PERCENTS[i] == pct {
return Some(i);
}
i += 1;
}
None
}
/// The complete, frontend-agnostic color contract for one theme. Field order
/// groups by family (surfaces, text, accent, danger, warning, success, borders,
/// focus, extras, alpha) to match the Slint `ThemeColors` struct and the plan's
/// A.3 token list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThemeColors {
// --- surfaces ---
pub surface_main: Rgba,
pub surface_card: Rgba,
pub surface_elevated: Rgba,
/// Alpha-based hover overlay (translucent, polarity-correct).
pub surface_hover: Rgba,
/// Opaque theme `--bg-hover` hex (distinct from the alpha `surface_hover`).
pub bg_hover: Rgba,
// --- text ---
pub text_primary: Rgba,
pub text_secondary: Rgba,
pub text_muted: Rgba,
pub text_disabled: Rgba,
// --- accent ---
pub accent: Rgba,
pub accent_hover: Rgba,
pub accent_pressed: Rgba,
/// Text drawn ON an accent fill (`--btn-primary-text`).
pub accent_text: Rgba,
// --- danger family ---
pub danger: Rgba,
pub danger_bg: Rgba,
pub danger_border: Rgba,
pub danger_hover: Rgba,
// --- warning family ---
pub warning: Rgba,
pub warning_bg: Rgba,
pub warning_border: Rgba,
pub warning_hover: Rgba,
// --- success family (NEW vs Tauri parity) ---
pub success: Rgba,
pub success_bg: Rgba,
pub success_border: Rgba,
pub success_hover: Rgba,
// --- borders ---
/// Theme `--border-subtle` value. The legacy Slint `border-subtle` alias was
/// a translucent white hairline; for the P1 themes this keeps that value so
/// the 4 themes stay pixel-identical. Standard/a11y rows (P2/P3) feed the
/// theme `--border-subtle` hex.
pub border_subtle: Rgba,
/// Legacy Slint-only token (no Tauri equivalent): a stronger translucent
/// edge used by popovers/dropdowns. Kept so existing call sites compile.
pub border_muted: Rgba,
pub border_strong: Rgba,
// --- focus (NEW) ---
pub focus_ring: Rgba,
// --- extras ---
pub favorite: Rgba,
pub card_shadow: Rgba,
// --- alpha overlays (polarity baked in: white on dark, black on light) ---
pub alpha: [Rgba; ALPHA_COUNT],
}
impl ThemeColors {
/// Look up an alpha overlay by percentage (e.g. `8`, `55`). Falls back to
/// the nearest standard tier if an exact match is absent.
pub fn alpha_pct(&self, pct: u8) -> Rgba {
if let Some(i) = alpha_index(pct) {
return self.alpha[i];
}
// Nearest tier by absolute distance.
let mut best = 0usize;
let mut best_d = u8::MAX as i32;
for (i, &p) in ALPHA_PERCENTS.iter().enumerate() {
let d = (p as i32 - pct as i32).abs();
if d < best_d {
best_d = d;
best = i;
}
}
self.alpha[best]
}
}
/// Build the 24-tier alpha ramp for a theme of the given polarity.
/// `is_light` themes get a BLACK base (dark hairlines/hovers read on light
/// surfaces); dark themes get a WHITE base — matching Tauri's per-theme flip.
pub fn alpha_ramp(is_light: bool) -> [Rgba; ALPHA_COUNT] {
let (r, g, b) = if is_light { (0, 0, 0) } else { (255, 255, 255) };
let mut out = [Rgba::rgba(r, g, b, 0); ALPHA_COUNT];
let mut i = 0;
while i < ALPHA_COUNT {
out[i] = Rgba::rgba(r, g, b, alpha_byte(ALPHA_PERCENTS[i]));
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alpha_byte_rounds() {
assert_eq!(alpha_byte(8), 0x14); // 8% -> 20
assert_eq!(alpha_byte(10), 0x1a); // 10% -> 26
assert_eq!(alpha_byte(12), 0x1f); // 12% -> 31
assert_eq!(alpha_byte(18), 0x2e); // 18% -> 46
assert_eq!(alpha_byte(55), 0x8c); // 55% -> 140
assert_eq!(alpha_byte(65), 0xa6); // 65% -> 166
assert_eq!(alpha_byte(70), 0xb3); // 70% -> 179
assert_eq!(alpha_byte(75), 0xbf); // 75% -> 191
}
#[test]
fn ramp_polarity() {
let dark = alpha_ramp(false);
let light = alpha_ramp(true);
assert_eq!(dark[alpha_index(8).unwrap()], Rgba::rgba(255, 255, 255, 0x14));
assert_eq!(light[alpha_index(8).unwrap()], Rgba::rgba(0, 0, 0, 0x14));
}
#[test]
fn alpha_count_is_24() {
assert_eq!(ALPHA_COUNT, 24);
assert_eq!(ALPHA_PERCENTS.len(), 24);
}
}
+273
View File
@@ -0,0 +1,273 @@
//! Stable theme identity: the enum, its persisted slug, display name (proper-
//! noun data, NOT an i18n key — see ADR / i18n rule), category grouping, and a
//! luminance-derived light/dark flag.
use serde::{Deserialize, Serialize};
/// Grouping shown in the Settings theme list. Mirrors the Tauri SettingsView
/// registry comment blocks (Core / Dark / Light / Accessibility).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThemeCategory {
Core,
Dark,
Light,
Accessibility,
}
impl ThemeCategory {
pub fn slug(self) -> &'static str {
match self {
ThemeCategory::Core => "core",
ThemeCategory::Dark => "dark",
ThemeCategory::Light => "light",
ThemeCategory::Accessibility => "accessibility",
}
}
}
/// Every theme the registry can produce. The four marked "(P1)" are the only
/// ones materialized in Phase 1; the rest are placeholders the P2/P3 phases
/// fill in. `from_slug`/`slug` are stable across releases (persisted in
/// `ui_prefs.theme`), so the variant ORDER may change freely but the slugs must
/// not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThemeId {
// --- Core ---
Dark, // P1 — :root
Oled, // P1 — DEFAULT theme
Light,
System, // P1 — meta (OS-following; resolved in the frontend)
// --- Dark (branded / community) ---
Warm,
Nord,
Dracula,
TokyoNight, // P1
CatppuccinMocha,
BreezeDark,
AdwaitaDark,
Aurora,
Ikari,
Ayanami,
Iscariot,
Stratego,
Rumi,
Zoey,
Mira,
Frost, // registered light, visually dark
Langley, // registered light, visually dark
// --- Light (branded / community) ---
Alucard,
RosePineDawn,
BreezeLight,
AdwaitaLight,
DuotoneSnow,
SnowStorm,
Kurosaki,
// --- Accessibility (REDESIGNED in P3) ---
WcagLight,
WcagDark,
HighContrast,
HighContrastLight,
Colorblind,
}
/// All theme variants in display order (Core, Dark, Light, Accessibility).
pub const ALL: &[ThemeId] = &[
ThemeId::Dark,
ThemeId::Oled,
ThemeId::Light,
ThemeId::System,
ThemeId::Warm,
ThemeId::Nord,
ThemeId::Dracula,
ThemeId::TokyoNight,
ThemeId::CatppuccinMocha,
ThemeId::BreezeDark,
ThemeId::AdwaitaDark,
ThemeId::Aurora,
ThemeId::Ikari,
ThemeId::Ayanami,
ThemeId::Iscariot,
ThemeId::Stratego,
ThemeId::Rumi,
ThemeId::Zoey,
ThemeId::Mira,
ThemeId::Frost,
ThemeId::Langley,
ThemeId::Alucard,
ThemeId::RosePineDawn,
ThemeId::BreezeLight,
ThemeId::AdwaitaLight,
ThemeId::DuotoneSnow,
ThemeId::SnowStorm,
ThemeId::Kurosaki,
ThemeId::WcagLight,
ThemeId::WcagDark,
ThemeId::HighContrast,
ThemeId::HighContrastLight,
ThemeId::Colorblind,
];
impl ThemeId {
/// The default theme on a fresh profile (owner decision 2026-06-20).
pub const fn default_id() -> ThemeId {
ThemeId::Oled
}
/// Whether this theme is fully materialized by the registry in P1. Used by
/// the frontend list builder to expose only ready themes during P1/P2.
pub fn is_implemented(self) -> bool {
matches!(
self,
ThemeId::Dark | ThemeId::Oled | ThemeId::TokyoNight | ThemeId::System
)
}
/// Stable persisted slug. MUST NOT change once shipped.
pub fn slug(self) -> &'static str {
match self {
ThemeId::Dark => "dark",
ThemeId::Oled => "oled",
ThemeId::Light => "light",
ThemeId::System => "system",
ThemeId::Warm => "warm",
ThemeId::Nord => "nord",
ThemeId::Dracula => "dracula",
ThemeId::TokyoNight => "tokyo-night",
ThemeId::CatppuccinMocha => "catppuccin-mocha",
ThemeId::BreezeDark => "breeze-dark",
ThemeId::AdwaitaDark => "adwaita-dark",
ThemeId::Aurora => "aurora",
ThemeId::Ikari => "ikari",
ThemeId::Ayanami => "ayanami",
ThemeId::Iscariot => "iscariot",
ThemeId::Stratego => "stratego",
ThemeId::Rumi => "rumi",
ThemeId::Zoey => "zoey",
ThemeId::Mira => "mira",
ThemeId::Frost => "frost",
ThemeId::Langley => "langley",
ThemeId::Alucard => "alucard",
ThemeId::RosePineDawn => "rose-pine-dawn",
ThemeId::BreezeLight => "breeze-light",
ThemeId::AdwaitaLight => "adwaita-light",
ThemeId::DuotoneSnow => "duotone-snow",
ThemeId::SnowStorm => "snow-storm",
ThemeId::Kurosaki => "kurosaki",
ThemeId::WcagLight => "wcag-light",
ThemeId::WcagDark => "wcag-dark",
ThemeId::HighContrast => "high-contrast",
ThemeId::HighContrastLight => "high-contrast-light",
ThemeId::Colorblind => "colorblind",
}
}
/// Parse a persisted slug back to a `ThemeId`. Unknown slugs return `None`
/// (the caller falls back to the default).
pub fn from_slug(s: &str) -> Option<ThemeId> {
ALL.iter().copied().find(|id| id.slug() == s)
}
/// Human-facing display name. This is proper-noun DATA (theme names like
/// "Nord", "Tokyo Night", "OLED Black") — NOT a translatable UI string, so
/// it lives here in the registry, not in the i18n catalog.
pub fn display_name(self) -> &'static str {
match self {
ThemeId::Dark => "Dark",
ThemeId::Oled => "OLED Black",
ThemeId::Light => "Light",
ThemeId::System => "System",
ThemeId::Warm => "Warm",
ThemeId::Nord => "Nord",
ThemeId::Dracula => "Dracula",
ThemeId::TokyoNight => "Tokyo Night",
ThemeId::CatppuccinMocha => "Catppuccin Mocha",
ThemeId::BreezeDark => "Breeze Dark",
ThemeId::AdwaitaDark => "Adwaita Dark",
ThemeId::Aurora => "Aurora",
ThemeId::Ikari => "Ikari",
ThemeId::Ayanami => "Ayanami",
ThemeId::Iscariot => "Iscariot",
ThemeId::Stratego => "Stratego",
ThemeId::Rumi => "Rumi",
ThemeId::Zoey => "Zoey",
ThemeId::Mira => "Mira",
ThemeId::Frost => "Frost",
ThemeId::Langley => "Langley",
ThemeId::Alucard => "Alucard",
ThemeId::RosePineDawn => "Rose Pine Dawn",
ThemeId::BreezeLight => "Breeze Light",
ThemeId::AdwaitaLight => "Adwaita Light",
ThemeId::DuotoneSnow => "Duotone Snow",
ThemeId::SnowStorm => "Snow Storm",
ThemeId::Kurosaki => "Kurosaki",
ThemeId::WcagLight => "WCAG Light",
ThemeId::WcagDark => "WCAG Dark",
ThemeId::HighContrast => "High Contrast",
ThemeId::HighContrastLight => "High Contrast Light",
ThemeId::Colorblind => "Colorblind",
}
}
/// Category grouping for the Settings list. Note the corrected placement of
/// `Frost`/`Langley` (visually dark despite the Tauri `type:light` flag) and
/// `Alucard` (a genuine light theme grouped under "Dark" in Tauri).
pub fn category(self) -> ThemeCategory {
use ThemeId::*;
match self {
Dark | Oled | Light | System => ThemeCategory::Core,
Warm | Nord | Dracula | TokyoNight | CatppuccinMocha | BreezeDark | AdwaitaDark
| Aurora | Ikari | Ayanami | Iscariot | Stratego | Rumi | Zoey | Mira | Frost
| Langley => ThemeCategory::Dark,
Alucard | RosePineDawn | BreezeLight | AdwaitaLight | DuotoneSnow | SnowStorm
| Kurosaki => ThemeCategory::Light,
WcagLight | WcagDark | HighContrast | HighContrastLight | Colorblind => {
ThemeCategory::Accessibility
}
}
}
}
/// The default theme slug (`"oled"`). Convenience for `ui_prefs::default_theme`.
pub fn default_slug() -> &'static str {
ThemeId::default_id().slug()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slug_roundtrip_all() {
for &id in ALL {
assert_eq!(ThemeId::from_slug(id.slug()), Some(id), "slug {} failed", id.slug());
}
}
#[test]
fn slugs_are_unique() {
let mut seen = std::collections::HashSet::new();
for &id in ALL {
assert!(seen.insert(id.slug()), "duplicate slug {}", id.slug());
}
assert_eq!(seen.len(), ALL.len());
}
#[test]
fn default_is_oled() {
assert_eq!(ThemeId::default_id(), ThemeId::Oled);
assert_eq!(default_slug(), "oled");
}
#[test]
fn unknown_slug_is_none() {
assert_eq!(ThemeId::from_slug("does-not-exist"), None);
}
#[test]
fn p1_themes_implemented() {
for id in [ThemeId::Dark, ThemeId::Oled, ThemeId::TokyoNight, ThemeId::System] {
assert!(id.is_implemented(), "{:?} should be P1-implemented", id);
}
}
}
+119
View File
@@ -0,0 +1,119 @@
//! `qbz-theme` — the frontend-agnostic theme/palette registry (ADR-006).
//!
//! Pure Rust data + hand-rolled color/contrast math. NO Slint, NO Tauri, NO
//! heavy deps, so it compiles and unit-tests fast on its own and can be reused
//! by any frontend (Slint, the Tauri build, a TUI, contrast unit tests).
//!
//! The contract: a [`ThemeId`] maps to one fully-materialized [`ThemeColors`]
//! struct (no CSS cascade — every field is populated). The frontend converts
//! each [`Rgba`] to its own color type and pushes the struct into a single
//! theme global on theme change.
//!
//! Phase 1 materializes only the four existing themes; [`ThemeId::is_implemented`]
//! reports which rows are ready so the Settings list can expose only those.
mod color;
mod colors;
mod id;
mod registry;
pub use color::{apca_lc, contrast_ratio, relative_luminance, Rgba};
pub use colors::{alpha_byte, alpha_index, alpha_ramp, ThemeColors, ALPHA_COUNT, ALPHA_PERCENTS};
pub use id::{default_slug, ThemeCategory, ThemeId, ALL};
pub use registry::palette;
/// A single entry in the Settings theme list: the stable id plus the data the
/// dropdown needs (display name, category, light/dark, ready flag).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThemeListEntry {
pub id: ThemeId,
pub display_name: &'static str,
pub slug: &'static str,
pub category: ThemeCategory,
/// Luminance-derived (NOT the unreliable Tauri `type` flag): `true` when the
/// theme's `surface_main` is light. Drives the dark/light list filter.
pub is_light: bool,
/// Whether the registry fully materializes this row yet (P1 gating).
pub implemented: bool,
}
/// The default theme on a fresh profile (owner decision 2026-06-20: OLED Dark).
pub fn default_theme_id() -> ThemeId {
ThemeId::default_id()
}
/// Whether a theme reads as "light" from its actual base surface luminance.
/// This is the corrected light/dark flag the plan mandates (Frost/Langley are
/// registered light in Tauri but are visually dark; Alucard is genuinely light).
pub fn is_light(id: ThemeId) -> bool {
// System has no static palette; treat it as dark for filter purposes (it
// follows the OS at runtime).
if id == ThemeId::System {
return false;
}
relative_luminance(palette(id).surface_main) >= 0.5
}
/// Build the full Settings theme list in display order. The frontend filters by
/// `is_light` and may hide `!implemented` rows during P1/P2.
pub fn theme_list() -> Vec<ThemeListEntry> {
ALL.iter()
.map(|&id| ThemeListEntry {
id,
display_name: id.display_name(),
slug: id.slug(),
category: id.category(),
is_light: is_light(id),
implemented: id.is_implemented(),
})
.collect()
}
/// The implemented-only theme list (what the Settings dropdown shows in P1).
pub fn implemented_theme_list() -> Vec<ThemeListEntry> {
theme_list().into_iter().filter(|e| e.implemented).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_is_oled() {
assert_eq!(default_theme_id(), ThemeId::Oled);
}
#[test]
fn registry_returns_populated_struct_for_default() {
let c = palette(default_theme_id());
// OLED: pure-black base, white text, full alpha ramp.
assert_eq!(c.surface_main, Rgba::rgb(0, 0, 0));
assert_eq!(c.text_primary, Rgba::rgb(0xff, 0xff, 0xff));
assert_eq!(c.alpha.len(), ALPHA_COUNT);
}
#[test]
fn light_dark_flag_from_luminance() {
// The 4 P1 themes are all dark.
assert!(!is_light(ThemeId::Dark));
assert!(!is_light(ThemeId::Oled));
assert!(!is_light(ThemeId::TokyoNight));
assert!(!is_light(ThemeId::System));
}
#[test]
fn implemented_list_is_the_four_p1_themes() {
let list = implemented_theme_list();
assert_eq!(list.len(), 4);
let slugs: Vec<&str> = list.iter().map(|e| e.slug).collect();
assert!(slugs.contains(&"dark"));
assert!(slugs.contains(&"oled"));
assert!(slugs.contains(&"tokyo-night"));
assert!(slugs.contains(&"system"));
}
#[test]
fn full_list_has_all_entries() {
assert_eq!(theme_list().len(), ALL.len());
}
}
+251
View File
@@ -0,0 +1,251 @@
//! The theme registry: `ThemeId` -> fully-materialized [`ThemeColors`].
//!
//! P1 materializes only the four existing themes (Dark / OLED / Tokyo Night /
//! System-fallback). Every value for the standard themes is transcribed from
//! `src/app.css` (see `qbz-nix-docs/.../01-tauri-themes-inventory.md`). The new
//! token families (danger/warning/success bg+border+hover, border-strong,
//! focus-ring, the full 24-tier alpha ramp) are DERIVED here so the four P1
//! rows are complete and look unchanged for the already-consumed tokens.
//!
//! P2/P3 extend `palette()` with the remaining standard + redesigned a11y rows.
use crate::color::Rgba;
use crate::colors::{alpha_ramp, ThemeColors};
use crate::id::ThemeId;
/// Legacy translucent edge values the existing 4 Slint themes used directly,
/// reproduced 1:1 so P1 stays pixel-identical:
/// surface-hover = ~6% white (#ffffff10)
/// border-subtle = ~8% white (#ffffff14)
/// border-muted = ~22% white (#ffffff38)
/// card-shadow = rgba(0,0,0,0.4) (#00000066)
const LEGACY_SURFACE_HOVER: Rgba = Rgba::rgba(255, 255, 255, 0x10);
const LEGACY_BORDER_SUBTLE: Rgba = Rgba::rgba(255, 255, 255, 0x14);
const LEGACY_BORDER_MUTED: Rgba = Rgba::rgba(255, 255, 255, 0x38);
const LEGACY_CARD_SHADOW: Rgba = Rgba::rgba(0, 0, 0, 0x66);
/// Resolve a theme id to its concrete color set.
///
/// `System` has no static palette — at runtime the Slint side follows the OS
/// (std-widgets `Palette`) for the tokens it overrides, exactly as before. This
/// returns the Dark set as a safe fallback for any caller that needs a concrete
/// struct for `System` (it is NOT what paints the System theme; that stays the
/// `is-system` path in `theme.slint`).
pub fn palette(id: ThemeId) -> ThemeColors {
match id {
ThemeId::Dark => dark(),
ThemeId::Oled => oled(),
ThemeId::TokyoNight => tokyo_night(),
ThemeId::System => dark(),
// P2/P3: remaining standard + redesigned a11y rows. Until then, fall
// back to Dark so the registry always returns a fully-populated struct.
_ => dark(),
}
}
/// `:root` Dark — the base every other theme inherits omissions from.
/// All hex values cite `src/app.css :root` via the inventory doc.
fn dark() -> ThemeColors {
// Danger / warning solid hues from :root; their bg/border/hover were rgba()
// tints of the hue at 0.1/0.3/0.2. We bake those as straight-alpha overlays
// of the solid hue so they composite identically.
let danger = Rgba::rgb(0xef, 0x44, 0x44); // --danger
let warning = Rgba::rgb(0xfb, 0xbf, 0x24); // --warning
// Success is NEW (no Tauri parity). Use the project green (#3fae6a) and the
// same 0.1/0.3/0.2 tint shape so toasts/banners can stop hardcoding hex.
let success = Rgba::rgb(0x3f, 0xae, 0x6a);
ThemeColors {
surface_main: Rgba::rgb(0x0f, 0x0f, 0x0f), // --bg-primary
surface_card: Rgba::rgb(0x1a, 0x1a, 0x1a), // --bg-secondary
surface_elevated: Rgba::rgb(0x2a, 0x2a, 0x2a), // --bg-tertiary
surface_hover: LEGACY_SURFACE_HOVER,
bg_hover: Rgba::rgb(0x1f, 0x1f, 0x1f), // --bg-hover
text_primary: Rgba::rgb(0xff, 0xff, 0xff), // --text-primary
text_secondary: Rgba::rgb(0xcc, 0xcc, 0xcc), // --text-secondary
text_muted: Rgba::rgb(0x88, 0x88, 0x88), // --text-muted
text_disabled: Rgba::rgb(0x55, 0x55, 0x55), // --text-disabled
accent: Rgba::rgb(0x42, 0x85, 0xf4), // --accent-primary
accent_hover: Rgba::rgb(0x5a, 0x9b, 0xf4), // --accent-hover
accent_pressed: Rgba::rgb(0x32, 0x75, 0xe4), // --accent-active
accent_text: Rgba::rgb(0xff, 0xff, 0xff), // --btn-primary-text
danger,
danger_bg: with_alpha(danger, 0.1),
danger_border: with_alpha(danger, 0.3),
danger_hover: with_alpha(danger, 0.2),
warning,
warning_bg: with_alpha(warning, 0.1),
warning_border: with_alpha(warning, 0.3),
warning_hover: with_alpha(warning, 0.2),
success,
success_bg: with_alpha(success, 0.1),
success_border: with_alpha(success, 0.3),
success_hover: with_alpha(success, 0.2),
border_subtle: LEGACY_BORDER_SUBTLE,
border_muted: LEGACY_BORDER_MUTED,
border_strong: Rgba::rgb(0x3a, 0x3a, 0x3a), // --border-strong
focus_ring: Rgba::rgb(0x42, 0x85, 0xf4), // = accent (no Tauri token; new)
favorite: danger, // the loved-heart uses danger red
card_shadow: LEGACY_CARD_SHADOW,
alpha: alpha_ramp(false), // dark theme -> white-based overlays
}
}
/// OLED Black — inherits everything from Dark except backgrounds + borders.
/// The legacy Slint OLED only overrode the three surfaces; keep that exactly,
/// inherit the rest from `dark()`.
fn oled() -> ThemeColors {
ThemeColors {
surface_main: Rgba::rgb(0x00, 0x00, 0x00), // --bg-primary
surface_card: Rgba::rgb(0x0a, 0x0a, 0x0a), // --bg-secondary
surface_elevated: Rgba::rgb(0x1a, 0x1a, 0x1a), // --bg-tertiary
bg_hover: Rgba::rgb(0x11, 0x11, 0x11), // --bg-hover (oled)
border_strong: Rgba::rgb(0x2a, 0x2a, 0x2a), // --border-strong (oled)
..dark()
}
}
/// Tokyo Night — full recolor. Surfaces/text/accent transcribed from the legacy
/// Slint ternary (which matches `src/app.css [data-theme="tokyo-night"]`).
fn tokyo_night() -> ThemeColors {
let danger = Rgba::rgb(0xdb, 0x4b, 0x4b); // --danger
let warning = Rgba::rgb(0xe0, 0xaf, 0x68); // --warning
let success = Rgba::rgb(0x3f, 0xae, 0x6a);
ThemeColors {
surface_main: Rgba::rgb(0x1a, 0x1b, 0x26), // --bg-primary
surface_card: Rgba::rgb(0x16, 0x16, 0x1e), // --bg-secondary
surface_elevated: Rgba::rgb(0x1c, 0x1d, 0x29), // --bg-tertiary
surface_hover: LEGACY_SURFACE_HOVER,
bg_hover: Rgba::rgb(0x20, 0x23, 0x30), // --bg-hover
text_primary: Rgba::rgb(0xa9, 0xb1, 0xd6), // --text-primary
text_secondary: Rgba::rgb(0x78, 0x7c, 0x99), // --text-secondary
text_muted: Rgba::rgb(0x54, 0x5c, 0x7e), // --text-muted
text_disabled: Rgba::rgb(0x3d, 0x42, 0x5e), // --text-disabled
accent: Rgba::rgb(0x7a, 0xa2, 0xf7), // --accent-primary
accent_hover: Rgba::rgb(0x7d, 0xcf, 0xff), // --accent-hover
accent_pressed: Rgba::rgb(0xbb, 0x9a, 0xf7), // --accent-active
accent_text: Rgba::rgb(0x1a, 0x1b, 0x26), // --btn-primary-text
danger,
danger_bg: with_alpha(danger, 0.1),
danger_border: with_alpha(danger, 0.3),
danger_hover: with_alpha(danger, 0.2),
warning,
warning_bg: with_alpha(warning, 0.1),
warning_border: with_alpha(warning, 0.3),
warning_hover: with_alpha(warning, 0.2),
success,
success_bg: with_alpha(success, 0.1),
success_border: with_alpha(success, 0.3),
success_hover: with_alpha(success, 0.2),
border_subtle: LEGACY_BORDER_SUBTLE,
border_muted: LEGACY_BORDER_MUTED,
border_strong: Rgba::rgb(0x20, 0x23, 0x30), // --border-strong
focus_ring: Rgba::rgb(0x7a, 0xa2, 0xf7), // = accent
favorite: danger,
card_shadow: LEGACY_CARD_SHADOW,
alpha: alpha_ramp(false), // dark theme -> white-based overlays
}
}
/// Straight-alpha overlay of an opaque hue at `frac` opacity (0.0..=1.0).
/// Used to reproduce Tauri's `rgba(hue, frac)` danger/warning/success tints.
const fn with_alpha(c: Rgba, frac: f32) -> Rgba {
let a = (frac * 255.0 + 0.5) as u8;
Rgba::rgba(c.r, c.g, c.b, a)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::colors::ALPHA_COUNT;
#[test]
fn p1_rows_are_fully_populated() {
for id in [ThemeId::Dark, ThemeId::Oled, ThemeId::TokyoNight, ThemeId::System] {
let c = palette(id);
// Spot-check a few fields are non-degenerate / the ramp is full.
assert_eq!(c.alpha.len(), ALPHA_COUNT);
assert_ne!(c.surface_main, Rgba::rgba(0, 0, 0, 0));
assert_ne!(c.text_primary, Rgba::rgba(0, 0, 0, 0));
assert_ne!(c.accent, Rgba::rgba(0, 0, 0, 0));
// every alpha tier carries some opacity
assert!(c.alpha.iter().all(|a| a.a > 0));
}
}
#[test]
fn dark_matches_root_css() {
let c = palette(ThemeId::Dark);
assert_eq!(c.surface_main, Rgba::rgb(0x0f, 0x0f, 0x0f));
assert_eq!(c.surface_card, Rgba::rgb(0x1a, 0x1a, 0x1a));
assert_eq!(c.surface_elevated, Rgba::rgb(0x2a, 0x2a, 0x2a));
assert_eq!(c.text_primary, Rgba::rgb(0xff, 0xff, 0xff));
assert_eq!(c.accent, Rgba::rgb(0x42, 0x85, 0xf4));
assert_eq!(c.border_strong, Rgba::rgb(0x3a, 0x3a, 0x3a));
assert_eq!(c.favorite, c.danger);
}
#[test]
fn oled_overrides_only_surfaces_and_borders() {
let d = palette(ThemeId::Dark);
let o = palette(ThemeId::Oled);
assert_eq!(o.surface_main, Rgba::rgb(0, 0, 0));
assert_eq!(o.surface_card, Rgba::rgb(0x0a, 0x0a, 0x0a));
assert_eq!(o.surface_elevated, Rgba::rgb(0x1a, 0x1a, 0x1a));
assert_eq!(o.bg_hover, Rgba::rgb(0x11, 0x11, 0x11));
assert_eq!(o.border_strong, Rgba::rgb(0x2a, 0x2a, 0x2a));
// inherited from Dark:
assert_eq!(o.accent, d.accent);
assert_eq!(o.text_primary, d.text_primary);
assert_eq!(o.danger, d.danger);
}
#[test]
fn tokyo_legacy_values_preserved() {
let c = palette(ThemeId::TokyoNight);
assert_eq!(c.surface_main, Rgba::rgb(0x1a, 0x1b, 0x26));
assert_eq!(c.surface_card, Rgba::rgb(0x16, 0x16, 0x1e));
assert_eq!(c.surface_elevated, Rgba::rgb(0x1c, 0x1d, 0x29));
assert_eq!(c.text_primary, Rgba::rgb(0xa9, 0xb1, 0xd6));
assert_eq!(c.accent, Rgba::rgb(0x7a, 0xa2, 0xf7));
assert_eq!(c.accent_text, Rgba::rgb(0x1a, 0x1b, 0x26));
}
#[test]
fn legacy_alpha_aliases_unchanged() {
// The exact translucent values the old Slint Theme exposed.
for id in [ThemeId::Dark, ThemeId::Oled, ThemeId::TokyoNight] {
let c = palette(id);
assert_eq!(c.surface_hover, Rgba::rgba(255, 255, 255, 0x10));
assert_eq!(c.border_subtle, Rgba::rgba(255, 255, 255, 0x14));
assert_eq!(c.border_muted, Rgba::rgba(255, 255, 255, 0x38));
assert_eq!(c.card_shadow, Rgba::rgba(0, 0, 0, 0x66));
// legacy fixed-white alpha steps consumed by the miniplayer:
assert_eq!(c.alpha_pct(8), Rgba::rgba(255, 255, 255, 0x14));
assert_eq!(c.alpha_pct(10), Rgba::rgba(255, 255, 255, 0x1a));
assert_eq!(c.alpha_pct(12), Rgba::rgba(255, 255, 255, 0x1f));
assert_eq!(c.alpha_pct(18), Rgba::rgba(255, 255, 255, 0x2e));
assert_eq!(c.alpha_pct(55), Rgba::rgba(255, 255, 255, 0x8c));
assert_eq!(c.alpha_pct(65), Rgba::rgba(255, 255, 255, 0xa6));
assert_eq!(c.alpha_pct(70), Rgba::rgba(255, 255, 255, 0xb3));
assert_eq!(c.alpha_pct(75), Rgba::rgba(255, 255, 255, 0xbf));
}
}
}