Skip to content

Commit

Permalink
ratatui counter example
Browse files Browse the repository at this point in the history
  • Loading branch information
Kacperacy committed Apr 17, 2024
1 parent ce32604 commit c57dd46
Show file tree
Hide file tree
Showing 2 changed files with 159 additions and 34 deletions.
175 changes: 141 additions & 34 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,149 @@
use crossterm::{
event::{self, KeyCode, KeyEventKind},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use std::io;

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use ratatui::{
prelude::{CrosstermBackend, Stylize, Terminal},
widgets::Paragraph,
prelude::*,
symbols::border,
widgets::{block::*, *},
};
use std::io::{stdout, Result};

fn main() -> Result<()> {
stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.clear()?;

loop {
terminal.draw(|frame| {
let area = frame.size();
frame.render_widget(
Paragraph::new("Hello Ratatui! (press 'q' to quit)")
.white()
.on_blue(),
area,
);
})?;

if event::poll(std::time::Duration::from_millis(16))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
break;
}

mod tui;

fn main() -> io::Result<()> {
let mut terminal = tui::init()?;
let app_result = App::default().run(&mut terminal);
tui::restore()?;
app_result
}

#[derive(Debug, Default)]
pub struct App {
counter: u8,
exit: bool,
}

impl App {
pub fn run(&mut self, terminal: &mut tui::Tui) -> io::Result<()> {
while !self.exit {
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events()?;
}
Ok(())
}

fn render_frame(&self, frame: &mut Frame) {
frame.render_widget(self, frame.size());
}

fn handle_events(&mut self) -> io::Result<()> {
match event::read()? {
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) {
match key_event.code {
KeyCode::Char('q') => self.exit(),
KeyCode::Left => self.decrement_counter(),
KeyCode::Right => self.increment_counter(),
_ => {}
}
}

stdout().execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
fn exit(&mut self) {
self.exit = true;
}

fn increment_counter(&mut self) {
self.counter += 1;
}

fn decrement_counter(&mut self) {
self.counter -= 1;
}
}

impl Widget for &App {
fn render(self, area: Rect, buf: &mut Buffer) {
let title = Title::from(" Counter App Tutorial ".bold());
let instructions = Title::from(Line::from(vec![
" Decrement ".into(),
"<Left>".blue().bold(),
" Increment ".into(),
"<Right>".blue().bold(),
" Quit ".into(),
"<Q> ".blue().bold(),
]));
let block = Block::default()
.title(title.alignment(Alignment::Center))
.title(
instructions
.alignment(Alignment::Center)
.position(Position::Bottom),
)
.borders(Borders::ALL)
.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::*;

#[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);

// note ratatui also has an assert_buffer_eq! macro that can be used to
// compare buffers and display the differences in a more readable way
assert_eq!(buf, expected);
}

#[test]
fn handle_key_event() -> io::Result<()> {
let mut app = App::default();
app.handle_key_event(KeyCode::Right.into());
assert_eq!(app.counter, 1);

app.handle_key_event(KeyCode::Left.into());
assert_eq!(app.counter, 0);

let mut app = App::default();
app.handle_key_event(KeyCode::Char('q').into());
assert_eq!(app.exit, true);

Ok(())
}
}
18 changes: 18 additions & 0 deletions src/tui.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use std::io::{self, stdout, Stdout};

use crossterm::{execute, terminal::*};
use ratatui::prelude::*;

pub type Tui = Terminal<CrosstermBackend<Stdout>>;

pub fn init() -> io::Result<Tui> {
execute!(stdout(), EnterAlternateScreen)?;
enable_raw_mode()?;
Terminal::new(CrosstermBackend::new(stdout()))
}

pub fn restore() -> io::Result<()> {
execute!(stdout(), LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}

0 comments on commit c57dd46

Please sign in to comment.