inquire/prompts/
custom_type.rs

1use std::str::FromStr;
2
3use crate::{
4    config::get_configuration,
5    error::{InquireError, InquireResult},
6    formatter::CustomTypeFormatter,
7    input::Input,
8    parser::CustomTypeParser,
9    terminal::get_default_terminal,
10    ui::{Backend, CustomTypeBackend, Key, RenderConfig},
11    validator::{CustomTypeValidator, ErrorMessage, Validation},
12};
13
14/// Generic prompt suitable for when you need to parse the user input into a specific type, for example an `f64` or a `rust_decimal`, maybe even an `uuid`.
15///
16/// This prompt has all of the validation, parsing and error handling features built-in to reduce as much boilerplaste as possible from your prompts. Its defaults are necessarily very simple in order to cover a large range of generic cases, for example a "Invalid input" error message.
17///
18/// You can customize as many aspects of this prompt as you like: prompt message, help message, default value, placeholder, value parser and value formatter.
19///
20/// # Behavior
21///
22/// When initializing this prompt via the `new()` method, some constraints on the return type `T` are added to make sure we can apply a default parser and formatter to the prompt.
23///
24/// The default parser calls the [`str.parse`](https://doc.rust-lang.org/stable/std/primitive.str.html#method.parse) method, which means that `T` must implement the `FromStr` trait. When the parsing fails for any reason, a default error message "Invalid input" is displayed to the user.
25///
26/// After the user submits, the prompt handler tries to parse the input into the expected type. If the operation succeeds, the value is returned to the prompt caller. If it fails, the message defined in `error_message` is displayed to the user.
27///
28/// The default formatter simply calls `to_string()` on the parsed value, which means that `T` must implement the `ToString` trait, which normally happens implicitly when you implement the `Display` trait.
29///
30/// If your type `T` does not satisfy these constraints, you can always manually instantiate the entire struct yourself like this:
31///
32/// ```no_run
33/// use inquire::{CustomType, ui::RenderConfig};
34///
35/// let amount_prompt: CustomType<f64> = CustomType {
36///     message: "How much is your travel going to cost?",
37///     formatter: &|i| format!("${:.2}", i),
38///     default_value_formatter: &|i| format!("${:.2}", i),
39///     default: None,
40///     validators: vec![],
41///     placeholder: Some("123.45"),
42///     error_message: "Please type a valid number.".into(),
43///     help_message: "Do not use currency and the number should use dots as the decimal separator.".into(),
44///     parser: &|i| match i.parse::<f64>() {
45///         Ok(val) => Ok(val),
46///         Err(_) => Err(()),
47///     },
48///     render_config: RenderConfig::default(),
49/// };
50/// ```
51///
52/// # Example
53///
54/// ```no_run
55/// use inquire::CustomType;
56///
57/// let amount = CustomType::<f64>::new("How much do you want to donate?")
58///     .with_formatter(&|i| format!("${:.2}", i))
59///     .with_error_message("Please type a valid number")
60///     .with_help_message("Type the amount in US dollars using a decimal point as a separator")
61///     .prompt();
62///
63/// match amount {
64///     Ok(_) => println!("Thanks a lot for donating that much money!"),
65///     Err(_) => println!("We could not process your donation"),
66/// }
67/// ```
68///
69/// [`CustomType`]: crate::CustomType
70#[derive(Clone)]
71pub struct CustomType<'a, T> {
72    /// Message to be presented to the user.
73    pub message: &'a str,
74
75    /// Default value, returned when the user input is empty.
76    pub default: Option<T>,
77
78    /// Short hint that describes the expected value of the input.
79    pub placeholder: Option<&'a str>,
80
81    /// Help message to be presented to the user.
82    pub help_message: Option<&'a str>,
83
84    /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
85    pub formatter: CustomTypeFormatter<'a, T>,
86
87    /// Function that formats the provided value. Useful for example when you want to format a default `true` to the string "Y/n", common in confirmation prompts.
88    pub default_value_formatter: CustomTypeFormatter<'a, T>,
89
90    /// Function that parses the user input and returns the result value.
91    pub parser: CustomTypeParser<'a, T>,
92
93    /// Collection of validators to apply to the user input.
94    ///
95    /// Validators are executed in the order they are stored, stopping at and displaying to the user
96    /// only the first validation error that might appear.
97    ///
98    /// The possible error is displayed to the user one line above the prompt.
99    pub validators: Vec<Box<dyn CustomTypeValidator<T>>>,
100
101    /// Error message displayed when value could not be parsed from input.
102    pub error_message: String,
103
104    /// RenderConfig to apply to the rendered interface.
105    ///
106    /// Note: The default render config considers if the NO_COLOR environment variable
107    /// is set to decide whether to render the colored config or the empty one.
108    ///
109    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
110    /// config is treated as the only source of truth. If you want to customize colors
111    /// and still suport NO_COLOR, you will have to do this on your end.
112    pub render_config: RenderConfig,
113}
114
115impl<'a, T> CustomType<'a, T>
116where
117    T: Clone,
118{
119    /// Default validators added to the [CustomType] prompt, none.
120    pub const DEFAULT_VALIDATORS: Vec<Box<dyn CustomTypeValidator<T>>> = vec![];
121
122    /// Creates a [CustomType] with the provided message and default configuration values.
123    pub fn new(message: &'a str) -> Self
124    where
125        T: FromStr + ToString,
126    {
127        Self {
128            message,
129            default: None,
130            placeholder: None,
131            help_message: None,
132            formatter: &|val| val.to_string(),
133            default_value_formatter: &|val| val.to_string(),
134            parser: &|a| a.parse::<T>().map_err(|_| ()),
135            validators: Self::DEFAULT_VALIDATORS,
136            error_message: "Invalid input".into(),
137            render_config: get_configuration(),
138        }
139    }
140
141    /// Sets the default input.
142    pub fn with_default(mut self, default: T) -> Self {
143        self.default = Some(default);
144        self
145    }
146
147    /// Sets the placeholder.
148    pub fn with_placeholder(mut self, placeholder: &'a str) -> Self {
149        self.placeholder = Some(placeholder);
150        self
151    }
152
153    /// Sets the help message of the prompt.
154    pub fn with_help_message(mut self, message: &'a str) -> Self {
155        self.help_message = Some(message);
156        self
157    }
158
159    /// Sets the formatter
160    pub fn with_formatter(mut self, formatter: CustomTypeFormatter<'a, T>) -> Self {
161        self.formatter = formatter;
162        self
163    }
164
165    /// Sets the formatter for default values.
166    ///
167    /// Useful for example when you want to format a default `true` to the string "Y/n", common in confirmation prompts,
168    /// when the final answer would be displayed likely as "Yes" or "No".
169    pub fn with_default_value_formatter(mut self, formatter: CustomTypeFormatter<'a, T>) -> Self {
170        self.default_value_formatter = formatter;
171        self
172    }
173
174    /// Sets the parser.
175    pub fn with_parser(mut self, parser: CustomTypeParser<'a, T>) -> Self {
176        self.parser = parser;
177        self
178    }
179
180    /// Adds a validator to the collection of validators. You might want to use this feature
181    /// in case you need to require certain features from the parsed user's answer.
182    ///
183    /// Validators are executed in the order they are stored, stopping at and displaying to the user
184    /// only the first validation error that might appear.
185    ///
186    /// The possible error is displayed to the user one line above the prompt.
187    pub fn with_validator<V>(mut self, validator: V) -> Self
188    where
189        V: CustomTypeValidator<T> + 'static,
190    {
191        // Directly make space for at least 5 elements, so we won't to re-allocate too often when
192        // calling this function repeatedly.
193        if self.validators.capacity() == 0 {
194            self.validators.reserve(5);
195        }
196
197        self.validators.push(Box::new(validator));
198        self
199    }
200
201    /// Adds the validators to the collection of validators in the order they are given.
202    /// You might want to use this feature in case you need to require certain features
203    /// from the parsed user's answer.
204    ///
205    /// Validators are executed in the order they are stored, stopping at and displaying to the user
206    /// only the first validation error that might appear.
207    ///
208    /// The possible error is displayed to the user one line above the prompt.
209    pub fn with_validators(mut self, validators: &[Box<dyn CustomTypeValidator<T>>]) -> Self {
210        for validator in validators {
211            #[allow(clippy::clone_double_ref)]
212            self.validators.push(validator.clone());
213        }
214        self
215    }
216
217    /// Sets a custom error message displayed when a submission could not be parsed to a value.
218    pub fn with_error_message(mut self, error_message: &'a str) -> Self {
219        self.error_message = String::from(error_message);
220        self
221    }
222
223    /// Sets the provided color theme to this prompt.
224    ///
225    /// Note: The default render config considers if the NO_COLOR environment variable
226    /// is set to decide whether to render the colored config or the empty one.
227    ///
228    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
229    /// config is treated as the only source of truth. If you want to customize colors
230    /// and still suport NO_COLOR, you will have to do this on your end.
231    pub fn with_render_config(mut self, render_config: RenderConfig) -> Self {
232        self.render_config = render_config;
233        self
234    }
235
236    /// Parses the provided behavioral and rendering options and prompts
237    /// the CLI user for input according to the defined rules.
238    ///
239    /// This method is intended for flows where the user skipping/cancelling
240    /// the prompt - by pressing ESC - is considered normal behavior. In this case,
241    /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
242    ///
243    /// Meanwhile, if the user does submit an answer, the method wraps the return
244    /// type with `Some`.
245    pub fn prompt_skippable(self) -> InquireResult<Option<T>> {
246        match self.prompt() {
247            Ok(answer) => Ok(Some(answer)),
248            Err(InquireError::OperationCanceled) => Ok(None),
249            Err(err) => Err(err),
250        }
251    }
252
253    /// Parses the provided behavioral and rendering options and prompts
254    /// the CLI user for input according to the defined rules.
255    pub fn prompt(self) -> InquireResult<T> {
256        let terminal = get_default_terminal()?;
257        let mut backend = Backend::new(terminal, self.render_config)?;
258        self.prompt_with_backend(&mut backend)
259    }
260
261    pub(crate) fn prompt_with_backend<B: CustomTypeBackend>(
262        self,
263        backend: &mut B,
264    ) -> InquireResult<T> {
265        CustomTypePrompt::from(self).prompt(backend)
266    }
267}
268
269struct CustomTypePrompt<'a, T> {
270    message: &'a str,
271    error: Option<ErrorMessage>,
272    help_message: Option<&'a str>,
273    default: Option<T>,
274    input: Input,
275    formatter: CustomTypeFormatter<'a, T>,
276    default_value_formatter: CustomTypeFormatter<'a, T>,
277    validators: Vec<Box<dyn CustomTypeValidator<T>>>,
278    parser: CustomTypeParser<'a, T>,
279    error_message: String,
280}
281
282impl<'a, T> From<CustomType<'a, T>> for CustomTypePrompt<'a, T>
283where
284    T: Clone,
285{
286    fn from(co: CustomType<'a, T>) -> Self {
287        Self {
288            message: co.message,
289            error: None,
290            default: co.default,
291            help_message: co.help_message,
292            formatter: co.formatter,
293            default_value_formatter: co.default_value_formatter,
294            validators: co.validators,
295            parser: co.parser,
296            input: co
297                .placeholder
298                .map(|p| Input::new().with_placeholder(p))
299                .unwrap_or_else(Input::new),
300            error_message: co.error_message,
301        }
302    }
303}
304
305impl<'a, T> CustomTypePrompt<'a, T>
306where
307    T: Clone,
308{
309    fn on_change(&mut self, key: Key) {
310        self.input.handle_key(key);
311    }
312
313    fn validate_current_answer(&self, value: &T) -> InquireResult<Validation> {
314        for validator in &self.validators {
315            match validator.validate(value) {
316                Ok(Validation::Valid) => {}
317                Ok(Validation::Invalid(msg)) => return Ok(Validation::Invalid(msg)),
318                Err(err) => return Err(InquireError::Custom(err)),
319            }
320        }
321
322        Ok(Validation::Valid)
323    }
324
325    fn get_final_answer(&self) -> Result<T, String> {
326        match &self.default {
327            Some(val) if self.input.content().is_empty() => return Ok(val.clone()),
328            _ => {}
329        }
330
331        match (self.parser)(self.input.content()) {
332            Ok(val) => Ok(val),
333            Err(_) => Err(self.error_message.clone()),
334        }
335    }
336
337    fn render<B: CustomTypeBackend>(&mut self, backend: &mut B) -> InquireResult<()> {
338        let prompt = &self.message;
339
340        backend.frame_setup()?;
341
342        if let Some(error) = &self.error {
343            backend.render_error_message(error)?;
344        }
345
346        let default_value_formatter = self.default_value_formatter;
347        let default_message = self
348            .default
349            .as_ref()
350            .map(|val| default_value_formatter(val.clone()));
351
352        backend.render_prompt(prompt, default_message.as_deref(), &self.input)?;
353
354        if let Some(message) = self.help_message {
355            backend.render_help_message(message)?;
356        }
357
358        backend.frame_finish()?;
359
360        Ok(())
361    }
362
363    fn prompt<B: CustomTypeBackend>(mut self, backend: &mut B) -> InquireResult<T> {
364        let final_answer: T;
365
366        loop {
367            self.render(backend)?;
368
369            let key = backend.read_key()?;
370
371            match key {
372                Key::Interrupt => interrupt_prompt!(),
373                Key::Cancel => cancel_prompt!(backend, self.message),
374                Key::Submit => match self.get_final_answer() {
375                    Ok(answer) => match self.validate_current_answer(&answer)? {
376                        Validation::Valid => {
377                            final_answer = answer;
378                            break;
379                        }
380                        Validation::Invalid(msg) => self.error = Some(msg),
381                    },
382                    Err(message) => self.error = Some(message.into()),
383                },
384                key => self.on_change(key),
385            }
386        }
387
388        let formatted = (self.formatter)(final_answer.clone());
389
390        finish_prompt_with_answer!(backend, self.message, &formatted, final_answer);
391    }
392}