Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: MultiCount Interface #236

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
<!-- next-header -->

## [Unreleased] <!-- ReleaseDate -->

- No changes since the latest release below.
- The MultiCount prompt was added, allowing users to set numerical values for multiple options from a list.

## [0.7.3] - 2024-03-21

Expand Down
30 changes: 30 additions & 0 deletions inquire/examples/multicount.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use inquire::{
formatter::MultiCountFormatter, list_option::ListOption, validator::Validation, MultiCount,
};

fn main() {
let options = vec![
"Banana",
"Apple",
"Strawberry",
"Grapes",
"Lemon",
"Tangerine",
"Watermelon",
"Orange",
"Pear",
"Avocado",
"Pineapple",
];

let formatter: MultiCountFormatter<'_, &str> = &|a| format!("{} different fruits", a.len());

let ans = MultiCount::new("Select the fruits for your shopping list:", options)
.with_formatter(formatter)
.prompt();

match ans {
Ok(_) => println!("I'll get right on it"),
Err(_) => println!("The shopping list could not be processed"),
}
}
37 changes: 37 additions & 0 deletions inquire/src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,43 @@ pub type OptionFormatter<'a, T> = &'a dyn Fn(ListOption<&T>) -> String;
/// ```
pub type MultiOptionFormatter<'a, T> = &'a dyn Fn(&[ListOption<&T>]) -> String;

use crate::list_option::CountedListOption;
/// Type alias for formatters used in [`MultiCount`](crate::MultiCount) prompts.
///
/// Formatters receive the user input and return a [(u32, String)] to be displayed
/// to the user as the final answer.
///
/// # Examples
///
/// ```
/// use inquire::list_option::{ListOption, CountedListOption};
/// use inquire::formatter::MultiCountFormatter;
///
/// let formatter: MultiCountFormatter<str> = &|opts| {
/// let len = opts.len();
/// let options = match len {
/// 1 => "option",
/// _ => "options",
/// };
/// let values = match len {
/// 1 => "value",
/// _ => "values",
/// };
/// let counts = match len {
/// 1 => "count",
/// _ => "counts",
/// };
/// format!("You selected {} {} with {}: {:?} and {}: {:?}", len, options, values, opts.iter().map(|c| c.list_option.value).collect::<Vec<_>>(), counts, opts.iter().map(|c| c.count).collect::<Vec<_>>())
/// };
///
/// let mut ans = vec![CountedListOption::new(1, ListOption::new(1,"a"))];
/// assert_eq!(String::from("You selected 1 option with value: [\"a\"] and count: [1]"), formatter(&ans));
///
/// ans.push(CountedListOption::new(3, ListOption::new(3, "d")));
/// assert_eq!(String::from("You selected 2 options with values: [\"a\", \"d\"] and counts: [1, 3]"), formatter(&ans));
/// ```
pub type MultiCountFormatter<'a, T> = &'a dyn Fn(&[CountedListOption<&T>]) -> String;

/// Type alias for formatters used in [`CustomType`](crate::CustomType) prompts.
///
/// Formatters receive the user input and return a [String] to be displayed
Expand Down
38 changes: 38 additions & 0 deletions inquire/src/list_option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,41 @@ where
self.value.fmt(f)
}
}

/// Represents a selection made by a user alongside a count of said options, when prompted
/// to select a count of each of several presented options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CountedListOption<T> {
/// The count of the option selected.
pub count: u32,
/// The option selected.
pub list_option: ListOption<T>,
}

impl<T> CountedListOption<T> {
/// Constructor for `CountedListOption`.
///
/// # Arguments
///
/// * `count` - Count of elements chosen.
/// * `list_option` - A ListOption representing the choice.
///
/// # Examples
///
/// ```
/// use inquire::list_option::{ListOption, CountedListOption};
///
/// let answer = CountedListOption::new(0, ListOption::new(0, "a"));
/// ```
pub fn new(count: u32, list_option: ListOption<T>) -> Self {
Self { count, list_option }
}

/// Converts from `&CountedListOption<T>` to `CountedListOption<&T>`.
pub fn as_ref(&self) -> CountedListOption<&T> {
CountedListOption {
count: self.count,
list_option: self.list_option.as_ref(),
}
}
}
2 changes: 2 additions & 0 deletions inquire/src/prompts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod custom_type;
mod dateselect;
#[cfg(feature = "editor")]
mod editor;
mod multicount;
mod multiselect;
mod one_liners;
mod password;
Expand All @@ -21,6 +22,7 @@ pub use custom_type::*;
pub use dateselect::*;
#[cfg(feature = "editor")]
pub use editor::*;
pub use multicount::*;
pub use multiselect::*;
#[cfg(feature = "one-liners")]
pub use one_liners::*;
Expand Down
77 changes: 77 additions & 0 deletions inquire/src/prompts/multicount/action.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use crate::{
ui::{Key, KeyModifiers},
InnerAction, InputAction,
};

use super::config::MultiCountConfig;

/// Set of actions for a MultiCountPrompt.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum MultiCountPromptAction {
/// Action on the value text input handler.
FilterInput(InputAction),
/// Moves the cursor to the option above.
MoveUp,
/// Moves the cursor to the option below.
MoveDown,
/// Moves the cursor to the page above.
PageUp,
/// Moves the cursor to the page below.
PageDown,
/// Moves the cursor to the start of the list.
MoveToStart,
/// Moves the cursor to the end of the list.
MoveToEnd,
/// Toggles the selection of the current option.
SetCountCurrentOption(u32),
/// Increments the current selection by one
Increment,
/// Decrements the current selection by one
Decrement,
/// Increments the current selection by the given amount
MultiIncrement(u32),
/// Decrements the current selection by the given amount
MultiDecrement(u32),
/// Clears counts for all options.
ClearSelections,
}

impl InnerAction for MultiCountPromptAction {
type Config = MultiCountConfig;

fn from_key(key: Key, config: &MultiCountConfig) -> Option<Self> {
if config.vim_mode {
let action = match key {
Key::Char('k', KeyModifiers::NONE) => Some(Self::MoveUp),
Key::Char('j', KeyModifiers::NONE) => Some(Self::MoveDown),
Key::Char('+', KeyModifiers::NONE) => Some(Self::Increment),
Key::Char('-', KeyModifiers::NONE) => Some(Self::Decrement),
_ => None,
};
if action.is_some() {
return action;
}
}

let action = match key {
Key::Up(KeyModifiers::NONE) | Key::Char('p', KeyModifiers::CONTROL) => Self::MoveUp,

Key::PageUp(_) => Self::PageUp,
Key::Home => Self::MoveToStart,

Key::Down(KeyModifiers::NONE) | Key::Char('n', KeyModifiers::CONTROL) => Self::MoveDown,
Key::PageDown(_) => Self::PageDown,
Key::End => Self::MoveToEnd,

Key::Right(KeyModifiers::NONE) => Self::Increment,
Key::Left(KeyModifiers::NONE) => Self::Decrement,
Key::Right(KeyModifiers::SHIFT) => Self::MultiIncrement(10),
Key::Left(KeyModifiers::SHIFT) => Self::MultiDecrement(10),
key => match InputAction::from_key(key, &()) {
Some(action) => Self::FilterInput(action),
None => return None,
},
};
Some(action)
}
}
25 changes: 25 additions & 0 deletions inquire/src/prompts/multicount/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use crate::MultiCount;

/// Configuration settings used in the execution of a MultiCountPrompt.
#[derive(Copy, Clone, Debug)]
pub struct MultiCountConfig {
/// Whether to use vim-style keybindings.
pub vim_mode: bool,
/// Page size of the list of options.
pub page_size: usize,
/// Whether to keep the filter text when an option is selected.
pub keep_filter: bool,
/// Whether to reset the cursor to the first option on filter input change.
pub reset_cursor: bool,
}

impl<T> From<&MultiCount<'_, T>> for MultiCountConfig {
fn from(value: &MultiCount<'_, T>) -> Self {
Self {
vim_mode: value.vim_mode,
page_size: value.page_size,
keep_filter: value.keep_filter,
reset_cursor: value.reset_cursor,
}
}
}
Loading
Loading