widget_switch/
widget_switch.rs1use {
2 matetui::{
3 ratatui::{
4 backend::CrosstermBackend,
5 crossterm::{
6 event::{self},
7 execute,
8 terminal::{
9 disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
10 },
11 },
12 layout::{Constraint, Layout},
13 Terminal,
14 },
15 widgets::{
16 switch::Switch,
17 textarea::{Input, Key},
18 },
19 },
20 ratatui::layout::Flex,
21 std::io,
22};
23
24fn main() -> io::Result<()> {
25 let stdout = io::stdout();
26 let mut stdout = stdout.lock();
27
28 enable_raw_mode()?;
29 execute!(stdout, EnterAlternateScreen)?;
30 let backend = CrosstermBackend::new(stdout);
31 let mut term = Terminal::new(backend)?;
32 let mut switch_state = false;
33
34 loop {
35 term.draw(|f| {
36 let switch =
38 Switch::with_status(switch_state).with_color_on(ratatui::style::Color::Green);
39
40 let [horiz] = Layout::horizontal([Constraint::Percentage(100)])
41 .flex(Flex::Center)
42 .areas(f.area());
43
44 let [verti] = Layout::vertical([Constraint::Length(2)]).flex(Flex::Center).areas(horiz);
45
46 let [centered] =
47 Layout::horizontal([Constraint::Length(14)]).flex(Flex::Center).areas(verti);
48
49 f.render_widget(switch, centered);
50 })?;
51 match event::read()?.into() {
52 Input { key: Key::Esc, .. }
53 | Input {
54 key: Key::Char('c'),
55 shift: false,
56 ctrl: true,
57 alt: false,
58 } => break,
59 Input {
60 key: Key::Enter,
61 ctrl: false,
62 shift: false,
63 alt: false,
64 }
65 | Input {
66 key: Key::Char(' '),
67 ..
68 } => {
69 switch_state = !switch_state;
70 }
71 _ => {}
72 }
73 }
74
75 disable_raw_mode()?;
76 execute!(term.backend_mut(), LeaveAlternateScreen)?;
77 term.show_cursor()?;
78
79 Ok(())
80}