use crate::graphic_rendition::ColorEffect;
use std::borrow::Borrow;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ClassStyle {
pub class: Option<String>,
pub style: Option<String>,
}
impl ClassStyle {
pub fn push_class(&mut self, new: impl Borrow<str>) {
const DELIMITER: char = ' ';
let class = self.class.get_or_insert_with(String::new);
if !class.is_empty() && !class.ends_with(DELIMITER) {
class.push(DELIMITER);
}
class.push_str(new.borrow());
}
pub fn push_style(&mut self, new: impl Borrow<str>) {
const DELIMITER: char = ';';
let style = self.style.get_or_insert_with(String::new);
if !style.is_empty() && !style.ends_with(DELIMITER) {
style.push(DELIMITER);
}
style.push_str(new.borrow());
}
}
pub trait StyleBuilder: Default {
fn finish(self) -> ClassStyle;
fn bold(&mut self);
fn italic(&mut self);
fn underline(&mut self);
fn fg_color(&mut self, color: &ColorEffect);
fn bg_color(&mut self, color: &ColorEffect);
}
#[derive(Clone, Debug, Default)]
pub struct InlineStyle(ClassStyle);
impl InlineStyle {
const CSS_BOLD: &'static str = "font-weight:bold;";
const CSS_ITALIC: &'static str = "font-style:italic;";
const CSS_UNDERLINE: &'static str = "text-decoration:underline;";
}
impl StyleBuilder for InlineStyle {
fn finish(self) -> ClassStyle {
self.0
}
fn bold(&mut self) {
self.0.push_style(Self::CSS_BOLD);
}
fn italic(&mut self) {
self.0.push_style(Self::CSS_ITALIC);
}
fn underline(&mut self) {
self.0.push_style(Self::CSS_UNDERLINE);
}
fn fg_color(&mut self, color: &ColorEffect) {
if let Some(code) = color.rgb() {
self.0.push_style(format!("color:#{:06x};", code));
}
}
fn bg_color(&mut self, color: &ColorEffect) {
if let Some(code) = color.rgb() {
self.0
.push_style(format!("background-color:#{:06x};", code));
}
}
}