04_counter/
04_counter.rs

1//! Displays a counter than can be incremented and decremented with `k` and `j`.
2
3use std::cmp::Ordering;
4
5use milk_tea::{
6    area::{Area, Element},
7    draw_call::{DrawCall, DrawCallKind},
8    event::{Event, KeyCode, KeyEvent, KeyEventKind},
9    run,
10    style::{ContentStyle, Stylize},
11    text_size::UnicodeSize,
12};
13
14fn main() {
15    run(Model::default(), view, update).unwrap();
16}
17
18fn view(state: &Model, area: &mut Area) {
19    let style = match state.count.cmp(&0) {
20        Ordering::Greater => ContentStyle::new().cyan(),
21        Ordering::Less => ContentStyle::new().magenta(),
22        Ordering::Equal => ContentStyle::new().grey(),
23    };
24
25    area.push_element(area.rect(), center(style, format!("{}", state.count)))
26}
27
28/// Returns an `Element` with centered text. `Element`s are just closures that take in an `&mut
29/// Area` to push draw calls to.
30fn center(style: ContentStyle, text: String) -> Element {
31    Box::new(move |area| {
32        area.push_all(vec![
33            DrawCall::new(
34                area.center_rect(text.rect()).pos,
35                DrawCallKind::SetStyle(style),
36            ),
37            DrawCall::new(
38                area.center_rect(text.rect()).pos,
39                DrawCallKind::PrintLine(text.limit_size(area.size())),
40            ),
41        ]);
42    })
43}
44
45fn update(event: Event, model: &mut Model) {
46    if let Event::Key(KeyEvent {
47        code,
48        kind: KeyEventKind::Press,
49        ..
50    }) = event
51    {
52        // Update the count based on the key pressed.
53        match code {
54            KeyCode::Esc => model.should_exit = true,
55            KeyCode::Char('k') => model.count += 1,
56            KeyCode::Char('j') => model.count -= 1,
57            _ => {}
58        }
59    }
60}
61
62#[derive(Default, Clone, PartialEq, Eq)]
63struct Model {
64    should_exit: bool,
65    count: i32,
66}
67
68impl milk_tea::Model for Model {
69    fn should_exit(&self) -> bool {
70        self.should_exit
71    }
72}