cliux/components/
confirm.rs

1use crate::components::note::get_border;
2use crate::layout::pad;
3
4pub struct Confirm {
5    label: String,
6    default: Option<bool>,
7    color: Option<String>,
8    bold: bool,
9    style: Option<String>,
10    width: usize,
11}
12
13impl Confirm {
14    pub fn new(label: &str) -> Self {
15        Self {
16            label: label.to_string(),
17            default: None,
18            color: None,
19            bold: false,
20            style: Some("square".to_string()),
21            width: 40,
22        }
23    }
24
25    pub fn default(mut self, value: bool) -> Self {
26        self.default = Some(value);
27        self
28    }
29
30    pub fn color(mut self, color: &str) -> Self {
31        self.color = Some(color.to_string());
32        self
33    }
34
35    pub fn bold(mut self, bold: bool) -> Self {
36        self.bold = bold;
37        self
38    }
39
40    pub fn style(mut self, style: &str) -> Self {
41        self.style = Some(style.to_string());
42        self
43    }
44
45    pub fn width(mut self, width: usize) -> Self {
46        self.width = width;
47        self
48    }
49
50    pub fn prompt(&self) -> bool {
51        use ansi_term::Style;
52        use std::io::{self, Write};
53
54        let (tl, tr, bl, br, h, v) = get_border(self.style.as_deref().unwrap_or("plain"));
55        let mut style = Style::new();
56
57        if let Some(ref color) = self.color {
58            if let Some(colour) = crate::components::label::parse_colour(color) {
59                style = style.fg(colour);
60            }
61        }
62        if self.bold {
63            style = style.bold();
64        }
65
66        let padded_label = pad(&format!("{} (y/n)", self.label), self.width);
67        let styled_label = style.paint(padded_label).to_string();
68
69        // Draw box
70        println!("{}{}{}", tl, h.to_string().repeat(self.width), tr);
71        println!("{}{}{}", v, styled_label, v);
72        println!("{}{}{}", bl, h.to_string().repeat(self.width), br);
73
74        // Input line
75        print!("> ");
76        io::stdout().flush().unwrap();
77
78        let mut input = String::new();
79        io::stdin().read_line(&mut input).unwrap();
80        let input = input.trim().to_lowercase();
81
82        match input.as_str() {
83            "y" | "yes" => true,
84            "n" | "no" => false,
85            "" => self.default.unwrap_or(false),
86            _ => {
87                println!("Invalid input. Please enter y or n.");
88                self.prompt()
89            }
90        }
91    }
92}