askr 0.1.7

Interactive CLI input tool with real-time validation and choice menus
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
use super::{ChoiceMenu, ColorScheme, Colorizer, LayoutManager, Screen, Terminal};
use crate::cli::config::PromptConfig;
use crate::error::{PromptError, Result};
use crate::validation::{ValidationEngine, ValidatorType};
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use std::io::{self, stderr};
use std::time::Duration;

pub struct InteractivePrompt {
    terminal: Terminal,
    validation_engine: ValidationEngine,
    config: PromptConfig,
}

impl InteractivePrompt {
    pub fn new(
        mut terminal: Terminal,
        validation_engine: ValidationEngine,
        config: PromptConfig,
    ) -> Result<Self> {
        // Only enter raw mode if we have cursor control (i.e., we're in a TTY)
        if terminal.capabilities().cursor_control {
            terminal.enter_raw_mode()?;
        }

        Ok(Self {
            terminal,
            validation_engine,
            config,
        })
    }

    pub fn prompt(&mut self) -> Result<String> {
        let prompt_text = self
            .config
            .prompt_text
            .as_deref()
            .unwrap_or("Enter input:")
            .to_string();

        // Check if we have choice validation - if so, use choice menu
        if let Some(choice_config) = self.find_choice_validator() {
            return self.prompt_with_choice_menu(&prompt_text, choice_config);
        }
        let has_help = self.config.ui_config.help_text.is_some();

        // Set up UI components
        let _capabilities = self.terminal.capabilities().clone();
        let (width, height) = self.terminal.size()?;

        let color_scheme = if self.config.ui_config.no_color {
            ColorScheme::no_color()
        } else {
            ColorScheme::default()
        };

        let colorizer = Colorizer::new(color_scheme, self.config.ui_config.no_color);

        // Calculate space needed and reserve it
        let reserved_lines = self.calculate_and_reserve_space(width, &prompt_text)?;

        let layout = LayoutManager::new(width, height);
        let mut screen = Screen::new(stderr(), layout, colorizer);

        // Calculate layout with reserved space context
        screen.layout_mut().calculate_layout(has_help);

        // Move cursor to the reserved prompt position
        self.move_to_prompt_position(reserved_lines)?;

        // Draw initial screen
        let prompt_width = screen.write_prompt(&prompt_text)?;

        // Don't write help text initially - only show it when there are validation errors

        screen.flush()?;

        // Input loop
        let mut input = String::new();
        let mut cursor_pos = 0; // Track cursor position within the input
        let mut attempts = 0;
        let max_attempts = self
            .config
            .interaction_config
            .max_attempts
            .unwrap_or(u32::MAX);

        loop {
            // Position cursor at the correct position within the input
            screen.position_cursor_at_input_pos(&input, cursor_pos, prompt_width)?;
            screen.flush()?;

            // Handle timeout
            let timeout = self
                .config
                .interaction_config
                .timeout
                .unwrap_or(Duration::from_secs(300));

            // Read input event
            if event::poll(timeout)? {
                if let Event::Key(key_event) = event::read()? {
                    match self.handle_key_event(
                        key_event,
                        &mut input,
                        &mut cursor_pos,
                        &mut screen,
                        prompt_width,
                    )? {
                        InputAction::Continue => {
                            // Validate and update display, then reposition cursor
                            self.update_validation_display(
                                &input,
                                &mut screen,
                                cursor_pos,
                                prompt_width,
                            )?;
                        }
                        InputAction::Submit => {
                            // Final validation
                            let summary = self.validation_engine.validate(&input);
                            if summary.valid {
                                // Handle confirmation if required
                                if self.config.interaction_config.require_confirmation {
                                    match self.prompt_confirmation(&input)? {
                                        Some(confirmed_input) => return Ok(confirmed_input),
                                        None => {
                                            // Confirmation failed, continue with original input loop
                                            continue;
                                        }
                                    }
                                } else {
                                    return Ok(input);
                                }
                            } else {
                                attempts += 1;
                                if attempts >= max_attempts {
                                    return Err(PromptError::MaxAttemptsExceeded);
                                }
                                // Show errors and continue
                                self.update_validation_display(
                                    &input,
                                    &mut screen,
                                    cursor_pos,
                                    prompt_width,
                                )?;
                            }
                        }
                        InputAction::Cancel => {
                            return Err(PromptError::Interrupted);
                        }
                    }
                }
            } else {
                return Err(PromptError::Timeout);
            }
        }
    }

    fn handle_key_event(
        &self,
        key_event: KeyEvent,
        input: &mut String,
        cursor_pos: &mut usize,
        screen: &mut Screen<io::Stderr>,
        prompt_width: u16,
    ) -> Result<InputAction> {
        match key_event {
            // Submit on Enter
            KeyEvent {
                code: KeyCode::Enter,
                ..
            } => {
                // Check if we have a default value and input is empty
                if input.is_empty() && self.config.interaction_config.default_value.is_some() {
                    *input = self
                        .config
                        .interaction_config
                        .default_value
                        .as_ref()
                        .unwrap()
                        .clone();
                    *cursor_pos = input.chars().count();
                }
                Ok(InputAction::Submit)
            }

            // Cancel on Ctrl+C
            KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => Ok(InputAction::Cancel),

            // Cancel on Ctrl+D (EOF) - only if input is empty
            KeyEvent {
                code: KeyCode::Char('d'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                if input.is_empty() {
                    Ok(InputAction::Cancel)
                } else {
                    Ok(InputAction::Continue)
                }
            }

            // Ctrl+A - Jump to beginning of line
            KeyEvent {
                code: KeyCode::Char('a'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                *cursor_pos = 0;
                Ok(InputAction::Continue)
            }

            // Ctrl+E - Jump to end of line
            KeyEvent {
                code: KeyCode::Char('e'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                *cursor_pos = input.chars().count();
                Ok(InputAction::Continue)
            }

            // Ctrl+K - Kill from cursor to end of line
            KeyEvent {
                code: KeyCode::Char('k'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                let chars: Vec<char> = input.chars().collect();
                if *cursor_pos < chars.len() {
                    let new_input: String = chars[..*cursor_pos].iter().collect();
                    *input = new_input;
                    self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                }
                Ok(InputAction::Continue)
            }

            // Ctrl+U - Kill from beginning of line to cursor
            KeyEvent {
                code: KeyCode::Char('u'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                let chars: Vec<char> = input.chars().collect();
                if *cursor_pos > 0 {
                    let new_input: String = chars[*cursor_pos..].iter().collect();
                    *input = new_input;
                    *cursor_pos = 0;
                    self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                }
                Ok(InputAction::Continue)
            }

            // Ctrl+W - Delete word before cursor
            KeyEvent {
                code: KeyCode::Char('w'),
                modifiers: KeyModifiers::CONTROL,
                ..
            } => {
                if *cursor_pos > 0 {
                    let chars: Vec<char> = input.chars().collect();
                    let mut new_cursor = *cursor_pos;

                    // Skip whitespace before cursor
                    while new_cursor > 0 && chars[new_cursor - 1].is_whitespace() {
                        new_cursor -= 1;
                    }

                    // Delete word characters
                    while new_cursor > 0 && !chars[new_cursor - 1].is_whitespace() {
                        new_cursor -= 1;
                    }

                    let mut new_chars = chars;
                    new_chars.drain(new_cursor..*cursor_pos);
                    *input = new_chars.iter().collect();
                    *cursor_pos = new_cursor;
                    self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                }
                Ok(InputAction::Continue)
            }

            // Arrow keys for cursor movement
            KeyEvent {
                code: KeyCode::Left,
                ..
            } => {
                if *cursor_pos > 0 {
                    *cursor_pos -= 1;
                }
                Ok(InputAction::Continue)
            }

            KeyEvent {
                code: KeyCode::Right,
                ..
            } => {
                if *cursor_pos < input.chars().count() {
                    *cursor_pos += 1;
                }
                Ok(InputAction::Continue)
            }

            // Home key - jump to beginning
            KeyEvent {
                code: KeyCode::Home,
                ..
            } => {
                *cursor_pos = 0;
                Ok(InputAction::Continue)
            }

            // End key - jump to end
            KeyEvent {
                code: KeyCode::End, ..
            } => {
                *cursor_pos = input.chars().count();
                Ok(InputAction::Continue)
            }

            // Backspace - delete character before cursor
            KeyEvent {
                code: KeyCode::Backspace,
                ..
            } => {
                if *cursor_pos > 0 {
                    let mut chars: Vec<char> = input.chars().collect();
                    chars.remove(*cursor_pos - 1);
                    *input = chars.iter().collect();
                    *cursor_pos -= 1;
                    self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                }
                Ok(InputAction::Continue)
            }

            // Delete key - delete character at cursor
            KeyEvent {
                code: KeyCode::Delete,
                ..
            } => {
                let mut chars: Vec<char> = input.chars().collect();
                if *cursor_pos < chars.len() {
                    chars.remove(*cursor_pos);
                    *input = chars.iter().collect();
                    self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                }
                Ok(InputAction::Continue)
            }

            // Regular character input
            KeyEvent {
                code: KeyCode::Char(c),
                modifiers,
                ..
            } => {
                // Skip if this is a control character we already handled
                if modifiers.contains(KeyModifiers::CONTROL) {
                    return Ok(InputAction::Continue);
                }

                // Insert character at cursor position
                let mut chars: Vec<char> = input.chars().collect();
                chars.insert(*cursor_pos, c);
                *input = chars.iter().collect();
                *cursor_pos += 1;

                // Redraw input (masking handled in redraw_input method)
                self.redraw_input(input, cursor_pos, screen, prompt_width)?;
                Ok(InputAction::Continue)
            }

            // Ignore other keys
            _ => Ok(InputAction::Continue),
        }
    }

    fn redraw_input(
        &self,
        input: &str,
        _cursor_pos: &usize,
        screen: &mut Screen<io::Stderr>,
        prompt_width: u16,
    ) -> Result<()> {
        let display_input = if self.config.interaction_config.mask_input {
            "*".repeat(input.chars().count())
        } else {
            input.to_string()
        };
        screen.write_input(&display_input, prompt_width, None)?;
        Ok(())
    }

    fn calculate_and_reserve_space(&self, width: u16, _prompt_text: &str) -> Result<u16> {
        use std::io::{self, Write};

        // Get all potential error messages
        let messages = self.validation_engine.get_potential_error_messages();

        // Calculate lines needed for each component in order
        let mut total_lines = 0u16;

        // 1. Prompt line (always 1 line)
        total_lines += 1;

        // 2. Help text lines (if present)
        if let Some(help_text) = &self.config.ui_config.help_text {
            let wrapped_lines = self.calculate_wrapped_lines(help_text, width);
            total_lines += wrapped_lines;
        }

        // 3. Error messages (with text wrapping)
        for message in &messages {
            let wrapped_lines = self.calculate_wrapped_lines(message, width);
            total_lines += wrapped_lines;
        }

        // 4. Add some buffer for dynamic content and spacing
        total_lines += 3;

        // Ensure we don't try to reserve more lines than the terminal height
        let (_, terminal_height) = self.terminal.size()?;
        let max_reservable = terminal_height.saturating_sub(2); // Leave room for prompt
        total_lines = total_lines.min(max_reservable);

        // Print blank lines to reserve the space
        let mut stderr = io::stderr();
        for _ in 0..total_lines {
            writeln!(stderr)?;
        }
        stderr.flush()?;

        Ok(total_lines)
    }

    fn calculate_wrapped_lines(&self, text: &str, width: u16) -> u16 {
        if text.is_empty() || width == 0 {
            return 0;
        }

        let max_width = width as usize;
        let mut lines = 0u16;
        let mut current_line_width = 0;

        for word in text.split_whitespace() {
            let word_len = word.len();

            if current_line_width + word_len < max_width || current_line_width == 0 {
                if current_line_width > 0 {
                    current_line_width += 1; // space
                }
                current_line_width += word_len;
            } else {
                lines += 1;
                current_line_width = word_len;
            }
        }

        if current_line_width > 0 {
            lines += 1;
        }

        lines.max(1) // At least 1 line for any non-empty text
    }

    fn move_to_prompt_position(&mut self, reserved_lines: u16) -> Result<()> {
        use crossterm::{cursor::MoveUp, ExecutableCommand};
        use std::io::stderr;

        // Move cursor back up to where we want to start the prompt
        stderr().execute(MoveUp(reserved_lines))?;

        Ok(())
    }

    fn update_validation_display(
        &self,
        input: &str,
        screen: &mut Screen<io::Stderr>,
        cursor_pos: usize,
        prompt_width: u16,
    ) -> Result<()> {
        if !self.config.interaction_config.mask_input {
            // Get validation results
            let errors = self.validation_engine.get_display_errors(input, Some(10));

            // Write errors below the input and help text if there are errors
            if !errors.is_empty() {
                screen.write_errors(&errors)?;

                if let Some(help_text) = &self.config.ui_config.help_text {
                    screen.write_help(help_text)?;
                }

                // Restore cursor to the prompt line
                screen.restore_saved_cursor()?;
            } else {
                // Clear any existing errors/help text when input is valid
                screen.write_errors(&errors)?; // This will clear the area
                screen.restore_saved_cursor()?;
            }

            // Position cursor at the correct input position after all display updates
            screen.position_cursor_at_input_pos(input, cursor_pos, prompt_width)?;

            screen.flush()?;
        }

        Ok(())
    }

    fn prompt_confirmation(&mut self, original_input: &str) -> Result<Option<String>> {
        use std::io::{self, Write};

        // Print newline and confirmation prompt
        eprintln!();
        eprint!("Confirm input: ");
        io::stderr().flush()?;

        // Create a new terminal instance for confirmation prompt
        let terminal = Terminal::new()?;
        let engine = ValidationEngine::new(); // No validation for confirmation, just matching

        // Create a simplified config for confirmation prompt
        let mut confirmation_config = self.config.clone();
        confirmation_config.prompt_text = Some("Confirm input:".to_string());
        confirmation_config.validation_rules.clear(); // No validation rules for confirmation
        confirmation_config.interaction_config.require_confirmation = false; // Avoid infinite recursion
        confirmation_config.interaction_config.mask_input =
            self.config.interaction_config.mask_input; // Keep same masking behavior

        let mut confirmation_prompt =
            InteractivePrompt::new(terminal, engine, confirmation_config)?;
        let confirmation_input = confirmation_prompt.prompt()?;

        // Check if inputs match
        if original_input == confirmation_input {
            Ok(Some(original_input.to_string()))
        } else {
            // Print mismatch error to stderr and return None to retry
            eprintln!("Error: Inputs do not match. Please try again.");
            Ok(None)
        }
    }

    fn find_choice_validator(&self) -> Option<ChoiceConfig> {
        for rule_config in &self.config.validation_rules {
            if let ValidatorType::Choices(choices) = &rule_config.validator_type {
                let min_choices = rule_config
                    .parameters
                    .get("min_choices")
                    .and_then(|s| s.parse::<usize>().ok())
                    .unwrap_or(1);
                let max_choices = rule_config
                    .parameters
                    .get("max_choices")
                    .and_then(|s| s.parse::<usize>().ok())
                    .unwrap_or(1);
                let selection_separator = rule_config
                    .parameters
                    .get("selection_separator")
                    .cloned()
                    .unwrap_or_else(|| ",".to_string());

                // Parse default selections if provided
                let default_selections =
                    if let Some(default_value) = &self.config.interaction_config.default_value {
                        self.parse_default_choices(default_value, &selection_separator, choices)
                    } else {
                        Vec::new()
                    };

                return Some(ChoiceConfig {
                    choices: choices.clone(),
                    allow_multiple: max_choices > 1,
                    min_choices,
                    max_choices,
                    selection_separator,
                    default_selections,
                });
            }
        }
        None
    }

    fn parse_default_choices(
        &self,
        default_value: &str,
        selection_separator: &str,
        available_choices: &[String],
    ) -> Vec<String> {
        // Parse the default value using the same separator as selections
        let default_choices: Vec<String> = default_value
            .split(selection_separator)
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        // Filter to only include valid choices that exist in available_choices
        default_choices
            .into_iter()
            .filter(|choice| {
                available_choices
                    .iter()
                    .any(|available| available == choice)
            })
            .collect()
    }

    fn prompt_with_choice_menu(
        &mut self,
        prompt_text: &str,
        choice_config: ChoiceConfig,
    ) -> Result<String> {
        // Create a new terminal instance for the choice menu
        let terminal = Terminal::new()?;
        let timeout = self
            .config
            .interaction_config
            .timeout
            .unwrap_or(Duration::from_secs(300));

        let mut choice_menu = ChoiceMenu::new(
            terminal,
            choice_config.choices,
            choice_config.allow_multiple,
            choice_config.min_choices,
            choice_config.max_choices,
            self.config.ui_config.no_color,
            timeout,
            choice_config.default_selections,
        )?;

        let selected_choices = choice_menu.show(prompt_text)?;

        if choice_config.allow_multiple {
            Ok(selected_choices.join(&choice_config.selection_separator))
        } else {
            Ok(selected_choices.into_iter().next().unwrap_or_default())
        }
    }
}

#[derive(Debug)]
struct ChoiceConfig {
    choices: Vec<String>,
    allow_multiple: bool,
    min_choices: usize,
    max_choices: usize,
    selection_separator: String,
    default_selections: Vec<String>,
}

impl Drop for InteractivePrompt {
    fn drop(&mut self) {
        // Clean up terminal state only if we have cursor control
        if self.terminal.capabilities().cursor_control {
            let _ = self.terminal.leave_raw_mode();
        }
    }
}

#[derive(Debug)]
enum InputAction {
    Continue,
    Submit,
    Cancel,
}