1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use std::time::Duration;

use indicatif::{ProgressBar, ProgressStyle};

use crate::Widget;

/// Spinner widget informing about an ongoing process.
pub struct Spinner {
    message: String,
}

impl Spinner {
    /// Create a new [`Spinner`] with the given message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    fn default_style() -> ProgressStyle {
        ProgressStyle::with_template("{spinner:.cyan} {wide_msg} {elapsed}").unwrap()
    }
}

/// Finishes the associated [`Spinner`] when dropped.
pub struct SpinnerHandle {
    pb: ProgressBar,
}

impl Drop for SpinnerHandle {
    fn drop(&mut self) {
        self.pb.finish_and_clear()
    }
}

impl Widget for Spinner {
    type Handle = SpinnerHandle;

    fn text(self) -> Self::Handle {
        let pb = ProgressBar::new_spinner()
            .with_style(Spinner::default_style())
            .with_message(self.message);
        pb.enable_steady_tick(Duration::from_millis(120));
        SpinnerHandle { pb }
    }
}