index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / ui / style_config.rs
-rw-r--r-- blob 541cb0dadd250f721d7164faafaa1cd011d34004 1323 bytes (plain)
1
use std::str::FromStr;
2
3
use anyhow::Context;
4
use ratatui::style::{Color, ParseColorError, Style};
5
use serde::{Deserialize, Serialize};
6
7
#[derive(Default, Clone, Deserialize, Serialize)]
8
#[serde(default)]
9
pub struct StyleConfig {
10
    pub fg: Option<String>,
11
    pub bg: Option<String>,
12
    pub bold: bool,
13
    pub italic: bool,
14
}
15
16
impl StyleConfig {
17
    pub fn format(&self) -> anyhow::Result<Style> {
18
        let style: Style = self.clone().try_into().with_context(|| {
19
            format!(
20
                "invalid style in config (fg: {:?}, bg: {:?}, bold: {:?}, italic: {:?})",
21
                self.fg, self.bg, self.bold, self.italic
22
            )
23
        })?;
24
        Ok(style)
25
    }
26
}
27
28
impl TryFrom<StyleConfig> for Style {
29
    type Error = ParseColorError;
30
31
    fn try_from(config: StyleConfig) -> Result<Self, Self::Error> {
32
        let mut style = Style::new();
33
        if let Some(fg_str) = config.fg {
34
            let color = Color::from_str(&fg_str)?;
35
            style = style.fg(color);
36
        }
37
38
        if let Some(bg_str) = config.bg {
39
            let color = Color::from_str(&bg_str)?;
40
            style = style.bg(color);
41
        }
42
43
        if config.bold {
44
            style = style.bold();
45
        }
46
47
        if config.italic {
48
            style = style.italic();
49
        }
50
51
        Ok(style)
52
    }
53
}