Skip to main content

egui_pop_tokens/
apca.rs

1//! APCA lightness contrast (Lc), informative only.
2//!
3//! The Accessible Perceptual Contrast Algorithm, as published with the
4//! WCAG 3 working draft (APCA-W3, constants of version 0.0.98G): a
5//! contrast that depends on which colour is the text and which the
6//! background, and on their polarity. Lc runs from about -108 (white
7//! text on black) to about 106 (black text on white); its sign says the
8//! polarity (positive: dark text on a light background), its size how
9//! readable the text is (Lc 60 is the floor for ordinary text, Lc 75 for
10//! body text, Lc 45 for large text and solid interface parts).
11//!
12//! egui-pop's theme contract stays on WCAG 2.x ([`crate::contrast`]):
13//! Lc is used where a direction must be chosen, to pick the text colour
14//! of an accent fill and to set the fill's lightness
15//! ([`crate::palette`]), and shown beside the WCAG ratio. This is a
16//! reimplementation of the published formula; egui_colors (MIT) does
17//! the same (`estimate_lc`).
18
19use crate::Color;
20
21// The exponents of the four polarity cases.
22const NORM_BG: f64 = 0.56;
23const NORM_TXT: f64 = 0.57;
24const REV_TXT: f64 = 0.62;
25const REV_BG: f64 = 0.65;
26// The soft clamp of near-black luminances.
27const BLACK_THRESHOLD: f64 = 0.022;
28const BLACK_CLAMP: f64 = 1.414;
29// Scaling, offsets and the low clip.
30const SCALE: f64 = 1.14;
31const LOW_OFFSET: f64 = 0.027;
32const LOW_CLIP: f64 = 0.1;
33const DELTA_Y_MIN: f64 = 0.0005;
34
35/// The screen luminance APCA reads: each sRGB channel raised to 2.4 (no
36/// linear segment), weighted as sRGB's luminance.
37fn screen_y(c: Color) -> f64 {
38    let ch = |v: f32| f64::from(v.clamp(0.0, 1.0)).powf(2.4);
39    0.212_672_9 * ch(c.r) + 0.715_152_2 * ch(c.g) + 0.072_175_0 * ch(c.b)
40}
41
42fn soft_clamp(y: f64) -> f64 {
43    if y > BLACK_THRESHOLD {
44        y
45    } else {
46        y + (BLACK_THRESHOLD - y).powf(BLACK_CLAMP)
47    }
48}
49
50/// The lightness contrast of `text` over `background`, alpha ignored
51/// (a translucent text is first painted over the background). Positive
52/// for dark text on a light background, negative for light text on a
53/// dark one; 0 when the two are too close to tell.
54///
55/// ```
56/// use egui_pop_tokens::{Color, apca};
57///
58/// let lc = apca::lc(Color::BLACK, Color::WHITE);
59/// assert!((lc - 106.04).abs() < 0.1);
60/// assert!(apca::lc(Color::WHITE, Color::BLACK) < -107.0);
61/// ```
62pub fn lc(text: Color, background: Color) -> f32 {
63    let background = Color {
64        a: 1.0,
65        ..background
66    };
67    let txt = soft_clamp(screen_y(text.over(background)));
68    let bg = soft_clamp(screen_y(background));
69    if (bg - txt).abs() < DELTA_Y_MIN {
70        return 0.0;
71    }
72    let out = if bg > txt {
73        let c = (bg.powf(NORM_BG) - txt.powf(NORM_TXT)) * SCALE;
74        if c < LOW_CLIP { 0.0 } else { c - LOW_OFFSET }
75    } else {
76        let c = (bg.powf(REV_BG) - txt.powf(REV_TXT)) * SCALE;
77        if c > -LOW_CLIP { 0.0 } else { c + LOW_OFFSET }
78    };
79    (out * 100.0) as f32
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    fn hex(s: &str) -> Color {
87        Color::from_hex(s).unwrap()
88    }
89
90    #[test]
91    fn matches_the_published_reference_values() {
92        // The reference pairs given with APCA-W3 0.0.98G.
93        let cases = [
94            ("#888888", "#ffffff", 63.06),
95            ("#ffffff", "#888888", -68.54),
96            ("#000000", "#aaaaaa", 58.15),
97            ("#aaaaaa", "#000000", -56.24),
98            ("#112233", "#ddeeff", 91.67),
99            ("#ddeeff", "#112233", -93.07),
100            ("#112233", "#444444", 8.32),
101            ("#444444", "#112233", -7.52),
102        ];
103        for (text, bg, want) in cases {
104            let got = lc(hex(text), hex(bg));
105            assert!(
106                (got - want).abs() < 0.2,
107                "{text} on {bg}: {got} (want {want})"
108            );
109        }
110    }
111
112    #[test]
113    fn the_same_colour_has_no_contrast() {
114        assert_eq!(lc(hex("#808080"), hex("#808080")), 0.0);
115    }
116}