1use crate::graphic_rendition::ColorEffect;
2use std::borrow::Borrow;
3
4#[derive(Clone, Debug, Default, Eq, PartialEq)]
9pub struct ClassStyle {
10 pub class: Option<String>,
11 pub style: Option<String>,
12}
13impl ClassStyle {
14 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 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
37pub trait StyleBuilder: Default {
39 fn finish(self) -> ClassStyle;
41
42 fn bold(&mut self);
44 fn italic(&mut self);
46 fn underline(&mut self);
48
49 fn fg_color(&mut self, color: &ColorEffect);
51 fn bg_color(&mut self, color: &ColorEffect);
53}
54
55#[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}