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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use miette::{Diagnostic, IntoDiagnostic, Result};
use ratatui::{
DefaultTerminal, Frame,
buffer::Buffer,
layout::Rect,
style::Stylize,
symbols::border,
text::{Line, Text},
widgets::{Block, Paragraph, Widget},
};
use thiserror::Error;
#[derive(Debug, Default)]
pub struct App {
counter: u8,
exit: bool,
}
#[derive(Diagnostic, Debug, Error, PartialEq)]
#[error("An overflow error occurred")]
#[diagnostic()]
pub struct OverflowError {
#[help]
_msg: String,
}
fn main() -> Result<()> {
ratatui::run(|term| App::default().run(term))
}
impl App {
/// runs the application's main loop until the user quits
pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<()> {
while !self.exit {
terminal.draw(|frame| self.draw(frame)).into_diagnostic()?;
self.handle_events()?;
}
Ok(())
}
fn draw(&self, frame: &mut Frame) {
frame.render_widget(self, frame.area());
}
fn handle_events(&mut self) -> Result<()> {
match event::read().into_diagnostic()? {
// it's important to check that the event is a key press event as
// crossterm also emits key release and repeat events on Windows.
Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
self.handle_key_event(key_event)
}
_ => Ok(()),
}
}
fn handle_key_event(&mut self, key_event: KeyEvent) -> Result<()> {
match key_event.code {
KeyCode::Char('q') => self.exit()?,
KeyCode::Left => self.decrement_counter()?,
KeyCode::Right => self.increment_counter()?,
_ => {}
};
Ok(())
}
fn exit(&mut self) -> Result<()> {
self.exit = true;
Ok(())
}
fn decrement_counter(&mut self) -> Result<(), OverflowError> {
if self.counter == 0 {
Err(OverflowError {
_msg: "Cannot count below 0".into(),
})
} else {
self.counter -= 1;
Ok(())
}
}
fn increment_counter(&mut self) -> Result<(), OverflowError> {
if self.counter == u8::MAX {
Err(OverflowError {
_msg: "Cannot count above u8::MAX".into(),
})
} else {
self.counter += 1;
Ok(())
}
}
}
impl Widget for &App {
fn render(self, area: Rect, buf: &mut Buffer) {
let title = Line::from(" Counter App Tutorial ".bold());
let instructions = Line::from(vec![
" Decrement ".into(),
"<Left>".blue().bold(),
" Increment ".into(),
"<Right>".blue().bold(),
" Quit ".into(),
"<Q> ".blue().bold(),
]);
let block = Block::bordered()
.title(title.centered())
.title_bottom(instructions.centered())
.border_set(border::THICK);
let counter_text = Text::from(vec![Line::from(vec![
"Value: ".into(),
self.counter.to_string().yellow(),
])]);
Paragraph::new(counter_text)
.centered()
.block(block)
.render(area, buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::style::Style;
#[test]
fn render() {
let app = App::default();
let mut buf = Buffer::empty(Rect::new(0, 0, 50, 4));
app.render(buf.area, &mut buf);
let mut expected = Buffer::with_lines(vec![
"┏━━━━━━━━━━━━━ Counter App Tutorial ━━━━━━━━━━━━━┓",
"┃ Value: 0 ┃",
"┃ ┃",
"┗━ Decrement <Left> Increment <Right> Quit <Q> ━━┛",
]);
let title_style = Style::new().bold();
let counter_style = Style::new().yellow();
let key_style = Style::new().blue().bold();
expected.set_style(Rect::new(14, 0, 22, 1), title_style);
expected.set_style(Rect::new(28, 1, 1, 1), counter_style);
expected.set_style(Rect::new(13, 3, 6, 1), key_style);
expected.set_style(Rect::new(30, 3, 7, 1), key_style);
expected.set_style(Rect::new(43, 3, 4, 1), key_style);
assert_eq!(buf, expected);
}
#[test]
fn handle_key_event_inc_dec() {
let mut app = App::default();
let res = app.handle_key_event(KeyCode::Right.into());
assert!(res.is_ok());
assert_eq!(app.counter, 1);
let res = app.handle_key_event(KeyCode::Left.into());
assert!(res.is_ok());
assert_eq!(app.counter, 0);
}
#[test]
fn handle_key_event_exit() {
let mut app = App::default();
let res = app.handle_key_event(KeyCode::Char('q').into());
assert!(res.is_ok());
assert!(app.exit);
}
#[test]
fn handle_key_event_dec_error() {
let mut app = App::default();
let res = app.handle_key_event(KeyCode::Left.into());
assert!(res.is_err());
let res_err = res.unwrap_err();
let casted_val = res_err
.downcast_ref::<OverflowError>()
.expect("something bad occurred");
let expected_err_msg: String = "Cannot count below 0".into();
assert_eq!(casted_val._msg, expected_err_msg);
assert_eq!(
*casted_val,
OverflowError {
_msg: expected_err_msg,
},
);
}
#[test]
fn handle_key_event_inc_error() {
let mut app = App::default();
app.counter = u8::MAX;
let res = app.handle_key_event(KeyCode::Right.into());
assert!(res.is_err());
let res_err = res.unwrap_err();
let casted_val = res_err
.downcast_ref::<OverflowError>()
.expect("something bad occurred");
let expected_err_msg: String = "Cannot count above u8::MAX".into();
assert_eq!(casted_val._msg, expected_err_msg);
assert_eq!(
*casted_val,
OverflowError {
_msg: expected_err_msg,
},
);
}
}
|