inquire/prompts/select/mod.rs
1mod action;
2mod config;
3mod prompt;
4#[cfg(test)]
5#[cfg(feature = "crossterm")]
6mod test;
7
8pub use action::*;
9use std::fmt::Display;
10
11use crate::{
12 config::get_configuration,
13 error::{InquireError, InquireResult},
14 formatter::OptionFormatter,
15 list_option::ListOption,
16 prompts::prompt::Prompt,
17 terminal::get_default_terminal,
18 type_aliases::Scorer,
19 ui::{Backend, RenderConfig, SelectBackend},
20};
21
22use self::prompt::SelectPrompt;
23
24#[cfg(feature = "fuzzy")]
25use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
26#[cfg(feature = "fuzzy")]
27use std::sync::LazyLock;
28#[cfg(feature = "fuzzy")]
29static DEFAULT_MATCHER: LazyLock<SkimMatcherV2> =
30 LazyLock::new(|| SkimMatcherV2::default().ignore_case());
31/// Prompt suitable for when you need the user to select one option among many.
32///
33/// The user can select and submit the current highlighted option by pressing enter.
34///
35/// 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 selected option (`Vec` element) after the user submits.
36/// - If the list is empty, the prompt operation will fail with an `InquireError::InvalidConfiguration` error.
37///
38/// This prompt does not support custom validators because of its nature. A submission always selects exactly one of the options. If this option was not supposed to be selected or is invalid in some way, it probably should not be included in the options list.
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/// Like all others, this prompt also allows you to customize several aspects of it:
43///
44/// - **Prompt message**: Required when creating the prompt.
45/// - **Options list**: Options displayed to the user. Must be **non-empty**.
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 option string value by default.
51/// - **Page size**: Number of options displayed at once, 7 by default.
52/// - **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.
53/// - **Scorer function**: Function that defines the order of options and if displayed as all.
54///
55/// # Example
56///
57/// ```no_run
58/// use inquire::{error::InquireError, Select};
59///
60/// let options: Vec<&str> = vec!["Banana", "Apple", "Strawberry", "Grapes",
61/// "Lemon", "Tangerine", "Watermelon", "Orange", "Pear", "Avocado", "Pineapple",
62/// ];
63///
64/// let ans: Result<&str, InquireError> = Select::new("What's your favorite fruit?", options).prompt();
65///
66/// match ans {
67/// Ok(choice) => println!("{}! That's mine too!", choice),
68/// Err(_) => println!("There was an error, please try again"),
69/// }
70/// ```
71///
72/// [`InquireError::InvalidConfiguration`]: crate::error::InquireError::InvalidConfiguration
73#[derive(Clone)]
74pub struct Select<'a, T> {
75 /// Message to be presented to the user.
76 pub message: &'a str,
77
78 /// Options displayed to the user.
79 pub options: Vec<T>,
80
81 /// Help message to be presented to the user.
82 pub help_message: Option<&'a str>,
83
84 /// Page size of the options displayed to the user.
85 pub page_size: usize,
86
87 /// Whether vim mode is enabled. When enabled, the user can
88 /// navigate through the options using hjkl.
89 pub vim_mode: bool,
90
91 /// Starting cursor index of the selection.
92 pub starting_cursor: usize,
93
94 /// Starting filter input
95 pub starting_filter_input: Option<&'a str>,
96
97 /// Reset cursor position to first option on filter input change.
98 /// Defaults to true.
99 pub reset_cursor: bool,
100
101 /// Whether to allow the option list to be filtered by user input or not.
102 ///
103 /// Defaults to true.
104 pub filter_input_enabled: bool,
105
106 /// Function called with the current user input to score the provided
107 /// options.
108 pub scorer: Scorer<'a, T>,
109
110 /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
111 pub formatter: OptionFormatter<'a, T>,
112
113 /// RenderConfig to apply to the rendered interface.
114 ///
115 /// Note: The default render config considers if the NO_COLOR environment variable
116 /// is set to decide whether to render the colored config or the empty one.
117 ///
118 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
119 /// config is treated as the only source of truth. If you want to customize colors
120 /// and still support NO_COLOR, you will have to do this on your end.
121 pub render_config: RenderConfig<'a>,
122}
123
124impl<'a, T> Select<'a, T>
125where
126 T: Display,
127{
128 /// String formatter used by default in [Select](crate::Select) prompts.
129 /// Simply prints the string value contained in the selected option.
130 ///
131 /// # Examples
132 ///
133 /// ```
134 /// use inquire::list_option::ListOption;
135 /// use inquire::Select;
136 ///
137 /// let formatter = Select::<&str>::DEFAULT_FORMATTER;
138 /// assert_eq!(String::from("First option"), formatter(ListOption::new(0, &"First option")));
139 /// assert_eq!(String::from("First option"), formatter(ListOption::new(11, &"First option")));
140 /// ```
141 pub const DEFAULT_FORMATTER: OptionFormatter<'a, T> = &|ans| ans.to_string();
142
143 /// Default scoring function, which will create a score for the current option using the input value.
144 /// The return will be sorted in Descending order, leaving options with None as a score.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use inquire::Select;
150 ///
151 /// let scorer = Select::<&str>::DEFAULT_SCORER;
152 /// assert_eq!(None, scorer("sa", &"New York", "New York", 0));
153 /// assert_eq!(Some(49), scorer("sa", &"Sacramento", "Sacramento", 1));
154 /// assert_eq!(Some(35), scorer("sa", &"Kansas", "Kansas", 2));
155 /// assert_eq!(Some(35), scorer("sa", &"Mesa", "Mesa", 3));
156 /// assert_eq!(None, scorer("sa", &"Phoenix", "Phoenix", 4));
157 /// assert_eq!(None, scorer("sa", &"Philadelphia", "Philadelphia", 5));
158 /// assert_eq!(Some(49), scorer("sa", &"San Antonio", "San Antonio", 6));
159 /// assert_eq!(Some(49), scorer("sa", &"San Diego", "San Diego", 7));
160 /// assert_eq!(None, scorer("sa", &"Dallas", "Dallas", 8));
161 /// assert_eq!(Some(49), scorer("sa", &"San Francisco", "San Francisco", 9));
162 /// assert_eq!(None, scorer("sa", &"Austin", "Austin", 10));
163 /// assert_eq!(None, scorer("sa", &"Jacksonville", "Jacksonville", 11));
164 /// assert_eq!(Some(49), scorer("sa", &"San Jose", "San Jose", 12));
165 /// ```
166 #[cfg(feature = "fuzzy")]
167 pub const DEFAULT_SCORER: Scorer<'a, T> =
168 &|input, _option, string_value, _idx| -> Option<i64> {
169 DEFAULT_MATCHER.fuzzy_match(string_value, input)
170 };
171
172 #[cfg(not(feature = "fuzzy"))]
173 pub const DEFAULT_SCORER: Scorer<'a, T> =
174 &|input, _option, string_value, _idx| -> Option<i64> {
175 let filter = input.to_lowercase();
176 match string_value.to_lowercase().contains(&filter) {
177 true => Some(0),
178 false => None,
179 }
180 };
181
182 /// Default page size.
183 pub const DEFAULT_PAGE_SIZE: usize = crate::config::DEFAULT_PAGE_SIZE;
184
185 /// Default value of vim mode.
186 pub const DEFAULT_VIM_MODE: bool = crate::config::DEFAULT_VIM_MODE;
187
188 /// Default starting cursor index.
189 pub const DEFAULT_STARTING_CURSOR: usize = 0;
190
191 /// Default cursor behaviour on filter input change.
192 /// Defaults to true.
193 pub const DEFAULT_RESET_CURSOR: bool = true;
194
195 /// Default filter input enabled behaviour.
196 /// Defaults to true.
197 pub const DEFAULT_FILTER_INPUT_ENABLED: bool = true;
198
199 /// Default help message.
200 pub const DEFAULT_HELP_MESSAGE: Option<&'a str> =
201 Some("↑↓ to move, enter to select, type to filter");
202
203 /// Creates a [Select] with the provided message and options, along with default configuration values.
204 pub fn new(message: &'a str, options: Vec<T>) -> Self {
205 Self {
206 message,
207 options,
208 help_message: Self::DEFAULT_HELP_MESSAGE,
209 page_size: Self::DEFAULT_PAGE_SIZE,
210 vim_mode: Self::DEFAULT_VIM_MODE,
211 starting_cursor: Self::DEFAULT_STARTING_CURSOR,
212 reset_cursor: Self::DEFAULT_RESET_CURSOR,
213 filter_input_enabled: Self::DEFAULT_FILTER_INPUT_ENABLED,
214 scorer: Self::DEFAULT_SCORER,
215 formatter: Self::DEFAULT_FORMATTER,
216 render_config: get_configuration(),
217 starting_filter_input: None,
218 }
219 }
220
221 /// Sets the help message of the prompt.
222 pub fn with_help_message(mut self, message: &'a str) -> Self {
223 self.help_message = Some(message);
224 self
225 }
226
227 /// Removes the set help message.
228 pub fn without_help_message(mut self) -> Self {
229 self.help_message = None;
230 self
231 }
232
233 /// Sets the page size.
234 pub fn with_page_size(mut self, page_size: usize) -> Self {
235 self.page_size = page_size;
236 self
237 }
238
239 /// Enables or disables vim_mode.
240 pub fn with_vim_mode(mut self, vim_mode: bool) -> Self {
241 self.vim_mode = vim_mode;
242 self
243 }
244
245 /// Sets the scoring function.
246 pub fn with_scorer(mut self, scorer: Scorer<'a, T>) -> Self {
247 self.scorer = scorer;
248 self
249 }
250
251 /// Sets the formatter.
252 pub fn with_formatter(mut self, formatter: OptionFormatter<'a, T>) -> Self {
253 self.formatter = formatter;
254 self
255 }
256
257 /// Sets the starting cursor index.
258 ///
259 /// This index might be overridden if the `reset_cursor` option is set to true (default)
260 /// and starting_filter_input is set to something other than None.
261 pub fn with_starting_cursor(mut self, starting_cursor: usize) -> Self {
262 self.starting_cursor = starting_cursor;
263 self
264 }
265
266 /// Sets the starting filter input
267 pub fn with_starting_filter_input(mut self, starting_filter_input: &'a str) -> Self {
268 self.starting_filter_input = Some(starting_filter_input);
269 self
270 }
271
272 /// Sets the reset_cursor behaviour. Defaults to true.
273 ///
274 /// When there's an input change that results in a different list of options being displayed,
275 /// whether by filtering or re-ordering, the cursor will be reset to highlight the first option.
276 pub fn with_reset_cursor(mut self, reset_cursor: bool) -> Self {
277 self.reset_cursor = reset_cursor;
278 self
279 }
280
281 /// Disables the filter input, which means the user will not be able to filter the options
282 /// by typing.
283 ///
284 /// This is useful when you want to simplify the UX if the filter does not add any value,
285 /// such as when the list is already short.
286 pub fn without_filtering(mut self) -> Self {
287 self.filter_input_enabled = false;
288 self
289 }
290
291 /// Sets the provided color theme to this prompt.
292 ///
293 /// Note: The default render config considers if the NO_COLOR environment variable
294 /// is set to decide whether to render the colored config or the empty one.
295 ///
296 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
297 /// config is treated as the only source of truth. If you want to customize colors
298 /// and still support NO_COLOR, you will have to do this on your end.
299 pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
300 self.render_config = render_config;
301 self
302 }
303
304 /// Parses the provided behavioral and rendering options and prompts
305 /// the CLI user for input according to the defined rules.
306 ///
307 /// Returns the owned object selected by the user.
308 pub fn prompt(self) -> InquireResult<T> {
309 self.raw_prompt().map(|op| op.value)
310 }
311
312 /// Parses the provided behavioral and rendering options and prompts
313 /// the CLI user for input according to the defined rules.
314 ///
315 /// This method is intended for flows where the user skipping/cancelling
316 /// the prompt - by pressing ESC - is considered normal behavior. In this case,
317 /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
318 ///
319 /// Meanwhile, if the user does submit an answer, the method wraps the return
320 /// type with `Some`.
321 pub fn prompt_skippable(self) -> InquireResult<Option<T>> {
322 match self.prompt() {
323 Ok(answer) => Ok(Some(answer)),
324 Err(InquireError::OperationCanceled) => Ok(None),
325 Err(err) => Err(err),
326 }
327 }
328
329 /// Parses the provided behavioral and rendering options and prompts
330 /// the CLI user for input according to the defined rules.
331 ///
332 /// Returns a [`ListOption`](crate::list_option::ListOption) containing
333 /// the index of the selection and the owned object selected by the user.
334 ///
335 /// This method is intended for flows where the user skipping/cancelling
336 /// the prompt - by pressing ESC - is considered normal behavior. In this case,
337 /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
338 ///
339 /// Meanwhile, if the user does submit an answer, the method wraps the return
340 /// type with `Some`.
341 pub fn raw_prompt_skippable(self) -> InquireResult<Option<ListOption<T>>> {
342 match self.raw_prompt() {
343 Ok(answer) => Ok(Some(answer)),
344 Err(InquireError::OperationCanceled) => Ok(None),
345 Err(err) => Err(err),
346 }
347 }
348
349 /// Parses the provided behavioral and rendering options and prompts
350 /// the CLI user for input according to the defined rules.
351 ///
352 /// Returns a [`ListOption`](crate::list_option::ListOption) containing
353 /// the index of the selection and the owned object selected by the user.
354 pub fn raw_prompt(self) -> InquireResult<ListOption<T>> {
355 let (input_reader, terminal) = get_default_terminal()?;
356 let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
357 self.prompt_with_backend(&mut backend)
358 }
359
360 pub(crate) fn prompt_with_backend<B: SelectBackend>(
361 self,
362 backend: &mut B,
363 ) -> InquireResult<ListOption<T>> {
364 SelectPrompt::new(self)?.prompt(backend)
365 }
366}