inquire/prompts/multiselect/
mod.rs

1mod action;
2mod config;
3mod prompt;
4#[cfg(test)]
5#[cfg(feature = "crossterm")]
6mod test;
7
8pub use action::*;
9
10use std::fmt::Display;
11
12use crate::{
13    config::get_configuration,
14    error::{InquireError, InquireResult},
15    formatter::MultiOptionFormatter,
16    list_option::ListOption,
17    prompts::prompt::Prompt,
18    terminal::get_default_terminal,
19    type_aliases::Scorer,
20    ui::{Backend, MultiSelectBackend, RenderConfig},
21    validator::MultiOptionValidator,
22};
23
24use self::prompt::MultiSelectPrompt;
25
26#[cfg(feature = "fuzzy")]
27use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
28#[cfg(feature = "fuzzy")]
29use std::sync::LazyLock;
30#[cfg(feature = "fuzzy")]
31static DEFAULT_MATCHER: LazyLock<SkimMatcherV2> =
32    LazyLock::new(|| SkimMatcherV2::default().ignore_case());
33/// Prompt suitable for when you need the user to select many options (including none if applicable) among a list of them.
34///
35/// The user can select (or deselect) the current highlighted option by pressing space, clean all selections by pressing the left arrow and select all options by pressing the right arrow.
36///
37/// This prompt requires a prompt message and a **non-empty** `Vec` of options to be displayed to the user. The options can be of any type as long as they implement the `Display` trait. It is required that the `Vec` is moved to the prompt, as the prompt will return the ownership of the `Vec` after the user submits, with only the selected options inside it.
38/// - If the list is empty, the prompt operation will fail with an `InquireError::InvalidConfiguration` error.
39///
40/// The options are paginated in order to provide a smooth experience to the user, with the default page size being 7. The user can move from the options and the pages will be updated accordingly, including moving from the last to the first options (or vice-versa).
41///
42/// Customizable options:
43///
44/// - **Prompt message**: Required when creating the prompt.
45/// - **Options list**: Options displayed to the user. Must be **non-empty**.
46/// - **Default selections**: Options that are selected by default when the prompt is first rendered. The user can unselect them. If any of the indices is out-of-range of the option list, the prompt will fail with an [`InquireError::InvalidConfiguration`] error.
47/// - **Starting cursor**: Index of the cursor when the prompt is first rendered. Default is 0 (first option). If the index is out-of-range of the option list, the prompt will fail with an [`InquireError::InvalidConfiguration`] error.
48/// - **Starting filter input**: Sets the initial value of the filter section of the prompt.
49/// - **Help message**: Message displayed at the line below the prompt.
50/// - **Formatter**: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
51///   - Prints the selected options string value, joined using a comma as the separator, by default.
52/// - **Validator**: Custom validator to make sure a given submitted input pass the specified requirements, e.g. not allowing 0 selected options or limiting the number of options that the user is allowed to select.
53///   - No validators are on by default.
54/// - **Page size**: Number of options displayed at once, 7 by default.
55/// - **Display option indexes**: On long lists, it might be helpful to display the indexes of the options to the user. Via the `RenderConfig`, you can set the display mode of the indexes as a prefix of an option. The default configuration is `None`, to not render any index when displaying the options.
56/// - **Scorer function**: Function that defines the order of options and if displayed as all.
57/// - **Keep filter flag**: Whether the current filter input should be cleared or not after a selection is made. Defaults to true.
58///
59/// # Example
60///
61/// For a full-featured example, check the [GitHub repository](https://github.com/mikaelmello/inquire/blob/main/examples/multiselect.rs).
62///
63/// [`InquireError::InvalidConfiguration`]: crate::error::InquireError::InvalidConfiguration
64#[derive(Clone)]
65pub struct MultiSelect<'a, T> {
66    /// Message to be presented to the user.
67    pub message: &'a str,
68
69    /// Options displayed to the user.
70    pub options: Vec<T>,
71
72    /// Default indexes of options to be selected from the start.
73    pub default: Option<Vec<usize>>,
74
75    /// Help message to be presented to the user.
76    pub help_message: Option<&'a str>,
77
78    /// Page size of the options displayed to the user.
79    pub page_size: usize,
80
81    /// Whether vim mode is enabled. When enabled, the user can
82    /// navigate through the options using hjkl.
83    pub vim_mode: bool,
84
85    /// Starting cursor index of the selection.
86    pub starting_cursor: usize,
87
88    /// Starting filter input
89    pub starting_filter_input: Option<&'a str>,
90
91    /// Reset cursor position to first option on filter input change.
92    /// Defaults to true.
93    pub reset_cursor: bool,
94
95    /// Whether to allow the option list to be filtered by user input or not.
96    ///
97    /// Defaults to true.
98    pub filter_input_enabled: bool,
99
100    /// Function called with the current user input to score the provided
101    /// options.
102    /// The list of options is sorted in descending order (highest score first)
103    pub scorer: Scorer<'a, T>,
104
105    /// Whether the current filter typed by the user is kept or cleaned after a selection is made.
106    pub keep_filter: bool,
107
108    /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
109    pub formatter: MultiOptionFormatter<'a, T>,
110
111    /// Validator to apply to the user input.
112    ///
113    /// In case of error, the message is displayed one line above the prompt.
114    pub validator: Option<Box<dyn MultiOptionValidator<T>>>,
115
116    /// RenderConfig to apply to the rendered interface.
117    ///
118    /// Note: The default render config considers if the NO_COLOR environment variable
119    /// is set to decide whether to render the colored config or the empty one.
120    ///
121    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
122    /// config is treated as the only source of truth. If you want to customize colors
123    /// and still support NO_COLOR, you will have to do this on your end.
124    pub render_config: RenderConfig<'a>,
125}
126
127impl<'a, T> MultiSelect<'a, T>
128where
129    T: Display,
130{
131    /// String formatter used by default in [MultiSelect](crate::MultiSelect) prompts.
132    /// Prints the string value of all selected options, separated by commas.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use inquire::list_option::ListOption;
138    /// use inquire::MultiSelect;
139    ///
140    /// let formatter = MultiSelect::<&str>::DEFAULT_FORMATTER;
141    ///
142    /// let mut ans = vec![ListOption::new(0, &"New York")];
143    /// assert_eq!(String::from("New York"), formatter(&ans));
144    ///
145    /// ans.push(ListOption::new(3, &"Seattle"));
146    /// assert_eq!(String::from("New York, Seattle"), formatter(&ans));
147    ///
148    /// ans.push(ListOption::new(7, &"Vancouver"));
149    /// assert_eq!(String::from("New York, Seattle, Vancouver"), formatter(&ans));
150    /// ```
151    pub const DEFAULT_FORMATTER: MultiOptionFormatter<'a, T> = &|ans| {
152        ans.iter()
153            .map(|opt| opt.to_string())
154            .collect::<Vec<String>>()
155            .join(", ")
156    };
157
158    /// Default scoring function, which will create a score for the current option using the input value.
159    /// The return will be sorted in Descending order, leaving options with None as a score.
160    ///
161    /// # Examples
162    ///
163    /// ```
164    /// use inquire::MultiSelect;
165    ///
166    /// let scorer = MultiSelect::<&str>::DEFAULT_SCORER;
167    /// assert_eq!(None,     scorer("sa", &"New York",      "New York",      0));
168    /// assert_eq!(Some(49), scorer("sa", &"Sacramento",    "Sacramento",    1));
169    /// assert_eq!(Some(35), scorer("sa", &"Kansas",        "Kansas",        2));
170    /// assert_eq!(Some(35), scorer("sa", &"Mesa",          "Mesa",          3));
171    /// assert_eq!(None,     scorer("sa", &"Phoenix",       "Phoenix",       4));
172    /// assert_eq!(None,     scorer("sa", &"Philadelphia",  "Philadelphia",  5));
173    /// assert_eq!(Some(49), scorer("sa", &"San Antonio",   "San Antonio",   6));
174    /// assert_eq!(Some(49), scorer("sa", &"San Diego",     "San Diego",     7));
175    /// assert_eq!(None,     scorer("sa", &"Dallas",        "Dallas",        8));
176    /// assert_eq!(Some(49), scorer("sa", &"San Francisco", "San Francisco", 9));
177    /// assert_eq!(None,     scorer("sa", &"Austin",        "Austin",        10));
178    /// assert_eq!(None,     scorer("sa", &"Jacksonville",  "Jacksonville",  11));
179    /// assert_eq!(Some(49), scorer("sa", &"San Jose",      "San Jose",      12));
180    /// ```
181    #[cfg(feature = "fuzzy")]
182    pub const DEFAULT_SCORER: Scorer<'a, T> =
183        &|input, _option, string_value, _idx| -> Option<i64> {
184            DEFAULT_MATCHER.fuzzy_match(string_value, input)
185        };
186
187    #[cfg(not(feature = "fuzzy"))]
188    pub const DEFAULT_SCORER: Scorer<'a, T> =
189        &|input, _option, string_value, _idx| -> Option<i64> {
190            let filter = input.to_lowercase();
191            match string_value.to_lowercase().contains(&filter) {
192                true => Some(0),
193                false => None,
194            }
195        };
196
197    /// Default page size, equal to the global default page size [config::DEFAULT_PAGE_SIZE]
198    pub const DEFAULT_PAGE_SIZE: usize = crate::config::DEFAULT_PAGE_SIZE;
199
200    /// Default value of vim mode, equal to the global default value [config::DEFAULT_PAGE_SIZE]
201    pub const DEFAULT_VIM_MODE: bool = crate::config::DEFAULT_VIM_MODE;
202
203    /// Default starting cursor index.
204    pub const DEFAULT_STARTING_CURSOR: usize = 0;
205
206    /// Default cursor behaviour on filter input change.
207    /// Defaults to true.
208    pub const DEFAULT_RESET_CURSOR: bool = true;
209
210    /// Default filter input enabled behaviour.
211    /// Defaults to true.
212    pub const DEFAULT_FILTER_INPUT_ENABLED: bool = true;
213
214    /// Default behavior of keeping or cleaning the current filter value.
215    pub const DEFAULT_KEEP_FILTER: bool = true;
216
217    /// Default help message.
218    pub const DEFAULT_HELP_MESSAGE: Option<&'a str> =
219        Some("↑↓ to move, space to select one, → to all, ← to none, type to filter");
220
221    /// Creates a [MultiSelect] with the provided message and options, along with default configuration values.
222    pub fn new(message: &'a str, options: Vec<T>) -> Self {
223        Self {
224            message,
225            options,
226            default: None,
227            help_message: Self::DEFAULT_HELP_MESSAGE,
228            page_size: Self::DEFAULT_PAGE_SIZE,
229            vim_mode: Self::DEFAULT_VIM_MODE,
230            starting_cursor: Self::DEFAULT_STARTING_CURSOR,
231            starting_filter_input: None,
232            reset_cursor: Self::DEFAULT_RESET_CURSOR,
233            filter_input_enabled: Self::DEFAULT_FILTER_INPUT_ENABLED,
234            keep_filter: Self::DEFAULT_KEEP_FILTER,
235            scorer: Self::DEFAULT_SCORER,
236            formatter: Self::DEFAULT_FORMATTER,
237            validator: None,
238            render_config: get_configuration(),
239        }
240    }
241
242    /// Sets the help message of the prompt.
243    pub fn with_help_message(mut self, message: &'a str) -> Self {
244        self.help_message = Some(message);
245        self
246    }
247
248    /// Removes the set help message.
249    pub fn without_help_message(mut self) -> Self {
250        self.help_message = None;
251        self
252    }
253
254    /// Sets the page size.
255    pub fn with_page_size(mut self, page_size: usize) -> Self {
256        self.page_size = page_size;
257        self
258    }
259
260    /// Enables or disables vim_mode.
261    pub fn with_vim_mode(mut self, vim_mode: bool) -> Self {
262        self.vim_mode = vim_mode;
263        self
264    }
265
266    /// Sets the keep filter behavior.
267    pub fn with_keep_filter(mut self, keep_filter: bool) -> Self {
268        self.keep_filter = keep_filter;
269        self
270    }
271
272    /// Sets the scoring function.
273    pub fn with_scorer(mut self, scorer: Scorer<'a, T>) -> Self {
274        self.scorer = scorer;
275        self
276    }
277
278    /// Sets the formatter.
279    pub fn with_formatter(mut self, formatter: MultiOptionFormatter<'a, T>) -> Self {
280        self.formatter = formatter;
281        self
282    }
283
284    /// Sets the validator to apply to the user input. You might want to use this feature
285    /// in case you need to limit the user to specific choices, such as limiting the number
286    /// of selections.
287    ///
288    /// In case of error, the message is displayed one line above the prompt.
289    pub fn with_validator<V>(mut self, validator: V) -> Self
290    where
291        V: MultiOptionValidator<T> + 'static,
292    {
293        self.validator = Some(Box::new(validator));
294        self
295    }
296
297    /// Sets the indexes to be selected by default.
298    ///
299    /// The values should be valid indexes for the given option list. Any
300    /// numbers larger than the option list or duplicates will be ignored.
301    pub fn with_default(mut self, default: &'a [usize]) -> Self {
302        self.default = Some(default.to_vec());
303        self
304    }
305
306    /// Sets all options to be selected by default.
307    /// This overrides any previously set default and is equivalent to calling
308    /// `with_default` with a slice containing all indexes for the given
309    /// option list.
310    pub fn with_all_selected_by_default(mut self) -> Self {
311        self.default = Some((0..self.options.len()).collect::<Vec<_>>());
312        self
313    }
314
315    /// Sets the starting cursor index.
316    ///
317    /// This index might be overridden if the `reset_cursor` option is set to true (default)
318    /// and starting_filter_input is set to something other than None.
319    pub fn with_starting_cursor(mut self, starting_cursor: usize) -> Self {
320        self.starting_cursor = starting_cursor;
321        self
322    }
323
324    /// Sets the starting filter input
325    pub fn with_starting_filter_input(mut self, starting_filter_input: &'a str) -> Self {
326        self.starting_filter_input = Some(starting_filter_input);
327        self
328    }
329
330    /// Sets the reset_cursor behaviour. Defaults to true.
331    ///
332    /// When there's an input change that results in a different list of options being displayed,
333    /// whether by filtering or re-ordering, the cursor will be reset to highlight the first option.
334    pub fn with_reset_cursor(mut self, reset_cursor: bool) -> Self {
335        self.reset_cursor = reset_cursor;
336        self
337    }
338
339    /// Disables the filter input, which means the user will not be able to filter the options
340    /// by typing.
341    ///
342    /// This is useful when you want to simplify the UX if the filter does not add any value,
343    /// such as when the list is already short.
344    pub fn without_filtering(mut self) -> Self {
345        self.filter_input_enabled = false;
346        self
347    }
348
349    /// Sets the provided color theme to this prompt.
350    ///
351    /// Note: The default render config considers if the NO_COLOR environment variable
352    /// is set to decide whether to render the colored config or the empty one.
353    ///
354    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
355    /// config is treated as the only source of truth. If you want to customize colors
356    /// and still support NO_COLOR, you will have to do this on your end.
357    pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
358        self.render_config = render_config;
359        self
360    }
361
362    /// Parses the provided behavioral and rendering options and prompts
363    /// the CLI user for input according to the defined rules.
364    ///
365    /// Returns the owned objects selected by the user.
366    ///
367    /// This method is intended for flows where the user skipping/cancelling
368    /// the prompt - by pressing ESC - is considered normal behavior. In this case,
369    /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
370    ///
371    /// Meanwhile, if the user does submit an answer, the method wraps the return
372    /// type with `Some`.
373    pub fn prompt_skippable(self) -> InquireResult<Option<Vec<T>>> {
374        match self.prompt() {
375            Ok(answer) => Ok(Some(answer)),
376            Err(InquireError::OperationCanceled) => Ok(None),
377            Err(err) => Err(err),
378        }
379    }
380
381    /// Parses the provided behavioral and rendering options and prompts
382    /// the CLI user for input according to the defined rules.
383    ///
384    /// Returns the owned objects selected by the user.
385    pub fn prompt(self) -> InquireResult<Vec<T>> {
386        self.raw_prompt()
387            .map(|op| op.into_iter().map(|o| o.value).collect())
388    }
389
390    /// Parses the provided behavioral and rendering options and prompts
391    /// the CLI user for input according to the defined rules.
392    ///
393    /// Returns a vector of [`ListOption`](crate::list_option::ListOption)s containing
394    /// the index of the selections and the owned objects selected by the user.
395    ///
396    /// This method is intended for flows where the user skipping/cancelling
397    /// the prompt - by pressing ESC - is considered normal behavior. In this case,
398    /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
399    ///
400    /// Meanwhile, if the user does submit an answer, the method wraps the return
401    /// type with `Some`.
402    pub fn raw_prompt_skippable(self) -> InquireResult<Option<Vec<ListOption<T>>>> {
403        match self.raw_prompt() {
404            Ok(answer) => Ok(Some(answer)),
405            Err(InquireError::OperationCanceled) => Ok(None),
406            Err(err) => Err(err),
407        }
408    }
409
410    /// Parses the provided behavioral and rendering options and prompts
411    /// the CLI user for input according to the defined rules.
412    ///
413    /// Returns a [`ListOption`](crate::list_option::ListOption) containing
414    /// the index of the selection and the owned object selected by the user.
415    pub fn raw_prompt(self) -> InquireResult<Vec<ListOption<T>>> {
416        let (input_reader, terminal) = get_default_terminal()?;
417        let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
418        self.prompt_with_backend(&mut backend)
419    }
420
421    pub(crate) fn prompt_with_backend<B: MultiSelectBackend>(
422        self,
423        backend: &mut B,
424    ) -> InquireResult<Vec<ListOption<T>>> {
425        MultiSelectPrompt::new(self)?.prompt(backend)
426    }
427}