Skip to content

Commit

Permalink
version 0.14, ask! macro
Browse files Browse the repository at this point in the history
  • Loading branch information
Canop committed Jul 7, 2021
1 parent a040676 commit 5c03ed6
Show file tree
Hide file tree
Showing 7 changed files with 279 additions and 5 deletions.
6 changes: 4 additions & 2 deletions CHANGELOG.md
@@ -1,6 +1,8 @@
### next
<a name="v0.14.0"></a>
### v0.14.0 - 2021-07-07
- `ask!` macro and `Question` API
- the `mad_print_inline` and `mad_write_inline` macros now accept any argument supporting `to_string()` and not just `&str`
- fix a bug making tables sometimes exceed the goal width
- fix a bug making tables sometimes exceed the width limit

<a name="v0.13.0"></a>
### v0.13.0 - 2021-06-29
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "termimad"
version = "0.13.1-dev"
version = "0.14.0"
authors = ["dystroy <denys.seguret@gmail.com>"]
repository = "https://github.com/Canop/termimad"
description = "Markdown Renderer for the Terminal"
Expand Down
26 changes: 26 additions & 0 deletions README.md
Expand Up @@ -233,6 +233,32 @@ You'll find more text template functions in the documentation and in the example

You may also be interested in `OwningTemplateExpander`: an alternative expander owning the values which may be handy when you build them while iterating in sub templates.

### Asking questions

A frequent need in CLI apps is to ask the user to select an answer.
The `Question` API and the `ask!` macros cover most basic needs.

Here's an example of asking with a default choice (that you get by hitting *enter*) and a returned value:

```rust
let choice = ask!(skin, "Do you want to drink something ?", ('n') {
('w', "I'd like some **w**ater, please.") => {
mad_print_inline!(skin, "*Wait a minute, please, I'll fetch some.*\n");
Some("water")
}
('b', "Could I get a **b**eer glass ?") => {
mad_print_inline!(skin, "We have no glass. Would a *bottle* be ok ?\n");
Some("beer")
}
('n', "*No*, thank you.") => {
None
}
});
dbg!(choice);
```

![ask example](doc/ask.png)

## Advices to get started

* Start by reading the examples (in `/examples`): they cover almost the whole API, including templates, how to use an alternate screen or scroll the page, etc.
Expand Down
Binary file added doc/ask.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
66 changes: 66 additions & 0 deletions examples/ask/main.rs
@@ -0,0 +1,66 @@
//! run this example with
//! cargo run --example ask
//!
use {
crossterm::{
style::Color::*,
},
termimad::*,
};

fn run_app(skin: &MadSkin) -> Result<()> {
// using the struct api
let mut q = Question::new("Do you want some beer ?");
q.add_answer('y', "**Y**es, I *do* want some");
q.add_answer('n', "**N**o, I drink only Wasser");
q.set_default('y');
let a = q.ask(skin)?;
println!("The answer was {:?}", a);

// using the macro
ask!(skin, "Is everything **OK**?", {
('g', "Everything is **g**ood, thanks") => {
println!("Cool!");
}
('b', "Nooo... I'm **b**ad...") => {
println!("Oh I'm so sorry...");
}
});

// returning a value, using a default answer, imbricated macro calls,
// and not just chars as keys
let beverage = ask!(skin, "What do I serve you ?", {
('b', "**B**eer") => {
ask!(skin, "Really ? We have wine and orange juice too", (2) {
("oj", "**o**range **j**uice") => { "orange juice" }
('w' , "ok for some wine") => { "wine" }
('b' , "I said **beer**") => { "beer" }
( 2 , "Make it **2** beer glasses!") => { "beer x 2" }
})
}
('w', "**W**ine") => {
println!("An excellent choice!");
"wine"
}
});
dbg!(beverage);

Ok(())
}

fn make_skin() -> MadSkin {
let mut skin = MadSkin::default();
skin.table.align = Alignment::Center;
skin.set_headers_fg(AnsiValue(178));
skin.bold.set_fg(Yellow);
skin.italic.set_fg(Magenta);
skin.scrollbar.thumb.set_fg(AnsiValue(178));
skin.code_block.align = Alignment::Center;
skin
}

fn main() -> Result<()> {
let skin = make_skin();
run_app(&skin)
}

180 changes: 180 additions & 0 deletions src/ask.rs
@@ -0,0 +1,180 @@
use {
crate::*,
std::io,
};

/// a question that can be asked to the user, requiring
/// him to type the key of the desired answer
///
/// A question can be built using [Question::new] or with
/// the [ask!] macro
pub struct Question {
pub md: Option<String>,
pub answers: Vec<Answer>,
pub default_answer: Option<String>,
}

/// one of the proposed answers to a question
pub struct Answer {
pub key: String,
pub md: String,
}

impl Question {
/// Create a new question with some text.
pub fn new<S: Into<String>>(md: S) -> Self {
Self {
md: Some(md.into()),
answers: Vec::new(),
default_answer: None,
}
}

/// add a proposed answer, with a key
///
/// The user will have to type the result of calling `to_string()` on
/// the key (numbers, chars, or strings are naturally good options for keys)
pub fn add_answer<K: std::fmt::Display, S: Into<String>>(&mut self, key: K, md: S) {
self.answers.push(Answer {
key: key.to_string(),
md: md.into(),
});
}

/// set the value which will be returned if the user only hits enter.
///
/// It does *not* have to be one of the answers' key, except when you
/// use the [ask!] macro.
pub fn set_default<K: std::fmt::Display>(&mut self, default_answer: K) {
self.default_answer = Some(default_answer.to_string());
}

/// has a default been defined which isn't among the list of answers?
pub fn has_exotic_default(&self) -> bool {
if let Some(da) = self.default_answer.as_ref() {
for answer in &self.answers {
if &answer.key == da {
return false;
}
}
true
} else {
false
}
}

/// Does the asking and returns the inputted string, unless
/// the user just typed *enter* and there was a default value.
///
/// If the user types something not recognized, he's asking to
/// try again.
pub fn ask(&self, skin: &MadSkin) -> io::Result<String> {
if let Some(md) = &self.md {
skin.print_text(&md);
}
for a in &self.answers {
if self.default_answer.as_ref() == Some(&a.key) {
mad_print_inline!(skin, "[**$0**] ", a.key);
} else {
mad_print_inline!(skin, "[$0] ", a.key);
}
skin.print_text(&a.md);
}
loop {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
input.truncate(input.trim_end().len());
if input.is_empty() {
if let Some(da) = &self.default_answer {
return Ok(da.clone());
}
}
for a in &self.answers {
if a.key == input {
return Ok(input);
}
}
println!("answer {:?} not understoord", input);
}
}
}

/// ask the user to choose among proposed answers.
///
/// This macro makes it possible to propose several choices, with
/// an optional default ones, to execute blocks, to optionaly return
/// a value.
///
/// Example:
///
/// ```no_run
/// use termimad::*;
///
/// let skin = get_default_skin();
///
/// let beverage = ask!(skin, "What do I serve you ?", {
/// ('b', "**B**eer") => {
/// ask!(skin, "Really ? We have wine and orange juice too", (2) {
/// ("oj", "**o**range **j**uice") => { "orange juice" }
/// ('w' , "ok for some wine") => { "wine" }
/// ('b' , "I said **beer**") => { "beer" }
/// ( 2 , "Make it **2** beer glasses!") => { "beer x 2" }
/// })
/// }
/// ('w', "**W**ine") => {
/// println!("An excellent choice!");
/// "wine"
/// }
/// });
/// ```
///
/// Limits compared to the [Question] API:
/// - the default answer, if any, must be among the declared ones
///
/// Note that examples/ask contains several examples of this macro.
#[macro_export]
macro_rules! ask {
(
$skin: expr,
$question: expr,
{ $(($key: expr, $answer: expr) => $r: block)+ }
) => {{
let mut question = Question {
md: Some($question.to_string()),
answers: vec![$(Answer { key: $key.to_string(), md: $answer.to_string() }),*],
default_answer: None,
};
let key = question.ask($skin).unwrap();
let mut answers = question.answers.drain(..);
match key {
$(
_ if answers.next().unwrap().key == key => { $r }
)*
_ => { unreachable!(); }
}
}};
(
$skin: expr,
$question: expr,
($default_answer: expr)
{ $(($key: expr, $answer: expr) => $r: block)+ }
) => {{
let mut question = Question {
md: Some($question.to_string()),
answers: vec![$(Answer { key: $key.to_string(), md: $answer.to_string() }),*],
default_answer: Some($default_answer.to_string()),
};
if question.has_exotic_default() {
// I should rewrite this macro as a proc macro...
panic!("default answer when using the ask! macro must be among declared answers");
}
let key = question.ask($skin).unwrap();
let mut answers = question.answers.drain(..);
match key {
$(
_ if answers.next().unwrap().key == key => { $r }
)*
_ => { unreachable!() }
}
}}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Expand Up @@ -98,14 +98,13 @@ Main difference with using `print!(format!( ... ))`:
You'll find more examples and advice in the *templates* example.
Note that there's no macro yet supporting templates for whole markdown *texts* but they should be available soon.
# Examples
The repository contains several other examples, which hopefully cover the whole API while being simple enough. It's recommended you start by trying them or at least glance at their code.
*/

mod ask;
mod area;
mod code;
mod color;
Expand All @@ -130,6 +129,7 @@ mod tokens;
mod views;
mod wrap;

pub use ask::*;
pub use area::{compute_scrollbar, terminal_size, Area};
pub use color::{ansi, gray, rgb};
pub use composite::FmtComposite;
Expand Down

0 comments on commit 5c03ed6

Please sign in to comment.