docs(examples): refactor demo2 (#836)

Simplified a bunch of the logic in the demo2 example
- Moved destroy mode to its own file.
- Moved error handling to its own file.
- Removed AppContext
- Implemented Widget for &App. The app state is small enough that it
  doesn't matter here and we could just copy or clone the app state on
  every frame, but for larger apps this can be a significant performance
  improvement.
- Made the tabs stateful
- Made the term module just a collection of functions rather than a
  struct.
- Changed to use color_eyre for error handling.
- Changed keyboard shortcuts and rearranged the bottom bar.
- Use strum for the tabs enum.
This commit is contained in:
Josh McKinney 2024-01-24 11:44:16 -08:00 committed by GitHub
parent 815757fcbb
commit 847bacf32e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 414 additions and 374 deletions

View File

@ -1,252 +1,223 @@
use std::time::Duration;
use anyhow::{Context, Result};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use rand::Rng;
use rand_chacha::rand_core::SeedableRng;
use ratatui::{buffer::Cell, layout::Flex, prelude::*, widgets::Widget};
use unicode_width::UnicodeWidthStr;
use color_eyre::{eyre::Context, Result};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind};
use itertools::Itertools;
use ratatui::{prelude::*, widgets::*};
use strum::{Display, EnumIter, FromRepr, IntoEnumIterator};
use crate::{
big_text::{BigTextBuilder, PixelSize},
Root, Term,
};
use crate::{destroy, tabs::*, term, THEME};
#[derive(Debug)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct App {
term: Term,
context: AppContext,
mode: Mode,
tab: Tab,
about_tab: AboutTab,
recipe_tab: RecipeTab,
email_tab: EmailTab,
traceroute_tab: TracerouteTab,
weather_tab: WeatherTab,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum Mode {
#[default]
Normal,
Running,
Destroy,
Quit,
}
#[derive(Debug, Default, Clone, Copy)]
pub struct AppContext {
pub tab_index: usize,
pub row_index: usize,
#[derive(Debug, Clone, Copy, Default, Display, EnumIter, FromRepr, PartialEq, Eq)]
enum Tab {
#[default]
About,
Recipe,
Email,
Traceroute,
Weather,
}
pub fn run(terminal: &mut Terminal<impl Backend>) -> Result<()> {
App::new().run(terminal)
}
impl App {
fn new() -> Result<Self> {
Ok(Self {
term: Term::start()?,
context: AppContext::default(),
mode: Mode::Normal,
})
pub fn new() -> Self {
Self::default()
}
pub fn run() -> Result<()> {
install_panic_hook();
let mut app = Self::new()?;
while !app.should_quit() {
app.draw()?;
app.handle_events()?;
/// Run the app until the user quits.
pub fn run(&mut self, terminal: &mut Terminal<impl Backend>) -> Result<()> {
while self.is_running() {
self.draw(terminal)?;
self.handle_events()?;
}
Term::stop()?;
Ok(())
}
fn draw(&mut self) -> Result<()> {
self.term
fn is_running(&self) -> bool {
self.mode != Mode::Quit
}
/// Draw a single frame of the app.
fn draw(&self, terminal: &mut Terminal<impl Backend>) -> Result<()> {
terminal
.draw(|frame| {
frame.render_widget(Root::new(&self.context), frame.size());
frame.render_widget(self, frame.size());
if self.mode == Mode::Destroy {
destroy(frame);
destroy::destroy(frame);
}
})
.context("terminal.draw")?;
.wrap_err("terminal.draw")?;
Ok(())
}
/// Handle events from the terminal.
///
/// This function is called once per frame, The events are polled from the stdin with timeout of
/// 1/50th of a second. This was chosen to try to match the default frame rate of a GIF in VHS.
fn handle_events(&mut self) -> Result<()> {
// https://superuser.com/questions/1449366/do-60-fps-gifs-actually-exist-or-is-the-maximum-50-fps
const GIF_FRAME_RATE: f64 = 50.0;
match Term::next_event(Duration::from_secs_f64(1.0 / GIF_FRAME_RATE))? {
Some(Event::Key(key)) => self.handle_key_event(key),
Some(Event::Resize(width, height)) => {
Ok(self.term.resize(Rect::new(0, 0, width, height))?)
}
let timeout = Duration::from_secs_f64(1.0 / 50.0);
match term::next_event(timeout)? {
Some(Event::Key(key)) if key.kind == KeyEventKind::Press => self.handle_key_press(key),
_ => Ok(()),
}
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<()> {
if key.kind != KeyEventKind::Press {
return Ok(());
}
let context = &mut self.context;
const TAB_COUNT: usize = 5;
fn handle_key_press(&mut self, key: KeyEvent) -> Result<()> {
use KeyCode::*;
match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
self.mode = Mode::Quit;
}
KeyCode::Tab | KeyCode::BackTab if key.modifiers.contains(KeyModifiers::SHIFT) => {
let tab_index = context.tab_index + TAB_COUNT; // to wrap around properly
context.tab_index = tab_index.saturating_sub(1) % TAB_COUNT;
context.row_index = 0;
}
KeyCode::Tab | KeyCode::BackTab => {
context.tab_index = context.tab_index.saturating_add(1) % TAB_COUNT;
context.row_index = 0;
}
KeyCode::Up | KeyCode::Char('k') => {
context.row_index = context.row_index.saturating_sub(1);
}
KeyCode::Down | KeyCode::Char('j') => {
context.row_index = context.row_index.saturating_add(1);
}
KeyCode::Char('d') => {
self.mode = Mode::Destroy;
}
Char('q') | Esc => self.mode = Mode::Quit,
Char('h') | Left => self.prev_tab(),
Char('l') | Right => self.next_tab(),
Char('k') | Up => self.prev(),
Char('j') | Down => self.next(),
Char('d') | Delete => self.destroy(),
_ => {}
};
Ok(())
}
fn should_quit(&self) -> bool {
self.mode == Mode::Quit
fn prev(&mut self) {
match self.tab {
Tab::About => self.about_tab.prev_row(),
Tab::Recipe => self.recipe_tab.prev(),
Tab::Email => self.email_tab.prev(),
Tab::Traceroute => self.traceroute_tab.prev_row(),
Tab::Weather => self.weather_tab.prev(),
}
}
fn next(&mut self) {
match self.tab {
Tab::About => self.about_tab.next_row(),
Tab::Recipe => self.recipe_tab.next(),
Tab::Email => self.email_tab.next(),
Tab::Traceroute => self.traceroute_tab.next_row(),
Tab::Weather => self.weather_tab.next(),
}
}
fn prev_tab(&mut self) {
self.tab = self.tab.prev();
}
fn next_tab(&mut self) {
self.tab = self.tab.next()
}
fn destroy(&mut self) {
self.mode = Mode::Destroy
}
}
/// delay the start of the animation so it doesn't start immediately
const DELAY: usize = 240;
/// higher means more pixels per frame are modified in the animation
const DRIP_SPEED: usize = 50;
/// delay the start of the text animation so it doesn't start immediately after the initial delay
const TEXT_DELAY: usize = 240;
/// Implement Widget for &App rather than for App as we would otherwise have to clone or copy the
/// entire app state on every frame. For this example, the app state is small enough that it doesn't
/// matter, but for larger apps this can be a significant performance improvement.
impl Widget for &App {
fn render(self, area: Rect, buf: &mut Buffer) {
let vertical = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1),
]);
let [title_bar, tab, bottom_bar] = area.split(&vertical);
/// Destroy mode activated by pressing `d`
fn destroy(frame: &mut Frame<'_>) {
let frame_count = frame.count().saturating_sub(DELAY);
if frame_count == 0 {
return;
Block::new().style(THEME.root).render(area, buf);
self.render_title_bar(title_bar, buf);
self.render_selected_tab(tab, buf);
self.render_bottom_bar(bottom_bar, buf);
}
let area = frame.size();
let buf = frame.buffer_mut();
drip(frame_count, area, buf);
text(frame_count, area, buf);
}
/// Move a bunch of random pixels down one row.
///
/// Each pick some random pixels and move them each down one row. This is a very inefficient way to
/// do this, but it works well enough for this demo.
fn drip(frame_count: usize, area: Rect, buf: &mut Buffer) {
// a seeded rng as we have to move the same random pixels each frame
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(10);
let ramp_frames = 450;
let fractional_speed = frame_count as f64 / ramp_frames as f64;
let variable_speed = DRIP_SPEED as f64 * fractional_speed * fractional_speed * fractional_speed;
let pixel_count = (frame_count as f64 * variable_speed).floor() as usize;
for _ in 0..pixel_count {
let src_x = rng.gen_range(0..area.width);
let src_y = rng.gen_range(1..area.height - 2);
let src = buf.get_mut(src_x, src_y).clone();
// 1% of the time, move a blank or pixel (10:1) to the top line of the screen
if rng.gen_ratio(1, 100) {
let dest_x = rng
.gen_range(src_x.saturating_sub(5)..src_x.saturating_add(5))
.clamp(area.left(), area.right() - 1);
let dest_y = area.top() + 1;
impl App {
fn render_title_bar(&self, area: Rect, buf: &mut Buffer) {
let layout = Layout::horizontal([Constraint::Min(0), Constraint::Length(43)]);
let [title, tabs] = area.split(&layout);
let dest = buf.get_mut(dest_x, dest_y);
// copy the cell to the new location about 1/10 of the time blank out the cell the rest
// of the time. This has the effect of gradually removing the pixels from the screen.
if rng.gen_ratio(1, 10) {
*dest = src;
} else {
*dest = Cell::default();
}
} else {
// move the pixel down one row
let dest_x = src_x;
let dest_y = src_y.saturating_add(1).min(area.bottom() - 2);
// copy the cell to the new location
let dest = buf.get_mut(dest_x, dest_y);
*dest = src;
Span::styled("Ratatui", THEME.app_title).render(title, buf);
let titles = Tab::iter().map(|tab| tab.title());
Tabs::new(titles)
.style(THEME.tabs)
.highlight_style(THEME.tabs_selected)
.select(self.tab as usize)
.divider("")
.padding("", "")
.render(tabs, buf);
}
fn render_selected_tab(&self, area: Rect, buf: &mut Buffer) {
match self.tab {
Tab::About => self.about_tab.render(area, buf),
Tab::Recipe => self.recipe_tab.render(area, buf),
Tab::Email => self.email_tab.render(area, buf),
Tab::Traceroute => self.traceroute_tab.render(area, buf),
Tab::Weather => self.weather_tab.render(area, buf),
};
}
fn render_bottom_bar(&self, area: Rect, buf: &mut Buffer) {
let keys = [
("H/←", "Left"),
("L/→", "Right"),
("K/↑", "Up"),
("J/↓", "Down"),
("D/Del", "Destroy"),
("Q/Esc", "Quit"),
];
let spans = keys
.iter()
.flat_map(|(key, desc)| {
let key = Span::styled(format!(" {} ", key), THEME.key_binding.key);
let desc = Span::styled(format!(" {} ", desc), THEME.key_binding.description);
[key, desc]
})
.collect_vec();
Line::from(spans)
.centered()
.style((Color::Indexed(236), Color::Indexed(232)))
.render(area, buf);
}
}
impl Tab {
fn next(&self) -> Self {
let current_index = *self as usize;
let next_index = current_index.saturating_add(1);
Self::from_repr(next_index).unwrap_or(*self)
}
fn prev(&self) -> Self {
let current_index = *self as usize;
let prev_index = current_index.saturating_sub(1);
Self::from_repr(prev_index).unwrap_or(*self)
}
fn title(&self) -> String {
match self {
Tab::About => "".to_string(),
tab => format!(" {} ", tab),
}
}
}
/// draw some text fading in and out from black to red and back
fn text(frame_count: usize, area: Rect, buf: &mut Buffer) {
let sub_frame = frame_count.saturating_sub(TEXT_DELAY);
if sub_frame == 0 {
return;
}
let line = "RATATUI";
let big_text = BigTextBuilder::default()
.lines([line.into()])
.pixel_size(PixelSize::Full)
.style(Style::new().fg(Color::Rgb(255, 0, 0)))
.build()
.unwrap();
// the font size is 8x8 for each character and we have 1 line
let area = centered_rect(area, line.width() as u16 * 8, 8);
let mask_buf = &mut Buffer::empty(area);
big_text.render(area, mask_buf);
let percentage = (sub_frame as f64 / 480.0).clamp(0.0, 1.0);
for row in area.rows() {
for col in row.columns() {
let cell = buf.get_mut(col.x, col.y);
let mask_cell = mask_buf.get(col.x, col.y);
cell.set_symbol(mask_cell.symbol());
// blend the mask cell color with the cell color
let cell_color = cell.style().bg.unwrap_or(Color::Rgb(0, 0, 0));
let mask_color = mask_cell.style().fg.unwrap_or(Color::Rgb(255, 0, 0));
let color = blend(mask_color, cell_color, percentage);
cell.set_style(Style::new().fg(color));
}
}
}
fn blend(mask_color: Color, cell_color: Color, percentage: f64) -> Color {
let Color::Rgb(mask_red, mask_green, mask_blue) = mask_color else {
return mask_color;
};
let Color::Rgb(cell_red, cell_green, cell_blue) = cell_color else {
return mask_color;
};
let red = mask_red as f64 * percentage + cell_red as f64 * (1.0 - percentage);
let green = mask_green as f64 * percentage + cell_green as f64 * (1.0 - percentage);
let blue = mask_blue as f64 * percentage + cell_blue as f64 * (1.0 - percentage);
Color::Rgb(red as u8, green as u8, blue as u8)
}
/// a centered rect of the given size
fn centered_rect(area: Rect, width: u16, height: u16) -> Rect {
let horizontal = Layout::horizontal([width]).flex(Flex::Center);
let vertical = Layout::vertical([height]).flex(Flex::Center);
let [area] = area.split(&vertical);
let [area] = area.split(&horizontal);
area
}
pub fn install_panic_hook() {
better_panic::install();
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = Term::stop();
hook(info);
std::process::exit(1);
}));
}

131
examples/demo2/destroy.rs Normal file
View File

@ -0,0 +1,131 @@
use rand::Rng;
use rand_chacha::rand_core::SeedableRng;
use ratatui::{buffer::Cell, layout::Flex, prelude::*};
use unicode_width::UnicodeWidthStr;
use crate::big_text::{BigTextBuilder, PixelSize};
/// delay the start of the animation so it doesn't start immediately
const DELAY: usize = 240;
/// higher means more pixels per frame are modified in the animation
const DRIP_SPEED: usize = 50;
/// delay the start of the text animation so it doesn't start immediately after the initial delay
const TEXT_DELAY: usize = 240;
/// Destroy mode activated by pressing `d`
pub fn destroy(frame: &mut Frame<'_>) {
let frame_count = frame.count().saturating_sub(DELAY);
if frame_count == 0 {
return;
}
let area = frame.size();
let buf = frame.buffer_mut();
drip(frame_count, area, buf);
text(frame_count, area, buf);
}
/// Move a bunch of random pixels down one row.
///
/// Each pick some random pixels and move them each down one row. This is a very inefficient way to
/// do this, but it works well enough for this demo.
fn drip(frame_count: usize, area: Rect, buf: &mut Buffer) {
// a seeded rng as we have to move the same random pixels each frame
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(10);
let ramp_frames = 450;
let fractional_speed = frame_count as f64 / ramp_frames as f64;
let variable_speed = DRIP_SPEED as f64 * fractional_speed * fractional_speed * fractional_speed;
let pixel_count = (frame_count as f64 * variable_speed).floor() as usize;
for _ in 0..pixel_count {
let src_x = rng.gen_range(0..area.width);
let src_y = rng.gen_range(1..area.height - 2);
let src = buf.get_mut(src_x, src_y).clone();
// 1% of the time, move a blank or pixel (10:1) to the top line of the screen
if rng.gen_ratio(1, 100) {
let dest_x = rng
.gen_range(src_x.saturating_sub(5)..src_x.saturating_add(5))
.clamp(area.left(), area.right() - 1);
let dest_y = area.top() + 1;
let dest = buf.get_mut(dest_x, dest_y);
// copy the cell to the new location about 1/10 of the time blank out the cell the rest
// of the time. This has the effect of gradually removing the pixels from the screen.
if rng.gen_ratio(1, 10) {
*dest = src;
} else {
*dest = Cell::default();
}
} else {
// move the pixel down one row
let dest_x = src_x;
let dest_y = src_y.saturating_add(1).min(area.bottom() - 2);
// copy the cell to the new location
let dest = buf.get_mut(dest_x, dest_y);
*dest = src;
}
}
}
/// draw some text fading in and out from black to red and back
fn text(frame_count: usize, area: Rect, buf: &mut Buffer) {
let sub_frame = frame_count.saturating_sub(TEXT_DELAY);
if sub_frame == 0 {
return;
}
let line = "RATATUI";
let big_text = BigTextBuilder::default()
.lines([line.into()])
.pixel_size(PixelSize::Full)
.style(Style::new().fg(Color::Rgb(255, 0, 0)))
.build()
.unwrap();
// the font size is 8x8 for each character and we have 1 line
let area = centered_rect(area, line.width() as u16 * 8, 8);
let mask_buf = &mut Buffer::empty(area);
big_text.render(area, mask_buf);
let percentage = (sub_frame as f64 / 480.0).clamp(0.0, 1.0);
for row in area.rows() {
for col in row.columns() {
let cell = buf.get_mut(col.x, col.y);
let mask_cell = mask_buf.get(col.x, col.y);
cell.set_symbol(mask_cell.symbol());
// blend the mask cell color with the cell color
let cell_color = cell.style().bg.unwrap_or(Color::Rgb(0, 0, 0));
let mask_color = mask_cell.style().fg.unwrap_or(Color::Rgb(255, 0, 0));
let color = blend(mask_color, cell_color, percentage);
cell.set_style(Style::new().fg(color));
}
}
}
fn blend(mask_color: Color, cell_color: Color, percentage: f64) -> Color {
let Color::Rgb(mask_red, mask_green, mask_blue) = mask_color else {
return mask_color;
};
let Color::Rgb(cell_red, cell_green, cell_blue) = cell_color else {
return mask_color;
};
let red = mask_red as f64 * percentage + cell_red as f64 * (1.0 - percentage);
let green = mask_green as f64 * percentage + cell_green as f64 * (1.0 - percentage);
let blue = mask_blue as f64 * percentage + cell_blue as f64 * (1.0 - percentage);
Color::Rgb(red as u8, green as u8, blue as u8)
}
/// a centered rect of the given size
fn centered_rect(area: Rect, width: u16, height: u16) -> Rect {
let horizontal = Layout::horizontal([width]).flex(Flex::Center);
let vertical = Layout::vertical([height]).flex(Flex::Center);
let [area] = area.split(&vertical);
let [area] = area.split(&horizontal);
area
}

18
examples/demo2/errors.rs Normal file
View File

@ -0,0 +1,18 @@
use color_eyre::{config::HookBuilder, Result};
use crate::term;
pub fn init_hooks() -> Result<()> {
let (panic, error) = HookBuilder::default().into_hooks();
let panic = panic.into_panic_hook();
let error = error.into_eyre_hook();
color_eyre::eyre::set_hook(Box::new(move |e| {
let _ = term::restore();
error(e)
}))?;
std::panic::set_hook(Box::new(move |info| {
let _ = term::restore();
panic(info)
}));
Ok(())
}

View File

@ -1,18 +1,22 @@
use anyhow::Result;
pub use app::*;
pub use colors::*;
pub use root::*;
pub use term::*;
pub use theme::*;
mod app;
mod big_text;
mod colors;
mod root;
mod destroy;
mod errors;
mod tabs;
mod term;
mod theme;
pub use app::*;
use color_eyre::Result;
pub use colors::*;
pub use term::*;
pub use theme::*;
fn main() -> Result<()> {
App::run()
errors::init_hooks()?;
let terminal = &mut term::init()?;
App::new().run(terminal)?;
term::restore()?;
Ok(())
}

View File

@ -1,79 +0,0 @@
use itertools::Itertools;
use ratatui::{prelude::*, widgets::*};
use crate::{tabs::*, AppContext, THEME};
pub struct Root<'a> {
context: &'a AppContext,
}
impl<'a> Root<'a> {
pub fn new(context: &'a AppContext) -> Self {
Root { context }
}
}
impl Widget for Root<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
Block::new().style(THEME.root).render(area, buf);
let vertical = Layout::vertical([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1),
]);
let [title_bar, tab, bottom_bar] = area.split(&vertical);
self.render_title_bar(title_bar, buf);
self.render_selected_tab(tab, buf);
self.render_bottom_bar(bottom_bar, buf);
}
}
impl Root<'_> {
fn render_title_bar(&self, area: Rect, buf: &mut Buffer) {
let horizontal = Layout::horizontal([Constraint::Min(0), Constraint::Length(45)]);
let [title, tabs] = area.split(&horizontal);
Paragraph::new(Span::styled("Ratatui", THEME.app_title)).render(title, buf);
let titles = vec!["", " Recipe ", " Email ", " Traceroute ", " Weather "];
Tabs::new(titles)
.style(THEME.tabs)
.highlight_style(THEME.tabs_selected)
.select(self.context.tab_index)
.divider("")
.render(tabs, buf);
}
fn render_selected_tab(&self, area: Rect, buf: &mut Buffer) {
let row_index = self.context.row_index;
match self.context.tab_index {
0 => AboutTab::new(row_index).render(area, buf),
1 => RecipeTab::new(row_index).render(area, buf),
2 => EmailTab::new(row_index).render(area, buf),
3 => TracerouteTab::new(row_index).render(area, buf),
4 => WeatherTab::new(row_index).render(area, buf),
_ => unreachable!(),
};
}
fn render_bottom_bar(&self, area: Rect, buf: &mut Buffer) {
let keys = [
("Q/Esc", "Quit"),
("Tab", "Next Tab"),
("↑/k", "Up"),
("↓/j", "Down"),
];
let spans = keys
.iter()
.flat_map(|(key, desc)| {
let key = Span::styled(format!(" {} ", key), THEME.key_binding.key);
let desc = Span::styled(format!(" {} ", desc), THEME.key_binding.description);
[key, desc]
})
.collect_vec();
Paragraph::new(Line::from(spans))
.centered()
.fg(Color::Indexed(236))
.bg(Color::Indexed(232))
.render(area, buf);
}
}

View File

@ -38,13 +38,18 @@ const RATATUI_LOGO: [&str; 32] = [
" █xxxxxxxxxxxxxxxxxxxxx█ █ ",
];
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AboutTab {
selected_row: usize,
row_index: usize,
}
impl AboutTab {
pub fn new(selected_row: usize) -> Self {
Self { selected_row }
pub fn prev_row(&mut self) {
self.row_index = self.row_index.saturating_sub(1);
}
pub fn next_row(&mut self) {
self.row_index = self.row_index.saturating_add(1);
}
}
@ -54,7 +59,7 @@ impl Widget for AboutTab {
let horizontal = Layout::horizontal([Constraint::Length(34), Constraint::Min(0)]);
let [description, logo] = area.split(&horizontal);
render_crate_description(description, buf);
render_logo(self.selected_row, logo, buf);
render_logo(self.row_index, logo, buf);
}
}

View File

@ -39,16 +39,20 @@ const EMAILS: &[Email] = &[
},
];
#[derive(Debug, Default)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EmailTab {
selected_index: usize,
row_index: usize,
}
impl EmailTab {
pub fn new(selected_index: usize) -> Self {
Self {
selected_index: selected_index % EMAILS.len(),
}
/// Select the previous email (with wrap around).
pub fn prev(&mut self) {
self.row_index = self.row_index.saturating_add(EMAILS.len() - 1) % EMAILS.len();
}
/// Select the next email (with wrap around).
pub fn next(&mut self) {
self.row_index = self.row_index.saturating_add(1) % EMAILS.len();
}
}
@ -62,8 +66,8 @@ impl Widget for EmailTab {
Clear.render(area, buf);
let vertical = Layout::vertical([Constraint::Length(5), Constraint::Min(0)]);
let [inbox, email] = area.split(&vertical);
render_inbox(self.selected_index, inbox, buf);
render_email(self.selected_index, email, buf);
render_inbox(self.row_index, inbox, buf);
render_email(self.row_index, email, buf);
}
}
fn render_inbox(selected_index: usize, area: Rect, buf: &mut Buffer) {

View File

@ -84,16 +84,20 @@ const INGREDIENTS: &[Ingredient] = &[
},
];
#[derive(Debug)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct RecipeTab {
selected_row: usize,
row_index: usize,
}
impl RecipeTab {
pub fn new(selected_row: usize) -> Self {
Self {
selected_row: selected_row % INGREDIENTS.len(),
}
/// Select the previous item in the ingredients list (with wrap around)
pub fn prev(&mut self) {
self.row_index = self.row_index.saturating_add(INGREDIENTS.len() - 1) % INGREDIENTS.len();
}
/// Select the next item in the ingredients list (with wrap around)
pub fn next(&mut self) {
self.row_index = self.row_index.saturating_add(1) % INGREDIENTS.len();
}
}
@ -117,7 +121,7 @@ impl Widget for RecipeTab {
height: area.height - 3,
..area
};
render_scrollbar(self.selected_row, scrollbar_area, buf);
render_scrollbar(self.row_index, scrollbar_area, buf);
let area = area.inner(&Margin {
horizontal: 2,
@ -129,7 +133,7 @@ impl Widget for RecipeTab {
]));
render_recipe(recipe, buf);
render_ingredients(self.selected_row, ingredients, buf);
render_ingredients(self.row_index, ingredients, buf);
}
}

View File

@ -6,16 +6,20 @@ use ratatui::{
use crate::{RgbSwatch, THEME};
#[derive(Debug)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TracerouteTab {
selected_row: usize,
row_index: usize,
}
impl TracerouteTab {
pub fn new(selected_row: usize) -> Self {
Self {
selected_row: selected_row % HOPS.len(),
}
/// Select the previous row (with wrap around).
pub fn prev_row(&mut self) {
self.row_index = self.row_index.saturating_add(HOPS.len() - 1) % HOPS.len();
}
/// Select the next row (with wrap around).
pub fn next_row(&mut self) {
self.row_index = self.row_index.saturating_add(1) % HOPS.len();
}
}
@ -33,9 +37,9 @@ impl Widget for TracerouteTab {
let [left, map] = area.split(&horizontal);
let [hops, pings] = left.split(&vertical);
render_hops(self.selected_row, hops, buf);
render_ping(self.selected_row, pings, buf);
render_map(self.selected_row, map, buf);
render_hops(self.row_index, hops, buf);
render_ping(self.row_index, pings, buf);
render_map(self.row_index, map, buf);
}
}

View File

@ -8,13 +8,20 @@ use time::OffsetDateTime;
use crate::{color_from_oklab, RgbSwatch, THEME};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WeatherTab {
pub selected_row: usize,
pub download_progress: usize,
}
impl WeatherTab {
pub fn new(selected_row: usize) -> Self {
Self { selected_row }
/// Simulate a download indicator by decrementing the row index.
pub fn prev(&mut self) {
self.download_progress = self.download_progress.saturating_sub(1);
}
/// Simulate a download indicator by incrementing the row index.
pub fn next(&mut self) {
self.download_progress = self.download_progress.saturating_add(1);
}
}
@ -49,7 +56,7 @@ impl Widget for WeatherTab {
render_calendar(calendar, buf);
render_simple_barchart(simple, buf);
render_horizontal_barchart(horizontal, buf);
render_gauge(self.selected_row, gauges, buf);
render_gauge(self.download_progress, gauges, buf);
}
}

View File

@ -1,10 +1,9 @@
use std::{
io::{self, stdout, Stdout},
ops::{Deref, DerefMut},
io::{self, stdout},
time::Duration,
};
use anyhow::{Context, Result};
use color_eyre::{eyre::WrapErr, Result};
use crossterm::{
event::{self, Event},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
@ -12,60 +11,32 @@ use crossterm::{
};
use ratatui::prelude::*;
/// A wrapper around the terminal that handles setting up and tearing down the terminal
/// and provides a helper method to read events from the terminal.
#[derive(Debug)]
pub struct Term {
terminal: Terminal<CrosstermBackend<Stdout>>,
pub fn init() -> Result<Terminal<impl Backend>> {
// this size is to match the size of the terminal when running the demo
// using vhs in a 1280x640 sized window (github social preview size)
let options = TerminalOptions {
viewport: Viewport::Fixed(Rect::new(0, 0, 81, 18)),
};
let terminal = Terminal::with_options(CrosstermBackend::new(io::stdout()), options)?;
enable_raw_mode().context("enable raw mode")?;
stdout()
.execute(EnterAlternateScreen)
.wrap_err("enter alternate screen")?;
Ok(terminal)
}
impl Term {
pub fn start() -> Result<Self> {
// this size is to match the size of the terminal when running the demo
// using vhs in a 1280x640 sized window (github social preview size)
let options = TerminalOptions {
viewport: Viewport::Fixed(Rect::new(0, 0, 81, 18)),
};
let terminal = Terminal::with_options(CrosstermBackend::new(io::stdout()), options)?;
enable_raw_mode().context("enable raw mode")?;
stdout()
.execute(EnterAlternateScreen)
.context("enter alternate screen")?;
Ok(Self { terminal })
}
pub fn stop() -> Result<()> {
disable_raw_mode().context("disable raw mode")?;
stdout()
.execute(LeaveAlternateScreen)
.context("leave alternate screen")?;
Ok(())
}
pub fn next_event(timeout: Duration) -> io::Result<Option<Event>> {
if !event::poll(timeout)? {
return Ok(None);
}
let event = event::read()?;
Ok(Some(event))
}
pub fn restore() -> Result<()> {
disable_raw_mode().context("disable raw mode")?;
stdout()
.execute(LeaveAlternateScreen)
.wrap_err("leave alternate screen")?;
Ok(())
}
impl Deref for Term {
type Target = Terminal<CrosstermBackend<Stdout>>;
fn deref(&self) -> &Self::Target {
&self.terminal
}
}
impl DerefMut for Term {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.terminal
}
}
impl Drop for Term {
fn drop(&mut self) {
let _ = Term::stop();
pub fn next_event(timeout: Duration) -> Result<Option<Event>> {
if !event::poll(timeout)? {
return Ok(None);
}
let event = event::read()?;
Ok(Some(event))
}