From 72511867624c9bc416e64a1b856026ced5c4e1eb Mon Sep 17 00:00:00 2001 From: Florian Dehau Date: Mon, 8 Jun 2020 22:32:10 +0200 Subject: [PATCH] feat(style): add StyleDiff --- src/style.rs | 165 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/src/style.rs b/src/style.rs index 0f0a069..8e54dac 100644 --- a/src/style.rs +++ b/src/style.rs @@ -156,4 +156,169 @@ impl Style { self.modifier = modifier; self } + + /// Creates a new [`Style`] by applying the given diff to its properties. + /// + /// ## Examples + /// + /// ```rust + /// # use tui::style::{Color, Modifier, Style, StyleDiff}; + /// let style = Style::default().fg(Color::Green).bg(Color::Black).modifier(Modifier::BOLD); + /// + /// let diff = StyleDiff::default(); + /// let patched = style.patch(diff); + /// assert_eq!(patched, style); + /// + /// let diff = StyleDiff::default().fg(Color::Blue).add_modifier(Modifier::ITALIC); + /// let patched = style.patch(diff); + /// assert_eq!( + /// patched, + /// Style { + /// fg: Color::Blue, + /// bg: Color::Black, + /// modifier: Modifier::BOLD | Modifier::ITALIC, + /// } + /// ); + /// ``` + pub fn patch(mut self, diff: StyleDiff) -> Style { + if let Some(c) = diff.fg { + self.fg = c; + } + if let Some(c) = diff.bg { + self.bg = c; + } + if let Some(m) = diff.modifier { + self.modifier = m; + } + if let Some(m) = diff.add_modifier { + self.modifier.insert(m) + } + if let Some(m) = diff.sub_modifier { + self.modifier.remove(m) + } + self + } +} + +/// StyleDiff is a set of updates that can be applied to a [`Style`] to get a +/// new one. +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct StyleDiff { + fg: Option, + bg: Option, + modifier: Option, + add_modifier: Option, + sub_modifier: Option, +} + +impl Default for StyleDiff { + fn default() -> StyleDiff { + StyleDiff { + fg: None, + bg: None, + modifier: None, + add_modifier: None, + sub_modifier: None, + } + } +} + +impl From