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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use {
    crate::{
        style::TextInputStyle,
        util::CursorGuard,
        validation::{Validate, run_validator},
    },
    crossterm::{
        cursor,
        event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
        queue,
        terminal::{self, Clear, ClearType},
    },
    dyn_clone::DynClone,
    miette::IntoDiagnostic,
    owo_colors::OwoColorize,
    simsearch::SimSearch,
    std::io::{Write, stdout},
};

pub type Replacement = Option<String>;

pub trait Autocomplete: DynClone {
    fn get_suggestions(&mut self, input: &str) -> Result<Vec<String>, String>;

    fn get_completion(
        &mut self,
        input: &str,
        highlighted_suggestion: Option<String>,
    ) -> Result<Replacement, String>;
}

dyn_clone::clone_trait_object!(Autocomplete);

#[derive(Clone)]
pub struct SimpleAutocomplete {
    options: Vec<String>,
}

impl SimpleAutocomplete {
    pub fn new(options: Vec<String>) -> Self {
        Self { options }
    }
}

impl Autocomplete for SimpleAutocomplete {
    fn get_suggestions(&mut self, input: &str) -> Result<Vec<String>, String> {
        if input.is_empty() {
            return Ok(self.options.clone());
        }

        Ok(self
            .options
            .iter()
            .filter(|opt| opt.to_lowercase().starts_with(&input.to_lowercase()))
            .cloned()
            .collect())
    }

    fn get_completion(
        &mut self,
        input: &str,
        highlighted_suggestion: Option<String>,
    ) -> Result<Replacement, String> {
        if let Some(suggestion) = highlighted_suggestion {
            return Ok(Some(suggestion));
        }

        let suggestions = self.get_suggestions(input)?;
        if suggestions.is_empty() {
            return Ok(None);
        }

        if suggestions.len() == 1 {
            return Ok(Some(suggestions[0].clone()));
        }

        let first = &suggestions[0];
        let mut prefix = String::new();

        for (i, c) in first.chars().enumerate() {
            if suggestions
                .iter()
                .all(|s| s.chars().nth(i).map(|sc| sc == c).unwrap_or(false))
            {
                prefix.push(c);
            } else {
                break;
            }
        }

        if prefix.len() > input.len() {
            Ok(Some(prefix))
        } else {
            Ok(None)
        }
    }
}

#[derive(Clone)]
pub struct FuzzyAutocomplete {
    options: Vec<String>,
}

impl FuzzyAutocomplete {
    pub fn new(options: Vec<String>) -> Self {
        Self { options }
    }

    fn build_engine(&self) -> SimSearch<usize> {
        let mut engine = SimSearch::new();
        for (i, opt) in self.options.iter().enumerate() {
            engine.insert(i, opt);
        }
        engine
    }
}

impl Autocomplete for FuzzyAutocomplete {
    fn get_suggestions(&mut self, input: &str) -> Result<Vec<String>, String> {
        if input.is_empty() {
            return Ok(self.options.clone());
        }

        let engine = self.build_engine();
        let ids = engine.search(input);
        Ok(ids.into_iter().map(|i| self.options[i].clone()).collect())
    }

    fn get_completion(
        &mut self,
        input: &str,
        highlighted_suggestion: Option<String>,
    ) -> Result<Replacement, String> {
        if let Some(suggestion) = highlighted_suggestion {
            return Ok(Some(suggestion));
        }

        let suggestions = self.get_suggestions(input)?;
        if suggestions.is_empty() {
            return Ok(None);
        }

        if suggestions.len() == 1 {
            return Ok(Some(suggestions[0].clone()));
        }

        Ok(None)
    }
}

#[derive(Clone)]
pub struct TextInput {
    prompt: String,
    default: Option<String>,
    placeholder: Option<String>,
    initial_value: Option<String>,
    inline: bool,
    prompt_prefix: String,
    help_message: Option<String>,
    show_suggestions: bool,
    suggestion_page_size: usize,
    allow_escape: bool,
    style: TextInputStyle,
    validation: Option<Box<dyn Validate<str>>>,
    autocomplete: Option<Box<dyn Autocomplete>>,
    _cursor_guard: CursorGuard,
}

impl TextInput {
    pub fn new(prompt: impl Into<String>) -> Self {
        let _cursor_guard = CursorGuard::new().expect("Failed to initialize cursor guard");
        Self {
            prompt: prompt.into(),
            default: None,
            placeholder: None,
            initial_value: None,
            inline: false,
            prompt_prefix: "?".into(),
            help_message: None,
            show_suggestions: true,
            suggestion_page_size: 5,
            allow_escape: true,
            style: TextInputStyle::default(),
            validation: None,
            autocomplete: None,
            _cursor_guard,
        }
    }

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

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

    pub fn with_initial_value(mut self, value: impl Into<String>) -> Self {
        self.initial_value = Some(value.into());
        self
    }

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

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

    pub fn with_help_message(mut self, message: impl Into<String>) -> Self {
        self.help_message = Some(message.into());
        self
    }

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

    pub fn with_suggestion_page_size(mut self, size: usize) -> Self {
        self.suggestion_page_size = size;
        self
    }

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

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

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

    pub fn with_autocomplete<A: Autocomplete + 'static>(mut self, autocomplete: A) -> Self {
        self.autocomplete = Some(Box::new(autocomplete));
        self
    }

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

    pub fn ask(&mut self) -> miette::Result<String> {
        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 = self._ask_internal();

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

        result
    }

    pub fn _ask_internal(&mut self) -> miette::Result<String> {
        let mut input = self.initial_value.clone().unwrap_or_default();
        let mut cursor_pos = input.len();
        let mut suggestions: Vec<String> = Vec::new();
        let mut selected_suggestion: Option<usize> = None;
        let mut suggestion_scroll_offset: usize = 0;
        let mut buf = Vec::with_capacity(4096);
        let mut out = stdout();

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

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

        if let Some(ref mut ac) = self.autocomplete {
            suggestions = ac.get_suggestions(&input).unwrap_or_default();
        }

        let (mut _last_render_lines, mut last_input_line_position) = self.render(
            &mut buf,
            &input,
            cursor_pos,
            &suggestions,
            selected_suggestion,
            suggestion_scroll_offset,
        )?;
        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_key(
                    key_event,
                    &mut input,
                    &mut cursor_pos,
                    &mut suggestions,
                    &mut selected_suggestion,
                    &mut suggestion_scroll_offset,
                    &mut stdout(),
                ) {
                    Ok(Some(answer)) => {
                        terminal::disable_raw_mode().into_diagnostic()?;

                        buf.clear();
                        if last_input_line_position > 0 {
                            queue!(buf, cursor::MoveUp(last_input_line_position as u16))
                                .into_diagnostic()?;
                        }
                        queue!(buf, cursor::MoveToColumn(0)).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();
                        if last_input_line_position > 0 {
                            queue!(buf, cursor::MoveUp(last_input_line_position as u16))
                                .into_diagnostic()?;
                        }
                        queue!(buf, cursor::MoveToColumn(0)).into_diagnostic()?;
                        queue!(buf, Clear(ClearType::FromCursorDown)).into_diagnostic()?;
                        let (lines, input_pos) = self.render(
                            &mut buf,
                            &input,
                            cursor_pos,
                            &suggestions,
                            selected_suggestion,
                            suggestion_scroll_offset,
                        )?;
                        _last_render_lines = lines;
                        last_input_line_position = input_pos;
                        out.write_all(&buf).into_diagnostic()?;
                        out.flush().into_diagnostic()?;
                    }
                    Err(e) => {
                        terminal::disable_raw_mode().into_diagnostic()?;

                        buf.clear();
                        if last_input_line_position > 0 {
                            queue!(buf, cursor::MoveUp(last_input_line_position as u16))
                                .into_diagnostic()?;
                        }
                        queue!(buf, cursor::MoveToColumn(0)).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));
                    }
                }
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn handle_key(
        &mut self,
        key_event: KeyEvent,
        input: &mut String,
        cursor_pos: &mut usize,
        suggestions: &mut Vec<String>,
        selected_suggestion: &mut Option<usize>,
        suggestion_scroll_offset: &mut usize,
        _out: &mut std::io::Stdout,
    ) -> Result<Option<String>, 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::Enter => {
                if let Some(idx) = *selected_suggestion
                    && let Some(suggestion) = suggestions.get(idx)
                {
                    *input = suggestion.clone();
                    *cursor_pos = input.len();
                }

                let final_input = if input.is_empty() {
                    self.default.clone().unwrap_or_default()
                } else {
                    input.clone()
                };

                self.validate_and_return(&final_input)
            }
            KeyCode::Char(c) => {
                input.insert(*cursor_pos, c);
                *cursor_pos += 1;
                *selected_suggestion = None;
                *suggestion_scroll_offset = 0;

                if let Some(ref mut ac) = self.autocomplete {
                    *suggestions = ac.get_suggestions(input).unwrap_or_default();
                }

                Ok(None)
            }
            KeyCode::Backspace if *cursor_pos > 0 => {
                *cursor_pos -= 1;
                input.remove(*cursor_pos);
                *selected_suggestion = None;
                *suggestion_scroll_offset = 0;

                if let Some(ref mut ac) = self.autocomplete {
                    *suggestions = ac.get_suggestions(input).unwrap_or_default();
                }

                Ok(None)
            }
            KeyCode::Left if *cursor_pos > 0 => {
                *cursor_pos -= 1;
                Ok(None)
            }
            KeyCode::Right if *cursor_pos < input.len() => {
                *cursor_pos += 1;
                Ok(None)
            }
            KeyCode::Home => {
                *cursor_pos = 0;
                Ok(None)
            }
            KeyCode::End => {
                *cursor_pos = input.len();
                Ok(None)
            }
            KeyCode::Up if !suggestions.is_empty() => {
                *selected_suggestion = Some(match *selected_suggestion {
                    None => suggestions.len() - 1,
                    Some(0) => suggestions.len() - 1,
                    Some(n) => n - 1,
                });

                if let Some(selected) = *selected_suggestion {
                    if selected < *suggestion_scroll_offset {
                        *suggestion_scroll_offset = selected;
                    } else if selected >= *suggestion_scroll_offset + self.suggestion_page_size {
                        *suggestion_scroll_offset =
                            selected.saturating_sub(self.suggestion_page_size - 1);
                    }
                }
                Ok(None)
            }
            KeyCode::Down if !suggestions.is_empty() => {
                *selected_suggestion = Some(match *selected_suggestion {
                    None => 0,
                    Some(n) if n >= suggestions.len() - 1 => 0,
                    Some(n) => n + 1,
                });

                if let Some(selected) = *selected_suggestion {
                    if selected < *suggestion_scroll_offset {
                        *suggestion_scroll_offset = selected;
                    } else if selected >= *suggestion_scroll_offset + self.suggestion_page_size {
                        *suggestion_scroll_offset =
                            selected.saturating_sub(self.suggestion_page_size - 1);
                    }
                }
                Ok(None)
            }
            KeyCode::Tab if self.autocomplete.is_some() => {
                if let Some(ref mut ac) = self.autocomplete {
                    let highlighted =
                        selected_suggestion.and_then(|idx| suggestions.get(idx).cloned());

                    if let Ok(Some(replacement)) = ac.get_completion(input, highlighted) {
                        *input = replacement;
                        *cursor_pos = input.len();
                        *selected_suggestion = None;
                        *suggestion_scroll_offset = 0;

                        *suggestions = ac.get_suggestions(input).unwrap_or_default();
                    }
                }
                Ok(None)
            }
            KeyCode::Esc if self.allow_escape => Err("Cancelled".into()),
            _ => Ok(None),
        }
    }

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

        Ok(Some(value.to_string()))
    }

    pub fn render(
        &self,
        out: &mut impl Write,
        input: &str,
        cursor_pos: usize,
        suggestions: &[String],
        selected_suggestion: Option<usize>,
        suggestion_scroll_offset: usize,
    ) -> miette::Result<(usize, usize)> {
        let tw = crate::util::term_width();
        let mut line_count = 0;
        let mut prompt_prefix_for_cursor = 0;

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

        if let Some(ref help) = self.help_message {
            let line = format!("  {}", help.style(self.style.hint));
            line_count += crate::util::writeln_physical(out, &line, tw)?;
        }

        let display_text = if input.is_empty() {
            self.placeholder
                .as_deref()
                .unwrap_or("")
                .style(self.style.placeholder)
                .to_string()
        } else {
            input.style(self.style.input).to_string()
        };

        let mut input_line = format!("  {} ", display_text);

        if input.is_empty()
            && let Some(default) = self.default.clone()
        {
            input_line = format!(
                "{}(default: {}) ",
                input_line,
                &default.style(self.style.default_value)
            );
        }

        line_count += crate::util::writeln_physical(out, &input_line, tw)?;

        let input_line_position = line_count - 1;

        if self.show_suggestions && !suggestions.is_empty() {
            let end_offset =
                (suggestion_scroll_offset + self.suggestion_page_size).min(suggestions.len());
            let visible_suggestions: Vec<_> = suggestions[suggestion_scroll_offset..end_offset]
                .iter()
                .enumerate()
                .map(|(rel_idx, s)| (suggestion_scroll_offset + rel_idx, s))
                .collect();

            if !visible_suggestions.is_empty() {
                let line = format!("  {}", "Suggestions:".style(self.style.hint));
                line_count += crate::util::writeln_physical(out, &line, tw)?;

                for (abs_idx, suggestion) in visible_suggestions {
                    let marker = if Some(abs_idx) == selected_suggestion {
                        ""
                    } else {
                        " "
                    };

                    let style = if Some(abs_idx) == selected_suggestion {
                        self.style.selected
                    } else {
                        self.style.suggestion
                    };

                    let line = format!(
                        "    {} {}",
                        marker.style(self.style.selected),
                        suggestion.style(style)
                    );
                    line_count += crate::util::writeln_physical(out, &line, tw)?;
                }

                let (above_text, below_text) = (
                    if suggestion_scroll_offset > 0 {
                        format!("{} more above", suggestion_scroll_offset)
                    } else {
                        String::new()
                    },
                    if end_offset < suggestions.len() {
                        format!("{} more below", suggestions.len() - end_offset)
                    } else {
                        String::new()
                    },
                );

                let parts: Vec<&str> = [
                    if !above_text.is_empty() {
                        Some(above_text.as_str())
                    } else {
                        None
                    },
                    if !below_text.is_empty() {
                        Some(below_text.as_str())
                    } else {
                        None
                    },
                ]
                .iter()
                .filter_map(|&x| x)
                .collect();

                if !parts.is_empty() {
                    let line = format!(
                        "    {}",
                        format!("({})", parts.join(" | ")).style(self.style.hint)
                    );
                    line_count += crate::util::writeln_physical(out, &line, tw)?;
                }
            }
        }

        let mut hints = vec![];
        if self.autocomplete.is_some() {
            hints.push("Tab to autocomplete");
        }
        if !suggestions.is_empty() {
            hints.push("↑↓ to navigate");
        }
        hints.push("Enter to submit");
        if self.allow_escape {
            hints.push("Esc to cancel");
        }

        if !hints.is_empty() {
            let line = format!("  {}", hints.join(", ").style(self.style.hint));
            line_count += crate::util::writeln_physical(out, &line, tw)?;
        }

        let lines_to_move_up = line_count - input_line_position;
        if lines_to_move_up > 0 {
            queue!(out, cursor::MoveUp(lines_to_move_up as u16)).into_diagnostic()?;
        }

        let text_before_cursor = &input[..cursor_pos.min(input.len())];
        let cursor_column =
            prompt_prefix_for_cursor + 2 + crate::util::visible_width(text_before_cursor);
        queue!(out, cursor::MoveToColumn(cursor_column as u16)).into_diagnostic()?;
        queue!(out, cursor::Show).into_diagnostic()?;

        Ok((line_count, input_line_position))
    }

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

        Ok(())
    }

    pub fn show_result(&self, out: &mut impl Write, answer: &str) -> miette::Result<()> {
        let tw = crate::util::term_width();
        let line = format!(
            "{} {} {}",
            self.prompt_prefix.style(self.style.prompt_prefix),
            self.prompt.style(self.style.prompt),
            answer.style(self.style.input).bold(),
        );
        crate::util::writeln_physical(out, &line, tw)?;

        Ok(())
    }
}