theta_chart/
color.rs

1use palette::{rgb::Rgb, FromColor, IntoColor, Lch, ShiftHue, Srgb};
2use std::str::FromStr;
3
4pub const COLOR_PRIMARY_U32: u32 = 0x005bbe;
5pub const SHIFT_HUE: f32 = 70.;
6
7#[derive(Debug, Clone)]
8pub struct Color(Rgb);
9
10impl Default for Color {
11    fn default() -> Self {
12        Color(Srgb::from(COLOR_PRIMARY_U32).into_format())
13    }
14}
15
16impl From<&str> for Color {
17    fn from(hex: &str) -> Self {
18        match Rgb::from_str(hex) {
19            Ok(color) => Self(color.into_format()),
20            Err(_) => Self(Srgb::from(COLOR_PRIMARY_U32).into_format()),
21        }
22    }
23}
24
25impl Color {
26    // For web
27    pub fn to_string_hex(&self) -> String {
28        let com = self.0.into_format::<u8>().into_components();
29        format!("#{:02X?}{:02X?}{:02X?}", com.0, com.1, com.2)
30    }
31
32    pub fn shift_hue(&self) -> Color {
33        let lch_color: Lch = self.0.into_color();
34        Color(Srgb::from_color(lch_color.shift_hue(SHIFT_HUE)))
35    }
36
37    pub fn shift_hue_degrees_index(&self, degrees: f32, index: usize) -> Color {
38        let lch_color: Lch = self.0.into_color();
39        let degrees = degrees * index as f32;
40        Color(Srgb::from_color(lch_color.shift_hue(degrees)))
41    }
42}