use std::fmt::Display;
use crate::enums::{Color, Modifier};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
pub fg: Option<Color>,
pub bg: Option<Color>,
pub modifier: Modifier,
}
impl Style {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn reset(&mut self) {
self.fg = None;
self.bg = None;
self.modifier = Modifier::empty();
}
#[must_use]
pub fn fg<T>(mut self, fg: T) -> Self
where
T: Into<Option<Color>>,
{
self.fg = fg.into();
self
}
#[must_use]
pub fn bg<T>(mut self, bg: T) -> Self
where
T: Into<Option<Color>>,
{
self.bg = bg.into();
self
}
#[must_use]
pub fn modifier(mut self, flag: Modifier) -> Self {
self.modifier = Modifier::empty();
self.modifier.insert(flag);
self
}
#[must_use]
pub fn add_modifier(mut self, flag: Modifier) -> Self {
self.modifier.insert(flag);
self
}
#[must_use]
pub fn remove_modifier(mut self, flag: Modifier) -> Self {
self.modifier.remove(flag);
self
}
#[must_use]
pub fn combine<S>(mut self, other: S) -> Self
where
S: Into<Style>,
{
let other = other.into();
self.fg = other.fg.or(self.fg);
self.bg = other.bg.or(self.bg);
self.modifier = other.modifier;
self
}
}
impl Display for Style {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.modifier)?;
if let Some(fg) = self.fg {
write!(f, "{}", fg.to_fg())?;
}
if let Some(bg) = self.bg {
write!(f, "{}", bg.to_bg())?;
}
Ok(())
}
}
impl Default for Style {
fn default() -> Self {
Self {
fg: None,
bg: None,
modifier: Modifier::empty(),
}
}
}
impl From<Color> for Style {
fn from(value: Color) -> Self {
Self::new().fg(value)
}
}
impl From<(Color, Color)> for Style {
fn from((fg, bg): (Color, Color)) -> Self {
Self::new().fg(fg).bg(bg)
}
}
impl From<Modifier> for Style {
fn from(value: Modifier) -> Self {
Self::new().modifier(value)
}
}
impl From<(Color, Color, Modifier)> for Style {
fn from((fg, bg, modifier): (Color, Color, Modifier)) -> Self {
Self::new().fg(fg).bg(bg).modifier(modifier)
}
}