mikaelmello / inquire

A Rust library for building interactive prompts
https://docs.rs/inquire
MIT License
1.85k stars 75 forks source link

Allow callback when user changes selection without submitting #93

Open LucasOe opened 1 year ago

LucasOe commented 1 year ago

In a project I'm working on, I would like to use the users current selection inside a Select prompt without the user confirming his selection. In this specific use case I have a list of game objects and I would like the highlight the object currently selected as the user navigates through the list. As far as I am aware there is no alternative to achieve this behaviour.

I'm not too familiar with callbacks inside Rust, but I think a possible solution could look like this:

fn main() {
    let options: Vec<&str> = vec!["Banana", "Apple", "Strawberry", "Grapes"];
    // `with_callback` takes a function pointer as an argument
    let ans: Result<&str, InquireError> = Select::new("What's your favorite fruit?", options).with_callback(&current_selection).prompt();
}

fn current_selection(selection: &str) {
    println!("The current selected fruit is: {selection}");
}
RobWalt commented 1 year ago

I'm in need for a similar or the same feature as you described here. I want to implement a simple text based color picker prompt that previews the picked color on any change event.

I'm probably trying to implement that in the near future for the Text prompt. Do you think that it would make sense to implement the feature with a more general argument type to also cover your case?

Like instead of a callback of the form

fn(&str) -> ()

we could implement

fn(&str) -> D where D: Display

where D is some type that is displayed where the text input / fuzzy search term would normally be displayed. This would imply that your callback would need to look like this:

fn current_selection(selection: &str) -> &str {
  println!("Hello user, here is the {selection}");
  selection
}