inquire/prompts/text/
mod.rs

1mod action;
2mod config;
3mod prompt;
4#[cfg(test)]
5#[cfg(feature = "crossterm")]
6mod test;
7
8pub use action::*;
9
10use crate::{
11    autocompletion::Autocomplete,
12    config::get_configuration,
13    error::{InquireError, InquireResult},
14    formatter::{StringFormatter, DEFAULT_STRING_FORMATTER},
15    prompts::prompt::Prompt,
16    terminal::get_default_terminal,
17    ui::{Backend, RenderConfig, TextBackend},
18    validator::StringValidator,
19};
20
21use self::prompt::TextPrompt;
22
23const DEFAULT_HELP_MESSAGE_WITH_AC: &str = "↑↓ to move, tab to autocomplete, enter to submit";
24
25/// Standard text prompt that returns the user string input.
26///
27/// This is the standard the standard kind of prompt you would expect from a library like this one. It displays a message to the user, prompting them to type something back. The user's input is then stored in a `String` and returned to the prompt caller.
28///
29///
30/// ## Configuration options
31///
32/// - **Prompt message**: Main message when prompting the user for input, `"What is your name?"` in the example below.
33/// - **Help message**: Message displayed at the line below the prompt.
34/// - **Default value**: Default value returned when the user submits an empty response.
35/// - **Initial value**: Initial value of the prompt's text input, in case you want to display the prompt with something already filled in.
36/// - **Placeholder**: Short hint that describes the expected value of the input.
37/// - **Validators**: Custom validators to the user's input, displaying an error message if the input does not pass the requirements.
38/// - **Formatter**: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
39/// - **Suggester**: Custom function that returns a list of input suggestions based on the current text input. See more on "Autocomplete" below.
40///
41/// ## Default behaviors
42///
43/// Default behaviors for each one of `Text` configuration options:
44///
45/// - The input formatter just echoes back the given input.
46/// - No validators are called, accepting any sort of input including empty ones.
47/// - No default values or help messages.
48/// - No autocompletion features set-up.
49/// - Prompt messages are always required when instantiating via `new()`.
50///
51/// ## Autocomplete
52///
53/// With `Text` inputs, it is also possible to set-up an autocompletion system to provide a better UX when necessary.
54///
55/// You can call `with_autocomplete()` and provide a value that implements the `Autocomplete` trait. The `Autocomplete` trait has two provided methods: `get_suggestions` and `get_completion`.
56///
57/// - `get_suggestions` is called whenever the user's text input is modified, e.g. a new letter is typed, returning a `Vec<String>`. The `Vec<String>` is the list of suggestions that the prompt displays to the user according to their text input. The user can then navigate through the list and if they submit while highlighting one of these suggestions, the suggestion is treated as the final answer.
58/// - `get_completion` is called whenever the user presses the autocompletion hotkey (`tab` by default), with the current text input and the text of the currently highlighted suggestion, if any, as parameters. This method should return whether any text replacement (an autocompletion) should be made. If the prompt receives a replacement to be made, it substitutes the current text input for the string received from the `get_completion` call.
59///
60/// For example, in the `complex_autocompletion.rs` example file, the `FilePathCompleter` scans the file system based on the current text input, storing a list of paths that match the current text input.
61///
62/// Every time `get_suggestions` is called, the method returns the list of paths that match the user input. When the user presses the autocompletion hotkey, the `FilePathCompleter` checks whether there is any path selected from the list, if there is, it decides to replace the current text input for it. The interesting piece of functionality is that if there isn't a path selected from the list, the `FilePathCompleter` calculates the longest common prefix amongst all scanned paths and updates the text input to an unambiguous new value. Similar to how terminals work when traversing paths.
63///
64/// # Example
65///
66/// ```no_run
67/// use inquire::Text;
68///
69/// let name = Text::new("What is your name?").prompt();
70///
71/// match name {
72///     Ok(name) => println!("Hello {}", name),
73///     Err(_) => println!("An error happened when asking for your name, try again later."),
74/// }
75/// ```
76pub struct Text<'a, 'b> {
77    /// Message to be presented to the user.
78    pub message: &'a str,
79
80    /// Initial value of the prompt's text input.
81    ///
82    /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`default`].
83    ///
84    /// [`default`]: Self::default
85    pub initial_value: Option<&'a str>,
86
87    /// Default value, returned when the user input is empty.
88    pub default: Option<&'a str>,
89
90    /// Short hint that describes the expected value of the input.
91    pub placeholder: Option<&'a str>,
92
93    /// Help message to be presented to the user.
94    pub help_message: Option<&'a str>,
95
96    /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
97    pub formatter: StringFormatter<'a>,
98
99    /// Autocompleter responsible for handling suggestions and input completions.
100    pub autocompleter: Option<Box<dyn Autocomplete + 'b>>,
101
102    /// Collection of validators to apply to the user input.
103    ///
104    /// Validators are executed in the order they are stored, stopping at and displaying to the user
105    /// only the first validation error that might appear.
106    ///
107    /// The possible error is displayed to the user one line above the prompt.
108    pub validators: Vec<Box<dyn StringValidator + 'b>>,
109
110    /// Page size of the suggestions displayed to the user, when applicable.
111    pub page_size: usize,
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> Clone for Text<'a, 'static> {
125    fn clone(&self) -> Self {
126        Self {
127            message: self.message,
128            initial_value: self.initial_value,
129            default: self.default,
130            placeholder: self.placeholder,
131            help_message: self.help_message,
132            formatter: self.formatter,
133            autocompleter: self.autocompleter.clone(),
134            validators: self.validators.clone(),
135            page_size: self.page_size,
136            render_config: self.render_config,
137        }
138    }
139}
140
141impl<'a, 'b> Text<'a, 'b> {
142    /// Default formatter, set to [DEFAULT_STRING_FORMATTER](crate::formatter::DEFAULT_STRING_FORMATTER)
143    pub const DEFAULT_FORMATTER: StringFormatter<'a> = DEFAULT_STRING_FORMATTER;
144
145    /// Default page size, equal to the global default page size [config::DEFAULT_PAGE_SIZE]
146    pub const DEFAULT_PAGE_SIZE: usize = crate::config::DEFAULT_PAGE_SIZE;
147
148    /// Default validators added to the [Text] prompt, none.
149    pub const DEFAULT_VALIDATORS: Vec<Box<dyn StringValidator>> = vec![];
150
151    /// Default help message.
152    pub const DEFAULT_HELP_MESSAGE: Option<&'a str> = None;
153
154    /// Creates a [Text] with the provided message and default options.
155    pub fn new(message: &'a str) -> Self {
156        Self {
157            message,
158            placeholder: None,
159            initial_value: None,
160            default: None,
161            help_message: Self::DEFAULT_HELP_MESSAGE,
162            validators: Self::DEFAULT_VALIDATORS,
163            formatter: Self::DEFAULT_FORMATTER,
164            page_size: Self::DEFAULT_PAGE_SIZE,
165            autocompleter: None,
166            render_config: get_configuration(),
167        }
168    }
169
170    /// Sets the help message of the prompt.
171    pub fn with_help_message(mut self, message: &'a str) -> Self {
172        self.help_message = Some(message);
173        self
174    }
175
176    /// Sets the initial value of the prompt's text input.
177    ///
178    /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`with_default`].
179    ///
180    /// [`with_default`]: Self::with_default
181    pub fn with_initial_value(mut self, message: &'a str) -> Self {
182        self.initial_value = Some(message);
183        self
184    }
185
186    /// Sets the default input.
187    pub fn with_default(mut self, message: &'a str) -> Self {
188        self.default = Some(message);
189        self
190    }
191
192    /// Sets the placeholder.
193    pub fn with_placeholder(mut self, placeholder: &'a str) -> Self {
194        self.placeholder = Some(placeholder);
195        self
196    }
197
198    /// Sets a new autocompleter
199    pub fn with_autocomplete<AC>(mut self, ac: AC) -> Self
200    where
201        AC: Autocomplete + 'b,
202    {
203        self.autocompleter = Some(Box::new(ac));
204        self
205    }
206
207    /// Sets the formatter.
208    pub fn with_formatter(mut self, formatter: StringFormatter<'a>) -> Self {
209        self.formatter = formatter;
210        self
211    }
212
213    /// Sets the page size
214    pub fn with_page_size(mut self, page_size: usize) -> Self {
215        self.page_size = page_size;
216        self
217    }
218
219    /// Adds a validator to the collection of validators. You might want to use this feature
220    /// in case you need to require certain features from the user's answer, such as
221    /// defining a limit of characters.
222    ///
223    /// Validators are executed in the order they are stored, stopping at and displaying to the user
224    /// only the first validation error that might appear.
225    ///
226    /// The possible error is displayed to the user one line above the prompt.
227    pub fn with_validator<V>(mut self, validator: V) -> Self
228    where
229        V: StringValidator + 'b,
230    {
231        self.validators.push(Box::new(validator));
232        self
233    }
234
235    /// Adds the validators to the collection of validators in the order they are given.
236    /// You might want to use this feature in case you need to require certain features
237    /// from the user's answer, such as defining a limit of characters.
238    ///
239    /// Validators are executed in the order they are stored, stopping at and displaying to the user
240    /// only the first validation error that might appear.
241    ///
242    /// The possible error is displayed to the user one line above the prompt.
243    pub fn with_validators(mut self, validators: &[Box<dyn StringValidator>]) -> Self {
244        for validator in validators {
245            self.validators.push(validator.clone());
246        }
247        self
248    }
249
250    /// Sets the provided color theme to this prompt.
251    ///
252    /// Note: The default render config considers if the NO_COLOR environment variable
253    /// is set to decide whether to render the colored config or the empty one.
254    ///
255    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
256    /// config is treated as the only source of truth. If you want to customize colors
257    /// and still support NO_COLOR, you will have to do this on your end.
258    pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
259        self.render_config = render_config;
260        self
261    }
262
263    /// Parses the provided behavioral and rendering options and prompts
264    /// the CLI user for input according to the defined rules.
265    ///
266    /// This method is intended for flows where the user skipping/cancelling
267    /// the prompt - by pressing ESC - is considered normal behavior. In this case,
268    /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
269    ///
270    /// Meanwhile, if the user does submit an answer, the method wraps the return
271    /// type with `Some`.
272    pub fn prompt_skippable(self) -> InquireResult<Option<String>> {
273        match self.prompt() {
274            Ok(answer) => Ok(Some(answer)),
275            Err(InquireError::OperationCanceled) => Ok(None),
276            Err(err) => Err(err),
277        }
278    }
279
280    /// Parses the provided behavioral and rendering options and prompts
281    /// the CLI user for input according to the defined rules.
282    pub fn prompt(self) -> InquireResult<String> {
283        let (input_reader, terminal) = get_default_terminal()?;
284        let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
285        self.prompt_with_backend(&mut backend)
286    }
287
288    pub(crate) fn prompt_with_backend<B: TextBackend>(
289        self,
290        backend: &mut B,
291    ) -> InquireResult<String> {
292        TextPrompt::from(self).prompt(backend)
293    }
294}