//! CSS colours as a mail writes them, and the arithmetic of the dark reader: WCAG contrast, "is this grey", //! and lightening a colour in its own hue until it reads on the body. //! //! A mail's colour is hostile input like the rest of it: anything this parser does not know is `None`, and the //! sanitiser then drops it. use std::fmt; /// An opaque sRGB colour. Written (`Display`) as `#rrggbb`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Rgb { pub r: u8, pub g: u8, pub b: u8, } impl Rgb { pub const fn new(r: u8, g: u8, b: u8) -> Self { Self { r, g, b } } } impl fmt::Display for Rgb { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b) } } /// The contrast every text colour of a dark mail reaches on the body (WCAG AA for body text). pub const MIN_CONTRAST: f64 = 4.5; /// Under this HSL saturation a colour is a grey (black and white included): the sanitiser removes it. pub const GREY_SATURATION: f64 = 0.10; /// Under this chroma (the largest channel minus the smallest, of 255) a colour is a grey too: near-black and /// near-white tints such as `#1b2130` or `#fff8f0` have a high HSL saturation but read as black and white. pub const GREY_CHROMA: f64 = 0.10; /// How far one step of lightening moves the HSL lightness. const LIGHTEN_STEP: f64 = 0.01; fn linear(channel: u8) -> f64 { let s = f64::from(channel) / 255.0; if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) } } /// WCAG relative luminance. pub fn luminance(c: Rgb) -> f64 { 0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b) } /// WCAG contrast ratio, 1 to 21. pub fn contrast(a: Rgb, b: Rgb) -> f64 { let (x, y) = (luminance(a), luminance(b)); (x.max(y) + 0.05) / (x.min(y) + 0.05) } /// Hue in degrees, saturation and lightness in 0..=1. fn to_hsl(c: Rgb) -> (f64, f64, f64) { let (r, g, b) = (f64::from(c.r) / 255.0, f64::from(c.g) / 255.0, f64::from(c.b) / 255.0); let max = r.max(g).max(b); let min = r.min(g).min(b); let l = (max + min) / 2.0; let d = max - min; if d == 0.0 { return (0.0, 0.0, l); } let s = d / (1.0 - (2.0 * l - 1.0).abs()); let h = if max == r { 60.0 * (((g - b) / d).rem_euclid(6.0)) } else if max == g { 60.0 * ((b - r) / d + 2.0) } else { 60.0 * ((r - g) / d + 4.0) }; (h, s.min(1.0), l) } fn from_hsl(h: f64, s: f64, l: f64) -> Rgb { let c = (1.0 - (2.0 * l - 1.0).abs()) * s; let hp = h.rem_euclid(360.0) / 60.0; let x = c * (1.0 - (hp.rem_euclid(2.0) - 1.0).abs()); let (r, g, b) = match hp as u32 { 0 => (c, x, 0.0), 1 => (x, c, 0.0), 2 => (0.0, c, x), 3 => (0.0, x, c), 4 => (x, 0.0, c), _ => (c, 0.0, x), }; let m = l - c / 2.0; let byte = |v: f64| ((v + m) * 255.0).round().clamp(0.0, 255.0) as u8; Rgb::new(byte(r), byte(g), byte(b)) } /// Black, grey or white: removed in the dark, so the text is the body's own. pub fn is_grey(c: Rgb) -> bool { let (_, s, _) = to_hsl(c); let chroma = f64::from(c.r.max(c.g).max(c.b) - c.r.min(c.g).min(c.b)) / 255.0; s < GREY_SATURATION || chroma < GREY_CHROMA } /// The colour itself if it reaches `MIN_CONTRAST` on `body`; else the same hue and saturation, lightened step by /// step until it does. `body` must be dark (white reaches 4.5 : 1 on it), as the dark palette's is. pub fn readable_on(c: Rgb, body: Rgb) -> Rgb { if contrast(c, body) >= MIN_CONTRAST { return c; } let (h, s, l) = to_hsl(c); let mut step = 1.0; loop { let lightness = (l + LIGHTEN_STEP * step).min(1.0); let out = from_hsl(h, s, lightness); if contrast(out, body) >= MIN_CONTRAST || lightness >= 1.0 { return out; } step += 1.0; } } /// Values that name no colour at all: a background of these was not there to remove. pub(super) fn names_nothing(value: &str) -> bool { matches!( value.trim().to_ascii_lowercase().as_str(), "" | "none" | "transparent" | "inherit" | "initial" | "unset" | "revert" | "currentcolor" | "0" ) } /// The words of a CSS value, split on spaces outside parentheses (`1px solid rgb(1, 2, 3)` is three words). pub(super) fn words(value: &str) -> Vec<&str> { let mut out = Vec::new(); let mut depth = 0u32; let mut start = None; for (i, c) in value.char_indices() { match c { '(' => depth += 1, ')' => depth = depth.saturating_sub(1), _ => {} } if c.is_ascii_whitespace() && depth == 0 { if let Some(s) = start.take() { out.push(&value[s..i]); } } else if start.is_none() { start = Some(i); } } if let Some(s) = start { out.push(&value[s..]); } out } /// A CSS colour: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()`, `hsl()`/`hsla()` (commas or spaces, /// numbers or percentages) or a named colour. Alpha is ignored (text a mail makes transparent is shown). /// `transparent`, `currentcolor` and anything else are `None`. pub fn parse_colour(value: &str) -> Option { let v = value.trim().to_ascii_lowercase(); if let Some(hex) = v.strip_prefix('#') { return parse_hex(hex); } if let Some(args) = v.strip_prefix("rgba(").or_else(|| v.strip_prefix("rgb(")) { let n = arguments(args)?; let channel = |s: &str| -> Option { let x = match s.strip_suffix('%') { Some(p) => p.parse::().ok()? * 2.55, None => s.parse::().ok()?, }; x.is_finite().then(|| x.round().clamp(0.0, 255.0) as u8) }; return Some(Rgb::new(channel(n[0])?, channel(n[1])?, channel(n[2])?)); } if let Some(args) = v.strip_prefix("hsla(").or_else(|| v.strip_prefix("hsl(")) { let n = arguments(args)?; let h = n[0].strip_suffix("deg").unwrap_or(n[0]).parse::().ok()?; let percent = |s: &str| -> Option { s.strip_suffix('%').unwrap_or(s).parse::().ok().map(|p| (p / 100.0).clamp(0.0, 1.0)) }; let (s, l) = (percent(n[1])?, percent(n[2])?); return h.is_finite().then(|| from_hsl(h, s, l)); } NAMED.iter().find(|(name, _)| *name == v).map(|(_, hex)| Rgb::new((hex >> 16) as u8, (hex >> 8) as u8, *hex as u8)) } /// The 3 or 4 arguments of `rgb(…)` / `hsl(…)`, up to the closing parenthesis, which must end the value. fn arguments(args: &str) -> Option> { let inner = args.strip_suffix(')')?; let n: Vec<&str> = inner.split([',', ' ', '/']).filter(|s| !s.is_empty()).collect(); (n.len() == 3 || n.len() == 4).then_some(n) } fn parse_hex(hex: &str) -> Option { if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let digit = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok(); let pair = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok(); match hex.len() { 3 | 4 => Some(Rgb::new(digit(0)? * 17, digit(1)? * 17, digit(2)? * 17)), 6 | 8 => Some(Rgb::new(pair(0)?, pair(2)?, pair(4)?)), _ => None, } } /// The CSS named colours (CSS Color 4), but `transparent`. const NAMED: &[(&str, u32)] = &[ ("aliceblue", 0xf0f8ff), ("antiquewhite", 0xfaebd7), ("aqua", 0x00ffff), ("aquamarine", 0x7fffd4), ("azure", 0xf0ffff), ("beige", 0xf5f5dc), ("bisque", 0xffe4c4), ("black", 0x000000), ("blanchedalmond", 0xffebcd), ("blue", 0x0000ff), ("blueviolet", 0x8a2be2), ("brown", 0xa52a2a), ("burlywood", 0xdeb887), ("cadetblue", 0x5f9ea0), ("chartreuse", 0x7fff00), ("chocolate", 0xd2691e), ("coral", 0xff7f50), ("cornflowerblue", 0x6495ed), ("cornsilk", 0xfff8dc), ("crimson", 0xdc143c), ("cyan", 0x00ffff), ("darkblue", 0x00008b), ("darkcyan", 0x008b8b), ("darkgoldenrod", 0xb8860b), ("darkgray", 0xa9a9a9), ("darkgreen", 0x006400), ("darkgrey", 0xa9a9a9), ("darkkhaki", 0xbdb76b), ("darkmagenta", 0x8b008b), ("darkolivegreen", 0x556b2f), ("darkorange", 0xff8c00), ("darkorchid", 0x9932cc), ("darkred", 0x8b0000), ("darksalmon", 0xe9967a), ("darkseagreen", 0x8fbc8f), ("darkslateblue", 0x483d8b), ("darkslategray", 0x2f4f4f), ("darkslategrey", 0x2f4f4f), ("darkturquoise", 0x00ced1), ("darkviolet", 0x9400d3), ("deeppink", 0xff1493), ("deepskyblue", 0x00bfff), ("dimgray", 0x696969), ("dimgrey", 0x696969), ("dodgerblue", 0x1e90ff), ("firebrick", 0xb22222), ("floralwhite", 0xfffaf0), ("forestgreen", 0x228b22), ("fuchsia", 0xff00ff), ("gainsboro", 0xdcdcdc), ("ghostwhite", 0xf8f8ff), ("gold", 0xffd700), ("goldenrod", 0xdaa520), ("gray", 0x808080), ("green", 0x008000), ("greenyellow", 0xadff2f), ("grey", 0x808080), ("honeydew", 0xf0fff0), ("hotpink", 0xff69b4), ("indianred", 0xcd5c5c), ("indigo", 0x4b0082), ("ivory", 0xfffff0), ("khaki", 0xf0e68c), ("lavender", 0xe6e6fa), ("lavenderblush", 0xfff0f5), ("lawngreen", 0x7cfc00), ("lemonchiffon", 0xfffacd), ("lightblue", 0xadd8e6), ("lightcoral", 0xf08080), ("lightcyan", 0xe0ffff), ("lightgoldenrodyellow", 0xfafad2), ("lightgray", 0xd3d3d3), ("lightgreen", 0x90ee90), ("lightgrey", 0xd3d3d3), ("lightpink", 0xffb6c1), ("lightsalmon", 0xffa07a), ("lightseagreen", 0x20b2aa), ("lightskyblue", 0x87cefa), ("lightslategray", 0x778899), ("lightslategrey", 0x778899), ("lightsteelblue", 0xb0c4de), ("lightyellow", 0xffffe0), ("lime", 0x00ff00), ("limegreen", 0x32cd32), ("linen", 0xfaf0e6), ("magenta", 0xff00ff), ("maroon", 0x800000), ("mediumaquamarine", 0x66cdaa), ("mediumblue", 0x0000cd), ("mediumorchid", 0xba55d3), ("mediumpurple", 0x9370db), ("mediumseagreen", 0x3cb371), ("mediumslateblue", 0x7b68ee), ("mediumspringgreen", 0x00fa9a), ("mediumturquoise", 0x48d1cc), ("mediumvioletred", 0xc71585), ("midnightblue", 0x191970), ("mintcream", 0xf5fffa), ("mistyrose", 0xffe4e1), ("moccasin", 0xffe4b5), ("navajowhite", 0xffdead), ("navy", 0x000080), ("oldlace", 0xfdf5e6), ("olive", 0x808000), ("olivedrab", 0x6b8e23), ("orange", 0xffa500), ("orangered", 0xff4500), ("orchid", 0xda70d6), ("palegoldenrod", 0xeee8aa), ("palegreen", 0x98fb98), ("paleturquoise", 0xafeeee), ("palevioletred", 0xdb7093), ("papayawhip", 0xffefd5), ("peachpuff", 0xffdab9), ("peru", 0xcd853f), ("pink", 0xffc0cb), ("plum", 0xdda0dd), ("powderblue", 0xb0e0e6), ("purple", 0x800080), ("rebeccapurple", 0x663399), ("red", 0xff0000), ("rosybrown", 0xbc8f8f), ("royalblue", 0x4169e1), ("saddlebrown", 0x8b4513), ("salmon", 0xfa8072), ("sandybrown", 0xf4a460), ("seagreen", 0x2e8b57), ("seashell", 0xfff5ee), ("sienna", 0xa0522d), ("silver", 0xc0c0c0), ("skyblue", 0x87ceeb), ("slateblue", 0x6a5acd), ("slategray", 0x708090), ("slategrey", 0x708090), ("snow", 0xfffafa), ("springgreen", 0x00ff7f), ("steelblue", 0x4682b4), ("tan", 0xd2b48c), ("teal", 0x008080), ("thistle", 0xd8bfd8), ("tomato", 0xff6347), ("turquoise", 0x40e0d0), ("violet", 0xee82ee), ("wheat", 0xf5deb3), ("white", 0xffffff), ("whitesmoke", 0xf5f5f5), ("yellow", 0xffff00), ("yellowgreen", 0x9acd32), ]; #[cfg(test)] mod tests { use super::*; #[test] fn hsl_round_trips_every_grey_and_primary() { for c in [ Rgb::new(0, 0, 0), Rgb::new(255, 255, 255), Rgb::new(255, 0, 0), Rgb::new(0, 128, 0), Rgb::new(0x1a, 0x43, 0xa6), ] { let (h, s, l) = to_hsl(c); assert_eq!(from_hsl(h, s, l), c); } } #[test] fn words_keep_functions_whole() { assert_eq!(words(" 1px solid rgb(1, 2, 3) "), ["1px", "solid", "rgb(1, 2, 3)"]); assert_eq!(words(""), Vec::<&str>::new()); } #[test] fn hostile_colour_values_are_none_not_a_panic() { for v in [ "#", "#ééé", "rgb(", "rgb()", "rgb(1e999, 0, 0)", "rgb(nan, 0, 0)", "hsl(inf, 1%, 1%)", "rgb(1,2,3,4,5)", "ĉ", ] { let _ = parse_colour(v); } assert_eq!(parse_colour("rgb(1e999, 0, 0)"), None); assert_eq!(parse_colour("hsl(inf, 1%, 1%)"), None); assert_eq!(parse_colour("#ééé"), None); assert_eq!(parse_colour(" RGB(255 0 0 / 50%) "), Some(Rgb::new(255, 0, 0))); assert_eq!(parse_colour("#0f08"), Some(Rgb::new(0, 255, 0))); } }