inquire/prompts/custom_type/mod.rs
1mod action;
2mod config;
3mod prompt;
4
5pub use action::*;
6
7use std::str::FromStr;
8
9use crate::{
10 config::get_configuration,
11 error::{InquireError, InquireResult},
12 formatter::CustomTypeFormatter,
13 parser::CustomTypeParser,
14 prompts::prompt::Prompt,
15 terminal::get_default_terminal,
16 ui::{Backend, CustomTypeBackend, RenderConfig},
17 validator::CustomTypeValidator,
18};
19
20use self::prompt::CustomTypePrompt;
21
22/// 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`.
23///
24/// 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.
25///
26/// You can customize as many aspects of this prompt as you like: prompt message, help message, default value, placeholder, value parser and value formatter.
27///
28/// # Behavior
29///
30/// 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.
31///
32/// 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.
33///
34/// 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.
35///
36/// 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.
37///
38/// If your type `T` does not satisfy these constraints, you can always manually instantiate the entire struct yourself like this:
39///
40/// ```no_run
41/// use inquire::{CustomType, ui::RenderConfig};
42///
43/// let amount_prompt: CustomType<f64> = CustomType {
44/// message: "How much is your travel going to cost?",
45/// starting_input: None,
46/// formatter: &|i| format!("${:.2}", i),
47/// default_value_formatter: &|i| format!("${:.2}", i),
48/// default: None,
49/// validators: vec![],
50/// placeholder: Some("123.45"),
51/// error_message: "Please type a valid number.".into(),
52/// help_message: "Do not use currency and the number should use dots as the decimal separator.".into(),
53/// parser: &|i| match i.parse::<f64>() {
54/// Ok(val) => Ok(val),
55/// Err(_) => Err(()),
56/// },
57/// render_config: RenderConfig::default(),
58/// };
59/// ```
60///
61/// # Example
62///
63/// ```no_run
64/// use inquire::CustomType;
65///
66/// let amount = CustomType::<f64>::new("How much do you want to donate?")
67/// .with_formatter(&|i| format!("${:.2}", i))
68/// .with_error_message("Please type a valid number")
69/// .with_help_message("Type the amount in US dollars using a decimal point as a separator")
70/// .prompt();
71///
72/// match amount {
73/// Ok(_) => println!("Thanks a lot for donating that much money!"),
74/// Err(_) => println!("We could not process your donation"),
75/// }
76/// ```
77///
78/// [`CustomType`]: crate::CustomType
79#[derive(Clone)]
80pub struct CustomType<'a, T> {
81 /// Message to be presented to the user.
82 pub message: &'a str,
83
84 /// Initial value of the prompt's text input.
85 ///
86 /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`default`].
87 ///
88 /// [`default`]: Self::default
89 pub starting_input: Option<&'a str>,
90
91 /// Default value, returned when the user input is empty.
92 pub default: Option<T>,
93
94 /// Short hint that describes the expected value of the input.
95 pub placeholder: Option<&'a str>,
96
97 /// Help message to be presented to the user.
98 pub help_message: Option<&'a str>,
99
100 /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
101 pub formatter: CustomTypeFormatter<'a, T>,
102
103 /// 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.
104 pub default_value_formatter: CustomTypeFormatter<'a, T>,
105
106 /// Function that parses the user input and returns the result value.
107 pub parser: CustomTypeParser<'a, T>,
108
109 /// Collection of validators to apply to the user input.
110 ///
111 /// Validators are executed in the order they are stored, stopping at and displaying to the user
112 /// only the first validation error that might appear.
113 ///
114 /// The possible error is displayed to the user one line above the prompt.
115 pub validators: Vec<Box<dyn CustomTypeValidator<T>>>,
116
117 /// Error message displayed when value could not be parsed from input.
118 pub error_message: String,
119
120 /// RenderConfig to apply to the rendered interface.
121 ///
122 /// Note: The default render config considers if the NO_COLOR environment variable
123 /// is set to decide whether to render the colored config or the empty one.
124 ///
125 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
126 /// config is treated as the only source of truth. If you want to customize colors
127 /// and still support NO_COLOR, you will have to do this on your end.
128 pub render_config: RenderConfig<'a>,
129}
130
131impl<'a, T> CustomType<'a, T>
132where
133 T: Clone,
134{
135 /// Default validators added to the [CustomType] prompt, none.
136 pub const DEFAULT_VALIDATORS: Vec<Box<dyn CustomTypeValidator<T>>> = vec![];
137
138 /// Creates a [CustomType] with the provided message and default configuration values.
139 pub fn new(message: &'a str) -> Self
140 where
141 T: FromStr + ToString,
142 {
143 Self {
144 message,
145 starting_input: None,
146 default: None,
147 placeholder: None,
148 help_message: None,
149 formatter: &|val| val.to_string(),
150 default_value_formatter: &|val| val.to_string(),
151 parser: &|a| a.parse::<T>().map_err(|_e| ()),
152 validators: Self::DEFAULT_VALIDATORS,
153 error_message: "Invalid input".into(),
154 render_config: get_configuration(),
155 }
156 }
157
158 /// Sets the initial value of the prompt's text input.
159 ///
160 /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`with_default`].
161 ///
162 /// [`with_default`]: Self::with_default
163 pub fn with_starting_input(mut self, message: &'a str) -> Self {
164 self.starting_input = Some(message);
165 self
166 }
167
168 /// Sets the default input.
169 pub fn with_default(mut self, default: T) -> Self {
170 self.default = Some(default);
171 self
172 }
173
174 /// Sets the placeholder.
175 pub fn with_placeholder(mut self, placeholder: &'a str) -> Self {
176 self.placeholder = Some(placeholder);
177 self
178 }
179
180 /// Sets the help message of the prompt.
181 pub fn with_help_message(mut self, message: &'a str) -> Self {
182 self.help_message = Some(message);
183 self
184 }
185
186 /// Sets the formatter
187 pub fn with_formatter(mut self, formatter: CustomTypeFormatter<'a, T>) -> Self {
188 self.formatter = formatter;
189 self
190 }
191
192 /// Sets the formatter for default values.
193 ///
194 /// Useful for example when you want to format a default `true` to the string "Y/n", common in confirmation prompts,
195 /// when the final answer would be displayed likely as "Yes" or "No".
196 pub fn with_default_value_formatter(mut self, formatter: CustomTypeFormatter<'a, T>) -> Self {
197 self.default_value_formatter = formatter;
198 self
199 }
200
201 /// Sets the parser.
202 pub fn with_parser(mut self, parser: CustomTypeParser<'a, T>) -> Self {
203 self.parser = parser;
204 self
205 }
206
207 /// Adds a validator to the collection of validators. You might want to use this feature
208 /// in case you need to require certain features from the parsed user's answer.
209 ///
210 /// Validators are executed in the order they are stored, stopping at and displaying to the user
211 /// only the first validation error that might appear.
212 ///
213 /// The possible error is displayed to the user one line above the prompt.
214 pub fn with_validator<V>(mut self, validator: V) -> Self
215 where
216 V: CustomTypeValidator<T> + 'static,
217 {
218 self.validators.push(Box::new(validator));
219 self
220 }
221
222 /// Adds the validators to the collection of validators in the order they are given.
223 /// You might want to use this feature in case you need to require certain features
224 /// from the parsed user's answer.
225 ///
226 /// Validators are executed in the order they are stored, stopping at and displaying to the user
227 /// only the first validation error that might appear.
228 ///
229 /// The possible error is displayed to the user one line above the prompt.
230 pub fn with_validators(mut self, validators: &[Box<dyn CustomTypeValidator<T>>]) -> Self {
231 for validator in validators {
232 #[allow(suspicious_double_ref_op)]
233 self.validators.push(validator.clone());
234 }
235 self
236 }
237
238 /// Sets a custom error message displayed when a submission could not be parsed to a value.
239 pub fn with_error_message(mut self, error_message: &'a str) -> Self {
240 self.error_message = String::from(error_message);
241 self
242 }
243
244 /// Sets the provided color theme to this prompt.
245 ///
246 /// Note: The default render config considers if the NO_COLOR environment variable
247 /// is set to decide whether to render the colored config or the empty one.
248 ///
249 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
250 /// config is treated as the only source of truth. If you want to customize colors
251 /// and still support NO_COLOR, you will have to do this on your end.
252 pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
253 self.render_config = render_config;
254 self
255 }
256
257 /// Parses the provided behavioral and rendering options and prompts
258 /// the CLI user for input according to the defined rules.
259 ///
260 /// This method is intended for flows where the user skipping/cancelling
261 /// the prompt - by pressing ESC - is considered normal behavior. In this case,
262 /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
263 ///
264 /// Meanwhile, if the user does submit an answer, the method wraps the return
265 /// type with `Some`.
266 pub fn prompt_skippable(self) -> InquireResult<Option<T>> {
267 match self.prompt() {
268 Ok(answer) => Ok(Some(answer)),
269 Err(InquireError::OperationCanceled) => Ok(None),
270 Err(err) => Err(err),
271 }
272 }
273
274 /// Parses the provided behavioral and rendering options and prompts
275 /// the CLI user for input according to the defined rules.
276 pub fn prompt(self) -> InquireResult<T> {
277 let (input_reader, terminal) = get_default_terminal()?;
278 let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
279 self.prompt_with_backend(&mut backend)
280 }
281
282 pub(crate) fn prompt_with_backend<B: CustomTypeBackend>(
283 self,
284 backend: &mut B,
285 ) -> InquireResult<T> {
286 CustomTypePrompt::from(self).prompt(backend)
287 }
288}