use std::io::{self, BufRead, Write};
use super::display::{WizardTheme, render_card};
pub(super) trait Prompter {
fn ask_text(&mut self, title: &str, detail: &str, default: &str) -> io::Result<Option<String>>;
fn confirm(&mut self, title: &str, detail: &str) -> io::Result<bool> {
self.confirm_with_default(title, detail, false)
}
fn confirm_with_default(
&mut self,
title: &str,
detail: &str,
default: bool,
) -> io::Result<bool>;
}
pub(super) struct Terminal<I, O> {
pub(super) input: I,
pub(super) output: O,
pub(super) theme: WizardTheme,
}
const CARD_WIDTH: usize = 78;
impl<I: BufRead, O: Write> Terminal<I, O> {
fn show(&mut self, title: &str, detail: &str) -> io::Result<()> {
self.output
.write_all(render_card(title, detail, self.theme, CARD_WIDTH).as_bytes())
}
fn read_line(&mut self, prompt: &str) -> io::Result<Option<String>> {
self.output.write_all(prompt.as_bytes())?;
self.output.flush()?;
let mut answer = String::new();
if self.input.read_line(&mut answer)? == 0 {
return Ok(None);
}
Ok(Some(answer.trim().to_owned()))
}
}
impl<I: BufRead, O: Write> Prompter for Terminal<I, O> {
fn ask_text(&mut self, title: &str, detail: &str, default: &str) -> io::Result<Option<String>> {
self.show(title, detail)?;
let prompt = if default.is_empty() {
format!("{title}: ")
} else {
format!("{title} [{default}]: ")
};
Ok(self.read_line(&prompt)?.map(|answer| {
if answer.is_empty() {
default.to_owned()
} else {
answer
}
}))
}
fn confirm_with_default(
&mut self,
title: &str,
detail: &str,
default: bool,
) -> io::Result<bool> {
self.show(title, detail)?;
let hint = if default { "Y/n" } else { "y/N" };
loop {
match self.read_line(&format!("{title} [{hint}]: "))?.as_deref() {
Some(answer)
if answer.eq_ignore_ascii_case("yes") || answer.eq_ignore_ascii_case("y") =>
{
return Ok(true);
}
None => return Ok(false),
Some("") => return Ok(default),
Some(answer)
if answer.eq_ignore_ascii_case("no") || answer.eq_ignore_ascii_case("n") =>
{
return Ok(false);
}
Some(_) => writeln!(self.output, "Enter yes or no.")?,
}
}
}
}
pub(super) struct Defaults;
impl Prompter for Defaults {
fn ask_text(
&mut self,
_title: &str,
_detail: &str,
default: &str,
) -> io::Result<Option<String>> {
Ok(Some(default.to_owned()))
}
fn confirm(&mut self, _title: &str, _detail: &str) -> io::Result<bool> {
Ok(true)
}
fn confirm_with_default(
&mut self,
_title: &str,
_detail: &str,
default: bool,
) -> io::Result<bool> {
Ok(default)
}
}