syncat_stylesheet/style/
mod.rs1#[cfg(feature = "ansi_term")]
2use ansi_term::Style as ANSIStyle;
3use std::collections::BTreeMap;
4use std::convert::TryFrom;
5
6mod value;
7pub use value::{FromValueError, Value};
8
9#[derive(Clone, Debug, Default)]
10pub struct Style<'s>(BTreeMap<&'s str, Value>);
11
12impl<'s> Style<'s> {
13 pub fn get(&self, key: &str) -> Option<&Value> {
14 self.0.get(key)
15 }
16
17 pub fn try_get<T: TryFrom<Value>>(&self, key: &str) -> Result<Option<T>, T::Error> {
18 self.0
19 .get(key)
20 .map_or(Ok(None), |value| Ok(Some(T::try_from(value.clone())?)))
21 }
22
23 pub(crate) fn insert(&mut self, key: &'s str, value: Value) {
24 self.0.insert(key, value);
25 }
26
27 pub(crate) fn merge(mut self, mut other: Self) -> Self {
28 other.0.append(&mut self.0);
29 other
30 }
31}
32
33#[cfg(feature = "ansi_term")]
34impl TryFrom<Style<'_>> for ANSIStyle {
35 type Error = FromValueError;
36
37 fn try_from(style: Style) -> Result<Self, Self::Error> {
38 let mut ansi_style = ANSIStyle::new();
39 if let Some(true) = style.try_get("bold")? {
40 ansi_style = ansi_style.bold();
41 }
42 if let Some(true) = style.try_get("italic")? {
43 ansi_style = ansi_style.italic()
44 }
45 if let Some(true) = style.try_get("dim")? {
46 ansi_style = ansi_style.dimmed()
47 }
48 if let Some(true) = style.try_get("underline")? {
49 ansi_style = ansi_style.underline()
50 }
51 if let Some(true) = style.try_get("strikethrough")? {
52 ansi_style = ansi_style.strikethrough()
53 }
54 if let Some(true) = style.try_get("blink")? {
55 ansi_style = ansi_style.blink()
56 }
57 if let Some(true) = style.try_get("reverse")? {
58 ansi_style = ansi_style.reverse()
59 }
60 if let Some(true) = style.try_get("hidden")? {
61 ansi_style = ansi_style.hidden()
62 }
63 if let Some(color) = style.try_get("color")? {
64 ansi_style = ansi_style.fg(color)
65 }
66 if let Some(color) = style.try_get("background-color")? {
67 ansi_style = ansi_style.on(color)
68 }
69 Ok(ansi_style)
70 }
71}