1use std::fmt;
5
6#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Color {
10 pub r: f32,
11 pub g: f32,
12 pub b: f32,
13 pub a: f32,
14}
15
16impl Color {
17 pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
18 pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
19 pub const MISSING: Color = Color::rgb(1.0, 0.0, 1.0);
21
22 pub const fn rgb(r: f32, g: f32, b: f32) -> Color {
24 Color { r, g, b, a: 1.0 }
25 }
26
27 pub fn from_hex(text: &str) -> Option<Color> {
29 let h = text.strip_prefix('#')?;
30 if !h.is_ascii() {
31 return None;
32 }
33 let byte = |i: usize| {
34 u8::from_str_radix(h.get(i..i + 2)?, 16)
35 .ok()
36 .map(|b| f32::from(b) / 255.0)
37 };
38 let nibble = |i: usize| {
39 u8::from_str_radix(h.get(i..=i)?, 16)
40 .ok()
41 .map(|b| f32::from(b * 17) / 255.0)
42 };
43 match h.len() {
44 3 => Some(Color::rgb(nibble(0)?, nibble(1)?, nibble(2)?)),
45 6 => Some(Color::rgb(byte(0)?, byte(2)?, byte(4)?)),
46 8 => Some(Color {
47 a: byte(6)?,
48 ..Color::rgb(byte(0)?, byte(2)?, byte(4)?)
49 }),
50 _ => None,
51 }
52 }
53
54 pub fn from_oklch(l: f32, c: f32, h: f32, alpha: f32) -> Color {
57 let (hs, hc) = f64::from(h).to_radians().sin_cos();
58 let c = f64::from(c);
59 Color::from_oklab(f64::from(l), c * hc, c * hs, alpha)
60 }
61
62 pub fn from_oklab(l: f64, a: f64, b: f64, alpha: f32) -> Color {
64 let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
65 let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
66 let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
67 let (l3, m3, s3) = (l_.powi(3), m_.powi(3), s_.powi(3));
68 let r = 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3;
69 let g = -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3;
70 let bl = -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3;
71 Color {
72 r: encode(r),
73 g: encode(g),
74 b: encode(bl),
75 a: alpha,
76 }
77 }
78
79 pub fn from_linear(r: f32, g: f32, b: f32, alpha: f32) -> Color {
81 Color {
82 r: encode(f64::from(r)),
83 g: encode(f64::from(g)),
84 b: encode(f64::from(b)),
85 a: alpha,
86 }
87 }
88
89 pub fn to_linear(self) -> [f64; 3] {
91 [decode(self.r), decode(self.g), decode(self.b)]
92 }
93
94 pub fn to_oklab(self) -> [f64; 3] {
97 let [r, g, b] = self.to_linear();
98 linear_to_oklab(r, g, b)
99 }
100
101 pub fn to_srgba_u8(self) -> [u8; 4] {
103 let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
104 [b(self.r), b(self.g), b(self.b), b(self.a)]
105 }
106
107 pub fn to_hex(self) -> String {
109 let [r, g, b, a] = self.to_srgba_u8();
110 if a == 255 {
111 format!("#{r:02x}{g:02x}{b:02x}")
112 } else {
113 format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
114 }
115 }
116
117 pub fn over(self, background: Color) -> Color {
119 let a = self.a.clamp(0.0, 1.0);
120 let mix = |f: f32, b: f32| f * a + b * (1.0 - a);
121 Color::rgb(
122 mix(self.r, background.r),
123 mix(self.g, background.g),
124 mix(self.b, background.b),
125 )
126 }
127
128 pub fn relative_luminance(self) -> f32 {
130 let [r, g, b] = self.to_linear();
131 (0.2126 * r + 0.7152 * g + 0.0722 * b) as f32
132 }
133
134 pub fn is_dark(self) -> bool {
137 self.relative_luminance() < 0.18
138 }
139}
140
141impl fmt::Display for Color {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str(&self.to_hex())
144 }
145}
146
147fn decode(c: f32) -> f64 {
149 let c = f64::from(c.clamp(0.0, 1.0));
150 if c <= 0.040_45 {
151 c / 12.92
152 } else {
153 ((c + 0.055) / 1.055).powf(2.4)
154 }
155}
156
157pub(crate) fn linear_to_oklab(r: f64, g: f64, b: f64) -> [f64; 3] {
159 let l = 0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b;
160 let m = 0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b;
161 let s = 0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b;
162 let (l, m, s) = (l.cbrt(), m.cbrt(), s.cbrt());
163 [
164 0.210_454_255_3 * l + 0.793_617_785_0 * m - 0.004_072_046_8 * s,
165 1.977_998_495_1 * l - 2.428_592_205_0 * m + 0.450_593_709_9 * s,
166 0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766_0 * s,
167 ]
168}
169
170fn encode(x: f64) -> f32 {
172 let x = x.clamp(0.0, 1.0);
173 let v = if x <= 0.003_130_8 {
174 12.92 * x
175 } else {
176 1.055 * x.powf(1.0 / 2.4) - 0.055
177 };
178 v as f32
179}
180
181pub fn contrast_ratio(foreground: Color, background: Color) -> f32 {
185 let background = Color {
186 a: 1.0,
187 ..background
188 };
189 let fg = foreground.over(background).relative_luminance();
190 let bg = background.relative_luminance();
191 let (hi, lo) = if fg > bg { (fg, bg) } else { (bg, fg) };
192 (hi + 0.05) / (lo + 0.05)
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn hex_round_trips() {
201 for text in ["#000000", "#f0c060", "#12345678"] {
202 assert_eq!(Color::from_hex(text).unwrap().to_hex(), text);
203 }
204 assert_eq!(Color::from_hex("#fff"), Some(Color::WHITE));
205 assert_eq!(Color::from_hex("f0c060"), None);
206 assert_eq!(Color::from_hex("#f0c06"), None);
207 assert_eq!(Color::from_hex("#gg0000"), None);
208 }
209
210 #[test]
211 fn contrast_matches_wcag_reference_values() {
212 assert!((contrast_ratio(Color::BLACK, Color::WHITE) - 21.0).abs() < 1e-3);
213 assert!((contrast_ratio(Color::WHITE, Color::WHITE) - 1.0).abs() < 1e-6);
214 let grey = Color::from_hex("#767676").unwrap();
216 assert!((contrast_ratio(grey, Color::WHITE) - 4.54).abs() < 0.01);
217 assert_eq!(
219 contrast_ratio(grey, Color::BLACK),
220 contrast_ratio(Color::BLACK, grey)
221 );
222 }
223
224 #[test]
225 fn translucent_foregrounds_are_composited_first() {
226 let half_white = Color {
227 a: 0.5,
228 ..Color::WHITE
229 };
230 let r = contrast_ratio(half_white, Color::BLACK);
231 assert!(r > 1.0 && r < 21.0 / 2.0, "{r}");
232 }
233
234 #[test]
235 fn oklch_converts_to_srgb() {
236 assert_eq!(Color::from_oklch(1.0, 0.0, 0.0, 1.0).to_hex(), "#ffffff");
237 assert_eq!(Color::from_oklch(0.0, 0.0, 0.0, 1.0).to_hex(), "#000000");
238 assert_eq!(
240 Color::from_oklch(0.832, 0.126, 83.0, 1.0).to_hex(),
241 "#f0c060"
242 );
243 }
244}