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
use crate::event::*;
use crate::style::{Color, Styled, Symbol};
use crate::{Prompt, PromptInput, PromptState, RenderPayload};

const S_ACTIVE: Symbol = Symbol("●", ">");
const S_INACTIVE: Symbol = Symbol("○", " ");

/// A trait for formatting the [`Confirm`] prompt.
///
/// All methods have default implementations, allowing you to override only the specific formatting process you need.
///
/// # Examples
///
/// ```no_run
/// use promptuity::prompts::{Confirm, ConfirmFormatter};
///
/// struct CustomFormatter;
///
/// impl ConfirmFormatter for CustomFormatter {
///     fn layout(&self, yes: String, no: String) -> String {
///         format!("{} or {}", yes, no)
///     }
/// }
///
/// let _ = Confirm::new("...").with_formatter(CustomFormatter);
/// ```
pub trait ConfirmFormatter {
    /// Formats the "Yes" option.
    fn yes(&self, active: bool) -> String {
        let icon = if active {
            Styled::new(S_ACTIVE).fg(Color::Green).to_string()
        } else {
            Styled::new(S_INACTIVE).fg(Color::DarkGrey).to_string()
        };
        format!("{} Yes", icon)
    }

    /// Formats the "No" option.
    fn no(&self, active: bool) -> String {
        let icon = if active {
            Styled::new(S_ACTIVE).fg(Color::Green).to_string()
        } else {
            Styled::new(S_INACTIVE).fg(Color::DarkGrey).to_string()
        };
        format!("{} No", icon)
    }

    /// Formats the layout of the active prompt.
    fn layout(&self, yes: String, no: String) -> String {
        format!("{}  /  {}", yes, no)
    }

    /// Formats the submitted value.
    fn submit(&self, value: bool) -> String {
        if value {
            "Yes".into()
        } else {
            "No".into()
        }
    }
}

/// The default formatter for [`Confirm`].
pub struct DefaultConfirmFormatter;

impl DefaultConfirmFormatter {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self
    }
}

impl ConfirmFormatter for DefaultConfirmFormatter {}

/// A prompt for inputting a Yes/No choice.
///
/// # Options
///
/// - **Formatter**: Customizes the prompt display. See [`ConfirmFormatter`].
/// - **Hint**: A message to assist with field input. Defaults to `None`.
/// - **Default Value**: The default value of `bool`. Defaults to `false`.
///
/// # Examples
///
/// ```no_run
/// use promptuity::prompts::Confirm;
///
/// let _ = Confirm::new("Are you sure?").with_default(true);
/// ```
pub struct Confirm {
    formatter: Box<dyn ConfirmFormatter>,
    message: String,
    hint: Option<String>,
    value: bool,
}

impl Confirm {
    /// Creates a new [`Confirm`] prompt.
    pub fn new(message: impl std::fmt::Display) -> Self {
        Self {
            formatter: Box::new(DefaultConfirmFormatter),
            message: message.to_string(),
            hint: None,
            value: false,
        }
    }

    /// Sets the formatter for the prompt.
    pub fn with_formatter(&mut self, formatter: impl ConfirmFormatter + 'static) -> &mut Self {
        self.formatter = Box::new(formatter);
        self
    }

    /// Sets the hint message for the prompt.
    pub fn with_hint(&mut self, hint: impl std::fmt::Display) -> &mut Self {
        self.hint = Some(hint.to_string());
        self
    }

    /// Sets the default value for the prompt.
    pub fn with_default(&mut self, value: bool) -> &mut Self {
        self.value = value;
        self
    }
}

impl AsMut<Confirm> for Confirm {
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}

impl<W: std::io::Write> Prompt<W> for Confirm {
    type Output = bool;

    fn handle(&mut self, code: KeyCode, modifiers: KeyModifiers) -> PromptState {
        match (code, modifiers) {
            (KeyCode::Enter, _) => PromptState::Submit,
            (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => PromptState::Cancel,
            (KeyCode::Char('y'), KeyModifiers::NONE) | (KeyCode::Char('Y'), KeyModifiers::NONE) => {
                self.value = true;
                PromptState::Submit
            }
            (KeyCode::Char('n'), KeyModifiers::NONE) | (KeyCode::Char('N'), KeyModifiers::NONE) => {
                self.value = false;
                PromptState::Submit
            }
            (KeyCode::Left, _)
            | (KeyCode::Char('h'), _)
            | (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
                self.value = true;
                PromptState::Active
            }
            (KeyCode::Right, _)
            | (KeyCode::Char('l'), _)
            | (KeyCode::Char('n'), KeyModifiers::CONTROL) => {
                self.value = false;
                PromptState::Active
            }
            _ => PromptState::Active,
        }
    }

    fn render(&mut self, state: &PromptState) -> Result<RenderPayload, String> {
        let payload = RenderPayload::new(self.message.clone(), self.hint.clone(), None);

        match state {
            PromptState::Submit => {
                Ok(payload.input(PromptInput::Raw(self.formatter.submit(self.value))))
            }

            PromptState::Cancel => Ok(payload),

            _ => Ok(payload.input(PromptInput::Raw(self.formatter.layout(
                self.formatter.yes(self.value),
                self.formatter.no(!self.value),
            )))),
        }
    }

    fn submit(&mut self) -> Self::Output {
        self.value
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_prompt;

    test_prompt!(
        test_hint,
        Confirm,
        Confirm::new("test message").with_hint("hint message"),
        vec![]
    );

    test_prompt!(
        test_default_enter,
        Confirm,
        Confirm::new("test message").as_mut(),
        vec![(KeyCode::Enter, KeyModifiers::NONE)]
    );

    test_prompt!(
        test_default_yes,
        Confirm,
        Confirm::new("test message").with_default(true),
        vec![(KeyCode::Enter, KeyModifiers::NONE)]
    );

    test_prompt!(
        test_move,
        Confirm,
        Confirm::new("test message").as_mut(),
        vec![
            (KeyCode::Left, KeyModifiers::NONE),
            (KeyCode::Right, KeyModifiers::NONE),
            (KeyCode::Char('h'), KeyModifiers::NONE),
            (KeyCode::Char('l'), KeyModifiers::NONE),
            (KeyCode::Char('h'), KeyModifiers::CONTROL),
            (KeyCode::Char('l'), KeyModifiers::CONTROL),
            (KeyCode::Char('p'), KeyModifiers::CONTROL),
            (KeyCode::Char('n'), KeyModifiers::CONTROL),
            (KeyCode::Enter, KeyModifiers::NONE),
        ]
    );

    test_prompt!(
        test_direct_lower_yes,
        Confirm,
        Confirm::new("test message").with_default(false),
        vec![(KeyCode::Char('y'), KeyModifiers::NONE)]
    );

    test_prompt!(
        test_direct_upper_yes,
        Confirm,
        Confirm::new("test message").with_default(false),
        vec![(KeyCode::Char('Y'), KeyModifiers::NONE)]
    );

    test_prompt!(
        test_direct_lower_no,
        Confirm,
        Confirm::new("test message").with_default(true),
        vec![(KeyCode::Char('n'), KeyModifiers::NONE)]
    );

    test_prompt!(
        test_direct_upper_no,
        Confirm,
        Confirm::new("test message").with_default(true),
        vec![(KeyCode::Char('N'), KeyModifiers::NONE)]
    );
}