Skip to content

Commit

Permalink
feat: Use mode that is common across root app and components ✨ (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
kdheepak authored Jan 7, 2024
1 parent 0a00d95 commit 975f5cf
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 57 deletions.
13 changes: 11 additions & 2 deletions async/ratatui-counter/.config/config.json5
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"keybindings": {
"Home": {
"<q>": "Quit", // Quit the application
"Normal": {
"<q><q>": "Quit", // Quit the application
"<j>": "ScheduleIncrement",
"<k>": "ScheduleDecrement",
"<?>": "ToggleShowHelp",
Expand All @@ -10,5 +10,14 @@
"<Ctrl-c>": "Quit", // Yet another way to quit
"<Ctrl-z>": "Suspend" // Suspend the application
},
"Processing": {
"<j>": "ScheduleIncrement",
"<k>": "ScheduleDecrement",
},
"Help": {
"<q>": "ToggleShowHelp", // Quit the application
"<?>": "ToggleShowHelp",
"<ESC>": "ToggleShowHelp",
},
}
}
2 changes: 0 additions & 2 deletions async/ratatui-counter/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ pub enum Action {
EnterInsert,
EnterProcessing,
ExitProcessing,
EnterModeHomeInput,
EnterModeHomeNormal,
Update,
}
//// ANCHOR_END: action_enum
30 changes: 24 additions & 6 deletions async/ratatui-counter/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
use std::{
cell::{Cell, RefCell},
rc::Rc,
};

use color_eyre::eyre::Result;
use crossterm::event::KeyEvent;
use ratatui::prelude::Rect;
Expand All @@ -19,16 +24,16 @@ pub struct App {
pub components: Vec<Box<dyn Component>>,
pub should_quit: bool,
pub should_suspend: bool,
pub mode: Mode,
pub mode: Rc<RefCell<Mode>>,
pub last_tick_key_events: Vec<KeyEvent>,
}

impl App {
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
let home = Home::new();
let mode = Rc::new(RefCell::new(Mode::Normal));
let home = Home::new(mode.clone());
let fps = FpsCounter::default();
let config = Config::new()?;
let mode = Mode::Home;
Ok(Self {
tick_rate,
frame_rate,
Expand Down Expand Up @@ -67,7 +72,7 @@ impl App {
tui::Event::Render => action_tx.send(Action::Render)?,
tui::Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
tui::Event::Key(key) => {
if let Some(keymap) = self.config.keybindings.get(&self.mode) {
if let Some(keymap) = self.config.keybindings.get(&self.mode.borrow()) {
if let Some(action) = keymap.get(&vec![key]) {
log::info!("Got action: {action:?}");
action_tx.send(action.clone())?;
Expand Down Expand Up @@ -104,8 +109,21 @@ impl App {
Action::Quit => self.should_quit = true,
Action::Suspend => self.should_suspend = true,
Action::Resume => self.should_suspend = false,
Action::EnterModeHomeInput => self.mode = Mode::HomeInput,
Action::EnterModeHomeNormal => self.mode = Mode::Home,
Action::EnterInsert => *self.mode.borrow_mut() = Mode::Insert,
Action::EnterNormal => *self.mode.borrow_mut() = Mode::Normal,
Action::EnterProcessing => {
*self.mode.borrow_mut() = Mode::Processing;
},
Action::ExitProcessing => {
*self.mode.borrow_mut() = Mode::Normal;
},
Action::ToggleShowHelp => {
if *self.mode.borrow() != Mode::Help {
*self.mode.borrow_mut() = Mode::Help;
} else {
*self.mode.borrow_mut() = Mode::Normal;
}
},
Action::Resize(w, h) => {
tui.resize(Rect::new(0, 0, w, h))?;
tui.draw(|f| {
Expand Down
58 changes: 13 additions & 45 deletions async/ratatui-counter/src/components/home.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, time::Duration};
use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};

use color_eyre::eyre::Result;
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
Expand All @@ -12,16 +12,7 @@ use tracing::trace;
use tui_input::{backend::crossterm::EventHandler, Input};

use super::{Component, Frame};
use crate::{action::Action, config::key_event_to_string, tui::Event};

#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub enum Mode {
#[default]
Normal,
Insert,
Processing,
Help,
}
use crate::{action::Action, config::key_event_to_string, mode::Mode, tui::Event};

#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonState {
Expand All @@ -37,7 +28,7 @@ pub struct Home {
pub counter: usize,
pub app_ticker: usize,
pub render_ticker: usize,
pub mode: Mode,
pub mode: Rc<RefCell<Mode>>,
pub input: Input,
pub action_tx: Option<UnboundedSender<Action>>,
pub keymap: HashMap<KeyEvent, Action>,
Expand All @@ -52,8 +43,8 @@ pub struct Home {
}

impl Home {
pub fn new() -> Self {
Self::default()
pub fn new(mode: Rc<RefCell<Mode>>) -> Self {
Self { mode, ..Default::default() }
}

pub fn keymap(mut self, keymap: HashMap<KeyEvent, Action>) -> Self {
Expand Down Expand Up @@ -134,7 +125,7 @@ impl Home {
.title("ratatui async template")
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_style(match self.mode {
.border_style(match *self.mode.borrow() {
Mode::Processing => Style::default().fg(Color::Yellow),
_ => Style::default(),
})
Expand All @@ -148,7 +139,7 @@ impl Home {
let width = self.main_rect.width.max(3) - 3; // keep 2 for borders and 1 for cursor
let scroll = self.input.visual_scroll(width as usize);
Paragraph::new(self.input.value())
.style(match self.mode {
.style(match *self.mode.borrow() {
Mode::Insert => Style::default().fg(Color::Yellow),
_ => Style::default(),
})
Expand All @@ -174,7 +165,7 @@ impl Home {
Row::new(vec!["/", "Enter Input"]),
Row::new(vec!["ESC", "Exit Input"]),
Row::new(vec!["Enter", "Submit Input"]),
Row::new(vec!["q", "Quit"]),
Row::new(vec!["qq", "Quit"]),
Row::new(vec!["?", "Open Help"]),
];
let table = Table::new(rows, &[Constraint::Percentage(10), Constraint::Percentage(90)])
Expand Down Expand Up @@ -223,7 +214,7 @@ impl Component for Home {

fn handle_key_events(&mut self, key: KeyEvent) -> Result<Option<Action>> {
self.last_events.push(key.clone());
let action = match self.mode {
let action = match *self.mode.borrow() {
Mode::Normal | Mode::Processing | Mode::Help => return Ok(None),
Mode::Insert => {
match key.code {
Expand All @@ -250,34 +241,11 @@ impl Component for Home {
match action {
Action::Tick => self.tick(),
Action::Render => self.render_tick(),
Action::ToggleShowHelp if self.mode != Mode::Insert => {
self.show_help = !self.show_help;
if self.show_help {
self.mode = Mode::Help;
} else {
self.mode = Mode::Normal;
}
},
Action::ScheduleIncrement if self.mode == Mode::Normal => self.schedule_increment(1),
Action::ScheduleDecrement if self.mode == Mode::Normal => self.schedule_decrement(1),
Action::ScheduleIncrement if *self.mode.borrow() == Mode::Normal => self.schedule_increment(1),
Action::ScheduleDecrement if *self.mode.borrow() == Mode::Normal => self.schedule_decrement(1),
Action::Increment(i) => self.increment(i),
Action::Decrement(i) => self.decrement(i),
Action::CompleteInput(s) => self.add(s),
Action::EnterNormal => {
self.mode = Mode::Normal;
return Ok(Some(Action::EnterModeHomeNormal));
},
Action::EnterInsert => {
self.mode = Mode::Insert;
return Ok(Some(Action::EnterModeHomeInput));
},
Action::EnterProcessing => {
self.mode = Mode::Processing;
},
Action::ExitProcessing => {
// TODO: Make this go to previous mode instead
self.mode = Mode::Normal;
},
_ => (),
}
Ok(None)
Expand Down Expand Up @@ -354,14 +322,14 @@ impl Component for Home {
f.render_widget(self.input_widget(), input_rect);
self.input_rect = input_rect;

if self.mode == Mode::Insert {
if *self.mode.borrow() == Mode::Insert {
f.set_cursor(
(input_rect.x + 1 + self.input.cursor() as u16).min(input_rect.x + input_rect.width - 2),
input_rect.y + 1,
)
}

if self.show_help {
if *self.mode.borrow() == Mode::Help {
let rect = rect.inner(&Margin { horizontal: 4, vertical: 2 });
f.render_widget(Clear, rect);
let (block, table) = self.help_widget();
Expand Down
6 changes: 4 additions & 2 deletions async/ratatui-counter/src/mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize};
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Mode {
#[default]
Home,
HomeInput,
Normal,
Insert,
Processing,
Help,
}

0 comments on commit 975f5cf

Please sign in to comment.