television_screen/
spinner.rs

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use ratatui::{
    buffer::Buffer, layout::Rect, style::Style, widgets::StatefulWidget,
};

const FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

/// A spinner widget.
#[derive(Debug, Clone, Copy)]
pub struct Spinner {
    frames: &'static [&'static str],
}

impl Spinner {
    pub fn new(frames: &'static [&str]) -> Spinner {
        Spinner { frames }
    }

    pub fn frame(&self, index: usize) -> &str {
        self.frames[index]
    }
}

impl Default for Spinner {
    fn default() -> Spinner {
        Spinner::new(FRAMES)
    }
}

#[derive(Debug)]
pub struct SpinnerState {
    pub current_frame: usize,
    total_frames: usize,
}

impl SpinnerState {
    pub fn new(total_frames: usize) -> SpinnerState {
        SpinnerState {
            current_frame: 0,
            total_frames,
        }
    }

    fn tick(&mut self) {
        self.current_frame = (self.current_frame + 1) % self.total_frames;
    }
}

impl From<&Spinner> for SpinnerState {
    fn from(spinner: &Spinner) -> SpinnerState {
        SpinnerState::new(spinner.frames.len())
    }
}

impl StatefulWidget for Spinner {
    type State = SpinnerState;

    /// Renders the spinner in the given area.
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        buf.set_string(
            area.left(),
            area.top(),
            self.frame(state.current_frame),
            Style::default(),
        );
        state.tick();
    }
}
impl StatefulWidget for &Spinner {
    type State = SpinnerState;

    /// Renders the spinner in the given area.
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        buf.set_string(
            area.left(),
            area.top(),
            self.frame(state.current_frame),
            Style::default(),
        );
        state.tick();
    }
}