Handling key event doesn't register until other key event is triggered, using Crossterm

44 Views Asked by At

I just started Rust and wanted to make a simple and easy project that could help me learn more about the language.

I'm making an interactive Todo app in the terminal using Crossterm. Everything was going fine, until I encountered this really strange behavior. I want 2 different "tabs", one tab to keep track of the tasks which need to be done, and the other for the tasks which are completed. I also want to be able to cycle through the tasks, so that later you can edit them and modify the elements.

I'm using the Tab key event to toggle between the two different tabs, TODO and DONE, which is done by setting the contents of a mutable variable, curr_tab. It works on the first Tab press, but after that, the only way to switch is to press Tab and then the up arrow, but will switch back after the next arrow key input.

I make a mutable variable like so:

let mut curr_tab = Action::DONE;

And use it like so:

list.print_header(&curr_tab);
list.print_list(&curr_tab, index);

Here's the code I use to handle keys:

if let Event::Key(event) = read()? {
    match event.code {
        KeyCode::Up => index = index.checked_sub(1).unwrap_or(0),
        KeyCode::Down => index = min(index + 1, curr_vec.len() - 1),
        KeyCode::Tab => {
            curr_tab = match curr_tab {
                Action::TODO => Action::DONE,
                Action::DONE => Action::TODO,
            }
        },
        KeyCode::Char('q') => break,
        _ => continue,
    }
}

This read call is in a non-blocking poll, so it shouldn't be an issue.

Here's a gist to the entire code if you care to reproduce it: gist

Any help is appreciated.

0

There are 0 best solutions below