From 90ab28447c5416ec4552a4b682b068bd46fa3f50 Mon Sep 17 00:00:00 2001 From: AntwortEinesLebens Date: Sun, 19 Jan 2025 18:07:17 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20Add=20a=20displayer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/displayer.rs | 109 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/displayer.rs diff --git a/src/displayer.rs b/src/displayer.rs new file mode 100644 index 0000000..bd347ec --- /dev/null +++ b/src/displayer.rs @@ -0,0 +1,109 @@ +use console::{Emoji, Style}; +use indicatif::{ProgressBar, ProgressStyle}; +use std::{borrow::Cow, fmt::Display, time::Duration}; + +pub struct Displayer { + spinner: ProgressBar, + emojis: Emojis, + styles: Styles, +} + +pub struct Emojis { + pub success: Emoji<'static, 'static>, + pub failure: Emoji<'static, 'static>, +} + +pub struct Styles { + pub success: Style, + pub failure: Style, +} + +impl Displayer { + pub fn new(spinner: ProgressBar, emojis: Emojis, styles: Styles) -> Self { + Self { + spinner, + emojis, + styles, + } + } + + pub fn loading(&mut self, message: impl Into> + Display) { + self.stop(); + + self.spinner.set_message(message); + self.spinner.enable_steady_tick(Duration::from_millis(100)); + } + + pub fn success(&mut self, message: impl Into> + Display) { + self.stop(); + + println!( + "{}", + self.format(&self.emojis.success, &self.styles.success, message) + ); + } + + pub fn failure(&mut self, message: impl Into> + Display) { + self.stop(); + + eprintln!( + "{}", + self.format(&self.emojis.failure, &self.styles.failure, message) + ); + } + + fn stop(&mut self) { + self.spinner.finish_and_clear(); + self.spinner = ProgressBar::new_spinner().with_style(self.spinner.style()); + } + + fn format( + &self, + emoji: &Emoji<'_, '_>, + style: &Style, + message: impl Into> + Display, + ) -> String { + format!("{}{}", style.apply_to(emoji), message) + } +} + +impl Default for Displayer { + fn default() -> Self { + Self { + spinner: ProgressBar::new_spinner() + .with_style(ProgressStyle::with_template("{spinner:.yellow.bold} {msg}").unwrap()), + emojis: Emojis::default(), + styles: Styles::default(), + } + } +} + +impl Emojis { + fn new(success: Emoji<'static, 'static>, failure: Emoji<'static, 'static>) -> Self { + Self { success, failure } + } +} + +impl Default for Emojis { + fn default() -> Self { + Self { + success: Emoji("✔️ ", ""), + failure: Emoji("❌ ", ""), + } + } +} + +impl Styles { + fn new(success: Style, failure: Style) -> Self { + Self { success, failure } + } +} + +impl Default for Styles { + fn default() -> Self { + Self { + success: Style::new().green().bold(), + failure: Style::new().red().bold().for_stderr(), + } + } +}