Skip to content

Commit

Permalink
feat: ✨ Add a displayer
Browse files Browse the repository at this point in the history
  • Loading branch information
AntwortEinesLebens committed Jan 19, 2025
1 parent ecd7fe5 commit 90ab284
Showing 1 changed file with 109 additions and 0 deletions.
109 changes: 109 additions & 0 deletions src/displayer.rs
Original file line number Diff line number Diff line change
@@ -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<Cow<'static, str>> + 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<Cow<'static, str>> + Display) {
self.stop();

println!(
"{}",
self.format(&self.emojis.success, &self.styles.success, message)
);
}

pub fn failure(&mut self, message: impl Into<Cow<'static, str>> + 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<Cow<'static, str>> + 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(),
}
}
}

0 comments on commit 90ab284

Please sign in to comment.