diff --git a/crates/forge-web/src/accent.rs b/crates/forge-web/src/accent.rs index d8f4244..62f7426 100644 --- a/crates/forge-web/src/accent.rs +++ b/crates/forge-web/src/accent.rs @@ -61,15 +61,39 @@ pub fn base_ids() -> impl Iterator { BASES.iter().map(|b| b.id) } -/// The hue N of a `hue-N` id: an integer `0..=359` with no leading zeros (except `hue-0`). Any -/// other id is None. +/// The hue and vividness of a custom id. `hue-H` (legacy) takes `default_vivid`; `hue-H-vV` takes V. +/// H is `0..=359` and V is `0..=100`, both plain decimal numbers with no sign, spaces or leading +/// zeros (except `0` itself). Any other id is None. +pub fn custom_of(id: &str, default_vivid: u8) -> Option<(u16, u8)> { + let rest = id.strip_prefix("hue-")?; + match rest.split_once("-v") { + Some((hue, vivid)) => Some(( + canonical_number(hue, 359)?, + canonical_number(vivid, 100)? as u8, + )), + None => Some((canonical_number(rest, 359)?, default_vivid)), + } +} + +/// The stored id of a custom accent or base in the `hue-H-vV` form, which `custom_of` reads back. +#[allow(dead_code)] // The settings picker writes its custom ids with this. +pub fn custom_id(hue: u16, vivid: u8) -> String { + format!("hue-{hue}-v{vivid}") +} + +/// The hue N of a legacy or `hue-H-vV` id, whatever its vividness. Any other id is None. pub fn hue_of(id: &str) -> Option { - let digits = id.strip_prefix("hue-")?; + custom_of(id, 50).map(|(hue, _)| hue) +} + +/// A decimal number of at most three digits, no sign, no leading zeros (except `0`), and at most +/// `max`. +fn canonical_number(digits: &str, max: u16) -> Option { let canonical = digits == "0" || (!digits.is_empty() && !digits.starts_with('0')); if !canonical || digits.len() > 3 || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } - digits.parse::().ok().filter(|hue| *hue < 360) + digits.parse::().ok().filter(|n| *n <= max) } /// The OKLCH hue, in degrees, of a preset accent's light colour. None for an id that is not a @@ -96,8 +120,8 @@ pub fn preset_base_hue(id: &str) -> Option { /// gets the accent built for its hue; an id forge does not offer gets the default's. #[allow(dead_code)] // The settings picker shows its chips with this. pub fn swatch(id: &str, dark: bool) -> String { - match hue_of(id) { - Some(hue) => custom_colour::accent_tokens(hue, dark).accent, + match custom_of(id, 50) { + Some((hue, vivid)) => custom_colour::accent_tokens(hue, vivid, dark).accent, None => { let palette = resolve(id); let tokens = if dark { &palette.dark } else { &palette.light }; @@ -110,9 +134,9 @@ pub fn swatch(id: &str, dark: bool) -> String { /// the base built for its hue; an id forge does not offer gets the default's. #[allow(dead_code)] // The settings picker shows its chips with this. pub fn base_swatch(id: &str, dark: bool) -> (String, String) { - match hue_of(id) { - Some(hue) => { - let tokens = custom_colour::base_tokens(hue, dark); + match custom_of(id, 30) { + Some((hue, vivid)) => { + let tokens = custom_colour::base_tokens(hue, vivid, dark); (tokens.bg, tokens.text) } None => { @@ -221,8 +245,8 @@ mod tests { let hues = (0..360u16).map(|hue| { ( format!("hue-{hue}"), - accent_tokens(hue, false), - accent_tokens(hue, true), + accent_tokens(hue, 50, false), + accent_tokens(hue, 50, true), ) }); presets.chain(hues).collect() @@ -236,8 +260,8 @@ mod tests { let hues = (0..360u16).map(|hue| { ( format!("hue-{hue}"), - base_tokens(hue, false), - base_tokens(hue, true), + base_tokens(hue, 30, false), + base_tokens(hue, 30, true), ) }); presets.chain(hues).collect() @@ -361,14 +385,17 @@ mod tests { fn swatches_show_the_accent_and_the_base_for_presets_and_hues() { assert_eq!(swatch("sage", false), "#5E7D63"); assert_eq!(swatch("sage", true), "#9DBEA2"); - assert_eq!(swatch("hue-215", false), accent_tokens(215, false).accent); - assert_eq!(swatch("hue-215", true), accent_tokens(215, true).accent); + assert_eq!( + swatch("hue-215", false), + accent_tokens(215, 50, false).accent + ); + assert_eq!(swatch("hue-215", true), accent_tokens(215, 50, true).accent); assert_eq!(swatch("ember", false), swatch("sage", false)); let (bg, text) = base_swatch("fern", false); assert_eq!((bg.as_str(), text.as_str()), ("#F6F8F5", "#1E2420")); let (bg, text) = base_swatch("hue-215", true); - assert_eq!(bg, base_tokens(215, true).bg); - assert_eq!(text, base_tokens(215, true).text); + assert_eq!(bg, base_tokens(215, 30, true).bg); + assert_eq!(text, base_tokens(215, 30, true).text); } #[test] diff --git a/crates/forge-web/src/custom_colour.rs b/crates/forge-web/src/custom_colour.rs index 81941a7..f302d59 100644 --- a/crates/forge-web/src/custom_colour.rs +++ b/crates/forge-web/src/custom_colour.rs @@ -81,33 +81,37 @@ const NEUTRAL_CHROMA: f64 = 0.012; /// Slack for float error when testing whether a colour is inside sRGB. const GAMUT_EPS: f64 = 1e-6; -/// The accent colours for a hue, in one theme. Light: a mid accent with its ink darker than it. -/// Dark: a light accent with its ink lighter than it, on a dark soft tint. -pub fn accent_tokens(hue: u16, dark: bool) -> OwnedTokens { +/// The chroma factor of an accent at vividness `vivid` (0..=100). The default, 50, gives exactly 1.0 +/// so the legacy `hue-N` colours stay byte-identical. +fn accent_factor(vivid: u8) -> f64 { + if vivid == 50 { + return 1.0; + } + (0.03 + 0.16 * f64::from(vivid) / 100.0) / 0.11 +} + +/// The accent colours for a hue, in one theme, at a vividness (0..=100; 50 is the default). Light: +/// a mid accent with its ink darker than it. Dark: a light accent with its ink lighter than it, on +/// a dark soft tint. Every chroma is scaled by the vividness; the gamut clamp in `colour` holds the +/// lightness and hue. +pub fn accent_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedTokens { let h = f64::from(hue); + let f = accent_factor(vivid); + let c = |lightness: f64, chroma: f64| colour(lightness, chroma * f, h); let (accent, ink, soft, hunk_bg) = if dark { - ( - colour(0.75, 0.11, h), - colour(0.84, 0.09, h), - colour(0.27, 0.04, h), - colour(0.22, 0.03, h), - ) + (c(0.75, 0.11), c(0.84, 0.09), c(0.27, 0.04), c(0.22, 0.03)) } else { ( - colour(0.52, 0.12, h), - colour(0.46, 0.12, h), - colour(0.95, 0.025, h), - colour(0.975, 0.012, h), + c(0.52, 0.12), + c(0.46, 0.12), + c(0.95, 0.025), + c(0.975, 0.012), ) }; OwnedTokens { accent_text: text_on(&accent), focus: if dark { accent.clone() } else { ink.clone() }, - hunk_text: if dark { - accent.clone() - } else { - colour(0.44, 0.10, h) - }, + hunk_text: if dark { accent.clone() } else { c(0.44, 0.10) }, public_bg: soft.clone(), public_text: ink.clone(), note: ink.clone(), @@ -118,11 +122,35 @@ pub fn accent_tokens(hue: u16, dark: bool) -> OwnedTokens { } } -/// The neutral colours for a hue, in one theme. Each is a tint of the hue at `NEUTRAL_CHROMA`, at -/// the lightness the presets use for that role. -pub fn base_tokens(hue: u16, dark: bool) -> OwnedBaseTokens { +/// The neutral colours for a hue, in one theme, at a vividness (0..=100; 30 is the default). Each is +/// a tint of the hue at `NEUTRAL_CHROMA` scaled by the vividness, at the lightness the presets use +/// for that role. Vividness 0 is a grey. If the text, surface or muted colour reads below WCAG 4.5:1, +/// the chroma steps down by 0.8, at most ten times, until it passes. +pub fn base_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedBaseTokens { + let mut factor = f64::from(vivid) / 30.0; + let mut tokens = base_tokens_at(hue, factor, dark); + for _ in 0..10 { + if base_is_readable(&tokens) { + break; + } + factor *= 0.8; + tokens = base_tokens_at(hue, factor, dark); + } + tokens +} + +/// True when the text, the surface and the muted colour all read at 4.5:1 or more on the background. +fn base_is_readable(tokens: &OwnedBaseTokens) -> bool { + const MIN: f64 = 4.5; + contrast_ratio(&tokens.text, &tokens.bg) >= MIN + && contrast_ratio(&tokens.text, &tokens.surface) >= MIN + && contrast_ratio(&tokens.muted, &tokens.bg) >= MIN +} + +/// The neutral colours of a base at one chroma factor (1.0 is the default vividness). +fn base_tokens_at(hue: u16, factor: f64, dark: bool) -> OwnedBaseTokens { let h = f64::from(hue); - let n = |l: f64| colour(l, NEUTRAL_CHROMA, h); + let n = |l: f64| colour(l, NEUTRAL_CHROMA * factor, h); if dark { let surface_2 = n(0.26); let text_2 = n(0.82); @@ -182,31 +210,49 @@ pub fn contrast_ratio(a: &str, b: &str) -> f64 { (x.max(y) + 0.05) / (x.min(y) + 0.05) } -/// The rules for the custom ids of one stylesheet: each argument is the hue of an accent or base -/// id (`None` for a preset, which `build.rs` already styles). They mirror `build.rs`: the light -/// tokens go on the light attribute, the dark tokens on the dark attribute in both dark states. +/// One custom choice of `stylesheet`: the id as stored, its hue and its vividness. The id is the +/// stored string, so the selector matches the `` attribute (a legacy `hue-N` stays `hue-N`). +pub type CustomSlot<'a> = Option<(&'a str, u16, u8)>; + +/// The rules for the custom ids of one stylesheet: each slot is an accent or base id with its hue +/// and vividness (`None` for a preset, which `build.rs` already styles). They mirror `build.rs`: the +/// light tokens go on the light attribute, the dark tokens on the dark attribute in both dark states. pub fn stylesheet( - accent_light: Option, - accent_dark: Option, - base_light: Option, - base_dark: Option, + accent_light: CustomSlot, + accent_dark: CustomSlot, + base_light: CustomSlot, + base_dark: CustomSlot, ) -> String { let mut css = String::new(); - if let Some(hue) = accent_light { - let selector = format!(":root[data-accent-light=\"hue-{hue}\"]"); - rule(&mut css, "", &selector, &accent_tokens(hue, false).decls()); + if let Some((id, hue, vivid)) = accent_light { + let selector = format!(":root[data-accent-light=\"{id}\"]"); + rule( + &mut css, + "", + &selector, + &accent_tokens(hue, vivid, false).decls(), + ); } - if let Some(hue) = accent_dark { - let selector = format!(":root[data-accent-dark=\"hue-{hue}\"]"); - dark_rules(&mut css, &selector, &accent_tokens(hue, true).decls()); + if let Some((id, hue, vivid)) = accent_dark { + let selector = format!(":root[data-accent-dark=\"{id}\"]"); + dark_rules( + &mut css, + &selector, + &accent_tokens(hue, vivid, true).decls(), + ); } - if let Some(hue) = base_light { - let selector = format!(":root[data-base-light=\"hue-{hue}\"]"); - rule(&mut css, "", &selector, &base_tokens(hue, false).decls()); + if let Some((id, hue, vivid)) = base_light { + let selector = format!(":root[data-base-light=\"{id}\"]"); + rule( + &mut css, + "", + &selector, + &base_tokens(hue, vivid, false).decls(), + ); } - if let Some(hue) = base_dark { - let selector = format!(":root[data-base-dark=\"hue-{hue}\"]"); - dark_rules(&mut css, &selector, &base_tokens(hue, true).decls()); + if let Some((id, hue, vivid)) = base_dark { + let selector = format!(":root[data-base-dark=\"{id}\"]"); + dark_rules(&mut css, &selector, &base_tokens(hue, vivid, true).decls()); } css } @@ -356,14 +402,14 @@ mod tests { fn every_hue_gives_hex_colours_with_the_right_token_names_and_keyed_rules() { for hue in 0..360 { for dark in [false, true] { - let accent = accent_tokens(hue, dark); + let accent = accent_tokens(hue, 50, dark); let names: Vec<&str> = accent.decls().iter().map(|(n, _)| *n).collect(); let expected: Vec<&str> = TOKEN_VARS.iter().map(|t| t.name).collect(); assert_eq!(names, expected); for (name, value) in accent.decls() { assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}"); } - let base = base_tokens(hue, dark); + let base = base_tokens(hue, 30, dark); let names: Vec<&str> = base.decls().iter().map(|(n, _)| *n).collect(); let expected: Vec<&str> = BASE_TOKEN_VARS.iter().map(|t| t.name).collect(); assert_eq!(names, expected); @@ -372,7 +418,12 @@ mod tests { } } } - let css = stylesheet(Some(215), Some(215), None, Some(7)); + let css = stylesheet( + Some(("hue-215", 215, 50)), + Some(("hue-215", 215, 50)), + None, + Some(("hue-7", 7, 30)), + ); assert!( css.contains(":root[data-accent-light=\"hue-215\"] {\n --accent: #"), "{css}" @@ -394,4 +445,31 @@ mod tests { assert!(!css.contains("data-base-light"), "{css}"); assert!(stylesheet(None, None, None, None).is_empty()); } + + #[test] + fn legacy_and_explicit_default_vividness_give_the_same_accent() { + let legacy = crate::accent::custom_of("hue-215", 50).unwrap(); + let explicit = crate::accent::custom_of("hue-215-v50", 50).unwrap(); + assert_eq!(legacy, explicit); + for dark in [false, true] { + let a = accent_tokens(legacy.0, legacy.1, dark); + let b = accent_tokens(explicit.0, explicit.1, dark); + assert_eq!(a.decls(), b.decls()); + } + } + + #[test] + fn full_vividness_bases_keep_text_readable() { + for hue in (0..360).step_by(30) { + for dark in [false, true] { + let base = base_tokens(hue, 100, dark); + assert!( + contrast_ratio(&base.text, &base.bg) >= 4.5, + "{hue} {dark}: {} on {}", + base.text, + base.bg + ); + } + } + } } diff --git a/crates/forge-web/src/pages/assets.rs b/crates/forge-web/src/pages/assets.rs index 3f3d2be..266ebab 100644 --- a/crates/forge-web/src/pages/assets.rs +++ b/crates/forge-web/src/pages/assets.rs @@ -91,20 +91,26 @@ async fn highlight_css_route() -> Result<(StatusCode, HeaderMap, &'static str)> /// so the response is immutable like the others. #[route(GET "/theme/custom.css")] async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { - let mut hues: [Option; 4] = [None; 4]; + // Each slot: the id as given, its hue and its vividness. A legacy `hue-N` gets the default. + let mut slots: [Option<(String, u16, u8)>; 4] = Default::default(); if let Some(query) = uri(cx).query() { for (key, value) in form_urlencoded::parse(query.as_bytes()) { - let slot = match key.as_ref() { - "al" => 0, - "ad" => 1, - "bl" => 2, - "bd" => 3, + let (slot, default_vivid) = match key.as_ref() { + "al" => (0, 50), + "ad" => (1, 50), + "bl" => (2, 30), + "bd" => (3, 30), _ => continue, }; - hues[slot] = accent::hue_of(&value); + if let Some((hue, vivid)) = accent::custom_of(&value, default_vivid) { + slots[slot] = Some((value.into_owned(), hue, vivid)); + } } } - let [accent_light, accent_dark, base_light, base_dark] = hues; + let [accent_light, accent_dark, base_light, base_dark] = slots.each_ref().map(|slot| { + slot.as_ref() + .map(|(id, hue, vivid)| (id.as_str(), *hue, *vivid)) + }); let css = custom_colour::stylesheet(accent_light, accent_dark, base_light, base_dark); let mut headers = HeaderMap::new(); headers.insert( @@ -342,8 +348,16 @@ mod tests { // Each bundle is immutable under its own type. Its body holds the marker, when one is given. for (uri, kind, marker) in [ ("/assets/main.css", "text/css; charset=utf-8", ""), - (crate::views::NAV_SCRIPT_HREF, "text/javascript; charset=utf-8", "__forgeSoft"), - (crate::views::highlight_href(), "text/css; charset=utf-8", ""), + ( + crate::views::NAV_SCRIPT_HREF, + "text/javascript; charset=utf-8", + "__forgeSoft", + ), + ( + crate::views::highlight_href(), + "text/css; charset=utf-8", + "", + ), ] { let req = Request::builder() .method("GET")