From c66ae09aac4b9fccb4c8ecd6c98637ffa5364f86 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 22 Nov 2026 07:03:55 +0700 Subject: [PATCH] theme, ui-contract: RootEnv::accent derives the theme's accent colours and the text on them from the user's seed --- crates/theme/src/tests.rs | 30 ++++++++++++ crates/theme/src/theme.rs | 46 ++++++++++++++++++- crates/theme/src/values.rs | 13 ++++++ crates/ui-contract/src/runtime/env/root.rs | 12 +++-- crates/ui-contract/src/runtime/env/tokens.rs | 22 ++++++--- .../tests/it/style/library_theme.rs | 20 ++++++++ 6 files changed, 131 insertions(+), 12 deletions(-) diff --git a/crates/theme/src/tests.rs b/crates/theme/src/tests.rs index fb681c26a..da03e12f8 100644 --- a/crates/theme/src/tests.rs +++ b/crates/theme/src/tests.rs @@ -17,3 +17,33 @@ fn contrast_moves_keep_greys_neutral() { } } } + +/// A user's accent over each built-in theme, in each mode and contrast and for each app the theme overrides, gives +/// the accent fill its own colour even where the theme fixes the fill, and fails no contrast pair the theme alone +/// passes. +#[test] +fn an_accent_over_a_theme_takes_its_fill_and_fails_no_pair_the_theme_passes() { + use std::collections::BTreeSet; + let failing = |resolved: &Resolved| resolved.warnings.iter().map(|check| (check.fg, check.bg)).collect::>(); + let seeds = [Rgba::rgb(0xff, 0xd8, 0x00), Rgba::rgb(0x12, 0x18, 0x60), Rgba::rgb(0xd0, 0x20, 0x30)]; + for theme in builtins() { + for app in std::iter::once(None).chain(theme.apps.keys().map(Some)) { + for (mode, contrast) in + [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Light, Contrast::High), (Mode::Dark, Contrast::High)] + { + let appearance = Appearance { mode, contrast, size: Size::default(), text_size: TextSize::default(), reduced_motion: false }; + let own = failing(&resolve(theme, appearance, app)); + let fills: Vec = seeds + .iter() + .map(|&seed| { + let accented = resolve(&theme.with_accent(seed), appearance, app); + let new: Vec<_> = failing(&accented).difference(&own).copied().collect(); + assert!(new.is_empty(), "{} {app:?} {mode:?} {contrast:?} with accent {seed:?} fails {new:?}", theme.id.as_str()); + accented.tokens.color(ColorToken::AccentSolid) + }) + .collect(); + assert!(fills[0] != fills[1], "{} {app:?} {mode:?} {contrast:?}: the fill follows the accent: {fills:?}", theme.id.as_str()); + } + } + } +} diff --git a/crates/theme/src/theme.rs b/crates/theme/src/theme.rs index 021b2648b..140d7e3ce 100644 --- a/crates/theme/src/theme.rs +++ b/crates/theme/src/theme.rs @@ -1,6 +1,6 @@ //! What a theme supplies (seeds, pins, optional shape) and what the user chooses (appearance). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use super::color::Rgba; use super::ramp::Mode; @@ -66,6 +66,50 @@ impl ThemeDef { }, } } + + /// This theme with `seed` as its accent in both modes: a user's accent over the theme they picked. The accent + /// colours (the tokens the accent ramp gives, and the ones derived from them) and the text of every contrast pair + /// drawn on an accent colour drop their pins and references in every layer, the high-contrast and per-app ones + /// included, so they derive from the seed and the contrast pass fits them as it fits an unpinned theme. A token + /// the theme refers to an accent colour keeps its reference, and so follows the seed. + #[must_use] + pub fn with_accent(&self, seed: Rgba) -> ThemeDef { + let mut theme = self.clone(); + theme.seeds.accent = seed; + theme.mode_seeds.light.accent = None; + theme.mode_seeds.dark.accent = None; + for mode in [Mode::Light, Mode::Dark] { + let derived = self.accent_derived(mode); + let apps = theme.apps.values_mut().flat_map(|app| [&mut app.pins, &mut app.high_contrast]); + for layer in [&mut theme.pins, &mut theme.high_contrast].into_iter().chain(apps) { + let pins = match mode { + Mode::Light => &mut layer.light, + Mode::Dark => &mut layer.dark, + }; + pins.colors.retain(|token, _| !derived.contains(token)); + pins.refs.retain(|token, _| !derived.contains(token)); + } + } + theme + } + + /// The tokens [`with_accent`](Self::with_accent) derives in `mode`: the ones whose default follows the accent ramp, + /// and the text of each contrast pair drawn on an accent colour, counting the tokens a layer refers to one. + fn accent_derived(&self, mode: Mode) -> BTreeSet { + use crate::values::{Bg, RULES, follows_accent}; + let own: BTreeSet = ColorToken::ALL.iter().copied().filter(|&token| follows_accent(token, mode)).collect(); + let layers = [&self.pins, &self.high_contrast].into_iter().chain(self.apps.values().flat_map(|app| [&app.pins, &app.high_contrast])); + let refs: Vec<(ColorToken, ColorToken)> = layers.flat_map(|layer| layer.get(mode).refs.iter().map(|(&token, &to)| (token, to))).collect(); + let mut shown = own.clone(); + while let Some(token) = refs.iter().find(|(token, to)| shown.contains(to) && !shown.contains(token)).map(|&(token, _)| token) { + shown.insert(token); + } + let texts = RULES + .iter() + .filter(|rule| rule.bgs.iter().any(|bg| matches!(bg, Bg::Token(fill) if shown.contains(fill)))) + .flat_map(|rule| rule.fgs.iter().copied()); + own.iter().copied().chain(texts).collect() + } } /// Seed colours. Each one becomes a 12-step ramp per mode. diff --git a/crates/theme/src/values.rs b/crates/theme/src/values.rs index 9329dac96..6f380a73c 100644 --- a/crates/theme/src/values.rs +++ b/crates/theme/src/values.rs @@ -160,6 +160,19 @@ pub(super) fn panel_step(mode: Mode) -> usize { } } +/// Whether `token`'s default in `mode` comes from the accent ramp, directly or through the tokens it derives from (the +/// text on an accent fill, a faded accent). +pub(super) fn follows_accent(token: ColorToken, mode: Mode) -> bool { + match source(token, mode) { + ColorSource::Accent(_) | ColorSource::AccentMix { .. } => true, + ColorSource::Same(other) | ColorSource::Faded(other, _) | ColorSource::SolidFrom(other) | ColorSource::ShiftedFrom { base: other, .. } => { + follows_accent(other, mode) + } + ColorSource::OnSolid(solids) => solids.iter().any(|&solid| follows_accent(solid, mode)), + _ => false, + } +} + /// The default source of `token` in `mode`. pub(super) fn source(token: ColorToken, mode: Mode) -> ColorSource { use ColorSource::{ diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index 02b2c9577..cb25830b0 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -51,6 +51,8 @@ pub struct RootEnv { /// The definition of `theme` when it is a library theme: no built-in has its id, so the tokens resolve from this. /// Set only with `theme`, by `library_theme`; `theme(id)` clears it. pub(super) theme_def: Option>, + /// The user's accent over the theme (`ThemeDef::with_accent`); `None` keeps the theme's own. + pub(super) accent: Option, /// Root app values. pub values: AppValues, /// Today's date in the host's time zone; the runtime reads no wall clock. @@ -80,6 +82,7 @@ impl Default for RootEnv { tooltips: true, theme: ThemeId::suite_default(), theme_def: None, + accent: None, values: AppValues::default(), today: None, wheel: WheelSpeed::default(), @@ -154,10 +157,11 @@ impl RootEnv { } /// Overrides `seeds.accent` of whichever theme resolves, built-in or library, in both modes; the accent ramp derives - /// from the seed. `None` keeps the theme's own. - pub fn accent(self, seed: Option) -> Self { - let _ = seed; - todo!("sh.K20") + /// from the seed, and the theme's fixed accent colours give way to it ([`ThemeDef::with_accent`]). `None` keeps the + /// theme's own. + pub fn accent(mut self, seed: Option) -> Self { + self.accent = seed; + self } /// What the choices resolve to on `ctx`'s pass: the one place `System` is replaced by the OS's answer, as diff --git a/crates/ui-contract/src/runtime/env/tokens.rs b/crates/ui-contract/src/runtime/env/tokens.rs index e8c82f414..45a2a51d5 100644 --- a/crates/ui-contract/src/runtime/env/tokens.rs +++ b/crates/ui-contract/src/runtime/env/tokens.rs @@ -4,7 +4,7 @@ use super::root::{ResolvedRoot, RootEnv}; use crate::runtime::egui::pass; use crate::runtime::pass_state; use crate::style::UiTokens; -use craft_theme::{AppId, AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins}; +use craft_theme::{AppId, AppSizes, Appearance, Contrast, Mode, Rgba, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins}; use egui::Context; use std::sync::Arc; @@ -105,12 +105,15 @@ fn resolve_inputs(inputs: &TokenInputs) -> Arc { let appearance = Appearance { mode: inputs.mode, contrast: inputs.contrast, size: inputs.density, text_size: inputs.text_size, reduced_motion: false }; let themes = builtins(); - if let Some(def) = &inputs.theme_def { - return Arc::new(UiTokens::of_theme(def, appearance, inputs.app.as_ref(), &inputs.sizes)); - } - let theme: &ThemeDef = - [inputs.theme.as_str(), SUITE_DEFAULT].into_iter().find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)).unwrap_or(&themes[0]); - Arc::new(UiTokens::of_theme(theme, appearance, inputs.app.as_ref(), &inputs.sizes)) + let theme: &ThemeDef = match &inputs.theme_def { + Some(def) => def, + None => [inputs.theme.as_str(), SUITE_DEFAULT] + .into_iter() + .find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)) + .unwrap_or(&themes[0]), + }; + let accented = inputs.accent.map(|seed| theme.with_accent(seed)); + Arc::new(UiTokens::of_theme(accented.as_ref().unwrap_or(theme), appearance, inputs.app.as_ref(), &inputs.sizes)) } /// What the resolved root tokens depend on. The sizes are compared by identity, as `set_input` does. @@ -119,6 +122,8 @@ pub(crate) struct TokenInputs { pub(super) sizes: Arc, pub(super) theme: ThemeId, pub(super) theme_def: Option>, + /// The user's accent over the theme. + pub(super) accent: Option, pub(super) mode: Mode, pub(super) contrast: Contrast, pub(super) density: Size, @@ -134,6 +139,7 @@ impl TokenInputs { sizes: root.sizes.clone(), theme: root.theme.clone(), theme_def: root.theme_def.clone(), + accent: root.accent, mode: resolved.mode, contrast: resolved.contrast, density: root.density, @@ -148,6 +154,7 @@ impl TokenInputs { (Arc::ptr_eq(&self.sizes, &other.sizes) || self.sizes == other.sizes) && self.theme == other.theme && same_def(&self.theme_def, &other.theme_def) + && self.accent == other.accent && self.mode == other.mode && self.contrast == other.contrast && self.density == other.density @@ -159,6 +166,7 @@ impl TokenInputs { Arc::ptr_eq(&self.sizes, &other.sizes) && self.theme == other.theme && same_def(&self.theme_def, &other.theme_def) + && self.accent == other.accent && self.mode == other.mode && self.contrast == other.contrast && self.density == other.density diff --git a/crates/ui-contract/tests/it/style/library_theme.rs b/crates/ui-contract/tests/it/style/library_theme.rs index 64fe07855..cd04a4e82 100644 --- a/crates/ui-contract/tests/it/style/library_theme.rs +++ b/crates/ui-contract/tests/it/style/library_theme.rs @@ -28,3 +28,23 @@ fn a_library_theme_resolves_from_its_definition_and_an_unknown_id_from_the_defau let renamed = panel(dark(RootEnv::new().library_theme(Arc::new(mine.clone())).theme(mine.id.clone()))); assert_eq!(renamed, unknown, "naming a theme by id drops the earlier definition"); } + +/// A root accent replaces the accent fill of the theme that resolves, the built-in default and a library theme alike; +/// without one the theme keeps its own. +#[trial] +fn a_root_accent_replaces_the_accent_fill_of_the_theme() { + let fill = |root: RootEnv| { + let mut frames = Frames::new(); + frames.root(root); + let mut seen = None; + frames.frame(Vec::new(), |ui| seen = Some(Env::of(ui).tokens.tokens().color(ColorToken::AccentSolid))); + seen.expect("a pass ran") + }; + let (yellow, navy) = (Some(craft_theme::Rgba::rgb(0xff, 0xd8, 0x00)), Some(craft_theme::Rgba::rgb(0x12, 0x18, 0x60))); + let library = Arc::new(builtins().iter().find(|theme| theme.id.as_str() == "craft.studio").expect("a built-in").clone()); + for root in [RootEnv::new(), RootEnv::new().library_theme(library)] { + let own = fill(root.clone()); + assert_eq!(fill(root.clone().accent(None)), own, "no accent keeps the theme's"); + assert_ne!(fill(root.clone().accent(yellow)), fill(root.accent(navy)), "the fill follows the accent"); + } +}