Nacre/src/theme.rs
astar76 7b7e0cec7f S015: Material You foundation: M3 schemes, Outfit, icons, springs, widgets, gallery
Fixes R1-01 (icon glyphs) and R1-02 (clock contrast).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:36:53 -06:00

684 lines
27 KiB
Rust

//! The design tokens (docs/DESIGN.md "UI system"): Material You colour roles from a seed colour, shape, space, type
//! and motion. Everything the interface draws takes its colours, radii, sizes and springs from here.
use egui::{Color32, Context, CornerRadius, FontFamily, FontId, Id, Visuals};
use material_colors::color::Argb;
use material_colors::dynamic_color::{DynamicScheme, Variant};
use material_colors::hct::Hct;
use material_colors::palette::TonalPalette;
use crate::store::settings::{ColourFallback, ColourSource, Motion, Roundness, Settings, ThemeMode};
/// Palette presets shown in Appearance (the swatches in the screenshot).
pub const PRESETS: &[&str] = &["#6750A4", "#B3261E", "#7D5260", "#006A6A", "#386A20", "#984061", "#0061A4", "#8B5000", "#5B5F97", "#006E1C", "#9C4146", "#625B71"];
/// Scheme styles: (key, label).
pub const VARIANTS: &[(&str, &str)] = &[("tonal_spot", "Tonal spot"), ("vibrant", "Vibrant"), ("expressive", "Expressive"), ("neutral", "Neutral"), ("monochrome", "Monochrome"), ("fidelity", "Fidelity"), ("content", "Content")];
pub fn parse_hex(text: &str) -> Option<Color32> {
let t = text.trim().trim_start_matches('#');
let v = u32::from_str_radix(t, 16).ok()?;
match t.len() {
6 => Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8)),
3 => {
let r = ((v >> 8) & 0xF) as u8 * 17;
let g = ((v >> 4) & 0xF) as u8 * 17;
let b = (v & 0xF) as u8 * 17;
Some(Color32::from_rgb(r, g, b))
},
_ => None,
}
}
/// "rgb(1, 2, 3)", "rgba(...)" or "#abc" from CSS.
pub fn parse_css_color(text: &str) -> Option<Color32> {
let t = text.trim();
if t.starts_with('#') {
return parse_hex(t);
}
let inner = t.strip_prefix("rgba(").or_else(|| t.strip_prefix("rgb("))?.trim_end_matches(')');
let nums: Vec<f32> = inner.split([',', ' ', '/']).filter(|s| !s.is_empty()).filter_map(|s| s.trim().parse().ok()).collect();
if nums.len() < 3 || nums.get(3).is_some_and(|a| *a < 0.5) {
return None;
}
Some(Color32::from_rgb(nums[0] as u8, nums[1] as u8, nums[2] as u8))
}
pub fn to_hex(c: Color32) -> String {
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
}
/// The system accent colour: KDE's kdeglobals, else GNOME's accent-color setting.
pub fn system_accent() -> Option<Color32> {
#[cfg(unix)]
{
if let Some(path) = dirs::config_dir().map(|d| d.join("kdeglobals"))
&& let Ok(text) = std::fs::read_to_string(path)
{
let mut in_general = false;
for line in text.lines() {
let line = line.trim();
if line.starts_with('[') {
in_general = line == "[General]";
} else if in_general && let Some(v) = line.strip_prefix("AccentColor=") {
let n: Vec<u8> = v.split(',').filter_map(|p| p.trim().parse().ok()).collect();
if n.len() >= 3 {
return Some(Color32::from_rgb(n[0], n[1], n[2]));
}
}
}
}
if let Ok(out) = std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.interface", "accent-color"]).output() {
let name = String::from_utf8_lossy(&out.stdout).trim().trim_matches('\'').to_owned();
let c = match name.as_str() {
"blue" => "#3584E4",
"teal" => "#2190A4",
"green" => "#3A944A",
"yellow" => "#C88800",
"orange" => "#ED5B00",
"red" => "#E62D42",
"pink" => "#D56199",
"purple" => "#9141AC",
"slate" => "#6F8396",
_ => "",
};
if !c.is_empty() {
return parse_hex(c);
}
}
None
}
#[cfg(not(unix))]
{
None
}
}
/// Whether the system prefers dark (used for "System" mode before winit reports a theme).
pub fn system_dark(winit_theme: Option<winit::window::Theme>) -> bool {
match winit_theme {
Some(winit::window::Theme::Dark) => true,
Some(winit::window::Theme::Light) => false,
None => {
#[cfg(unix)]
{
std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.interface", "color-scheme"]).output().map(|o| String::from_utf8_lossy(&o.stdout).contains("dark")).unwrap_or(true)
}
#[cfg(not(unix))]
{
true
}
},
}
}
// ---------------------------------------------------------------------------------------------------------------
// Colour
/// The colour roles of a Material 3 scheme. The first block holds the names the older UI code uses; they alias M3
/// roles (see `Palette::new`). New code uses the M3 names.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Palette {
pub dark: bool,
/// = primary.
pub accent: Color32,
/// = on_primary.
pub on_accent: Color32,
/// = secondary_container.
pub accent_soft: Color32,
/// = surface.
pub surface: Color32,
/// = surface_container_high.
pub surface_high: Color32,
/// = surface_container_lowest.
pub surface_low: Color32,
/// = on_surface.
pub text: Color32,
/// = on_surface_variant.
pub text_weak: Color32,
pub outline: Color32,
pub error: Color32,
/// Not an M3 role: an amber from a fixed hue, at the tones primary uses.
pub warning: Color32,
/// Not an M3 role: a green from a fixed hue, at the tones primary uses.
pub success: Color32,
pub primary: Color32,
pub on_primary: Color32,
pub primary_container: Color32,
pub on_primary_container: Color32,
pub inverse_primary: Color32,
pub secondary: Color32,
pub on_secondary: Color32,
pub secondary_container: Color32,
pub on_secondary_container: Color32,
pub tertiary: Color32,
pub on_tertiary: Color32,
pub tertiary_container: Color32,
pub on_tertiary_container: Color32,
pub on_error: Color32,
pub error_container: Color32,
pub on_error_container: Color32,
pub surface_dim: Color32,
pub surface_bright: Color32,
pub surface_container_lowest: Color32,
pub surface_container_low: Color32,
pub surface_container: Color32,
pub surface_container_high: Color32,
pub surface_container_highest: Color32,
pub on_surface: Color32,
pub on_surface_variant: Color32,
pub outline_variant: Color32,
pub inverse_surface: Color32,
pub inverse_on_surface: Color32,
pub scrim: Color32,
pub shadow: Color32,
}
fn argb(c: Color32) -> Argb {
Argb::new(255, c.r(), c.g(), c.b())
}
fn color(a: Argb) -> Color32 {
Color32::from_rgb(a.red, a.green, a.blue)
}
impl Palette {
/// The scheme for `seed`: `variant` is one of `VARIANTS`' keys, `contrast` runs from -1 (less) to 1 (more).
pub fn new(seed: Color32, dark: bool, variant: &str, contrast: f32) -> Palette {
let variant = match variant {
"vibrant" => Variant::Vibrant,
"expressive" => Variant::Expressive,
"neutral" => Variant::Neutral,
"monochrome" => Variant::Monochrome,
"fidelity" => Variant::Fidelity,
"content" => Variant::Content,
_ => Variant::TonalSpot,
};
let s = DynamicScheme::by_variant(argb(seed), &variant, dark, Some(f64::from(contrast.clamp(-1.0, 1.0))));
// Status colours keep their own hue and follow primary's tones, so they sit with the scheme.
let tone = if dark { 80 } else { 40 };
let status = |hue: f64, chroma: f64| color(TonalPalette::of(hue, chroma).tone(tone));
Palette {
dark,
accent: color(s.primary()),
on_accent: color(s.on_primary()),
accent_soft: color(s.secondary_container()),
surface: color(s.surface()),
surface_high: color(s.surface_container_high()),
surface_low: color(s.surface_container_lowest()),
text: color(s.on_surface()),
text_weak: color(s.on_surface_variant()),
outline: color(s.outline()),
error: color(s.error()),
warning: status(75.0, 60.0),
success: status(140.0, 48.0),
primary: color(s.primary()),
on_primary: color(s.on_primary()),
primary_container: color(s.primary_container()),
on_primary_container: color(s.on_primary_container()),
inverse_primary: color(s.inverse_primary()),
secondary: color(s.secondary()),
on_secondary: color(s.on_secondary()),
secondary_container: color(s.secondary_container()),
on_secondary_container: color(s.on_secondary_container()),
tertiary: color(s.tertiary()),
on_tertiary: color(s.on_tertiary()),
tertiary_container: color(s.tertiary_container()),
on_tertiary_container: color(s.on_tertiary_container()),
on_error: color(s.on_error()),
error_container: color(s.error_container()),
on_error_container: color(s.on_error_container()),
surface_dim: color(s.surface_dim()),
surface_bright: color(s.surface_bright()),
surface_container_lowest: color(s.surface_container_lowest()),
surface_container_low: color(s.surface_container_low()),
surface_container: color(s.surface_container()),
surface_container_high: color(s.surface_container_high()),
surface_container_highest: color(s.surface_container_highest()),
on_surface: color(s.on_surface()),
on_surface_variant: color(s.on_surface_variant()),
outline_variant: color(s.outline_variant()),
inverse_surface: color(s.inverse_surface()),
inverse_on_surface: color(s.inverse_on_surface()),
scrim: color(s.scrim()),
shadow: color(s.shadow()),
}
}
}
/// `over` laid on `base` at `amount` (0..1): state layers (hover, press) and tints, always opaque.
pub fn layer(base: Color32, over: Color32, amount: f32) -> Color32 {
let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount.clamp(0.0, 1.0)).round() as u8;
Color32::from_rgb(mix(base.r(), over.r()), mix(base.g(), over.g()), mix(base.b(), over.b()))
}
/// State layer opacities (M3): the content colour laid over the container.
pub const HOVER: f32 = 0.08;
pub const FOCUS: f32 = 0.10;
pub const PRESS: f32 = 0.10;
pub const DRAG: f32 = 0.16;
/// Disabled controls: content and container opacity.
pub const DISABLED_CONTENT: f32 = 0.38;
pub const DISABLED_CONTAINER: f32 = 0.12;
/// Seed colour from the settings; `site` is the current page's colour when the source is "Website". Greys and
/// near-black or near-white site colours make poor seeds, so they fall back.
pub fn seed(settings: &Settings, site: Option<Color32>, system: Option<Color32>) -> Color32 {
let preset = parse_hex(&settings.theme.preset).unwrap_or(Color32::from_rgb(0x67, 0x50, 0xA4));
let fallback = || match settings.theme.fallback {
ColourFallback::System => system.unwrap_or(preset),
ColourFallback::Palette => preset,
};
match settings.theme.source {
ColourSource::Website => site.filter(|c| usable_seed(*c)).unwrap_or_else(fallback),
ColourSource::System => system.unwrap_or(preset),
ColourSource::Palette => preset,
ColourSource::Custom => parse_hex(&settings.theme.custom).unwrap_or(preset),
}
}
fn usable_seed(c: Color32) -> bool {
let hct = Hct::new(argb(c));
hct.get_chroma() >= 12.0 && (8.0..=95.0).contains(&hct.get_tone())
}
pub fn is_dark(settings: &Settings, system_is_dark: bool) -> bool {
match settings.theme.mode {
ThemeMode::System => system_is_dark,
ThemeMode::Light => false,
ThemeMode::Dark => true,
}
}
// ---------------------------------------------------------------------------------------------------------------
// Shape and space
/// Corner radii (M3 shape scale) at the Default roundness. Read them through `radius`, which applies the
/// Roundness setting. `FULL` makes pills and circles.
pub const XS: f32 = 4.0;
pub const S: f32 = 8.0;
pub const M: f32 = 12.0;
pub const L: f32 = 16.0;
pub const XL: f32 = 28.0;
pub const FULL: f32 = 1000.0;
/// Spacing on a 4 px grid.
pub const GAP_XS: f32 = 4.0;
pub const GAP_S: f32 = 8.0;
pub const GAP_M: f32 = 12.0;
pub const GAP_L: f32 = 16.0;
pub const GAP_XL: f32 = 24.0;
/// Control heights: compact chrome controls, standard buttons and fields, list rows.
pub const CONTROL_SMALL: f32 = 32.0;
pub const CONTROL: f32 = 40.0;
pub const ROW: f32 = 56.0;
fn roundness_scale(settings: &Settings) -> f32 {
match settings.ui.roundness {
Roundness::Subtle => 0.5,
Roundness::Normal => 1.0,
Roundness::Round => 1.4,
}
}
/// A radius token with the Roundness setting applied. `FULL` stays full.
pub fn radius(ctx: &Context, token: f32) -> f32 {
if token >= FULL { FULL } else { token * tokens(ctx).roundness }
}
/// egui's corner type, which holds whole points up to 255.
pub fn corner_radius(r: f32) -> CornerRadius {
CornerRadius::same(r.round().clamp(0.0, 255.0) as u8)
}
/// Corner radius of small controls (the egui default widgets), from the Roundness setting.
pub fn corner(settings: &Settings) -> u8 {
(S * roundness_scale(settings)).round() as u8
}
// ---------------------------------------------------------------------------------------------------------------
// Type
/// Type scale. Weight and colour carry hierarchy before size does.
pub const SMALL: f32 = 12.0;
pub const BODY: f32 = 14.0;
pub const TITLE: f32 = 18.0;
pub const HEADLINE: f32 = 24.0;
pub const DISPLAY: f32 = 64.0;
/// Outfit weights registered as font families (`ui::fonts`). Regular is egui's Proportional family.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Weight {
Thin,
Light,
Regular,
Medium,
SemiBold,
}
impl Weight {
pub const ALL: [Weight; 5] = [Weight::Thin, Weight::Light, Weight::Regular, Weight::Medium, Weight::SemiBold];
pub fn wght(self) -> f32 {
match self {
Weight::Thin => 200.0,
Weight::Light => 300.0,
Weight::Regular => 400.0,
Weight::Medium => 500.0,
Weight::SemiBold => 600.0,
}
}
pub fn family(self) -> FontFamily {
match self {
Weight::Regular => FontFamily::Proportional,
Weight::Thin => FontFamily::Name("outfit-thin".into()),
Weight::Light => FontFamily::Name("outfit-light".into()),
Weight::Medium => FontFamily::Name("outfit-medium".into()),
Weight::SemiBold => FontFamily::Name("outfit-semibold".into()),
}
}
}
pub fn font(size: f32, weight: Weight) -> FontId {
FontId::new(size, weight.family())
}
/// Material Symbols families: outlined (FILL 0) and filled (FILL 1, for selected states).
pub fn icon_font(size: f32, filled: bool) -> FontId {
FontId::new(size, FontFamily::Name(if filled { "icons-filled" } else { "icons" }.into()))
}
/// Icon sizes: in chrome and lists, and large (empty states, cards).
pub const ICON: f32 = 20.0;
pub const ICON_LARGE: f32 = 32.0;
// ---------------------------------------------------------------------------------------------------------------
// Motion
/// A spring: `stiffness` and `damping` ratio (1 = critically damped, no overshoot). Presets from M3 Expressive.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub stiffness: f32,
pub damping: f32,
}
/// Press and small controls.
pub const FAST: Spring = Spring { stiffness: 1400.0, damping: 0.62 };
/// Panels and movement.
pub const DEFAULT: Spring = Spring { stiffness: 700.0, damping: 0.68 };
/// Big transitions.
pub const SLOW: Spring = Spring { stiffness: 300.0, damping: 0.74 };
/// Colour, opacity and tints: never overshoots.
pub const EFFECT: Spring = Spring { stiffness: 900.0, damping: 1.0 };
/// Motion setting as a time factor: 1 = Normal, 0 = Off.
fn motion_scale(settings: &Settings) -> f32 {
match settings.ui.motion {
Motion::Off => 0.0,
Motion::Fast => 0.6,
Motion::Normal => 1.0,
Motion::Slow => 1.8,
}
}
/// Seconds for egui's own animations (collapsing headers, scroll), 0 = off.
pub fn animation_time(settings: &Settings) -> f32 {
0.1 * motion_scale(settings)
}
#[derive(Clone, Copy, Debug)]
struct SpringState {
value: f32,
velocity: f32,
frame: u64,
}
/// A spring's current value, for tests.
#[cfg(test)]
pub fn spring_value(ctx: &Context, id: Id) -> Option<f32> {
ctx.data(|d| d.get_temp::<SpringState>(id)).map(|s| s.value)
}
/// Animates towards `target` with `spring` and returns this frame's value. The first call for an `id` starts at
/// the target. Retargeting mid-flight keeps the velocity, so motion never snaps. Repaints only while moving; with
/// Motion off it returns the target.
pub fn spring(ctx: &Context, id: Id, target: f32, spring: Spring) -> f32 {
let scale = tokens(ctx).motion;
let frame = ctx.cumulative_frame_nr();
let dt = ctx.input(|i| i.stable_dt).min(0.05);
let (value, moving) = ctx.data_mut(|d| {
let s = d.get_temp_mut_or_insert_with(id, || SpringState { value: target, velocity: 0.0, frame });
if scale <= 0.0 {
*s = SpringState { value: target, velocity: 0.0, frame };
} else if s.frame != frame {
s.frame = frame;
spring_step(s, target, spring, scale, dt);
}
(s.value, s.value != target)
});
if moving {
ctx.request_repaint();
}
value
}
/// A 0..1 value for an on/off state with the `EFFECT` spring: hover and selection tints, fades.
pub fn effect(ctx: &Context, id: Id, on: bool) -> f32 {
spring(ctx, id, if on { 1.0 } else { 0.0 }, EFFECT).clamp(0.0, 1.0)
}
/// Semi-implicit Euler in steps of at most 1/240 s. `scale` stretches time: the spring's stiffness drops with its
/// square, so Slow takes `scale` times as long with the same shape.
fn spring_step(s: &mut SpringState, target: f32, spring: Spring, scale: f32, dt: f32) {
let k = spring.stiffness / (scale * scale);
let c = 2.0 * spring.damping * k.sqrt();
let steps = (dt * 240.0).ceil().max(1.0);
let h = dt / steps;
for _ in 0..steps as u32 {
let a = -k * (s.value - target) - c * s.velocity;
s.velocity += a * h;
s.value += s.velocity * h;
}
if (s.value - target).abs() < 1e-3 && s.velocity.abs() < 1e-2 {
s.value = target;
s.velocity = 0.0;
}
}
// ---------------------------------------------------------------------------------------------------------------
// Applying the tokens
/// The tokens a window draws with, kept in its egui context so widgets can reach them from any `Ui`.
#[derive(Clone, Copy, Debug)]
pub struct Tokens {
pub palette: Palette,
/// Roundness setting as a factor on the radius tokens.
pub roundness: f32,
/// Motion setting as a time factor (0 = off).
pub motion: f32,
}
pub fn tokens(ctx: &Context) -> Tokens {
ctx.data(|d| d.get_temp::<Tokens>(Id::NULL)).unwrap_or_else(|| Tokens { palette: Palette::new(Color32::from_rgb(0x67, 0x50, 0xA4), true, "tonal_spot", 0.0), roundness: 1.0, motion: 1.0 })
}
/// Shortcut for the palette in widgets.
pub fn palette(ctx: &Context) -> Palette {
tokens(ctx).palette
}
/// Styles a window's egui context: tokens, visuals, text styles and spacing.
pub fn apply(ctx: &Context, palette: &Palette, settings: &Settings) {
ctx.data_mut(|d| d.insert_temp(Id::NULL, Tokens { palette: *palette, roundness: roundness_scale(settings), motion: motion_scale(settings) }));
// Pin egui's theme to ours so a system theme change can't swap in egui's default style.
ctx.set_theme(if palette.dark { egui::Theme::Dark } else { egui::Theme::Light });
ctx.set_visuals(visuals(palette, corner(settings)));
let time = animation_time(settings);
ctx.all_styles_mut(|style| {
use egui::TextStyle;
style.animation_time = time;
style.text_styles = [
(TextStyle::Small, FontId::proportional(SMALL)),
(TextStyle::Body, FontId::proportional(BODY)),
(TextStyle::Button, FontId::proportional(BODY)),
(TextStyle::Heading, font(HEADLINE, Weight::Medium)),
(TextStyle::Monospace, FontId::monospace(13.0)),
]
.into();
style.spacing.item_spacing = egui::vec2(GAP_S, 6.0);
style.spacing.button_padding = egui::vec2(GAP_M, GAP_XS);
style.spacing.interact_size.y = 24.0;
style.spacing.menu_margin = egui::Margin::same(GAP_S as i8);
});
}
/// egui visuals for a palette: egui's own widgets (plain buttons, fields, menus) in the scheme's roles.
pub fn visuals(p: &Palette, corner_radius: u8) -> Visuals {
let mut v = if p.dark { Visuals::dark() } else { Visuals::light() };
let r = CornerRadius::same(corner_radius);
let big = CornerRadius::same(corner_radius.saturating_mul(2));
v.panel_fill = p.surface;
v.window_fill = p.surface_container;
v.extreme_bg_color = p.surface_container_highest;
v.text_edit_bg_color = Some(p.surface_container_highest);
v.faint_bg_color = p.surface_container_low;
v.code_bg_color = p.surface_container_high;
v.override_text_color = Some(p.on_surface);
v.weak_text_color = Some(p.on_surface_variant);
v.hyperlink_color = p.primary;
v.selection.bg_fill = layer(p.surface, p.primary, 0.35);
v.selection.stroke.color = p.primary;
v.window_corner_radius = big;
v.menu_corner_radius = big;
v.window_stroke.color = p.outline_variant;
v.window_shadow = egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if p.dark { 90 } else { 40 }) };
v.popup_shadow = egui::Shadow { offset: [0, 2], blur: 10, spread: 0, color: Color32::from_black_alpha(if p.dark { 80 } else { 32 }) };
v.error_fg_color = p.error;
v.warn_fg_color = p.warning;
let base = p.surface_container_highest;
for (w, fill) in [
(&mut v.widgets.noninteractive, p.surface),
(&mut v.widgets.inactive, base),
(&mut v.widgets.hovered, layer(base, p.on_surface, HOVER)),
(&mut v.widgets.active, layer(base, p.on_surface, HOVER + PRESS)),
(&mut v.widgets.open, layer(base, p.on_surface, HOVER)),
] {
w.corner_radius = r;
w.bg_fill = fill;
w.weak_bg_fill = fill;
w.bg_stroke = egui::Stroke::NONE;
// Strong text is egui's active foreground: it must stay readable on the page (R1-02).
w.fg_stroke.color = p.on_surface;
w.expansion = 0.0;
}
v.widgets.noninteractive.bg_stroke = egui::Stroke::new(1.0, p.outline_variant);
v.widgets.noninteractive.fg_stroke.color = p.on_surface_variant;
v.widgets.inactive.fg_stroke.color = p.on_surface_variant;
v.widgets.hovered.bg_stroke = egui::Stroke::new(1.0, p.outline);
v.widgets.active.bg_stroke = egui::Stroke::new(1.0, p.primary);
v.widgets.open.bg_stroke = egui::Stroke::new(1.0, p.outline);
v
}
#[cfg(test)]
mod tests {
use super::*;
/// epaint 0.37.0 panicked rasterizing glyphs once Servo turned on vello_cpu's multithreading
/// (vendor/epaint patch). Laying out text renders glyphs.
#[test]
fn egui_draws_text() {
let ctx = egui::Context::default();
let output = ctx.run_ui(Default::default(), |ui| {
ui.label("Nacre");
});
assert!(!output.shapes.is_empty());
}
#[test]
fn colours() {
assert_eq!(parse_hex("#6750A4"), Some(Color32::from_rgb(0x67, 0x50, 0xA4)));
assert_eq!(parse_css_color("rgb(10, 20, 30)"), Some(Color32::from_rgb(10, 20, 30)));
assert_eq!(parse_css_color("rgba(0, 0, 0, 0)"), None);
assert_eq!(to_hex(Color32::from_rgb(200, 100, 50)), "#C86432");
}
fn hex(c: Color32) -> String {
to_hex(c)
}
/// Reference colours from Material Color Utilities' tonal spot tests (seed 0xff0000ff, standard contrast) and
/// Material Theme Builder (seed #6750A4).
#[test]
fn tonal_spot_reference_colours() {
let blue = Color32::from_rgb(0, 0, 255);
let light = Palette::new(blue, false, "tonal_spot", 0.0);
let dark = Palette::new(blue, true, "tonal_spot", 0.0);
assert_eq!(hex(light.primary), "#555992");
assert_eq!(hex(light.primary_container), "#E0E0FF");
assert_eq!(hex(dark.primary), "#BEC2FF");
let violet = parse_hex("#6750A4").unwrap();
assert_eq!(hex(Palette::new(violet, false, "tonal_spot", 0.0).primary), "#65558F");
assert_eq!(hex(Palette::new(violet, true, "tonal_spot", 0.0).primary), "#CFBDFE");
}
fn tone(c: Color32) -> f64 {
Hct::new(argb(c)).get_tone()
}
/// The scheme's tones follow the M3 spec for every preset seed: surface T98 / T6, primary T40 / T80, and text
/// at least 4.5:1 on every surface, in light and dark.
#[test]
fn scheme_tones_and_contrast() {
for preset in PRESETS {
let seed = parse_hex(preset).unwrap();
for dark in [false, true] {
let p = Palette::new(seed, dark, "tonal_spot", 0.0);
let (surface, primary) = if dark { (6.0, 80.0) } else { (98.0, 40.0) };
assert!((tone(p.surface) - surface).abs() < 1.0, "{preset} dark={dark} surface tone {}", tone(p.surface));
assert!((tone(p.primary) - primary).abs() < 1.0, "{preset} dark={dark} primary tone {}", tone(p.primary));
for (name, bg) in [("surface", p.surface), ("lowest", p.surface_container_lowest), ("highest", p.surface_container_highest)] {
for (text_name, fg) in [("on_surface", p.on_surface), ("on_surface_variant", p.on_surface_variant)] {
let ratio = material_colors::contrast::ratio_of_tones(tone(fg), tone(bg));
assert!(ratio >= 4.5, "{preset} dark={dark} {text_name} on {name}: {ratio:.2}");
}
}
let ratio = material_colors::contrast::ratio_of_tones(tone(p.on_primary), tone(p.primary));
assert!(ratio >= 4.5, "{preset} dark={dark} on_primary: {ratio:.2}");
}
}
}
/// Every variant builds, and grey site colours don't become seeds.
#[test]
fn variants_and_seeds() {
for (key, _) in VARIANTS {
let p = Palette::new(Color32::from_rgb(0x00, 0x6A, 0x6A), true, key, 0.0);
assert_ne!(p.primary, p.surface, "{key}");
}
assert!(!usable_seed(Color32::from_rgb(128, 128, 128)));
assert!(!usable_seed(Color32::WHITE));
assert!(usable_seed(Color32::from_rgb(0x0B, 0x57, 0xD0)));
}
#[test]
fn spring_settles_on_target() {
let mut s = SpringState { value: 0.0, velocity: 0.0, frame: 0 };
let mut peak: f32 = 0.0;
for _ in 0..120 {
spring_step(&mut s, 1.0, FAST, 1.0, 1.0 / 60.0);
peak = peak.max(s.value);
}
assert_eq!(s.value, 1.0);
assert!(peak > 1.0, "FAST overshoots a little");
let mut s = SpringState { value: 0.0, velocity: 0.0, frame: 0 };
for _ in 0..120 {
spring_step(&mut s, 1.0, EFFECT, 1.0, 1.0 / 60.0);
assert!(s.value <= 1.0, "EFFECT never overshoots");
}
assert_eq!(s.value, 1.0);
}
}