yew_ansi/
style.rs

1use crate::graphic_rendition::ColorEffect;
2use std::borrow::Borrow;
3
4/// Combination of classes and inline styles.
5///
6/// While it is possible to use inline styles only, it is not doable
7/// with just classes due to the amount of RGB colour values.
8#[derive(Clone, Debug, Default, Eq, PartialEq)]
9pub struct ClassStyle {
10    pub class: Option<String>,
11    pub style: Option<String>,
12}
13impl ClassStyle {
14    /// Push a new class to the classes.
15    /// This function doesn't validate the given string in any way.
16    pub fn push_class(&mut self, new: impl Borrow<str>) {
17        const DELIMITER: char = ' ';
18        let class = self.class.get_or_insert_with(String::new);
19        if !class.is_empty() && !class.ends_with(DELIMITER) {
20            class.push(DELIMITER);
21        }
22        class.push_str(new.borrow());
23    }
24
25    /// Push a new property to the style.
26    /// This function doesn't validate the given string in any way.
27    pub fn push_style(&mut self, new: impl Borrow<str>) {
28        const DELIMITER: char = ';';
29        let style = self.style.get_or_insert_with(String::new);
30        if !style.is_empty() && !style.ends_with(DELIMITER) {
31            style.push(DELIMITER);
32        }
33        style.push_str(new.borrow());
34    }
35}
36
37/// Builder for [`ClassStyle`].
38pub trait StyleBuilder: Default {
39    /// Finish building and create a `ClassStyle`.
40    fn finish(self) -> ClassStyle;
41
42    /// Apply bold.
43    fn bold(&mut self);
44    /// Apply italic.
45    fn italic(&mut self);
46    /// Apply underline.
47    fn underline(&mut self);
48
49    /// Set the foreground colour.
50    fn fg_color(&mut self, color: &ColorEffect);
51    /// Set the background colour.
52    fn bg_color(&mut self, color: &ColorEffect);
53}
54
55/// Style builder using only inline style attributes.
56#[derive(Clone, Debug, Default)]
57pub struct InlineStyle(ClassStyle);
58impl InlineStyle {
59    const CSS_BOLD: &'static str = "font-weight:bold;";
60    const CSS_ITALIC: &'static str = "font-style:italic;";
61    const CSS_UNDERLINE: &'static str = "text-decoration:underline;";
62}
63impl StyleBuilder for InlineStyle {
64    fn finish(self) -> ClassStyle {
65        self.0
66    }
67
68    fn bold(&mut self) {
69        self.0.push_style(Self::CSS_BOLD);
70    }
71
72    fn italic(&mut self) {
73        self.0.push_style(Self::CSS_ITALIC);
74    }
75
76    fn underline(&mut self) {
77        self.0.push_style(Self::CSS_UNDERLINE);
78    }
79
80    fn fg_color(&mut self, color: &ColorEffect) {
81        if let Some(code) = color.rgb() {
82            self.0.push_style(format!("color:#{:06x};", code));
83        }
84    }
85
86    fn bg_color(&mut self, color: &ColorEffect) {
87        if let Some(code) = color.rgb() {
88            self.0
89                .push_style(format!("background-color:#{:06x};", code));
90        }
91    }
92}