1use egui::epaint::{Mesh, Shape};
46use egui::{Color32, Painter, Rect, pos2};
47
48use crate::theme::Tokens;
49
50#[derive(Clone, Debug, PartialEq)]
53#[non_exhaustive]
54pub enum RampColor {
55 Color(Color32),
57 Token(String),
60}
61
62impl RampColor {
63 pub fn token(path: impl Into<String>) -> Self {
65 RampColor::Token(path.into())
66 }
67
68 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
97#[non_exhaustive]
98pub enum RampMode {
99 #[default]
102 Value,
103 Track,
105}
106
107#[derive(Clone, Debug, PartialEq)]
110pub struct Ramp {
111 stops: Vec<(f32, RampColor)>,
112}
113
114impl Ramp {
115 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 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 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 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 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 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
192pub(crate) fn high_contrast(tokens: &Tokens) -> bool {
195 tokens.resolved().spec().base.contains("high-contrast")
196}
197
198pub(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
215pub 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
231pub(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 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 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 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 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 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 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}