//! Cotton Vault's look as kit data (`kits/keys/look.json`): colour roles for //! light and dark, type roles, spacing and corners. `vault.look` answers it //! whole; the phones keep no colour or size of their own for this app. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; /// The kit file, as shipped. pub const SHIPPED: &str = include_str!("../../../kits/keys/look.json"); /// The roles every mode must carry: what the shapes' `Tone` and every screen name. pub const COLOUR_ROLES: &[&str] = &[ "background", "surface", "raised", "sheet", "separator", "field", "text", "secondary", "tertiary", "disabled", "accent", "on_accent", "safe", "safe_wash", "attention", "attention_wash", "danger", "danger_wash", "scrim", "on_tint", ]; /// The type roles every screen draws with. pub const TYPE_ROLES: &[&str] = &["large_title", "title", "headline", "body", "row_title", "row_detail", "label", "section", "button", "chip", "initials", "secret", "secret_large", "code"]; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Font { pub family: String, pub licence: String, pub weights: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TypeRole { /// `sans` or `mono`. pub font: String, pub size: f32, pub weight: u16, pub line: f32, pub tracking: f32, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Look { pub format_version: u32, pub id: String, pub purpose: String, pub fonts: BTreeMap, /// `light` and `dark`, each role → `#RRGGBB` or `#RRGGBBAA`. pub colours: BTreeMap>, #[serde(rename = "type")] pub type_roles: BTreeMap, pub space: BTreeMap, pub corners: BTreeMap, /// Semantic names → a colour role. pub roles: BTreeMap, } /// Why the look's data was refused. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum LookError { #[error("the look does not read: {0}")] DoesNotRead(String), #[error("{mode} has no colour for `{role}`")] MissingColour { mode: String, role: String }, #[error("{mode}.{role} is not #RRGGBB or #RRGGBBAA")] BadColour { mode: String, role: String }, #[error("no type role `{0}`")] MissingType(String), #[error("type role `{0}` names a font the look does not carry")] UnknownFont(String), #[error("role `{0}` names a colour the look does not carry")] UnknownRole(String), } impl Look { /// The shipped look, read once. pub fn shipped() -> &'static Look { static LOOK: std::sync::OnceLock = std::sync::OnceLock::new(); LOOK.get_or_init(|| Look::parse(SHIPPED).expect("kits/keys/look.json reads")) } pub fn parse(json: &str) -> Result { let look: Look = serde_json::from_str(json).map_err(|error| LookError::DoesNotRead(error.to_string()))?; look.check()?; Ok(look) } fn check(&self) -> Result<(), LookError> { for mode in ["light", "dark"] { let colours = self.colours.get(mode).ok_or_else(|| LookError::MissingColour { mode: mode.into(), role: "*".into() })?; let tints = (0..super::shapes::TINTS).map(|n| format!("tint.{n}")); for role in COLOUR_ROLES.iter().map(|role| role.to_string()).chain(tints) { let value = colours.get(&role).ok_or_else(|| LookError::MissingColour { mode: mode.into(), role: role.clone() })?; if rgba(value).is_none() { return Err(LookError::BadColour { mode: mode.into(), role }); } } } for role in TYPE_ROLES { let found = self.type_roles.get(*role).ok_or_else(|| LookError::MissingType(role.to_string()))?; if !self.fonts.contains_key(&found.font) { return Err(LookError::UnknownFont(role.to_string())); } } for target in self.roles.values() { if !self.colours["light"].contains_key(target) { return Err(LookError::UnknownRole(target.clone())); } } Ok(()) } } /// `#RRGGBB[AA]` as four bytes. pub fn rgba(hex: &str) -> Option<[u8; 4]> { let digits = hex.strip_prefix('#')?; if !(digits.len() == 6 || digits.len() == 8) || !digits.chars().all(|c| c.is_ascii_hexdigit()) { return None; } let byte = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).ok(); Some([byte(0)?, byte(2)?, byte(4)?, if digits.len() == 8 { byte(6)? } else { 255 }]) } /// WCAG contrast ratio of two opaque colours. pub fn contrast(a: &str, b: &str) -> Option { fn luminance(rgb: [u8; 4]) -> f64 { let channel = |c: u8| { let c = c as f64 / 255.0; if c <= 0.039_28 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } }; 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]) } let (la, lb) = (luminance(rgba(a)?), luminance(rgba(b)?)); let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) }; Some((hi + 0.05) / (lo + 0.05)) }