console-rs / dialoguer

Rust utility library for nice command line prompts and similar things
MIT License
1.31k stars 143 forks source link

Feature request: custom keyboard interactions #302

Open ThatFrogDev opened 6 months ago

ThatFrogDev commented 6 months ago

Hello, for my app based on Dialoguer I need custom keyboard shortcuts like Alt-Q for going back to the main loop or Shift-Enter for adding a multi-line input. However, when I try to accomplish that it simply does not register that output but instead, it just picks the letter without modifier and adds that to the input.

Screenshot

Here's an example to show what I mean: image Instead, it should in this example at least do nothing, but I also added a trigger for this shortcut so in my case it should turn back to the main() loop.

Code

This is the code I used to achieve this: In return_to_main.rs, I'm polling the shortcut like this:

use crossterm::event;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use std::time::Duration;

pub fn return_to_main() -> Result<(), Box<dyn std::error::Error>> {
    enable_raw_mode()?;

    loop {
        if event::poll(Duration::from_millis(1000))? {
            if let Event::Key(event) = event::read()? {
                match event {
                    KeyEvent {
                        code: KeyCode::Char('q'),
                        modifiers: KeyModifiers::ALT,
                        kind: _,
                        state: _,
                    } => return Ok(()),
                    _ => (),
                }
            }
        }

        disable_raw_mode()?;
    }
}

And in my main loop, I'm calling the function here:

if return_to_main().is_ok() {
  main()?;
}

Could you add support for crossterm::event::poll if possible? Thanks very much. Sincerely, @ThatFrogDev

N.B. If you need more code to find where the issue lies, this example is based off my app Notabena: https://github.com/thatfrogdev/notabena.