bearask 0.5.0

A really fast and featureful CLI prompting lib
Documentation
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use {
    crate::{
        style::ConfirmStyle,
        util::CursorGuard,
        validation::{Validate, run_validator},
    },
    crossterm::{
        cursor,
        event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
        queue,
        terminal::{self, Clear, ClearType},
    },
    miette::IntoDiagnostic,
    owo_colors::OwoColorize,
    std::io::{Write, stdout},
};

#[derive(Clone, Debug, PartialEq)]
pub enum ConfirmMode {
    TextInput,
    Interactive,
}

#[derive(Clone)]
pub struct Confirm {
    prompt: String,
    default: bool,
    inline: bool,
    mode: ConfirmMode,
    prompt_prefix: String,
    prompt_suffix: Option<String>,
    yes_text: String,
    no_text: String,
    show_hints: bool,
    show_error_hint: bool,
    show_confirmation: bool,
    allow_escape: bool,
    style: ConfirmStyle,
    _cursor_guard: CursorGuard,
    validation: Option<Box<dyn Validate<bool>>>,
}

impl Confirm {
    pub fn new(prompt: impl Into<String>) -> Self {
        let cursor_guard = CursorGuard::new().expect("Failed to initialize cursor guard");

        Self {
            prompt: prompt.into(),
            default: true,
            inline: false,
            mode: ConfirmMode::TextInput,
            prompt_prefix: "?".into(),
            prompt_suffix: None,
            yes_text: "yes".into(),
            no_text: "no".into(),
            show_hints: true,
            show_error_hint: true,
            show_confirmation: true,
            allow_escape: true,
            style: ConfirmStyle::default(),
            _cursor_guard: cursor_guard,
            validation: None,
        }
    }

    pub fn with_default(mut self, default: bool) -> Self {
        self.default = default;
        self
    }

    pub fn with_inline(mut self, inline: bool) -> Self {
        self.inline = inline;
        self
    }

    pub fn with_mode(mut self, mode: ConfirmMode) -> Self {
        self.mode = mode;
        self
    }

    pub fn with_prompt_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prompt_prefix = prefix.into();
        self
    }

    pub fn with_prompt_suffix(mut self, suffix: impl Into<String>) -> Self {
        self.prompt_suffix = Some(suffix.into());
        self
    }

    pub fn with_yes_text(mut self, text: impl Into<String>) -> Self {
        self.yes_text = text.into();
        self
    }

    pub fn with_no_text(mut self, text: impl Into<String>) -> Self {
        self.no_text = text.into();
        self
    }

    pub fn with_hints(mut self, enabled: bool) -> Self {
        self.show_hints = enabled;
        self
    }

    pub fn with_error_hint(mut self, enabled: bool) -> Self {
        self.show_error_hint = enabled;
        self
    }

    pub fn with_confirmation(mut self, enabled: bool) -> Self {
        self.show_confirmation = enabled;
        self
    }

    pub fn with_escape(mut self, allow: bool) -> Self {
        self.allow_escape = allow;
        self
    }

    pub fn with_style(mut self, style: ConfirmStyle) -> Self {
        self.style = style;
        self
    }

    pub fn with_validation(mut self, validation: impl Validate<bool> + 'static) -> Self {
        self.validation = Some(Box::new(validation));
        self
    }

    pub fn prompt(&self) -> &str {
        &self.prompt
    }

    pub fn ask(&self) -> miette::Result<bool> {
        let original_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |panic_info| {
            let _ = terminal::disable_raw_mode();
            std::panic::take_hook()(panic_info);
        }));

        let result = match self.mode {
            ConfirmMode::TextInput => self.ask_text_input(),
            ConfirmMode::Interactive => self.ask_interactive(),
        };

        let _ = std::panic::take_hook();
        std::panic::set_hook(original_hook);

        result
    }

    fn ask_interactive(&self) -> miette::Result<bool> {
        let mut out = stdout();
        let mut selected = self.default;
        let mut buf = Vec::with_capacity(4096);

        terminal::enable_raw_mode().into_diagnostic()?;

        while event::poll(std::time::Duration::from_millis(0)).into_diagnostic()? {
            event::read().into_diagnostic()?;
        }

        queue!(buf, cursor::SavePosition).into_diagnostic()?;
        self.render_interactive_prompt(&mut buf, selected)?;
        out.write_all(&buf).into_diagnostic()?;
        out.flush().into_diagnostic()?;

        loop {
            if let Event::Key(key_event) = event::read().into_diagnostic()? {
                if key_event.kind != KeyEventKind::Press {
                    continue;
                }

                match self.handle_interactive_key(key_event, &mut selected) {
                    Ok(Some(answer)) => {
                        terminal::disable_raw_mode().into_diagnostic()?;
                        if self.show_confirmation {
                            buf.clear();
                            queue!(buf, cursor::RestorePosition).into_diagnostic()?;
                            queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                            self.show_result(&mut buf, answer)?;
                            out.write_all(&buf).into_diagnostic()?;
                            out.flush().into_diagnostic()?;
                        }
                        return Ok(answer);
                    }
                    Ok(None) => {
                        buf.clear();
                        queue!(buf, cursor::RestorePosition).into_diagnostic()?;
                        queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                        self.render_interactive_prompt(&mut buf, selected)?;
                        out.write_all(&buf).into_diagnostic()?;
                        out.flush().into_diagnostic()?;
                    }
                    Err(e) => {
                        terminal::disable_raw_mode().into_diagnostic()?;
                        buf.clear();
                        queue!(buf, cursor::RestorePosition).into_diagnostic()?;
                        queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                        self.show_error(&mut buf, &e)?;
                        out.write_all(&buf).into_diagnostic()?;
                        out.flush().into_diagnostic()?;
                        return Err(miette::miette!(e));
                    }
                }
            }
        }
    }

    fn ask_text_input(&self) -> miette::Result<bool> {
        let mut out = stdout();
        let mut buf = Vec::with_capacity(4096);

        terminal::enable_raw_mode().into_diagnostic()?;

        while event::poll(std::time::Duration::from_millis(0)).into_diagnostic()? {
            event::read().into_diagnostic()?;
        }

        queue!(buf, cursor::SavePosition).into_diagnostic()?;
        self.render_prompt(&mut buf)?;
        out.write_all(&buf).into_diagnostic()?;
        out.flush().into_diagnostic()?;

        loop {
            if let Event::Key(key_event) = event::read().into_diagnostic()? {
                if key_event.kind != KeyEventKind::Press {
                    continue;
                }

                let result = self.handle_text_key(key_event, &mut out);

                match result {
                    Ok(Some(answer)) => {
                        terminal::disable_raw_mode().into_diagnostic()?;
                        if self.show_confirmation {
                            buf.clear();
                            queue!(buf, cursor::RestorePosition).into_diagnostic()?;
                            queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                            self.show_result(&mut buf, answer)?;
                            out.write_all(&buf).into_diagnostic()?;
                            out.flush().into_diagnostic()?;
                        }
                        return Ok(answer);
                    }
                    Ok(None) => {
                        continue;
                    }
                    Err(e) => {
                        buf.clear();
                        queue!(buf, cursor::RestorePosition).into_diagnostic()?;
                        queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                        self.show_error(&mut buf, &e)?;
                        self.render_prompt(&mut buf)?;
                        out.write_all(&buf).into_diagnostic()?;
                        out.flush().into_diagnostic()?;
                    }
                }
            }
        }
    }

    fn handle_text_key(
        &self,
        key_event: KeyEvent,
        _out: &mut std::io::Stdout,
    ) -> Result<Option<bool>, String> {
        if key_event.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key_event.code, KeyCode::Char('c'))
        {
            let _ = terminal::disable_raw_mode();
            std::process::exit(130);
        }

        match key_event.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => self.validate_and_return(true),
            KeyCode::Char('n') | KeyCode::Char('N') => self.validate_and_return(false),
            KeyCode::Char('1') | KeyCode::Char('t') | KeyCode::Char('T') => {
                self.validate_and_return(true)
            }
            KeyCode::Char('0') | KeyCode::Char('f') | KeyCode::Char('F') => {
                self.validate_and_return(false)
            }
            KeyCode::Enter => self.validate_and_return(self.default),
            KeyCode::Esc if self.allow_escape => Err("Cancelled".into()),
            _ => Err("Invalid input. Expected: y/n, 1/0, t/f, or Enter for default".to_string()),
        }
    }

    fn handle_interactive_key(
        &self,
        key_event: KeyEvent,
        selected: &mut bool,
    ) -> Result<Option<bool>, String> {
        if key_event.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key_event.code, KeyCode::Char('c'))
        {
            let _ = terminal::disable_raw_mode();
            std::process::exit(130);
        }

        match key_event.code {
            KeyCode::Left | KeyCode::Right | KeyCode::Tab => {
                *selected = !*selected;
                Ok(None)
            }
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                *selected = true;
                Ok(None)
            }
            KeyCode::Char('n') | KeyCode::Char('N') => {
                *selected = false;
                Ok(None)
            }
            KeyCode::Enter | KeyCode::Char(' ') => self.validate_and_return(*selected),
            KeyCode::Esc if self.allow_escape => Err("Cancelled".into()),
            _ => Ok(None),
        }
    }

    fn validate_and_return(&self, value: bool) -> Result<Option<bool>, String> {
        if let Some(ref validator) = self.validation {
            run_validator(validator.as_ref(), &value)?;
        }
        Ok(Some(value))
    }

    fn render_prompt(&self, out: &mut impl Write) -> miette::Result<()> {
        let tw = crate::util::term_width();

        if self.inline {
            let line = format!(
                "{} {} ",
                self.prompt_prefix.style(self.style.prompt_prefix),
                self.prompt.style(self.style.prompt),
            );
            write!(out, "{}", line).into_diagnostic()?;
        } else {
            let line = format!(
                "{} {}",
                self.prompt_prefix.style(self.style.prompt_prefix),
                self.prompt.style(self.style.prompt),
            );
            crate::util::writeln_physical(out, &line, tw)?;
        }

        if let Some(suffix) = &self.prompt_suffix {
            let line = format!("{} ", suffix.style(self.style.hint));
            write!(out, "{}", line).into_diagnostic()?;
        }

        if self.show_hints {
            let default_hint = if self.default {
                &self.yes_text
            } else {
                &self.no_text
            };
            let line = format!(
                "({}/{}, default: {}) ",
                self.yes_text.style(self.style.yes_style),
                self.no_text.style(self.style.no_style),
                default_hint.style(self.style.default_value),
            );
            write!(out, "{}", line).into_diagnostic()?;
        }

        Ok(())
    }

    fn render_interactive_prompt(
        &self,
        out: &mut impl Write,
        selected: bool,
    ) -> miette::Result<()> {
        let tw = crate::util::term_width();

        if self.inline {
            let line = format!(
                "{} {} ",
                self.prompt_prefix.style(self.style.prompt_prefix),
                self.prompt.style(self.style.prompt),
            );
            write!(out, "{}", line).into_diagnostic()?;
        } else {
            let line = format!(
                "{} {}",
                self.prompt_prefix.style(self.style.prompt_prefix),
                self.prompt.style(self.style.prompt),
            );
            crate::util::writeln_physical(out, &line, tw)?;
        }

        let options_line = if selected {
            format!(
                "  {}  {}",
                format!("{}", self.yes_text).style(self.style.selected),
                format!("  {}", self.no_text).style(self.style.no_style)
            )
        } else {
            format!(
                "  {}  {}",
                format!("  {}", self.yes_text).style(self.style.yes_style),
                format!("{}", self.no_text).style(self.style.selected)
            )
        };
        crate::util::writeln_physical(out, &options_line, tw)?;

        if self.show_hints {
            let hint_line = format!(
                "  {}",
                "← → to select, Enter to confirm, Esc to cancel".style(self.style.hint)
            );
            crate::util::writeln_physical(out, &hint_line, tw)?;
        }

        Ok(())
    }

    fn show_error(&self, out: &mut impl Write, error: &str) -> miette::Result<()> {
        if self.show_error_hint {
            let tw = crate::util::term_width();
            let line = format!(
                "{} {}",
                self.style
                    .error_prefix
                    .as_deref()
                    .unwrap_or("")
                    .style(self.style.error),
                error.style(self.style.error_hint),
            );
            crate::util::writeln_physical(out, &line, tw)?;
        }

        Ok(())
    }

    fn show_result(&self, out: &mut impl Write, answer: bool) -> miette::Result<()> {
        let result_text = if answer {
            &self.yes_text
        } else {
            &self.no_text
        };
        let result_style = if answer {
            self.style.yes_style
        } else {
            self.style.no_style
        };

        let tw = crate::util::term_width();
        let line = format!(
            "{} {} {}",
            self.prompt_prefix.style(self.style.prompt_prefix),
            self.prompt.style(self.style.prompt),
            result_text.style(result_style).bold(),
        );
        crate::util::writeln_physical(out, &line, tw)?;

        Ok(())
    }
}