index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / ui / list.rs
-rw-r--r-- blob a11c81163b52434b00473c9b5e7838e400aca84c 1145 bytes (plain)
1
use ratatui::widgets::TableState;
2
3
pub struct StatefulList<T> {
4
    pub state: TableState,
5
    pub items: Vec<T>,
6
}
7
impl<T> StatefulList<T> {
8
    pub fn with_items(items: Vec<T>) -> Self {
9
        Self {
10
            state: TableState::default(),
11
            items,
12
        }
13
    }
14
15
    pub fn next(&mut self) {
16
        if self.items.is_empty() {
17
            return; // Don't do anything if list is empty
18
        }
19
        let i = match self.state.selected() {
20
            Some(i) => {
21
                if i >= self.items.len() - 1 {
22
                    0
23
                } else {
24
                    i + 1
25
                }
26
            }
27
            _ => 0,
28
        };
29
        self.state.select(Some(i));
30
    }
31
32
    pub fn previous(&mut self) {
33
        if self.items.is_empty() {
34
            return; // Don't do anything if list is empty
35
        }
36
        let i = match self.state.selected() {
37
            Some(i) => {
38
                if i == 0 {
39
                    self.items.len() - 1
40
                } else {
41
                    i - 1
42
                }
43
            }
44
            _ => 0,
45
        };
46
        self.state.select(Some(i));
47
    }
48
}