forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

custom_colour.rs475 lines, 17.0 KiBHistoryRawDownload
1//! Colours for any hue. A stored `hue-N` id (see `accent::hue_of`) is not a row of
2//! `accent_palette.rs`: its colours are built here from the OKLCH hue N, in the same roles a preset
3//! has. The accent sits at one lightness and chroma, with black or white text by contrast. The
4//! background is a neutral with a little chroma toward the hue. `stylesheet` writes the rules that
5//! apply them, in the shape `build.rs` writes for the presets.
6
7/// The colours of one accent in one theme: the fields of `accent_palette::Tokens`, owned, because a
8/// hue is built at run time.
9#[derive(Debug, Clone)]
10pub struct OwnedTokens {
11 pub accent: String,
12 pub accent_ink: String,
13 pub accent_soft: String,
14 pub accent_text: String,
15 pub focus: String,
16 pub public_bg: String,
17 pub public_text: String,
18 pub note: String,
19 pub hunk_bg: String,
20 pub hunk_text: String,
21}
22
23impl OwnedTokens {
24 /// The `(property, value)` pairs, in the order of `accent_palette::TOKEN_VARS`.
25 pub fn decls(&self) -> Vec<(&'static str, &str)> {
26 vec![
27 ("--accent", self.accent.as_str()),
28 ("--accent-ink", self.accent_ink.as_str()),
29 ("--accent-soft", self.accent_soft.as_str()),
30 ("--accent-text", self.accent_text.as_str()),
31 ("--focus", self.focus.as_str()),
32 ("--public-bg", self.public_bg.as_str()),
33 ("--public-text", self.public_text.as_str()),
34 ("--note", self.note.as_str()),
35 ("--hunk-bg", self.hunk_bg.as_str()),
36 ("--hunk-text", self.hunk_text.as_str()),
37 ]
38 }
39}
40
41/// The neutral colours of one base in one theme: the fields of `accent_palette::BaseTokens`, owned.
42#[derive(Debug, Clone)]
43pub struct OwnedBaseTokens {
44 pub bg: String,
45 pub surface: String,
46 pub surface_2: String,
47 pub text: String,
48 pub text_2: String,
49 pub muted: String,
50 pub border: String,
51 pub border_strong: String,
52 pub code_bg: String,
53 pub private_bg: String,
54 pub private_text: String,
55 pub ln_text: String,
56}
57
58impl OwnedBaseTokens {
59 /// The `(property, value)` pairs, in the order of `accent_palette::BASE_TOKEN_VARS`.
60 pub fn decls(&self) -> Vec<(&'static str, &str)> {
61 vec![
62 ("--bg", self.bg.as_str()),
63 ("--surface", self.surface.as_str()),
64 ("--surface-2", self.surface_2.as_str()),
65 ("--text", self.text.as_str()),
66 ("--text-2", self.text_2.as_str()),
67 ("--muted", self.muted.as_str()),
68 ("--border", self.border.as_str()),
69 ("--border-strong", self.border_strong.as_str()),
70 ("--code-bg", self.code_bg.as_str()),
71 ("--private-bg", self.private_bg.as_str()),
72 ("--private-text", self.private_text.as_str()),
73 ("--ln-text", self.ln_text.as_str()),
74 ]
75 }
76}
77
78/// Chroma of the neutrals: small, like the bases on offer.
79const NEUTRAL_CHROMA: f64 = 0.012;
80
81/// Slack for float error when testing whether a colour is inside sRGB.
82const GAMUT_EPS: f64 = 1e-6;
83
84/// The chroma factor of an accent at vividness `vivid` (0..=100). The default, 50, gives exactly 1.0
85/// so the legacy `hue-N` colours stay byte-identical.
86fn accent_factor(vivid: u8) -> f64 {
87 if vivid == 50 {
88 return 1.0;
89 }
90 (0.03 + 0.16 * f64::from(vivid) / 100.0) / 0.11
91}
92
93/// The accent colours for a hue, in one theme, at a vividness (0..=100; 50 is the default). Light:
94/// a mid accent with its ink darker than it. Dark: a light accent with its ink lighter than it, on
95/// a dark soft tint. Every chroma is scaled by the vividness; the gamut clamp in `colour` holds the
96/// lightness and hue.
97pub fn accent_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedTokens {
98 let h = f64::from(hue);
99 let f = accent_factor(vivid);
100 let c = |lightness: f64, chroma: f64| colour(lightness, chroma * f, h);
101 let (accent, ink, soft, hunk_bg) = if dark {
102 (c(0.75, 0.11), c(0.84, 0.09), c(0.27, 0.04), c(0.22, 0.03))
103 } else {
104 (
105 c(0.52, 0.12),
106 c(0.46, 0.12),
107 c(0.95, 0.025),
108 c(0.975, 0.012),
109 )
110 };
111 OwnedTokens {
112 accent_text: text_on(&accent),
113 focus: if dark { accent.clone() } else { ink.clone() },
114 hunk_text: if dark { accent.clone() } else { c(0.44, 0.10) },
115 public_bg: soft.clone(),
116 public_text: ink.clone(),
117 note: ink.clone(),
118 accent_ink: ink,
119 accent_soft: soft,
120 hunk_bg,
121 accent,
122 }
123}
124
125/// The neutral colours for a hue, in one theme, at a vividness (0..=100; 30 is the default). Each is
126/// a tint of the hue at `NEUTRAL_CHROMA` scaled by the vividness, at the lightness the presets use
127/// for that role. Vividness 0 is a grey. If the text, surface or muted colour reads below WCAG 4.5:1,
128/// the chroma steps down by 0.8, at most ten times, until it passes.
129pub fn base_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedBaseTokens {
130 let mut factor = f64::from(vivid) / 30.0;
131 let mut tokens = base_tokens_at(hue, factor, dark);
132 for _ in 0..10 {
133 if base_is_readable(&tokens) {
134 break;
135 }
136 factor *= 0.8;
137 tokens = base_tokens_at(hue, factor, dark);
138 }
139 tokens
140}
141
142/// True when the text, the surface and the muted colour all read at 4.5:1 or more on the background.
143fn base_is_readable(tokens: &OwnedBaseTokens) -> bool {
144 const MIN: f64 = 4.5;
145 contrast_ratio(&tokens.text, &tokens.bg) >= MIN
146 && contrast_ratio(&tokens.text, &tokens.surface) >= MIN
147 && contrast_ratio(&tokens.muted, &tokens.bg) >= MIN
148}
149
150/// The neutral colours of a base at one chroma factor (1.0 is the default vividness).
151fn base_tokens_at(hue: u16, factor: f64, dark: bool) -> OwnedBaseTokens {
152 let h = f64::from(hue);
153 let n = |l: f64| colour(l, NEUTRAL_CHROMA * factor, h);
154 if dark {
155 let surface_2 = n(0.26);
156 let text_2 = n(0.82);
157 OwnedBaseTokens {
158 bg: n(0.19),
159 surface: n(0.225),
160 text: n(0.93),
161 muted: n(0.70),
162 border: n(0.30),
163 border_strong: n(0.38),
164 code_bg: surface_2.clone(),
165 private_bg: surface_2.clone(),
166 surface_2,
167 private_text: text_2.clone(),
168 text_2,
169 ln_text: n(0.70),
170 }
171 } else {
172 let surface_2 = n(0.945);
173 let text_2 = n(0.33);
174 OwnedBaseTokens {
175 bg: n(0.972),
176 surface: "#FFFFFF".to_owned(),
177 text: n(0.23),
178 muted: n(0.52),
179 border: n(0.89),
180 border_strong: n(0.82),
181 code_bg: surface_2.clone(),
182 private_bg: surface_2.clone(),
183 surface_2,
184 private_text: text_2.clone(),
185 text_2,
186 ln_text: n(0.50),
187 }
188 }
189}
190
191/// The `#RRGGBB` of an OKLCH colour (lightness 0..1, chroma, hue in degrees). Chroma is cut back
192/// until the colour fits sRGB, so the lightness and the hue hold.
193pub fn colour(lightness: f64, chroma: f64, hue: f64) -> String {
194 let c = fit_chroma(lightness, chroma, hue);
195 let [r, g, b] = oklch_to_linear(lightness, c, hue)
196 .map(|v| (encode(v.clamp(0.0, 1.0)) * 255.0).round() as u8);
197 format!("#{r:02X}{g:02X}{b:02X}")
198}
199
200/// The OKLCH hue of a `#RRGGBB` colour, rounded to a whole degree in `0..360`.
201#[allow(dead_code)] // Used by the preset hues, which the settings picker reads.
202pub fn hex_hue(hex: &str) -> u16 {
203 let (_, _, hue) = linear_to_oklch(hex_linear(hex));
204 (hue.round() as u16) % 360
205}
206
207/// The WCAG contrast ratio between two `#RRGGBB` colours.
208pub fn contrast_ratio(a: &str, b: &str) -> f64 {
209 let (x, y) = (relative_luminance(a), relative_luminance(b));
210 (x.max(y) + 0.05) / (x.min(y) + 0.05)
211}
212
213/// One custom choice of `stylesheet`: the id as stored, its hue and its vividness. The id is the
214/// stored string, so the selector matches the `<html>` attribute (a legacy `hue-N` stays `hue-N`).
215pub type CustomSlot<'a> = Option<(&'a str, u16, u8)>;
216
217/// The rules for the custom ids of one stylesheet: each slot is an accent or base id with its hue
218/// and vividness (`None` for a preset, which `build.rs` already styles). They mirror `build.rs`: the
219/// light tokens go on the light attribute, the dark tokens on the dark attribute in both dark states.
220pub fn stylesheet(
221 accent_light: CustomSlot,
222 accent_dark: CustomSlot,
223 base_light: CustomSlot,
224 base_dark: CustomSlot,
225) -> String {
226 let mut css = String::new();
227 if let Some((id, hue, vivid)) = accent_light {
228 let selector = format!(":root[data-accent-light=\"{id}\"]");
229 rule(
230 &mut css,
231 "",
232 &selector,
233 &accent_tokens(hue, vivid, false).decls(),
234 );
235 }
236 if let Some((id, hue, vivid)) = accent_dark {
237 let selector = format!(":root[data-accent-dark=\"{id}\"]");
238 dark_rules(
239 &mut css,
240 &selector,
241 &accent_tokens(hue, vivid, true).decls(),
242 );
243 }
244 if let Some((id, hue, vivid)) = base_light {
245 let selector = format!(":root[data-base-light=\"{id}\"]");
246 rule(
247 &mut css,
248 "",
249 &selector,
250 &base_tokens(hue, vivid, false).decls(),
251 );
252 }
253 if let Some((id, hue, vivid)) = base_dark {
254 let selector = format!(":root[data-base-dark=\"{id}\"]");
255 dark_rules(&mut css, &selector, &base_tokens(hue, vivid, true).decls());
256 }
257 css
258}
259
260/// Appends `selector { … }` with one `--token: value;` line per declaration. `indent` is 0 or 2.
261fn rule(css: &mut String, indent: &str, selector: &str, decls: &[(&str, &str)]) {
262 css.push_str(&format!("{indent}{selector} {{\n"));
263 for (name, value) in decls {
264 css.push_str(&format!("{indent} {name}: {value};\n"));
265 }
266 css.push_str(&format!("{indent}}}\n"));
267}
268
269/// The dark rules for one choice: by the OS, and by `data-theme`. The `:not` and the second
270/// attribute add specificity, so they win over the light rule whatever the light choice is.
271fn dark_rules(css: &mut String, selector: &str, decls: &[(&str, &str)]) {
272 css.push_str("@media (prefers-color-scheme: dark) {\n");
273 rule(
274 css,
275 " ",
276 &format!("{selector}:not([data-theme=\"light\"])"),
277 decls,
278 );
279 css.push_str("}\n");
280 rule(css, "", &format!("{selector}[data-theme=\"dark\"]"), decls);
281}
282
283/// The text colour on a fill: white or near-black, whichever reads better.
284fn text_on(fill: &str) -> String {
285 const WHITE: &str = "#FFFFFF";
286 const INK: &str = "#111111";
287 if contrast_ratio(WHITE, fill) >= contrast_ratio(INK, fill) {
288 WHITE.to_owned()
289 } else {
290 INK.to_owned()
291 }
292}
293
294/// The largest chroma up to `chroma` that fits sRGB at this lightness and hue.
295fn fit_chroma(lightness: f64, chroma: f64, hue: f64) -> f64 {
296 if in_gamut(lightness, chroma, hue) {
297 return chroma;
298 }
299 let (mut low, mut high) = (0.0, chroma);
300 for _ in 0..32 {
301 let mid = (low + high) / 2.0;
302 if in_gamut(lightness, mid, hue) {
303 low = mid;
304 } else {
305 high = mid;
306 }
307 }
308 low
309}
310
311fn in_gamut(lightness: f64, chroma: f64, hue: f64) -> bool {
312 oklch_to_linear(lightness, chroma, hue)
313 .iter()
314 .all(|v| (-GAMUT_EPS..=1.0 + GAMUT_EPS).contains(v))
315}
316
317/// OKLCH to linear sRGB. A channel can fall outside `0..=1` when the colour is out of gamut.
318fn oklch_to_linear(lightness: f64, chroma: f64, hue: f64) -> [f64; 3] {
319 let (sin, cos) = hue.to_radians().sin_cos();
320 let a = chroma * cos;
321 let b = chroma * sin;
322 let l = lightness + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
323 let m = lightness - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
324 let s = lightness - 0.089_484_177_5 * a - 1.291_485_548 * b;
325 let (l, m, s) = (l * l * l, m * m * m, s * s * s);
326 [
327 4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s,
328 -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s,
329 -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701 * s,
330 ]
331}
332
333/// Linear sRGB to OKLCH: lightness, chroma and hue in degrees.
334#[allow(dead_code)] // Used by `hex_hue`, which the settings picker reads through the preset hues.
335fn linear_to_oklch([r, g, b]: [f64; 3]) -> (f64, f64, f64) {
336 let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
337 let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
338 let s = (0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b).cbrt();
339 let lightness = 0.210_454_255_3 * l + 0.793_617_785 * m - 0.004_072_046_8 * s;
340 let a = 1.977_998_495_1 * l - 2.428_592_205 * m + 0.450_593_709_9 * s;
341 let b = 0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766 * s;
342 (
343 lightness,
344 a.hypot(b),
345 b.atan2(a).to_degrees().rem_euclid(360.0),
346 )
347}
348
349fn relative_luminance(hex: &str) -> f64 {
350 let [r, g, b] = hex_linear(hex);
351 0.2126 * r + 0.7152 * g + 0.0722 * b
352}
353
354/// The linear sRGB channels of a `#RRGGBB` colour. Our own colours only, so a bad one is a bug.
355fn hex_linear(hex: &str) -> [f64; 3] {
356 let channel = |i: usize| {
357 let byte = u8::from_str_radix(&hex[i..i + 2], 16).expect("a #RRGGBB colour");
358 decode(f64::from(byte) / 255.0)
359 };
360 [channel(1), channel(3), channel(5)]
361}
362
363/// sRGB transfer function, encoded value to linear light.
364fn decode(v: f64) -> f64 {
365 if v <= 0.040_45 {
366 v / 12.92
367 } else {
368 ((v + 0.055) / 1.055).powf(2.4)
369 }
370}
371
372/// Linear light to the sRGB encoded value.
373fn encode(v: f64) -> f64 {
374 if v <= 0.003_130_8 {
375 12.92 * v
376 } else {
377 1.055 * v.powf(1.0 / 2.4) - 0.055
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384 use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS};
385
386 fn is_hex_colour(value: &str) -> bool {
387 value.len() == 7
388 && value.starts_with('#')
389 && value[1..].bytes().all(|b| b.is_ascii_hexdigit())
390 }
391
392 #[test]
393 fn the_extremes_are_exact_and_a_preset_hue_reads_back() {
394 assert_eq!(colour(1.0, 0.0, 0.0), "#FFFFFF");
395 assert_eq!(colour(0.0, 0.0, 0.0), "#000000");
396 // Sage is about 149 degrees; Ocean about 240.
397 assert_eq!(hex_hue("#5E7D63"), 149);
398 assert_eq!(hex_hue("#467799"), 240);
399 }
400
401 #[test]
402 fn every_hue_gives_hex_colours_with_the_right_token_names_and_keyed_rules() {
403 for hue in 0..360 {
404 for dark in [false, true] {
405 let accent = accent_tokens(hue, 50, dark);
406 let names: Vec<&str> = accent.decls().iter().map(|(n, _)| *n).collect();
407 let expected: Vec<&str> = TOKEN_VARS.iter().map(|t| t.name).collect();
408 assert_eq!(names, expected);
409 for (name, value) in accent.decls() {
410 assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}");
411 }
412 let base = base_tokens(hue, 30, dark);
413 let names: Vec<&str> = base.decls().iter().map(|(n, _)| *n).collect();
414 let expected: Vec<&str> = BASE_TOKEN_VARS.iter().map(|t| t.name).collect();
415 assert_eq!(names, expected);
416 for (name, value) in base.decls() {
417 assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}");
418 }
419 }
420 }
421 let css = stylesheet(
422 Some(("hue-215", 215, 50)),
423 Some(("hue-215", 215, 50)),
424 None,
425 Some(("hue-7", 7, 30)),
426 );
427 assert!(
428 css.contains(":root[data-accent-light=\"hue-215\"] {\n --accent: #"),
429 "{css}"
430 );
431 assert!(
432 css.contains(
433 "@media (prefers-color-scheme: dark) {\n :root[data-accent-dark=\"hue-215\"]:not([data-theme=\"light\"]) {"
434 ),
435 "{css}"
436 );
437 assert!(
438 css.contains(":root[data-accent-dark=\"hue-215\"][data-theme=\"dark\"] {"),
439 "{css}"
440 );
441 assert!(
442 css.contains(":root[data-base-dark=\"hue-7\"][data-theme=\"dark\"] {"),
443 "{css}"
444 );
445 assert!(!css.contains("data-base-light"), "{css}");
446 assert!(stylesheet(None, None, None, None).is_empty());
447 }
448
449 #[test]
450 fn legacy_and_explicit_default_vividness_give_the_same_accent() {
451 let legacy = crate::accent::custom_of("hue-215", 50).unwrap();
452 let explicit = crate::accent::custom_of("hue-215-v50", 50).unwrap();
453 assert_eq!(legacy, explicit);
454 for dark in [false, true] {
455 let a = accent_tokens(legacy.0, legacy.1, dark);
456 let b = accent_tokens(explicit.0, explicit.1, dark);
457 assert_eq!(a.decls(), b.decls());
458 }
459 }
460
461 #[test]
462 fn full_vividness_bases_keep_text_readable() {
463 for hue in (0..360).step_by(30) {
464 for dark in [false, true] {
465 let base = base_tokens(hue, 100, dark);
466 assert!(
467 contrast_ratio(&base.text, &base.bg) >= 4.5,
468 "{hue} {dark}: {} on {}",
469 base.text,
470 base.bg
471 );
472 }
473 }
474 }
475}