color.rs

 1use anyhow::Result;
 2use gpui::Hsla;
 3use palette::FromColor;
 4
 5pub(crate) fn try_parse_color(color: &str) -> Result<Hsla> {
 6    let rgba = gpui::Rgba::try_from(color)?;
 7    let rgba = palette::rgb::Srgba::from_components((rgba.r, rgba.g, rgba.b, rgba.a));
 8    let hsla = palette::Hsla::from_color(rgba);
 9
10    let hsla = gpui::hsla(
11        hsla.hue.into_positive_degrees() / 360.,
12        hsla.saturation,
13        hsla.lightness,
14        hsla.alpha,
15    );
16
17    Ok(hsla)
18}
19
20pub(crate) fn pack_color(color: Hsla) -> u32 {
21    let hsla = palette::Hsla::from_components((color.h * 360., color.s, color.l, color.a));
22    let rgba = palette::rgb::Srgba::from_color(hsla);
23    let rgba = rgba.into_format::<u8, u8>();
24
25    u32::from(rgba)
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    pub fn test_serialize_color() {
34        let color = "#b4637aff";
35        let hsla = try_parse_color(color).unwrap();
36        let packed = pack_color(hsla);
37
38        assert_eq!(format!("#{:x}", packed), color);
39    }
40
41    #[test]
42    pub fn test_serialize_color_with_palette() {
43        let color = "#b4637aff";
44
45        let rgba = gpui::Rgba::try_from(color).unwrap();
46        let rgba = palette::rgb::Srgba::from_components((rgba.r, rgba.g, rgba.b, rgba.a));
47        let hsla = palette::Hsla::from_color(rgba);
48
49        let rgba = palette::rgb::Srgba::from_color(hsla);
50        let rgba = rgba.into_format::<u8, u8>();
51
52        assert_eq!(format!("#{:x}", rgba), color);
53    }
54}