zeus_theme/
hsla.rs

1use egui::Color32;
2use palette::{Hsl, IntoColor, Srgba};
3
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[derive(Debug, Clone, Copy)]
6pub struct Hsla {
7   /// Hue 0.0..=360.0
8   pub h: f32,
9   /// Saturation 0.0..=100.0
10   pub s: f32,
11   /// Lightness 0.0..=100.0
12   pub l: f32,
13   /// Alpha 0.0..=1.0
14   pub a: f32,
15}
16
17impl Hsla {
18   pub fn from_color32(c: Color32) -> Self {
19      let srgba = Srgba::new(
20         c.r() as f32 / 255.0,
21         c.g() as f32 / 255.0,
22         c.b() as f32 / 255.0,
23         c.a() as f32 / 255.0,
24      );
25      let hsl: Hsl = srgba.into_color();
26      let (h, s, l) = hsl.into_components();
27      // Normalize hue to [0, 360)
28      let mut hue = h.into_degrees();
29      hue = (hue % 360.0 + 360.0) % 360.0;
30      Hsla {
31         h: hue,
32         s: s * 100.0,
33         l: l * 100.0,
34         a: srgba.alpha,
35      }
36   }
37
38   pub fn to_color32(&self) -> Color32 {
39      let srgba = self.to_srgba();
40      let (r, g, b, a) = srgba.into_components();
41      Color32::from_rgba_unmultiplied(
42         (r * 255.0) as u8,
43         (g * 255.0) as u8,
44         (b * 255.0) as u8,
45         (a * 255.0) as u8,
46      )
47   }
48
49   pub fn to_srgba(&self) -> Srgba {
50      let hsl = Hsl::new(self.h, self.s / 100.0, self.l / 100.0);
51      hsl.into_color()
52   }
53
54   pub fn to_rgba_components(&self) -> (u8, u8, u8, u8) {
55      let srgba = self.to_srgba();
56      let (r, g, b, a) = srgba.into_components();
57      let r = (r * 255.0) as u8;
58      let g = (g * 255.0) as u8;
59      let b = (b * 255.0) as u8;
60      let a = (a * 255.0) as u8;
61      (r, g, b, a)
62   }
63
64   // Shade generator inspired by the app
65   pub fn shades(&self, num_shades: usize, direction: ShadeDirection) -> Vec<Color32> {
66      let mut shades = Vec::new();
67      let step = if direction == ShadeDirection::Lighter {
68         5.0
69      } else {
70         -5.0
71      };
72      let mut current = *self;
73      for _ in 0..num_shades {
74         shades.push(current.to_color32());
75         current.l = (current.l as f32 + step).clamp(0.0, 100.0);
76      }
77      shades
78   }
79}
80
81#[derive(Debug, PartialEq, Eq, Clone, Copy)]
82pub enum ShadeDirection {
83   Lighter,
84   Darker,
85}