From 1cce99014cd777151d7ab7328612c3c435ef1a06 Mon Sep 17 00:00:00 2001 From: renato-umeton <25375373+renato-umeton@users.noreply.github.com> Date: Sat, 2 Aug 2025 05:50:34 -0400 Subject: feat: eliminate return requirement for -e mode option selection (#1374) Co-authored-by: Claude Co-authored-by: sigoden --- src/utils/input.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/utils/mod.rs | 2 ++ 2 files changed, 49 insertions(+) create mode 100644 src/utils/input.rs (limited to 'src/utils') diff --git a/src/utils/input.rs b/src/utils/input.rs new file mode 100644 index 0000000..ebcb3cf --- /dev/null +++ b/src/utils/input.rs @@ -0,0 +1,47 @@ +use anyhow::Result; +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; +use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; +use std::io::{stdout, Write}; + +/// Reads a single character from stdin without requiring Enter +/// Returns the character if it's one of the valid options, or the default if Enter is pressed +pub fn read_single_key(valid_chars: &[char], default: char, prompt: &str) -> Result { + print!("{prompt}"); + stdout().flush()?; + + enable_raw_mode()?; + + let result = loop { + if let Ok(Event::Key(KeyEvent { + code, modifiers, .. + })) = event::read() + { + match code { + KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => { + break Err(anyhow::anyhow!("Interrupted")); + } + KeyCode::Char(c) => { + if valid_chars.contains(&c) { + break Ok(c); + } + // Invalid character, continue loop + } + KeyCode::Enter => { + break Ok(default); + } + _ => { + // Other keys are ignored, continue loop + } + } + } + }; + + disable_raw_mode()?; + + // Print the chosen character and newline for clean output + if let Ok(chosen) = &result { + println!("{chosen}"); + } + + result +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 8a90516..31a05e2 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -3,6 +3,7 @@ mod clipboard; mod command; mod crypto; mod html_to_md; +mod input; mod loader; mod path; mod render_prompt; @@ -15,6 +16,7 @@ pub use self::clipboard::set_text; pub use self::command::*; pub use self::crypto::*; pub use self::html_to_md::*; +pub use self::input::*; pub use self::loader::*; pub use self::path::*; pub use self::render_prompt::render_prompt; -- cgit v1.2.3