Skip to main content

egui_pop_tokens/
contrast.rs

1//! Contrast checks: the token pairs that must stay legible, and the WCAG
2//! 2.x ratios they must reach.
3
4use std::fmt;
5
6pub use crate::color::contrast_ratio;
7use crate::contract::CATEGORY;
8use crate::{Color, ResolvedTokens};
9
10/// What a pair is: text to read, or a user-interface part to see.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum PairKind {
13    /// Text over a background: 4.5:1 (WCAG 1.4.3), 7:1 in high contrast
14    /// (1.4.6).
15    Text,
16    /// A control's boundary, a state or a focus indicator over what is
17    /// around it: 3:1 (WCAG 1.4.11).
18    Ui,
19}
20
21/// The level a theme is checked at.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Level {
24    /// WCAG AA.
25    Normal,
26    /// WCAG AAA for text, for high-contrast themes.
27    High,
28}
29
30impl Level {
31    /// The ratio a pair of this kind must reach at this level.
32    pub fn required(self, kind: PairKind) -> f32 {
33        match (kind, self) {
34            (PairKind::Text, Level::Normal) => 4.5,
35            (PairKind::Text, Level::High) => 7.0,
36            (PairKind::Ui, _) => 3.0,
37        }
38    }
39}
40
41/// A foreground token over a background token.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct Pair {
44    pub foreground: &'static str,
45    pub background: &'static str,
46    pub kind: PairKind,
47}
48
49const fn text(foreground: &'static str, background: &'static str) -> Pair {
50    Pair {
51        foreground,
52        background,
53        kind: PairKind::Text,
54    }
55}
56
57const fn ui(foreground: &'static str, background: &'static str) -> Pair {
58    Pair {
59        foreground,
60        background,
61        kind: PairKind::Ui,
62    }
63}
64
65/// Every pair checked, listed by hand: where text is drawn and where a
66/// control must be seen. Decorative borders (`border.default`) are not
67/// in it.
68pub const PAIRS: &[Pair] = &[
69    // Ordinary text wherever it is drawn.
70    text("text.default", "surface.canvas"),
71    text("text.default", "surface.panel"),
72    text("text.default", "surface.raised"),
73    text("text.default", "surface.hover"),
74    text("text.default", "surface.overlay"),
75    text("text.default", "surface.sunken"),
76    text("text.default", "selection"),
77    // Text under the pointer or pressed, and titles.
78    text("text.strong", "surface.panel"),
79    text("text.strong", "surface.hover"),
80    text("text.strong", "surface.active"),
81    // Secondary text.
82    text("text.muted", "surface.canvas"),
83    text("text.muted", "surface.panel"),
84    text("text.muted", "surface.raised"),
85    text("text.muted", "surface.overlay"),
86    text("text.muted", "surface.sunken"),
87    // Text by role, on panels and on the raised surface cards use.
88    text("text-role.title.color", "surface.panel"),
89    text("text-role.title.color", "surface.raised"),
90    text("text-role.section.color", "surface.panel"),
91    text("text-role.section.color", "surface.raised"),
92    text("text-role.body.color", "surface.panel"),
93    text("text-role.body.color", "surface.raised"),
94    text("text-role.strong.color", "surface.panel"),
95    text("text-role.strong.color", "surface.raised"),
96    text("text-role.muted.color", "surface.panel"),
97    text("text-role.muted.color", "surface.raised"),
98    text("text-role.meta.color", "surface.panel"),
99    text("text-role.meta.color", "surface.raised"),
100    // Labels on accent fills, and the accent as link text.
101    text("text.on-accent", "accent.default"),
102    text("text.on-accent", "accent.hover"),
103    text("accent.default", "surface.panel"),
104    // Status colours are used as text.
105    text("danger", "surface.panel"),
106    text("danger", "surface.overlay"),
107    text("warning", "surface.panel"),
108    text("warning", "surface.overlay"),
109    text("success", "surface.panel"),
110    text("success", "surface.overlay"),
111    text("info", "surface.panel"),
112    text("info", "surface.overlay"),
113    // Log levels colour a log view's text, on the canvas or a panel.
114    text("palette.log.trace", "surface.canvas"),
115    text("palette.log.trace", "surface.panel"),
116    text("palette.log.debug", "surface.canvas"),
117    text("palette.log.debug", "surface.panel"),
118    text("palette.log.info", "surface.canvas"),
119    text("palette.log.info", "surface.panel"),
120    text("palette.log.warn", "surface.canvas"),
121    text("palette.log.warn", "surface.panel"),
122    text("palette.log.error", "surface.canvas"),
123    text("palette.log.error", "surface.panel"),
124    text("palette.log.critical", "surface.canvas"),
125    text("palette.log.critical", "surface.panel"),
126    // Components.
127    text("button.rest.text", "button.rest.fill"),
128    // Buttons by tone: the label on the tone's fill.
129    text("button.tone.accent.text", "button.tone.accent.fill"),
130    text(
131        "button.tone.accent.hover.text",
132        "button.tone.accent.hover.fill",
133    ),
134    text("button.tone.info.text", "button.tone.info.fill"),
135    text("button.tone.success.text", "button.tone.success.fill"),
136    text("button.tone.warning.text", "button.tone.warning.fill"),
137    text("button.tone.danger.text", "button.tone.danger.fill"),
138    text("button.tone.record.text", "button.tone.record.fill"),
139    text("menu-item.rest.text", "menu-item.hover.fill"),
140    text("menu-item.tone.muted.text", "surface.overlay"),
141    text("toast.rest.text", "toast.rest.fill"),
142    text("tooltip.rest.text", "tooltip.rest.fill"),
143    text("field.rest.text", "field.rest.fill"),
144    text("field.rest.text", "field.tone.muted.fill"),
145    text("field.tone.muted.text", "field.rest.fill"),
146    text("field.tone.danger.border-color", "surface.panel"),
147    text("dialog-header.rest.text", "header-band.rest.fill"),
148    text("header-band.rest.text", "header-band.rest.fill"),
149    text("band-icon-button.rest.text", "header-band.rest.fill"),
150    text(
151        "command-palette-row.rest.text",
152        "command-palette-row.selected.fill",
153    ),
154    text("pill.rest.text", "pill.rest.fill"),
155    text("readout.rest.text", "readout.rest.fill"),
156    // Editors: code over its background, line numbers over the gutter.
157    text("editor.line-number", "editor.gutter"),
158    text("editor.line-number-active", "editor.gutter"),
159    text("syntax.plain", "editor-frame.rest.fill"),
160    text("syntax.plain", "editor.current-line"),
161    text("syntax.plain", "editor.selection"),
162    text("syntax.keyword", "editor-frame.rest.fill"),
163    text("syntax.string", "editor-frame.rest.fill"),
164    text("syntax.number", "editor-frame.rest.fill"),
165    text("syntax.comment", "editor-frame.rest.fill"),
166    text("syntax.function", "editor-frame.rest.fill"),
167    text("syntax.type", "editor-frame.rest.fill"),
168    text("syntax.invalid", "editor-frame.rest.fill"),
169    ui("editor.cursor", "editor-frame.rest.fill"),
170    ui("editor.error", "editor.gutter"),
171    ui("editor.warning", "editor.gutter"),
172    ui("editor.breakpoint", "editor.gutter"),
173    // The terminal: its text over its background and the selection.
174    text("terminal.foreground", "terminal-frame.rest.fill"),
175    text("terminal.foreground", "terminal.selection"),
176    ui("terminal.cursor", "terminal-frame.rest.fill"),
177    // A cursor's strokes against the ring that carries them over images.
178    ui("cursor.fill", "cursor.outline"),
179    // Things that must be seen.
180    ui("border.strong", "surface.panel"),
181    ui("border.strong", "surface.raised"),
182    ui("border.strong", "surface.overlay"),
183    ui("focus.ring", "surface.panel"),
184    ui("focus.ring", "surface.raised"),
185    ui("focus.ring", "surface.overlay"),
186    ui("focus.ring", "surface.sunken"),
187    ui("accent.default", "surface.raised"),
188    ui("slider-fill.rest.fill", "slider.rest.fill"),
189    ui("progress-fill.rest.fill", "progress-bar.rest.fill"),
190    ui("slider-thumb.rest.fill", "slider.rest.fill"),
191    // Input fields: the state edges and markers over the field.
192    ui("field.tone.accent.border-color", "field.rest.fill"),
193    ui("field.tone.warning.border-color", "field.rest.fill"),
194    ui("field.tone.danger.border-color", "field.rest.fill"),
195    ui("field.tone.info.border-color", "field.rest.fill"),
196    // A card's edge in a tone, on the panel it sits on.
197    ui("card.tone.accent.border-color", "surface.panel"),
198    ui("card.tone.info.border-color", "surface.panel"),
199    ui("card.tone.success.border-color", "surface.panel"),
200    ui("card.tone.warning.border-color", "surface.panel"),
201    ui("card.tone.danger.border-color", "surface.panel"),
202    ui("card.tone.record.border-color", "surface.panel"),
203    ui("toast.rest.border-color", "surface.panel"),
204    // Micro-indicators: badge text on every tone's fill, the marks that
205    // carry a state on the surfaces they sit on, the outline against
206    // what it separates.
207    text("indicator-badge.rest.text", "indicator-badge.rest.fill"),
208    text(
209        "indicator-badge.rest.text",
210        "indicator-badge.tone.accent.fill",
211    ),
212    text(
213        "indicator-badge.rest.text",
214        "indicator-badge.tone.info.fill",
215    ),
216    text(
217        "indicator-badge.rest.text",
218        "indicator-badge.tone.success.fill",
219    ),
220    text(
221        "indicator-badge.rest.text",
222        "indicator-badge.tone.warning.fill",
223    ),
224    text(
225        "indicator-badge.rest.text",
226        "indicator-badge.tone.danger.fill",
227    ),
228    text(
229        "indicator-badge.rest.text",
230        "indicator-badge.tone.muted.fill",
231    ),
232    text(
233        "indicator-badge.rest.text",
234        "indicator-badge.tone.record.fill",
235    ),
236    ui("indicator-dot.tone.record.fill", "surface.panel"),
237    ui("indicator-dot.tone.record.fill", "surface.overlay"),
238    ui("indicator-dot.rest.border-color", "surface.panel"),
239    ui("indicator-dot.rest.border-color", "surface.overlay"),
240    ui("indicator-swatch.rest.border-color", "surface.panel"),
241    ui("indicator-swatch.rest.border-color", "surface.overlay"),
242    // A section's band: its title on the panel and under the pointer,
243    // its count on its pill, its disclosure mark on the panel.
244    text("section-band.rest.text", "surface.panel"),
245    text("section-band.rest.text", "section-band.hover.fill"),
246    text("section-count.rest.text", "section-count.rest.fill"),
247    ui("section-disclosure.rest.text", "surface.panel"),
248    ui(
249        "indicator-dot.tone.accent.fill",
250        "indicator-outline.rest.ring-color",
251    ),
252    ui(
253        "indicator-dot.tone.danger.fill",
254        "indicator-outline.rest.ring-color",
255    ),
256    // A rating's stars: a given star and an empty star's outline on the
257    // surfaces they sit on (an empty star is what says the item can be
258    // rated). The preview and the ghost are lighter on purpose, between
259    // the two.
260    ui("rating-star.selected.fill", "surface.panel"),
261    ui("rating-star.selected.fill", "surface.raised"),
262    ui("rating-star.rest.border-color", "surface.panel"),
263    ui("rating-star.rest.border-color", "surface.raised"),
264    ui("rating-star-display.selected.fill", "surface.panel"),
265    // A curve and its points over the curve editor's background.
266    ui("curve.line", "curve.background"),
267    ui("curve.point", "curve.background"),
268    // A selected node's outline over the node.
269    ui("graph.node-selected", "graph.node"),
270    // A hovered and a selected wire over the canvas.
271    ui("graph.wire-hover.color", "graph.background"),
272    ui("graph.wire-selected.color", "graph.background"),
273    // A plot: its axis text and its time cursor, at rest and under the
274    // pointer, over its background. Its grid (`plot.grid-color`) is a
275    // decoration, as `border.default` is: not checked.
276    text("plot.rest.text", "plot.rest.fill"),
277    ui("plot-cursor.rest.fill", "plot.rest.fill"),
278    ui("plot-cursor.hover.fill", "plot.rest.fill"),
279    // The categorical palette's series, on the surfaces charts are
280    // drawn on (WCAG 1.4.11, a graphical object).
281    ui("palette.category.0", "surface.canvas"),
282    ui("palette.category.0", "surface.panel"),
283    ui("palette.category.0", "surface.raised"),
284    ui("palette.category.1", "surface.canvas"),
285    ui("palette.category.1", "surface.panel"),
286    ui("palette.category.1", "surface.raised"),
287    ui("palette.category.2", "surface.canvas"),
288    ui("palette.category.2", "surface.panel"),
289    ui("palette.category.2", "surface.raised"),
290    ui("palette.category.3", "surface.canvas"),
291    ui("palette.category.3", "surface.panel"),
292    ui("palette.category.3", "surface.raised"),
293    ui("palette.category.4", "surface.canvas"),
294    ui("palette.category.4", "surface.panel"),
295    ui("palette.category.4", "surface.raised"),
296    ui("palette.category.5", "surface.canvas"),
297    ui("palette.category.5", "surface.panel"),
298    ui("palette.category.5", "surface.raised"),
299    ui("palette.category.6", "surface.canvas"),
300    ui("palette.category.6", "surface.panel"),
301    ui("palette.category.6", "surface.raised"),
302    ui("palette.category.7", "surface.canvas"),
303    ui("palette.category.7", "surface.panel"),
304    ui("palette.category.7", "surface.raised"),
305    ui("palette.category.8", "surface.canvas"),
306    ui("palette.category.8", "surface.panel"),
307    ui("palette.category.8", "surface.raised"),
308    ui("palette.category.9", "surface.canvas"),
309    ui("palette.category.9", "surface.panel"),
310    ui("palette.category.9", "surface.raised"),
311    // The axes' colours, seen on the viewport's background around an
312    // image or behind a 3D view.
313    ui("palette.axis.x", "viewport.background"),
314    ui("palette.axis.y", "viewport.background"),
315    ui("palette.axis.z", "viewport.background"),
316];
317
318/// The pairs drawn over an image, whose background is translucent: the
319/// background is painted over black and over white (an image's darkest
320/// and brightest pixels) and the foreground must read on both. [`check`]
321/// checks them with [`PAIRS`], reporting the poorer of the two ratios.
322pub const OVER_IMAGES: &[Pair] = &[
323    // A label over an image: an overlay's name, a HUD's readout.
324    text("viewport-label.rest.text", "viewport-label.rest.fill"),
325];
326
327/// The ratio of a pair of [`OVER_IMAGES`] in a theme, if both tokens are
328/// colours: its background painted over black and over white, the
329/// poorer of the two.
330pub fn over_image_ratio(tokens: &ResolvedTokens, pair: &Pair) -> Option<f32> {
331    let fg = tokens.color(pair.foreground)?;
332    let bg = tokens.color(pair.background)?;
333    Some(
334        [Color::BLACK, Color::WHITE]
335            .into_iter()
336            .map(|image| contrast_ratio(fg, bg.over(image)))
337            .fold(f32::INFINITY, f32::min),
338    )
339}
340
341/// A pair under its required ratio, or with a token missing.
342#[derive(Clone, Debug, PartialEq)]
343pub struct Failure {
344    pub pair: Pair,
345    /// The ratio reached; `None` when a token is not a colour.
346    pub ratio: Option<f32>,
347    pub required: f32,
348}
349
350impl fmt::Display for Failure {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        let Pair {
353            foreground,
354            background,
355            ..
356        } = self.pair;
357        match self.ratio {
358            Some(r) => write!(
359                f,
360                "{foreground} on {background}: {r:.2}:1, needs {}:1",
361                self.required
362            ),
363            None => write!(f, "{foreground} on {background}: not two colours"),
364        }
365    }
366}
367
368/// The ratio of one pair in a theme, if both tokens are colours.
369pub fn pair_ratio(tokens: &ResolvedTokens, pair: &Pair) -> Option<f32> {
370    Some(contrast_ratio(
371        tokens.color(pair.foreground)?,
372        tokens.color(pair.background)?,
373    ))
374}
375
376/// Checks every pair of [`PAIRS`] and [`OVER_IMAGES`] at a level; empty
377/// when all pass.
378pub fn check(tokens: &ResolvedTokens, level: Level) -> Vec<Failure> {
379    let plain = PAIRS.iter().map(|pair| (pair, pair_ratio(tokens, pair)));
380    let over = OVER_IMAGES
381        .iter()
382        .map(|pair| (pair, over_image_ratio(tokens, pair)));
383    plain
384        .chain(over)
385        .filter_map(|(pair, ratio)| {
386            let required = level.required(pair.kind);
387            ratio.is_none_or(|r| r < required).then_some(Failure {
388                pair: *pair,
389                ratio,
390                required,
391            })
392        })
393        .collect()
394}
395
396/// How a colour is seen, for telling the categorical palette's slots
397/// apart.
398#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
399pub enum Vision {
400    /// Full colour vision.
401    Normal,
402    /// No long-wavelength (red) cones.
403    Protanopia,
404    /// No medium-wavelength (green) cones.
405    Deuteranopia,
406}
407
408impl Vision {
409    pub const ALL: [Vision; 3] = [Vision::Normal, Vision::Protanopia, Vision::Deuteranopia];
410
411    pub fn name(self) -> &'static str {
412        match self {
413            Vision::Normal => "normal vision",
414            Vision::Protanopia => "protanopia",
415            Vision::Deuteranopia => "deuteranopia",
416        }
417    }
418
419    /// The colour as seen with this vision: Machado, Oliveira and
420    /// Fernandes' model (2009) at severity 1, in linear light.
421    pub fn simulate(self, c: Color) -> Color {
422        const PROTAN: [[f64; 3]; 3] = [
423            [0.152_286, 1.052_583, -0.204_868],
424            [0.114_503, 0.786_281, 0.099_216],
425            [-0.003_882, -0.048_116, 1.051_998],
426        ];
427        const DEUTAN: [[f64; 3]; 3] = [
428            [0.367_322, 0.860_646, -0.227_968],
429            [0.280_085, 0.672_501, 0.047_413],
430            [-0.011_820, 0.042_940, 0.968_881],
431        ];
432        let m = match self {
433            Vision::Normal => return c,
434            Vision::Protanopia => &PROTAN,
435            Vision::Deuteranopia => &DEUTAN,
436        };
437        let rgb = c.to_linear();
438        let row = |i: usize| {
439            (m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]).clamp(0.0, 1.0) as f32
440        };
441        Color::from_linear(row(0), row(1), row(2), c.a)
442    }
443}
444
445/// The perceptual distance between two colours, as seen with `vision`:
446/// the Euclidean distance in OKLab, times 100 (ΔE OK). About 2 is the
447/// smallest difference seen side by side; categorical palettes aim for
448/// 15 and more between neighbours.
449pub fn delta_e(a: Color, b: Color, vision: Vision) -> f32 {
450    let [l1, a1, b1] = vision.simulate(a).to_oklab();
451    let [l2, a2, b2] = vision.simulate(b).to_oklab();
452    (((l1 - l2).powi(2) + (a1 - a2).powi(2) + (b1 - b2).powi(2)).sqrt() * 100.0) as f32
453}
454
455/// Between two slots next to each other in the categorical palette
456/// (series 1 and 2 of a chart), with full colour vision.
457pub const CATEGORY_ADJACENT: f32 = 15.0;
458/// Between any two slots of the categorical palette, with full colour
459/// vision: a scatter or a legend puts any two side by side.
460pub const CATEGORY_ANY: f32 = 10.0;
461/// Between two slots next to each other, with protanopia or
462/// deuteranopia.
463pub const CATEGORY_CVD_ADJACENT: f32 = 8.0;
464
465/// Two slots of the categorical palette told apart too little.
466#[derive(Clone, Debug, PartialEq)]
467pub struct Separation {
468    /// The two slots, the lower first.
469    pub slots: (usize, usize),
470    pub vision: Vision,
471    /// The distance reached ([`delta_e`]); `None` when a slot is not a
472    /// colour.
473    pub delta_e: Option<f32>,
474    pub required: f32,
475}
476
477impl fmt::Display for Separation {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        let (a, b) = self.slots;
480        match self.delta_e {
481            Some(d) => write!(
482                f,
483                "palette.category.{a} and .{b} ({}): ΔE {d:.1}, needs {}",
484                self.vision.name(),
485                self.required
486            ),
487            None => write!(f, "palette.category.{a} and .{b}: not two colours"),
488        }
489    }
490}
491
492/// Checks that the categorical palette's slots are told apart: every two
493/// at [`CATEGORY_ANY`] and neighbours at [`CATEGORY_ADJACENT`] with full
494/// colour vision, neighbours at [`CATEGORY_CVD_ADJACENT`] with
495/// protanopia and deuteranopia. Empty when all pass. Their contrast with
496/// the surfaces is in [`PAIRS`].
497pub fn check_category(tokens: &ResolvedTokens) -> Vec<Separation> {
498    let colors: Vec<Option<Color>> = CATEGORY.iter().map(|p| tokens.color(p)).collect();
499    let mut out = Vec::new();
500    for i in 0..colors.len() {
501        for j in i + 1..colors.len() {
502            let adjacent = j == i + 1;
503            for vision in Vision::ALL {
504                let required = match (vision, adjacent) {
505                    (Vision::Normal, true) => CATEGORY_ADJACENT,
506                    (Vision::Normal, false) => CATEGORY_ANY,
507                    (_, true) => CATEGORY_CVD_ADJACENT,
508                    (_, false) => continue,
509                };
510                let d = colors[i].zip(colors[j]).map(|(a, b)| delta_e(a, b, vision));
511                if d.is_none_or(|d| d < required) {
512                    out.push(Separation {
513                        slots: (i, j),
514                        vision,
515                        delta_e: d,
516                        required,
517                    });
518                }
519            }
520        }
521    }
522    out
523}