1use std::fmt;
5use std::str::FromStr;
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct Rgb(pub u8, pub u8, pub u8);
22
23impl Rgb {
24 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub struct ColorTokens {
84 pub text: Rgb,
86 pub background: Rgb,
88 pub muted: Rgb,
90 pub link: Rgb,
92 pub accent: Rgb,
94 pub accent_text: Rgb,
96 pub border: Rgb,
98 pub notice_background: Rgb,
100 pub notice_text: Rgb,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub struct DesignTokens {
118 pub colors: ColorTokens,
120 pub font_body: String,
122 pub font_heading: String,
124 pub font_mono: String,
126 pub measure: String,
128 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
157#[serde(rename_all = "camelCase")]
158pub struct ContrastPair {
159 pub name: String,
161 pub foreground: Rgb,
163 pub background: Rgb,
165 pub ratio: f64,
167 pub required: f64,
169}
170
171impl ContrastPair {
172 pub fn passes(&self) -> bool {
174 self.ratio + 1e-9 >= self.required
175 }
176}
177
178impl DesignTokens {
179 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 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 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}