arnaucube
arnaucube/octo-tuiPublic Self-hosted repository
octo-tui/src/theme.rs
src/theme.rsRaw
  1use anyhow::{Result, bail};
  2use ratatui::style::Color;
  3use serde::{Deserialize, Serialize};
  4use std::str::FromStr;
  5
  6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
  7#[serde(rename_all = "kebab-case")]
  8pub enum Theme {
  9    Dark,
 10    Monokai,
 11    #[default]
 12    Spotifyish,
 13    Nord,
 14    Gruvbox,
 15    Daylight,
 16    Paper,
 17}
 18
 19pub struct Palette {
 20    pub bg: Color,
 21    pub panel: Color,
 22    pub accent: Color,
 23    pub muted: Color,
 24    pub text: Color,
 25    pub selection: Color,
 26    pub border: Color,
 27}
 28
 29impl Theme {
 30    pub fn name(self) -> &'static str {
 31        match self {
 32            Self::Dark => "dark",
 33            Self::Monokai => "monokai",
 34            Self::Spotifyish => "spotifyish",
 35            Self::Nord => "nord",
 36            Self::Gruvbox => "gruvbox",
 37            Self::Daylight => "daylight",
 38            Self::Paper => "paper",
 39        }
 40    }
 41    pub fn next(self) -> Self {
 42        match self {
 43            Self::Dark => Self::Monokai,
 44            Self::Monokai => Self::Spotifyish,
 45            Self::Spotifyish => Self::Nord,
 46            Self::Nord => Self::Gruvbox,
 47            Self::Gruvbox => Self::Daylight,
 48            Self::Daylight => Self::Paper,
 49            Self::Paper => Self::Dark,
 50        }
 51    }
 52    /// Shared semantic colors keep all widgets consistent when switching themes.
 53    pub fn palette(self) -> Palette {
 54        let (bg, panel, accent, muted, text, selection) = match self {
 55            Self::Dark => (0x10141c, 0x171d28, 0x64dcc2, 0x909bb1, 0xe0e7f1, 0x263a46),
 56            Self::Monokai => (0x272822, 0x34352f, 0xf92672, 0xa6a28c, 0xf8f8f2, 0x49483e),
 57            Self::Spotifyish => (0x121212, 0x202020, 0x1ed760, 0xb3b3b3, 0xffffff, 0x303d34),
 58            Self::Nord => (0x2e3440, 0x3b4252, 0x88c0d0, 0xa4b0c3, 0xeceff4, 0x4c566a),
 59            Self::Gruvbox => (0x282828, 0x3c3836, 0xfabd2f, 0xbdae93, 0xebdbb2, 0x504945),
 60            Self::Daylight => (0xffffff, 0xeef2f6, 0x004899, 0x384555, 0x111827, 0xdbe8ff),
 61            Self::Paper => (0xfff8e8, 0xf3ead4, 0x733510, 0x504538, 0x251e16, 0xe5d6b7),
 62        };
 63        let rgb = |hex: u32| Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8);
 64        Palette {
 65            bg: rgb(bg),
 66            panel: rgb(panel),
 67            accent: rgb(accent),
 68            muted: rgb(muted),
 69            text: rgb(text),
 70            selection: rgb(selection),
 71            border: rgb(match self {
 72                Self::Daylight => 0x526070,
 73                Self::Paper => 0x6b5c48,
 74                Self::Gruvbox => 0x665c54,
 75                _ => panel,
 76            }),
 77        }
 78    }
 79}
 80impl FromStr for Theme {
 81    type Err = anyhow::Error;
 82    fn from_str(value: &str) -> Result<Self> {
 83        match value.to_ascii_lowercase().as_str() {
 84            "dark" => Ok(Self::Dark),
 85            "monokai" => Ok(Self::Monokai),
 86            "spotifyish" => Ok(Self::Spotifyish),
 87            "nord" => Ok(Self::Nord),
 88            "gruvbox" => Ok(Self::Gruvbox),
 89            "daylight" => Ok(Self::Daylight),
 90            "paper" => Ok(Self::Paper),
 91            _ => {
 92                bail!(
 93                    "Unknown theme. Choose dark, monokai, spotifyish, nord, gruvbox, daylight, or paper."
 94                )
 95            }
 96        }
 97    }
 98}
 99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn theme_cycle_includes_light_themes_and_roundtrips_settings() {
106        let mut theme = Theme::default();
107        let mut names = std::collections::HashSet::new();
108        loop {
109            assert!(names.insert(theme.name()));
110            assert_eq!(theme.name().parse::<Theme>().unwrap(), theme);
111            assert_eq!(
112                serde_json::from_str::<Theme>(&serde_json::to_string(&theme).unwrap()).unwrap(),
113                theme
114            );
115            theme = theme.next();
116            if theme == Theme::default() {
117                break;
118            }
119        }
120        assert!(names.contains("gruvbox"));
121        assert!(names.contains("daylight"));
122        assert!(names.contains("paper"));
123    }
124    #[test]
125    fn outdoor_themes_keep_text_keys_and_borders_readable() {
126        let luminance = |color: Color| {
127            let Color::Rgb(r, g, b) = color else {
128                panic!("Expected RGB")
129            };
130            let linear = |value: u8| {
131                let v = f64::from(value) / 255.;
132                if v <= 0.04045 {
133                    v / 12.92
134                } else {
135                    ((v + 0.055) / 1.055).powf(2.4)
136                }
137            };
138            0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
139        };
140        let contrast = |a, b| {
141            let (a, b) = (luminance(a), luminance(b));
142            (a.max(b) + 0.05) / (a.min(b) + 0.05)
143        };
144        for theme in [Theme::Daylight, Theme::Paper] {
145            let palette = theme.palette();
146            for background in [palette.bg, palette.panel, palette.selection] {
147                for foreground in [palette.text, palette.accent, palette.muted] {
148                    assert!(
149                        contrast(foreground, background) >= 4.5,
150                        "{} has low text contrast",
151                        theme.name()
152                    );
153                }
154            }
155            assert!(contrast(palette.border, palette.bg) >= 3.);
156        }
157    }
158    #[test]
159    fn only_current_theme_name_is_accepted() {
160        let theme: Theme = serde_json::from_str("\"spotifyish\"").unwrap();
161        assert_eq!("spotifyish".parse::<Theme>().unwrap(), theme);
162        assert_eq!(serde_json::to_string(&theme).unwrap(), "\"spotifyish\"");
163        for removed in ["spotify", "spotify-ish"] {
164            assert!(removed.parse::<Theme>().is_err());
165            assert!(serde_json::from_str::<Theme>(&format!("\"{removed}\"")).is_err());
166        }
167    }
168}