Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added colors for spinners #32

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ include = ["src/**/*", "README.md"]
lazy_static = { version = "1.4.0" }
maplit = { version = "1.0.2" }
strum = { version = "0.24.0", features = ["derive"] }
yansi = { version = "0.5.1" }
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use std::thread::sleep;
use std::time::Duration;

fn main() {
let mut sp = Spinner::new(Spinners::Dots9, "Waiting for 3 seconds".into());
let mut sp = Spinner::new(Spinners::Dots9, "Waiting for 3 seconds".into(), None);
sleep(Duration::from_secs(3));
sp.stop();
}
Expand Down
12 changes: 12 additions & 0 deletions examples/color.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use spinners::{Color, Spinner, Spinners};
use std::{thread::sleep, time::Duration};

fn main() {
let mut sp = Spinner::new_with_color(
Spinners::Dots9,
"Waiting for 3 seconds".into(),
Color::Green,
);
sleep(Duration::from_secs(3));
sp.stop_with_message("Finishing waiting for 3 seconds".into());
}
2 changes: 1 addition & 1 deletion examples/cycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use strum::IntoEnumIterator;
fn main() {
// loop through each spinner and display them for 2 seconds
for spinner in Spinners::iter() {
let mut sp = Spinner::new(spinner.clone(), format!("{:?}", spinner));
let mut sp = Spinner::new(spinner, format!("{:?}", spinner));
sleep(Duration::from_secs(2));
sp.stop();
}
Expand Down
2 changes: 1 addition & 1 deletion examples/stop_persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ fn main() {
"Waiting for 3 seconds".into(),
);
sleep(Duration::from_secs(3));
sp.stop_and_persist("✔", "That worked!".to_string())
sp.stop_and_persist("✔", "That worked!".to_string());
}
1 change: 1 addition & 0 deletions examples/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ fn main() {
let mut sp = Spinner::with_timer(
Spinners::from_str(&spinner_name).unwrap(),
"Waiting for 3 seconds".into(),
None,
);
sleep(Duration::from_secs(3));
sp.stop_with_newline();
Expand Down
68 changes: 37 additions & 31 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use std::{

pub use crate::utils::spinner_names::SpinnerNames as Spinners;
use crate::utils::spinners_data::SPINNERS as SpinnersMap;
pub use crate::utils::stream::Stream;

pub use crate::utils::color::Color;
use crate::utils::color::colorize;
mod utils;

pub struct Spinner {
Expand Down Expand Up @@ -47,47 +47,43 @@ impl Spinner {
///
/// let sp = Spinner::new(Spinners::Dots, String::new());
/// ```
pub fn new(spinner: Spinners, message: String) -> Self {
#[must_use]
pub fn new(spinner: Spinners, message: String) -> Self {
Self::new_inner(spinner, message, None, None)
}

/// Create a new spinner that logs the time since it was created
pub fn with_timer(spinner: Spinners, message: String) -> Self {
Self::new_inner(spinner, message, Some(Instant::now()), None)
}

/// Creates a new spinner along with a message with a specified output stream
/// Create a new colored spinner along with a message
///
/// # Examples
///
/// Basic Usage:
///
/// ```
/// use spinners::{Spinner, Spinners, Stream};
///
/// let sp = Spinner::with_stream(Spinners::Dots, String::new(), Stream::Stderr);
/// ```
pub fn with_stream(spinner: Spinners, message: String, stream: Stream) -> Self {
Self::new_inner(spinner, message, None, Some(stream))
}

/// Creates a new spinner that logs the time since it was created with a specified output stream
/// use spinners::{Spinner, Spinners, Color};
///
/// # Examples
/// let sp = Spinner::new_with_color(Spinners::Dots, "Loading things into memory...".into(), Color::Blue);
/// ```
///
/// Basic Usage:
/// No Message:
///
/// ```
/// use spinners::{Spinner, Spinners, Stream};
///
/// let sp = Spinner::with_timer_and_stream(Spinners::Dots, String::new(), Stream::Stderr);
/// use spinners::{Spinner, Spinners};
///
/// let sp = Spinner::new_with_color(Spinners::Dots, String::new(), None);
/// ```
pub fn with_timer_and_stream(spinner: Spinners, message: String, stream: Stream) -> Self {
Copy link
Owner

@FGRibreau FGRibreau Aug 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the issue I'm having here is the cardinality of spinners crate options. For instance someone might want to have both a special stream AND a customized color.

While stream should be set everywhere, I think "color" is one special use-case of text customization and should be customizable through a text mapping function you can optionally set while creating a spinner.

Then we could update spinner create documentation to explain how to manage text colors.

From a library standpoint it makes way more sense don't you think?

Self::new_inner(spinner, message, Some(Instant::now()), Some(stream))
pub fn new_with_color<T>(spinner: Spinners, message: String, color: T) -> Self
where T: Into<Option<Color>> + std::marker::Send + 'static + std::marker::Copy {
Self::new_inner(spinner, message, color, None)
}

fn new_inner(spinner: Spinners, message: String, start_time: Option<Instant>, stream: Option<Stream>) -> Self
{
/// Create a new spinner that logs the time since it was created
pub fn with_timer<T>(spinner: Spinners, message: String, color: T) -> Self
where T: Into<Option<Color>> + std::marker::Send + 'static + std::marker::Copy {
Self::new_inner(spinner, message, color, Some(Instant::now()))
}

fn new_inner<T>(spinner: Spinners, message: String, color: T, start_time: Option<Instant>) -> Self
where T: Into<Option<Color>> + std::marker::Send + 'static + std::marker::Copy {
let spinner_name = spinner.to_string();
let spinner_data = SpinnersMap
.get(&spinner_name)
Expand All @@ -98,23 +94,33 @@ impl Spinner {
let (sender, recv) = channel::<(Instant, Option<String>)>();

let join = thread::spawn(move || 'outer: loop {

for frame in spinner_data.frames.iter() {
let mut stdout = stdout();
for frame in &spinner_data.frames {
let (do_stop, stop_time, stop_symbol) = match recv.try_recv() {
Ok((stop_time, stop_symbol)) => (true, Some(stop_time), stop_symbol),
Err(TryRecvError::Disconnected) => (true, None, None),
Err(TryRecvError::Empty) => (false, None, None),
};

let frame = stop_symbol.unwrap_or_else(|| frame.to_string());
let frame = stop_symbol.unwrap_or_else(|| (*frame).to_string());
match start_time {
None => {
print!("\r{} {}", colorize(frame, color.into()), message);
}
Some(start_time) => {
let now = stop_time.unwrap_or_else(Instant::now);
let duration = now.duration_since(start_time).as_secs_f64();
print!("\r{}{:>10.3} s\t{}", colorize(frame, color.into()), duration, message);
}
}

stream.write(&frame, &message, start_time, stop_time).expect("IO Error");

if do_stop {
break 'outer;
}

thread::sleep(Duration::from_millis(spinner_data.interval as u64));
thread::sleep(Duration::from_millis(u64::from(spinner_data.interval)));
}
});

Expand Down
27 changes: 27 additions & 0 deletions src/utils/color.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use yansi::Paint;

#[derive(Debug, Clone, Copy)]
pub enum Color {
Blue,
Green,
Red,
Yellow,
Cyan,
White,
Magenta,
Black,
}

pub fn colorize(input: String, color: Option<Color>) -> Paint<String> {
match color {
Some(Color::Blue) => Paint::blue(input),
Some(Color::Green) => Paint::green(input),
Some(Color::Red) => Paint::red(input),
Some(Color::Yellow) => Paint::yellow(input),
Some(Color::Cyan) => Paint::cyan(input),
Some(Color::White) => Paint::white(input),
Some(Color::Magenta) => Paint::magenta(input),
Some(Color::Black) => Paint::black(input),
None => Paint::new(input),
}
}
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod color;
pub mod spinner_data;
pub mod spinner_names;
pub mod spinners_data;
Expand Down
2 changes: 1 addition & 1 deletion src/utils/spinner_names.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use strum::{Display, EnumIter, EnumString};

#[derive(Debug, Clone, EnumIter, Display, EnumString)]
#[derive(Debug, Copy, Clone, EnumIter, Display, EnumString)]
pub enum SpinnerNames {
Dots,
Dots2,
Expand Down