Skip to main content

adk_site/theme/
tokens.rs

1//! Design tokens and their colour contrast (spec 3.5 §7.8 "Generator", §7.8.1
2//! "Accessibility").
3
4use std::fmt;
5use std::str::FromStr;
6
7use serde::{Deserialize, Serialize};
8
9/// An sRGB colour, written `#rrggbb` or `#rgb`.
10///
11/// # Example
12///
13/// ```rust
14/// use adk_site::theme::Rgb;
15///
16/// let ink: Rgb = "#1a1a1a".parse().unwrap();
17/// let paper: Rgb = "#fff".parse().unwrap();
18/// assert!(ink.contrast_ratio(paper) > 15.0);
19/// ```
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct Rgb(pub u8, pub u8, pub u8);
22
23impl Rgb {
24    /// The WCAG 2.2 relative luminance.
25    pub fn relative_luminance(self) -> f64 {
26        fn channel(value: u8) -> f64 {
27            let c = f64::from(value) / 255.0;
28            if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
29        }
30        0.2126 * channel(self.0) + 0.7152 * channel(self.1) + 0.0722 * channel(self.2)
31    }
32
33    /// The WCAG 2.2 contrast ratio against `other`, from 1 to 21.
34    pub fn contrast_ratio(self, other: Rgb) -> f64 {
35        let (a, b) = (self.relative_luminance(), other.relative_luminance());
36        let (light, dark) = if a >= b { (a, b) } else { (b, a) };
37        (light + 0.05) / (dark + 0.05)
38    }
39}
40
41impl fmt::Display for Rgb {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
44    }
45}
46
47impl FromStr for Rgb {
48    type Err = String;
49
50    fn from_str(text: &str) -> Result<Self, Self::Err> {
51        let hex = text
52            .trim()
53            .strip_prefix('#')
54            .ok_or_else(|| format!("colour '{text}' must start with '#'"))?;
55        let digits: Vec<u8> = hex
56            .chars()
57            .map(|c| c.to_digit(16).map(|d| d as u8))
58            .collect::<Option<_>>()
59            .ok_or_else(|| format!("colour '{text}' is not hexadecimal"))?;
60        match digits.as_slice() {
61            [r, g, b] => Ok(Self(r * 17, g * 17, b * 17)),
62            [r1, r2, g1, g2, b1, b2] => Ok(Self(r1 * 16 + r2, g1 * 16 + g2, b1 * 16 + b2)),
63            _ => Err(format!("colour '{text}' must be #rgb or #rrggbb")),
64        }
65    }
66}
67
68impl Serialize for Rgb {
69    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
70        serializer.serialize_str(&self.to_string())
71    }
72}
73
74impl<'de> Deserialize<'de> for Rgb {
75    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
76        String::deserialize(deserializer)?.parse().map_err(serde::de::Error::custom)
77    }
78}
79
80/// The colour roles a theme defines.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub struct ColorTokens {
84    /// Body text.
85    pub text: Rgb,
86    /// Page background.
87    pub background: Rgb,
88    /// Secondary text: dates, bylines, captions.
89    pub muted: Rgb,
90    /// Links.
91    pub link: Rgb,
92    /// Buttons and highlights.
93    pub accent: Rgb,
94    /// Text on the accent colour.
95    pub accent_text: Rgb,
96    /// Rules and outlines.
97    pub border: Rgb,
98    /// Correction, withdrawal and expiry notices: background.
99    pub notice_background: Rgb,
100    /// Correction, withdrawal and expiry notices: text.
101    pub notice_text: Rgb,
102}
103
104/// A theme's design tokens: colours, type and measure, emitted as CSS custom properties.
105///
106/// # Example
107///
108/// ```rust
109/// use adk_site::theme::DesignTokens;
110///
111/// let tokens = DesignTokens::default();
112/// assert!(tokens.contrast_pairs().iter().all(|pair| pair.passes()));
113/// assert!(tokens.css_variables().contains("--color-text: #"));
114/// ```
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub struct DesignTokens {
118    /// Colours.
119    pub colors: ColorTokens,
120    /// The body font stack.
121    pub font_body: String,
122    /// The heading font stack.
123    pub font_heading: String,
124    /// The monospace font stack.
125    pub font_mono: String,
126    /// The maximum width of the reading column, a CSS length.
127    pub measure: String,
128    /// The corner radius, a CSS length.
129    pub radius: String,
130}
131
132impl Default for DesignTokens {
133    fn default() -> Self {
134        Self {
135            colors: ColorTokens {
136                text: Rgb(0x1b, 0x1d, 0x21),
137                background: Rgb(0xff, 0xff, 0xff),
138                muted: Rgb(0x55, 0x5b, 0x65),
139                link: Rgb(0x0b, 0x57, 0xd0),
140                accent: Rgb(0x0b, 0x57, 0xd0),
141                accent_text: Rgb(0xff, 0xff, 0xff),
142                border: Rgb(0xd0, 0xd4, 0xda),
143                notice_background: Rgb(0xff, 0xf4, 0xd6),
144                notice_text: Rgb(0x4a, 0x35, 0x00),
145            },
146            font_body: "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif".into(),
147            font_heading: "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif".into(),
148            font_mono: "ui-monospace, \"SF Mono\", Menlo, Consolas, monospace".into(),
149            measure: "44rem".into(),
150            radius: "6px".into(),
151        }
152    }
153}
154
155/// A foreground and background pair the accessibility check measures.
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
157#[serde(rename_all = "camelCase")]
158pub struct ContrastPair {
159    /// The pair's name, such as `text/background`.
160    pub name: String,
161    /// The foreground colour.
162    pub foreground: Rgb,
163    /// The background colour.
164    pub background: Rgb,
165    /// The measured ratio.
166    pub ratio: f64,
167    /// The WCAG 2.2 AA minimum for the pair: 4.5 for text.
168    pub required: f64,
169}
170
171impl ContrastPair {
172    /// Whether the pair meets its minimum.
173    pub fn passes(&self) -> bool {
174        self.ratio + 1e-9 >= self.required
175    }
176}
177
178impl DesignTokens {
179    /// Every text pair the theme renders, with its WCAG 2.2 AA minimum (1.4.3: 4.5:1 for
180    /// normal text).
181    pub fn contrast_pairs(&self) -> Vec<ContrastPair> {
182        let c = &self.colors;
183        [
184            ("text/background", c.text, c.background),
185            ("muted/background", c.muted, c.background),
186            ("link/background", c.link, c.background),
187            ("accent_text/accent", c.accent_text, c.accent),
188            ("notice_text/notice_background", c.notice_text, c.notice_background),
189        ]
190        .into_iter()
191        .map(|(name, foreground, background)| ContrastPair {
192            name: name.into(),
193            foreground,
194            background,
195            ratio: foreground.contrast_ratio(background),
196            required: 4.5,
197        })
198        .collect()
199    }
200
201    /// The tokens as a `:root` block of CSS custom properties.
202    pub fn css_variables(&self) -> String {
203        let c = &self.colors;
204        let mut css = String::from(":root {\n");
205        for (name, value) in [
206            ("text", c.text),
207            ("background", c.background),
208            ("muted", c.muted),
209            ("link", c.link),
210            ("accent", c.accent),
211            ("accent-text", c.accent_text),
212            ("border", c.border),
213            ("notice-background", c.notice_background),
214            ("notice-text", c.notice_text),
215        ] {
216            css.push_str(&format!("  --color-{name}: {value};\n"));
217        }
218        css.push_str(&format!("  --font-body: {};\n", self.font_body));
219        css.push_str(&format!("  --font-heading: {};\n", self.font_heading));
220        css.push_str(&format!("  --font-mono: {};\n", self.font_mono));
221        css.push_str(&format!("  --measure: {};\n", self.measure));
222        css.push_str(&format!("  --radius: {};\n", self.radius));
223        css.push_str("}\n");
224        css
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn contrast_matches_wcag_reference_values() {
234        let black = Rgb(0, 0, 0);
235        let white = Rgb(255, 255, 255);
236        assert!((black.contrast_ratio(white) - 21.0).abs() < 1e-9);
237        assert!((white.contrast_ratio(white) - 1.0).abs() < 1e-9);
238        // #767676 on white is the classic 4.54:1 boundary colour.
239        let grey: Rgb = "#767676".parse().unwrap();
240        assert!((grey.contrast_ratio(white) - 4.54).abs() < 0.01);
241        let light: Rgb = "#777".parse().unwrap();
242        assert!(light.contrast_ratio(white) < 4.5);
243    }
244
245    #[test]
246    fn colours_parse_and_print() {
247        assert_eq!("#0B57D0".parse::<Rgb>().unwrap(), Rgb(0x0b, 0x57, 0xd0));
248        assert_eq!("#abc".parse::<Rgb>().unwrap(), Rgb(0xaa, 0xbb, 0xcc));
249        assert_eq!(Rgb(1, 2, 255).to_string(), "#0102ff");
250        assert!("0b57d0".parse::<Rgb>().is_err());
251        assert!("#12345".parse::<Rgb>().is_err());
252    }
253
254    #[test]
255    fn default_tokens_meet_aa() {
256        for pair in DesignTokens::default().contrast_pairs() {
257            assert!(pair.passes(), "{} is {:.2}", pair.name, pair.ratio);
258        }
259    }
260}