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