Skip to main content

egui_pop_core/slider/
ramp.rs

1//! A colour ramp on a slider or a knob: a colour for the minimum, one
2//! for the maximum (and optionally stops between), the value drawn in
3//! the colour between them (a white balance's temperature from blue to
4//! amber, a saturation from grey to colour, a warning from neutral to
5//! red).
6//!
7//! - **Two modes** ([`RampMode`]): [`RampMode::Value`] (the default)
8//!   paints what shows the value (a slider's fill, a knob's arc and
9//!   pointer) in the ramp's colour at the value; [`RampMode::Track`]
10//!   paints the whole track with the ramp, so the scale reads before a
11//!   touch, the value marked on it by the thumb or the pointer.
12//! - **Colours** are a theme's tokens (`"danger"`, `"accent.default"`,
13//!   any colour token by path, read in the theme drawn now, so a theme
14//!   switch follows) or explicit colours ([`RampColor`]).
15//! - **Interpolation in Oklab**, a perceptual space: the middle of a
16//!   ramp between two saturated colours stays bright and saturated,
17//!   where a blend of sRGB channels goes muddy. The ramp spans the soft
18//!   range; a value past it takes the end's colour.
19//! - **Accessibility**: the colour never carries the value alone, the
20//!   number and the thumb's place stay. In the value mode the colour is
21//!   lightened or darkened in Oklab until it stands 3:1 against the
22//!   track (WCAG 1.4.11), in dark and light themes alike. A
23//!   high-contrast theme draws no ramp: the control keeps the theme's
24//!   own fill, its accent.
25//!
26//! ```
27//! use egui::Color32;
28//! use egui_pop_core::slider::{Ramp, RampColor};
29//! use egui_pop_core::theme::Tokens;
30//!
31//! let t = Tokens::default();
32//! let ramp = Ramp::new(Color32::from_rgb(0, 0, 255), "danger");
33//! assert_eq!(ramp.color_at(0.0, &t), Color32::from_rgb(0, 0, 255));
34//! assert_eq!(ramp.color_at(1.0, &t), t.status.danger);
35//! // Past the ends: the ends' colours.
36//! assert_eq!(ramp.color_at(-2.0, &t), ramp.color_at(0.0, &t));
37//! let hue = Ramp::stops(&[
38//!     (0.0, RampColor::from(Color32::RED)),
39//!     (0.5, RampColor::from(Color32::GREEN)),
40//!     (1.0, RampColor::token("accent.default")),
41//! ]);
42//! assert_eq!(hue.color_at(0.5, &t), Color32::GREEN);
43//! ```
44
45use egui::epaint::{Mesh, Shape};
46use egui::{Color32, Painter, Rect, pos2};
47
48use crate::theme::Tokens;
49
50/// A ramp's colour: a theme token, read in the theme drawn now, or an
51/// explicit colour. A token the theme lacks shows as the accent.
52#[derive(Clone, Debug, PartialEq)]
53#[non_exhaustive]
54pub enum RampColor {
55    /// An explicit colour.
56    Color(Color32),
57    /// A colour token by path (`danger`, `accent.default`,
58    /// `warning`).
59    Token(String),
60}
61
62impl RampColor {
63    /// A colour token by path.
64    pub fn token(path: impl Into<String>) -> Self {
65        RampColor::Token(path.into())
66    }
67
68    /// The colour in `tokens`' theme.
69    pub fn resolve(&self, tokens: &Tokens) -> Color32 {
70        match self {
71            RampColor::Color(c) => *c,
72            RampColor::Token(path) => tokens.color(path).unwrap_or(tokens.accent.default),
73        }
74    }
75}
76
77impl From<Color32> for RampColor {
78    fn from(c: Color32) -> Self {
79        RampColor::Color(c)
80    }
81}
82
83impl From<&str> for RampColor {
84    fn from(path: &str) -> Self {
85        RampColor::token(path)
86    }
87}
88
89impl From<String> for RampColor {
90    fn from(path: String) -> Self {
91        RampColor::Token(path)
92    }
93}
94
95/// How a ramp is drawn (`Slider::ramp_track`, `Knob::ramp_track`).
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
97#[non_exhaustive]
98pub enum RampMode {
99    /// What shows the value (a slider's fill, a knob's arc and pointer)
100    /// in the ramp's colour at the value.
101    #[default]
102    Value,
103    /// The whole track in the ramp, the value marked on it.
104    Track,
105}
106
107/// Colours along the soft range, from 0 (its start) to 1 (its end),
108/// blended in Oklab in between.
109#[derive(Clone, Debug, PartialEq)]
110pub struct Ramp {
111    stops: Vec<(f32, RampColor)>,
112}
113
114impl Ramp {
115    /// From the minimum's colour to the maximum's.
116    pub fn new(min: impl Into<RampColor>, max: impl Into<RampColor>) -> Self {
117        Ramp {
118            stops: vec![(0.0, min.into()), (1.0, max.into())],
119        }
120    }
121
122    /// From stops `(place, colour)`, places in `[0, 1]` (sorted here; the
123    /// first and last colours run to the ends). No stop at all is the
124    /// accent throughout.
125    pub fn stops(stops: &[(f32, RampColor)]) -> Self {
126        let mut stops: Vec<(f32, RampColor)> = stops
127            .iter()
128            .filter(|(at, _)| at.is_finite())
129            .map(|(at, c)| (at.clamp(0.0, 1.0), c.clone()))
130            .collect();
131        stops.sort_by(|a, b| a.0.total_cmp(&b.0));
132        if stops.is_empty() {
133            stops.push((0.0, RampColor::token("accent.default")));
134        }
135        Ramp { stops }
136    }
137
138    /// The colour at `at` along the soft range (0 its start, 1 its end;
139    /// clamped), in `tokens`' theme.
140    pub fn color_at(&self, at: f32, tokens: &Tokens) -> Color32 {
141        let at = if at.is_finite() {
142            at.clamp(0.0, 1.0)
143        } else {
144            0.0
145        };
146        // Past the last stop, or before the first: the end's colour.
147        let Some(next) = self.stops.iter().position(|(p, _)| *p >= at) else {
148            return self.stops[self.stops.len() - 1].1.resolve(tokens);
149        };
150        let (b, cb) = &self.stops[next];
151        if next == 0 {
152            return cb.resolve(tokens);
153        }
154        let (a, ca) = &self.stops[next - 1];
155        let t = if b > a { (at - a) / (b - a) } else { 1.0 };
156        oklab_mix(ca.resolve(tokens), cb.resolve(tokens), t)
157    }
158
159    /// The colour at `at`, made to stand 3:1 against `track`
160    /// ([`with_contrast`]).
161    pub(crate) fn value_color(&self, at: f32, tokens: &Tokens, track: Color32) -> Color32 {
162        with_contrast(self.color_at(at, tokens), track, 3.0)
163    }
164
165    /// Paints the ramp over `rect`, left to right (`vertical`: bottom to
166    /// top), finely enough for the Oklab blend to show.
167    pub(crate) fn paint(&self, painter: &Painter, rect: Rect, tokens: &Tokens, vertical: bool) {
168        const N: usize = 32;
169        let mut mesh = Mesh::default();
170        for i in 0..=N {
171            let at = i as f32 / N as f32;
172            let c = self.color_at(at, tokens);
173            if vertical {
174                let y = rect.bottom() - rect.height() * at;
175                mesh.colored_vertex(pos2(rect.left(), y), c);
176                mesh.colored_vertex(pos2(rect.right(), y), c);
177            } else {
178                let x = rect.left() + rect.width() * at;
179                mesh.colored_vertex(pos2(x, rect.top()), c);
180                mesh.colored_vertex(pos2(x, rect.bottom()), c);
181            }
182            if i > 0 {
183                let b = 2 * i as u32;
184                mesh.add_triangle(b - 2, b - 1, b);
185                mesh.add_triangle(b - 1, b, b + 1);
186            }
187        }
188        painter.add(Shape::mesh(mesh));
189    }
190}
191
192/// Whether `tokens` are a high-contrast theme's, where a ramp gives way
193/// to the theme's own fill (its accent).
194pub(crate) fn high_contrast(tokens: &Tokens) -> bool {
195    tokens.resolved().spec().base.contains("high-contrast")
196}
197
198/// The ramp a control draws in `tokens`' theme: none in a high-contrast
199/// theme.
200pub(crate) fn active<'r>(ramp: Option<&'r Ramp>, tokens: &Tokens) -> Option<&'r Ramp> {
201    ramp.filter(|_| !high_contrast(tokens))
202}
203
204fn to_tokens(c: Color32) -> egui_pop_tokens::Color {
205    let [r, g, b, a] = c.to_srgba_unmultiplied();
206    let f = |v: u8| f32::from(v) / 255.0;
207    egui_pop_tokens::Color {
208        r: f(r),
209        g: f(g),
210        b: f(b),
211        a: f(a),
212    }
213}
214
215/// `a` to `b` at `t` (0 to 1, clamped), blended in Oklab; alpha
216/// blended straight.
217pub fn oklab_mix(a: Color32, b: Color32, t: f32) -> Color32 {
218    let t = t.clamp(0.0, 1.0);
219    let (ca, cb) = (to_tokens(a), to_tokens(b));
220    let (la, lb) = (ca.to_oklab(), cb.to_oklab());
221    let tt = f64::from(t);
222    let mix = |i: usize| la[i] + (lb[i] - la[i]) * tt;
223    crate::theme::color32(egui_pop_tokens::Color::from_oklab(
224        mix(0),
225        mix(1),
226        mix(2),
227        ca.a + (cb.a - ca.a) * t,
228    ))
229}
230
231/// `c`, lightened or darkened in Oklab (its hue and chroma kept) until
232/// it stands `ratio` against `against`, or as far as it goes; the
233/// direction is the one with more room.
234pub(crate) fn with_contrast(c: Color32, against: Color32, ratio: f32) -> Color32 {
235    let bg = to_tokens(against);
236    let fg = to_tokens(c);
237    if egui_pop_tokens::contrast::contrast_ratio(fg, bg) >= ratio {
238        return c;
239    }
240    let [l, a, b] = fg.to_oklab();
241    let up = bg.to_oklab()[0] < 0.5;
242    let mut l2 = l;
243    for _ in 0..50 {
244        l2 = if up {
245            (l2 + 0.02).min(1.0)
246        } else {
247            (l2 - 0.02).max(0.0)
248        };
249        let next = egui_pop_tokens::Color::from_oklab(l2, a, b, fg.a);
250        if egui_pop_tokens::contrast::contrast_ratio(next, bg) >= ratio || l2 <= 0.0 || l2 >= 1.0 {
251            return crate::theme::color32(next);
252        }
253    }
254    c
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use egui_pop_tokens::{ThemeSpec, Themes};
261
262    fn theme(name: &str) -> Tokens {
263        Tokens::new(Themes::default().resolve(&ThemeSpec::new(name)))
264    }
265
266    /// Distance from grey: the largest channel minus the smallest.
267    fn chroma(c: Color32) -> i32 {
268        let [r, g, b, _] = c.to_array();
269        i32::from(r.max(g).max(b)) - i32::from(r.min(g).min(b))
270    }
271
272    #[test]
273    fn the_colour_at_the_ends_and_the_middle() {
274        let t = theme("pop-dark");
275        let (blue, amber) = (
276            Color32::from_rgb(40, 90, 255),
277            Color32::from_rgb(255, 170, 30),
278        );
279        let ramp = Ramp::new(blue, amber);
280        assert_eq!(ramp.color_at(0.0, &t), blue);
281        assert_eq!(ramp.color_at(1.0, &t), amber);
282        assert_eq!(ramp.color_at(0.5, &t), oklab_mix(blue, amber, 0.5));
283        // Clamped outside the soft range.
284        assert_eq!(ramp.color_at(-1.0, &t), blue);
285        assert_eq!(ramp.color_at(7.0, &t), amber);
286        assert_eq!(ramp.color_at(f32::NAN, &t), blue);
287        // Grey to grey: the middle grey, in Oklab (its lightness halfway).
288        let g = Ramp::new(Color32::BLACK, Color32::WHITE).color_at(0.5, &t);
289        assert_eq!((g.r(), g.r()), (g.g(), g.b()));
290        assert!((95..=105).contains(&g.r()), "{g:?}");
291    }
292
293    #[test]
294    fn stops_are_sorted_and_run_to_the_ends() {
295        let t = theme("pop-dark");
296        let ramp = Ramp::stops(&[
297            (0.75, Color32::RED.into()),
298            (0.25, Color32::GREEN.into()),
299            (0.5, Color32::BLUE.into()),
300        ]);
301        assert_eq!(ramp.color_at(0.0, &t), Color32::GREEN);
302        assert_eq!(ramp.color_at(0.25, &t), Color32::GREEN);
303        assert_eq!(ramp.color_at(0.5, &t), Color32::BLUE);
304        assert_eq!(ramp.color_at(0.75, &t), Color32::RED);
305        assert_eq!(ramp.color_at(1.0, &t), Color32::RED);
306        assert_eq!(
307            Ramp::stops(&[]).color_at(0.3, &t),
308            t.accent.default,
309            "no stop: the accent"
310        );
311    }
312
313    #[test]
314    fn the_oklab_midpoint_is_not_muddy() {
315        // Blue to amber, green to magenta: in sRGB the middle sinks to a
316        // dull grey; in Oklab it keeps its lightness and some colour.
317        for (a, b) in [
318            (
319                Color32::from_rgb(0, 80, 255),
320                Color32::from_rgb(255, 176, 0),
321            ),
322            (Color32::from_rgb(0, 200, 0), Color32::from_rgb(220, 0, 220)),
323        ] {
324            let ok = oklab_mix(a, b, 0.5);
325            let srgb = Color32::from_rgb(
326                ((u16::from(a.r()) + u16::from(b.r())) / 2) as u8,
327                ((u16::from(a.g()) + u16::from(b.g())) / 2) as u8,
328                ((u16::from(a.b()) + u16::from(b.b())) / 2) as u8,
329            );
330            let l = |c: Color32| to_tokens(c).to_oklab()[0];
331            let ends = (l(a) + l(b)) / 2.0;
332            assert!(
333                (l(ok) - ends).abs() < 0.02,
334                "Oklab keeps the lightness: {ok:?}"
335            );
336            assert!(l(srgb) < l(ok) - 0.03, "sRGB darkens: {srgb:?} vs {ok:?}");
337            assert!(chroma(ok) >= chroma(srgb), "{ok:?} vs {srgb:?}");
338        }
339    }
340
341    #[test]
342    fn tokens_follow_a_theme_switch() {
343        let ramp = Ramp::new("surface.panel", "danger");
344        let (dark, light) = (theme("pop-dark"), theme("pop-light"));
345        assert_eq!(ramp.color_at(0.0, &dark), dark.surface.panel);
346        assert_eq!(ramp.color_at(0.0, &light), light.surface.panel);
347        assert_ne!(ramp.color_at(0.0, &dark), ramp.color_at(0.0, &light));
348        assert_eq!(ramp.color_at(1.0, &light), light.status.danger);
349        // A token the theme lacks: the accent.
350        let missing = Ramp::new("no.such.token", "no.such.token");
351        assert_eq!(missing.color_at(0.5, &dark), dark.accent.default);
352    }
353
354    #[test]
355    fn the_value_colour_stands_against_the_track_in_dark_and_light() {
356        let grey = Color32::from_gray(128);
357        for name in ["pop-dark", "pop-light", "github-dark", "solarized-light"] {
358            let t = theme(name);
359            // The track: the panel itself, the hardest case.
360            let track = t.surface.panel;
361            for c in [grey, track, Color32::from_rgb(255, 176, 0), Color32::BLUE] {
362                let v = Ramp::new(c, c).value_color(0.5, &t, track);
363                let ratio =
364                    egui_pop_tokens::contrast::contrast_ratio(to_tokens(v), to_tokens(track));
365                assert!(ratio >= 2.95, "{name}: {c:?} -> {v:?} at {ratio:.2}:1");
366            }
367        }
368    }
369
370    #[test]
371    fn high_contrast_themes_draw_no_ramp() {
372        let ramp = Ramp::new(Color32::BLUE, Color32::RED);
373        for name in egui_pop_tokens::BUILT_IN_THEMES {
374            let t = theme(name);
375            let shown = active(Some(&ramp), &t).is_some();
376            assert_eq!(shown, !name.contains("high-contrast"), "{name}");
377        }
378    }
379}