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
47
48
49
50
51
52
|
use anyhow::Result;
use crossterm::{cursor, queue, style, terminal};
use std::io::{Stdout, Write};
pub struct Spinner {
index: usize,
message: String,
stopped: bool,
}
impl Spinner {
const DATA: [&'static str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
pub fn new(message: &str) -> Self {
Spinner {
index: 0,
message: message.to_string(),
stopped: false,
}
}
pub fn step(&mut self, writer: &mut Stdout) -> Result<()> {
if self.stopped {
return Ok(());
}
let frame = Self::DATA[self.index % Self::DATA.len()];
let dots = ".".repeat((self.index / 5) % 4);
let line = format!("{frame}{}{:<3}", self.message, dots);
queue!(writer, cursor::MoveToColumn(0), style::Print(line),)?;
if self.index == 0 {
queue!(writer, cursor::Hide)?;
}
writer.flush()?;
self.index += 1;
Ok(())
}
pub fn stop(&mut self, writer: &mut Stdout) -> Result<()> {
if self.stopped {
return Ok(());
}
self.stopped = true;
queue!(
writer,
cursor::MoveToColumn(0),
terminal::Clear(terminal::ClearType::FromCursorDown),
cursor::Show
)?;
writer.flush()?;
Ok(())
}
}
|