Struct inquire::DateSelect
source · pub struct DateSelect<'a> {
pub message: &'a str,
pub week_start: Weekday,
pub starting_date: NaiveDate,
pub min_date: Option<NaiveDate>,
pub max_date: Option<NaiveDate>,
pub help_message: Option<&'a str>,
pub vim_mode: bool,
pub formatter: DateFormatter<'a>,
pub validators: Vec<Box<dyn DateValidator>>,
pub render_config: RenderConfig<'a>,
}
Expand description
Prompt that allows user to select a date (time not supported) from an interactive calendar. Available via the date
feature.
By default, the initial selected date is the current date. The user can navigate through the calendar by pressing the keyboard arrows. If the user also presses the control key along with the arrows, the user will be able to “fast-forward” to previous or next months or years.
More specifically:
- Left arrow moves to the day previous to the one selected, and to the month previous to the one selected when pressed with
ctrl
. - Analogously, right arrow does the same, but moving to the next day or month.
- Up arrow moves to the day above to the one selected, basically a week before the selected date. When pressed with
ctrl
, it moves to the previous year. - Analogously, the down arrow moves to a week later or a year later.
Finally, the user selects a date by pressing the space or enter keys.
DateSelect
prompts provide several options of configuration:
- Prompt message: Required when creating the prompt.
- Default value: Default value selected when the calendar is displayed and the one select if the user submits without any previous actions. Current date by default.
- Help message: Message displayed at the line below the prompt.
- Formatter: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
- Formats to “Month Day, Year” by default.
- Validators: Custom validators to the user’s selected date, displaying an error message if the date does not pass the requirements.
- Week start: Which day of the week should be displayed in the first column of the calendar, Sunday by default.
- Min and max date: Inclusive boundaries of allowed dates in the interactive calendar. If any boundary is set, the user will not be able to move past them, consequently not being able to select any dates out of the allowed range.
Example
use chrono::{NaiveDate, Weekday};
use inquire::DateSelect;
let date = DateSelect::new("When do you want to travel?")
.with_starting_date(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
Fields§
§message: &'a str
Message to be presented to the user.
week_start: Weekday
First day of the week when displaying week rows.
starting_date: NaiveDate
Starting date to be selected.
min_date: Option<NaiveDate>
Min date allowed to be selected.
max_date: Option<NaiveDate>
Max date allowed to be selected.
help_message: Option<&'a str>
Help message to be presented to the user.
vim_mode: bool
Whether vim mode is enabled. When enabled, the user can navigate through the options using hjkl.
formatter: DateFormatter<'a>
Function that formats the user input and presents it to the user as the final rendering of the prompt.
validators: Vec<Box<dyn DateValidator>>
Collection of validators to apply to the user input.
Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.
The possible error is displayed to the user one line above the prompt.
render_config: RenderConfig<'a>
RenderConfig to apply to the rendered interface.
Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.
When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still suport NO_COLOR, you will have to do this on your end.
Implementations§
source§impl<'a> DateSelect<'a>
impl<'a> DateSelect<'a>
sourcepub const DEFAULT_FORMATTER: DateFormatter<'a> = formatter::DEFAULT_DATE_FORMATTER
pub const DEFAULT_FORMATTER: DateFormatter<'a> = formatter::DEFAULT_DATE_FORMATTER
Default formatter, set to DEFAULT_DATE_FORMATTER
sourcepub const DEFAULT_VIM_MODE: bool = true
pub const DEFAULT_VIM_MODE: bool = true
Default value of vim mode. It is true because there is no typing functionality to be lost here.
sourcepub const DEFAULT_HELP_MESSAGE: Option<&'a str> = _
pub const DEFAULT_HELP_MESSAGE: Option<&'a str> = _
Default help message.
sourcepub const DEFAULT_VALIDATORS: Vec<Box<dyn DateValidator>> = _
pub const DEFAULT_VALIDATORS: Vec<Box<dyn DateValidator>> = _
Default validators added to the DateSelect prompt, none.
sourcepub const DEFAULT_WEEK_START: Weekday = chrono::Weekday::Sun
pub const DEFAULT_WEEK_START: Weekday = chrono::Weekday::Sun
Default week start.
sourcepub const DEFAULT_MIN_DATE: Option<NaiveDate> = None
pub const DEFAULT_MIN_DATE: Option<NaiveDate> = None
Default min date.
sourcepub const DEFAULT_MAX_DATE: Option<NaiveDate> = None
pub const DEFAULT_MAX_DATE: Option<NaiveDate> = None
Default max date.
sourcepub fn new(message: &'a str) -> Self
pub fn new(message: &'a str) -> Self
Creates a DateSelect with the provided message, along with default configuration values.
Examples found in repository?
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
fn date_select_default() {
println!("-------> Simple DateSelect");
println!();
DateSelect::new("Check-in date:").prompt().unwrap();
println!("We will be expecting you!");
println!();
}
fn custom_type_parsed_date_prompt() {
println!("-------> Date parsed from text input with Custom Type prompt");
println!();
let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
.with_placeholder("dd/mm/yyyy")
.with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
.with_formatter(DEFAULT_DATE_FORMATTER)
.with_error_message("Please type a valid date.")
.with_help_message("The necessary arrangements will be made")
.prompt();
match amount {
Ok(_) => println!("Thanks! We will be expecting you."),
Err(_) => println!("We could not process your reservation"),
}
println!();
}
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
fn date_select_with_validation() {
println!("-------> Date select with date validation");
println!();
let date = DateSelect::new("Validated input")
.with_validator(|d: NaiveDate| {
let now = chrono::Utc::now().naive_utc().date();
if d.ge(&now) {
Ok(Validation::Invalid("Date must be in the past".into()))
} else {
Ok(Validation::Valid)
}
})
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
fn date_select_with_starting_date() {
println!("-------> DateSelect with yesterday as initial value");
println!();
DateSelect::new("Check-in date:")
// Could also be `.with_default()`
.with_starting_date(
chrono::Local::now()
.date()
.naive_local()
.pred_opt()
.unwrap(),
)
.prompt()
.unwrap();
println!("We will be expecting you!");
println!();
}
More examples
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
fn main() -> InquireResult<()> {
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!("The balance of {} is now ${:.2}", account, account.balance);
Ok(())
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() -> InquireResult<()> {
inquire::set_global_render_config(RenderConfig::empty());
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!("The balance of {account} is now $311.09");
Ok(())
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
fn main() -> InquireResult<()> {
inquire::set_global_render_config(get_render_config());
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!(
"The balance of {} is now ${:.2}",
account.name, account.balance
);
Ok(())
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
fn main() -> InquireResult<()> {
let fruits = vec![
"Banana",
"Apple",
"Strawberry",
"Grapes",
"Lemon",
"Tangerine",
"Watermelon",
"Orange",
"Pear",
"Avocado",
"Pineapple",
];
let pineapple_index = fruits.len() - 1;
let languages = vec![
"C++",
"Rust",
"C",
"Python",
"Java",
"TypeScript",
"JavaScript",
"Go",
];
let _workplace = Text::new("Where do you work?")
.with_help_message("Don't worry, this will not be sold to third-party advertisers.")
.with_validator(min_length!(5, "Minimum of 5 characters"))
.with_default("Unemployed")
.prompt_skippable()?;
let _eats_pineapple = MultiSelect::new("What are your favorite fruits?", fruits)
.raw_prompt()?
.into_iter()
.any(|o| o.index == pineapple_index);
let _eats_pizza = Confirm::new("Do you eat pizza?")
.with_default(true)
.prompt_skippable()?;
let _language =
Select::new("What is your favorite programming language?", languages).prompt_skippable()?;
let _password = Password::new("Password:")
.with_validator(min_length!(8, "Minimum of 8 characters"))
.prompt_skippable()?;
let _when = DateSelect::new("When are you going to travel?").prompt_skippable()?;
println!("Based on our ML-powered analysis, we were able to conclude absolutely nothing.");
Ok(())
}
sourcepub fn with_help_message(self, message: &'a str) -> Self
pub fn with_help_message(self, message: &'a str) -> Self
Sets the help message of the prompt.
Examples found in repository?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn without_help_message(self) -> Self
pub fn without_help_message(self) -> Self
Removes the set help message.
sourcepub fn with_default(self, default: NaiveDate) -> Self
pub fn with_default(self, default: NaiveDate) -> Self
Sets the default date of the prompt. Equivalent to DateSelect::with_starting_date.
Examples found in repository?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn with_week_start(self, week_start: Weekday) -> Self
pub fn with_week_start(self, week_start: Weekday) -> Self
Sets the week start.
Examples found in repository?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn with_min_date(self, min_date: NaiveDate) -> Self
pub fn with_min_date(self, min_date: NaiveDate) -> Self
Sets the min date.
Examples found in repository?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn with_max_date(self, max_date: NaiveDate) -> Self
pub fn with_max_date(self, max_date: NaiveDate) -> Self
Sets the max date.
Examples found in repository?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn with_starting_date(self, starting_date: NaiveDate) -> Self
pub fn with_starting_date(self, starting_date: NaiveDate) -> Self
Sets the starting date. Equivalent to DateSelect::with_default.
Examples found in repository?
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
fn date_select_with_starting_date() {
println!("-------> DateSelect with yesterday as initial value");
println!();
DateSelect::new("Check-in date:")
// Could also be `.with_default()`
.with_starting_date(
chrono::Local::now()
.date()
.naive_local()
.pred_opt()
.unwrap(),
)
.prompt()
.unwrap();
println!("We will be expecting you!");
println!();
}
sourcepub fn with_validator<V>(self, validator: V) -> Selfwhere
V: DateValidator + 'static,
pub fn with_validator<V>(self, validator: V) -> Selfwhere V: DateValidator + 'static,
Adds a validator to the collection of validators. You might want to use this feature in case you need to limit the user to specific choices, such as not allowing weekends.
Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.
The possible error is displayed to the user one line above the prompt.
Examples found in repository?
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn date_select_with_validation() {
println!("-------> Date select with date validation");
println!();
let date = DateSelect::new("Validated input")
.with_validator(|d: NaiveDate| {
let now = chrono::Utc::now().naive_utc().date();
if d.ge(&now) {
Ok(Validation::Invalid("Date must be in the past".into()))
} else {
Ok(Validation::Valid)
}
})
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
sourcepub fn with_validators(self, validators: &[Box<dyn DateValidator>]) -> Self
pub fn with_validators(self, validators: &[Box<dyn DateValidator>]) -> Self
Adds the validators to the collection of validators in the order they are given. You might want to use this feature in case you need to limit the user to specific choices, such as not allowing weekends.
Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.
The possible error is displayed to the user one line above the prompt.
sourcepub fn with_vim_mode(self, vim_mode: bool) -> Self
pub fn with_vim_mode(self, vim_mode: bool) -> Self
Enables or disables vim_mode.
sourcepub fn with_formatter(self, formatter: DateFormatter<'a>) -> Self
pub fn with_formatter(self, formatter: DateFormatter<'a>) -> Self
Sets the formatter.
sourcepub fn with_render_config(self, render_config: RenderConfig<'a>) -> Self
pub fn with_render_config(self, render_config: RenderConfig<'a>) -> Self
Sets the provided color theme to this prompt.
Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.
When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still suport NO_COLOR, you will have to do this on your end.
sourcepub fn prompt_skippable(self) -> InquireResult<Option<NaiveDate>>
pub fn prompt_skippable(self) -> InquireResult<Option<NaiveDate>>
Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.
This method is intended for flows where the user skipping/cancelling
the prompt - by pressing ESC - is considered normal behavior. In this case,
it does not return Err(InquireError::OperationCanceled)
, but Ok(None)
.
Meanwhile, if the user does submit an answer, the method wraps the return
type with Some
.
Examples found in repository?
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
fn main() -> InquireResult<()> {
let fruits = vec![
"Banana",
"Apple",
"Strawberry",
"Grapes",
"Lemon",
"Tangerine",
"Watermelon",
"Orange",
"Pear",
"Avocado",
"Pineapple",
];
let pineapple_index = fruits.len() - 1;
let languages = vec![
"C++",
"Rust",
"C",
"Python",
"Java",
"TypeScript",
"JavaScript",
"Go",
];
let _workplace = Text::new("Where do you work?")
.with_help_message("Don't worry, this will not be sold to third-party advertisers.")
.with_validator(min_length!(5, "Minimum of 5 characters"))
.with_default("Unemployed")
.prompt_skippable()?;
let _eats_pineapple = MultiSelect::new("What are your favorite fruits?", fruits)
.raw_prompt()?
.into_iter()
.any(|o| o.index == pineapple_index);
let _eats_pizza = Confirm::new("Do you eat pizza?")
.with_default(true)
.prompt_skippable()?;
let _language =
Select::new("What is your favorite programming language?", languages).prompt_skippable()?;
let _password = Password::new("Password:")
.with_validator(min_length!(8, "Minimum of 8 characters"))
.prompt_skippable()?;
let _when = DateSelect::new("When are you going to travel?").prompt_skippable()?;
println!("Based on our ML-powered analysis, we were able to conclude absolutely nothing.");
Ok(())
}
sourcepub fn prompt(self) -> InquireResult<NaiveDate>
pub fn prompt(self) -> InquireResult<NaiveDate>
Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.
Examples found in repository?
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
fn date_select_default() {
println!("-------> Simple DateSelect");
println!();
DateSelect::new("Check-in date:").prompt().unwrap();
println!("We will be expecting you!");
println!();
}
fn custom_type_parsed_date_prompt() {
println!("-------> Date parsed from text input with Custom Type prompt");
println!();
let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
.with_placeholder("dd/mm/yyyy")
.with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
.with_formatter(DEFAULT_DATE_FORMATTER)
.with_error_message("Please type a valid date.")
.with_help_message("The necessary arrangements will be made")
.prompt();
match amount {
Ok(_) => println!("Thanks! We will be expecting you."),
Err(_) => println!("We could not process your reservation"),
}
println!();
}
fn date_select_misc_options() {
println!("-------> Date select with several possible options");
println!();
let date = DateSelect::new("When do you want to travel?")
// Could also be `.with_starting_date()`
.with_default(NaiveDate::from_ymd(2021, 8, 1))
.with_min_date(NaiveDate::from_ymd(2021, 8, 1))
.with_max_date(NaiveDate::from_ymd(2021, 12, 31))
.with_week_start(Weekday::Mon)
.with_help_message("Possible flights will be displayed according to the selected date")
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
fn date_select_with_validation() {
println!("-------> Date select with date validation");
println!();
let date = DateSelect::new("Validated input")
.with_validator(|d: NaiveDate| {
let now = chrono::Utc::now().naive_utc().date();
if d.ge(&now) {
Ok(Validation::Invalid("Date must be in the past".into()))
} else {
Ok(Validation::Valid)
}
})
.prompt();
match date {
Ok(_) => println!("No flights available for this date."),
Err(_) => println!("There was an error in the system."),
}
println!();
}
fn date_select_with_starting_date() {
println!("-------> DateSelect with yesterday as initial value");
println!();
DateSelect::new("Check-in date:")
// Could also be `.with_default()`
.with_starting_date(
chrono::Local::now()
.date()
.naive_local()
.pred_opt()
.unwrap(),
)
.prompt()
.unwrap();
println!("We will be expecting you!");
println!();
}
More examples
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
fn main() -> InquireResult<()> {
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!("The balance of {} is now ${:.2}", account, account.balance);
Ok(())
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn main() -> InquireResult<()> {
inquire::set_global_render_config(RenderConfig::empty());
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!("The balance of {account} is now $311.09");
Ok(())
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
fn main() -> InquireResult<()> {
inquire::set_global_render_config(get_render_config());
let _date = DateSelect::new("Date:").prompt()?;
let _category = Select::new("Category:", get_categories()).prompt()?;
let _payee = Text::new("Payee:")
.with_validator(required!("This field is required"))
.with_autocomplete(&payee_suggestor)
.with_help_message("e.g. Music Store")
.with_page_size(5)
.prompt()?;
let amount: f64 = CustomType::new("Amount:")
.with_formatter(&|i: f64| format!("${i}"))
.with_error_message("Please type a valid number")
.with_help_message("Type the amount in US dollars using a decimal point as a separator")
.prompt()
.unwrap();
let _description = Text::new("Description:")
.with_help_message("Optional notes")
.prompt()?;
let mut accounts = get_accounts();
let accounts_mut = accounts.iter_mut().collect();
let account = Select::new("Account:", accounts_mut).prompt()?;
account.balance -= amount;
let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;
println!("Your transaction has been successfully recorded.");
println!(
"The balance of {} is now ${:.2}",
account.name, account.balance
);
Ok(())
}
Trait Implementations§
source§impl<'a> Clone for DateSelect<'a>
impl<'a> Clone for DateSelect<'a>
source§fn clone(&self) -> DateSelect<'a>
fn clone(&self) -> DateSelect<'a>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more