1 2 3 4 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 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
//! Confirm
use crate::{
error::ClackError,
style::{ansi, chars},
};
use crossterm::{
cursor,
event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
execute, terminal,
};
use owo_colors::OwoColorize;
use std::{
fmt::Display,
io::{stdout, Write},
};
/// `Confirm` struct.
///
/// # Examples
///
/// ```no_run
/// use may_clack::confirm;
///
/// # fn main() -> Result<(), may_clack::error::ClackError> {
/// let answer = confirm("message")
/// .initial_value(true)
/// .prompts("true", "false")
/// .interact()?;
/// println!("answer {:?}", answer);
/// # Ok(())
/// # }
/// ```
pub struct Confirm<M: Display> {
message: M,
initial_value: bool,
prompts: (String, String),
cancel: Option<Box<dyn Fn()>>,
}
impl<M: Display> Confirm<M> {
/// Creates a new `Confirm` struct.
///
/// Has a shorthand in [`confirm()`].
///
/// # Examples
///
/// ```no_run
/// use may_clack::{confirm, confirm::Confirm};
///
/// // these two are equivalent
/// let question = Confirm::new("message");
/// let question = confirm("message");
/// ```
pub fn new(message: M) -> Confirm<M> {
Confirm {
message,
initial_value: false,
prompts: ("yes".into(), "no".into()),
cancel: None,
}
}
/// Specify the initial value.
///
/// Default: [`false`]
///
/// # Examples
///
/// ```no_run
/// use may_clack::confirm;
///
/// # fn main() -> Result<(), may_clack::error::ClackError> {
/// let answer = confirm("message").initial_value(true).interact()?;
/// println!("answer {:?}", answer);
/// # Ok(())
/// # }
/// ```
pub fn initial_value(&mut self, b: bool) -> &mut Self {
self.initial_value = b;
self
}
/// Specify the prompts to display for [`true`] and [`false`].
///
/// Default: `"yes"`, `"no"`.
///
/// # Examples
///
/// ```no_run
/// use may_clack::confirm;
///
/// # fn main() -> Result<(), may_clack::error::ClackError> {
/// let answer = confirm("message").prompts("true", "false").interact()?;
/// println!("answer {:?}", answer);
/// # Ok(())
/// # }
/// ```
pub fn prompts<S: Into<String>>(&mut self, yes: S, no: S) -> &mut Self {
self.prompts = (yes.into(), no.into());
self
}
/// Specify function to call on cancel.
///
/// # Examples
///
/// ```no_run
/// use may_clack::{confirm, cancel};
///
/// # fn main() -> Result<(), may_clack::error::ClackError> {
/// let answer = confirm("message").cancel(do_cancel).interact()?;
/// println!("answer {:?}", answer);
/// # Ok(())
/// # }
///
/// fn do_cancel() {
/// cancel!("operation cancelled");
/// panic!("operation cancelled");
/// }
pub fn cancel<F>(&mut self, cancel: F) -> &mut Self
where
F: Fn() + 'static,
{
let cancel = Box::new(cancel);
self.cancel = Some(cancel);
self
}
/// Wait for the user to submit an answer.
///
/// # Examples
///
/// ```no_run
/// use may_clack::confirm;
///
/// # fn main() -> Result<(), may_clack::error::ClackError> {
/// let answer = confirm("message")
/// .initial_value(true)
/// .prompts("true", "false")
/// .interact()?;
/// println!("answer {:?}", answer);
/// # Ok(())
/// # }
/// ```
pub fn interact(&self) -> Result<bool, ClackError> {
self.w_init();
let mut stdout = stdout();
let _ = execute!(stdout, crossterm::cursor::Hide);
terminal::enable_raw_mode()?;
let mut val = self.initial_value;
loop {
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
match (key.code, key.modifiers) {
(KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right, _) => {
val = !val;
self.draw(val);
}
(KeyCode::Char('y' | 'Y'), _) => {
let _ = execute!(stdout, crossterm::cursor::Show);
terminal::disable_raw_mode()?;
self.w_out(true);
return Ok(true);
}
(KeyCode::Char('n' | 'N'), _) => {
let _ = execute!(stdout, crossterm::cursor::Show);
terminal::disable_raw_mode()?;
self.w_out(false);
return Ok(false);
}
(KeyCode::Enter, _) => {
let _ = execute!(stdout, crossterm::cursor::Show);
terminal::disable_raw_mode()?;
self.w_out(val);
return Ok(val);
}
(KeyCode::Char('c' | 'd'), KeyModifiers::CONTROL) => {
let _ = execute!(stdout, crossterm::cursor::Show);
terminal::disable_raw_mode()?;
self.w_cancel(val);
if let Some(cancel) = self.cancel.as_deref() {
cancel();
}
return Err(ClackError::Cancelled);
}
_ => {}
}
}
}
}
}
}
impl<M: Display> Confirm<M> {
/// Format a radio point.
fn radio_pnt(&self, is_active: bool, prompt: &str) -> String {
if is_active {
format!("{} {}", (*chars::RADIO_ACTIVE).green(), prompt)
} else {
format!("{} {}", *chars::RADIO_INACTIVE, prompt)
.dimmed()
.to_string()
}
}
/// Format the actual prompt.
fn radio(&self, value: bool) -> String {
let yes = self.radio_pnt(value, &self.prompts.0);
let no = self.radio_pnt(!value, &self.prompts.1);
format!("{} / {}", yes, no)
}
/// Draw the prompt.
fn draw(&self, value: bool) {
let mut stdout = stdout();
let _ = execute!(stdout, cursor::MoveToColumn(0));
let r = self.radio(value);
print!("{} {}", (*chars::BAR).cyan(), r);
let _ = stdout.flush();
}
}
impl<M: Display> Confirm<M> {
/// Write initial prompt.
fn w_init(&self) {
println!("{}", *chars::BAR);
println!("{} {}", (*chars::STEP_ACTIVE).cyan(), self.message);
println!("{}", (*chars::BAR).cyan());
print!("{}", (*chars::BAR_END).cyan());
let mut stdout = stdout();
let _ = execute!(stdout, cursor::MoveToPreviousLine(1));
self.draw(self.initial_value);
}
/// Write outro prompt.
fn w_out(&self, value: bool) {
let mut stdout = stdout();
let _ = execute!(stdout, cursor::MoveToPreviousLine(1));
let answer = if value {
&self.prompts.0
} else {
&self.prompts.1
};
println!("{} {}", (*chars::STEP_SUBMIT).green(), self.message);
print!("{}", ansi::CLEAR_LINE);
println!("{} {}", *chars::BAR, answer.dimmed());
}
fn w_cancel(&self, value: bool) {
let mut stdout = stdout();
let _ = execute!(stdout, cursor::MoveToPreviousLine(1));
let answer = if value {
&self.prompts.0
} else {
&self.prompts.1
};
println!("{} {}", (*chars::STEP_CANCEL).red(), self.message);
print!("{}", ansi::CLEAR_LINE);
println!("{} {}", *chars::BAR, answer.strikethrough().dimmed());
}
}
/// Shorthand for [`Confirm::new()`]
pub fn confirm<M: Display>(message: M) -> Confirm<M> {
Confirm::new(message)
}