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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Interactive menu selection utilities
use crate::onboarding::navigation::NavResult;
use crate::onboarding::styled_output::{self, Colors, StepStatus};
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
use crossterm::execute;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use std::io::{self, Write, stdout};
use std::time::{Duration, Instant};
/// Internal helper: Select from a list of options with search capability
/// Returns NavResult to support back navigation
fn select_option_internal<T: Clone>(
options: &[(T, &str, bool)], // (value, display_name, is_recommended)
can_go_back: bool,
header_height: usize,
) -> NavResult<T> {
let mut selected = 0;
let mut search_input = String::new();
if enable_raw_mode().is_err() {
return NavResult::Cancel;
}
let mut previous_height = 0;
loop {
// If we previously rendered content, move cursor up and clear from there
if previous_height > 0 {
print!("\x1b[{}A", previous_height);
print!("\x1b[0J");
}
let mut current_height = 0;
// Render search line
print!(
" {}Search: {}{}\r\n",
Colors::gray(),
search_input,
Colors::reset()
);
current_height += 1;
// Filter options based on search
let filtered: Vec<_> = if search_input.is_empty() {
options.iter().collect()
} else {
options
.iter()
.filter(|(_, name, _)| name.to_lowercase().contains(&search_input.to_lowercase()))
.collect()
};
if !filtered.is_empty() {
if selected >= filtered.len() {
selected = filtered.len().saturating_sub(1);
}
// Render options
for (idx, (_, name, is_recommended)) in filtered.iter().enumerate() {
let display_name = if *name == "Anthropic" && idx == selected {
format!("{} {}(Claude Pro/Max or API key)", name, Colors::gray())
} else {
name.to_string()
};
styled_output::render_option(&display_name, idx == selected, *is_recommended);
current_height += 1;
}
} else {
print!(
" {}No matches found{}\r\n",
Colors::gray(),
Colors::reset()
);
current_height += 1;
}
print!("\r\n");
current_height += 1;
styled_output::render_footer_shortcuts();
current_height += 1;
let _ = stdout().flush();
previous_height = current_height;
if let Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) = event::read()
{
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
print!("\x1b[{}A", previous_height + header_height);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
if !filtered.is_empty() {
print!("\x1b[{}A", previous_height + header_height);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
return NavResult::Forward(filtered[selected].0.clone());
}
}
KeyCode::Up => {
selected = selected.saturating_sub(1);
}
KeyCode::Down => {
if selected < filtered.len().saturating_sub(1) {
selected += 1;
}
}
KeyCode::Char(c) => {
search_input.push(c);
selected = 0;
}
KeyCode::Backspace => {
search_input.pop();
selected = 0;
}
KeyCode::Esc => {
print!("\x1b[{}A", previous_height + header_height);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
if can_go_back {
return NavResult::Back;
} else {
return NavResult::Cancel;
}
}
_ => {}
}
}
}
}
/// Select from a list of options with search capability
/// Returns NavResult to support back navigation
pub fn select_option<T: Clone>(
title: &str,
options: &[(T, &str, bool)], // (value, display_name, is_recommended)
current_step: usize,
total_steps: usize,
can_go_back: bool,
) -> NavResult<T> {
// Render header: title and step indicators
styled_output::render_title(title);
let steps: Vec<_> = (0..total_steps)
.map(|i| {
let status = if i < current_step {
StepStatus::Completed
} else if i == current_step {
StepStatus::Active
} else {
StepStatus::Pending
};
(format!("Step {}", i + 1), status)
})
.collect();
styled_output::render_steps(&steps);
print!("\r\n");
// Header height: title (1) + steps (1) + empty line (1) = 3
select_option_internal(options, can_go_back, 3)
}
/// Select from a list of options without rendering title and step indicators
/// Used for sub-steps within a larger step (e.g., hybrid provider configuration)
/// Returns NavResult to support back navigation
pub fn select_option_no_header<T: Clone>(
options: &[(T, &str, bool)], // (value, display_name, is_recommended)
can_go_back: bool,
) -> NavResult<T> {
// No header, so header_height is 0
select_option_internal(options, can_go_back, 0)
}
/// Validate profile name (alphanumeric and underscores only, no spaces or special chars)
pub fn validate_profile_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("Profile name cannot be empty".to_string());
}
if name == "all" {
return Err("Cannot use 'all' as a profile name. It's reserved for defaults.".to_string());
}
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err("Profile name can only contain letters, numbers, and underscores".to_string());
}
Ok(())
}
/// Prompt for profile name with validation
/// Returns NavResult to support back navigation
pub fn prompt_profile_name(config_path: Option<&str>) -> NavResult<Option<String>> {
use crate::config::AppConfig;
use std::path::PathBuf;
let mut input = String::new();
let mut error_message: Option<String> = None;
if enable_raw_mode().is_err() {
return NavResult::Cancel;
}
loop {
// Clear the line and re-render prompt
print!("\r\x1b[K"); // Clear current line
print!(
"{}◆ {}Enter profile name: ",
Colors::yellow(),
Colors::cyan()
);
// Show error if any
if let Some(ref error) = error_message {
print!("{}({}){} ", Colors::yellow(), error, Colors::reset());
}
// Show current input (RESET color to match question)
print!("{}{}", Colors::reset(), input);
let _ = io::stdout().flush();
match event::read() {
Ok(Event::Paste(pasted_text)) => {
input.push_str(&pasted_text);
error_message = None;
}
Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) => {
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
let trimmed = input.trim();
if trimmed.is_empty() {
error_message = Some("Profile name cannot be empty".to_string());
input.clear();
continue;
}
// Validate format
if let Err(e) = validate_profile_name(trimmed) {
error_message = Some(e);
input.clear();
continue;
}
// Check if profile exists
let custom_path = config_path.map(PathBuf::from);
if let Ok(existing_profiles) =
AppConfig::list_available_profiles(custom_path.as_deref())
&& existing_profiles.contains(&trimmed.to_string())
{
error_message = Some(format!("Profile '{}' already exists", trimmed));
input.clear();
continue;
}
// Clear the prompt line before returning
print!("\r\x1b[K"); // Clear current line
print!("\r\n");
disable_raw_mode().ok();
return NavResult::Forward(Some(trimmed.to_string()));
}
KeyCode::Esc => {
print!("\r\n");
disable_raw_mode().ok();
return NavResult::Back;
}
KeyCode::Backspace => {
input.pop();
error_message = None;
}
KeyCode::Char(c) => {
input.push(c);
error_message = None;
}
_ => {}
}
}
_ => {}
}
}
}
/// Prompt for text input
/// Returns NavResult to support back navigation
pub fn prompt_text(prompt: &str, required: bool) -> NavResult<Option<String>> {
let mut input = String::new();
let mut show_required = false;
if enable_raw_mode().is_err() {
return NavResult::Cancel;
}
loop {
// Clear the line and re-render prompt
print!("\r\x1b[K"); // Clear current line
print!("{}◆ {}{}: ", Colors::yellow(), Colors::cyan(), prompt);
if show_required && required {
print!("{}(Required){} ", Colors::yellow(), Colors::reset());
}
// Show current input
print!("{}{}", Colors::cyan(), input);
let _ = io::stdout().flush();
match event::read() {
Ok(Event::Paste(pasted_text)) => {
// Handle paste event - add all characters at once
input.push_str(&pasted_text);
}
Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) => {
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
let trimmed = input.trim();
if required && trimmed.is_empty() {
show_required = true;
input.clear();
// Don't disable raw mode - continue the loop
continue;
}
print!("\r\n");
disable_raw_mode().ok();
return NavResult::Forward(if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
});
}
KeyCode::Esc => {
print!("\r\n");
disable_raw_mode().ok();
return NavResult::Back;
}
KeyCode::Backspace => {
input.pop();
}
KeyCode::Char(c) => {
input.push(c);
}
_ => {}
}
}
_ => {}
}
}
}
/// Prompt for password/API key (hidden input)
/// Returns NavResult to support back navigation
pub fn prompt_password(prompt: &str, required: bool) -> NavResult<Option<String>> {
let mut password = String::new();
let mut show_required = false;
if enable_raw_mode().is_err() {
return NavResult::Cancel;
}
// Enable bracketed paste mode for better paste handling
let _ = execute!(stdout(), EnableBracketedPaste);
// Buffer for rapid character input (paste detection)
let mut paste_buffer = String::new();
let mut last_char_time = Instant::now();
const PASTE_TIMEOUT_MS: u64 = 50; // Characters arriving within 50ms are considered a paste
loop {
// Get terminal width for wrapping calculation
let terminal_width = crossterm::terminal::size()
.map(|(w, _)| w as usize)
.unwrap_or(80)
.max(40);
// Calculate what we're about to print
let prompt_text = format!("◆ {}: ", prompt);
let required_text = if show_required && required {
" (Required) "
} else {
""
};
let prefix_len = prompt_text.len() + required_text.len();
let display_len = password.len() + paste_buffer.len();
let available_width = terminal_width.saturating_sub(prefix_len);
// Show asterisks for password (including buffered paste)
// Cap the number of stars to available width to prevent wrapping issues
let stars_to_show = display_len.min(available_width.saturating_sub(1));
print!("\r\x1b[K"); // Clear current line
// Render prompt
print!("{}◆ {}{}: ", Colors::yellow(), Colors::cyan(), prompt);
if show_required && required {
print!("{}(Required){} ", Colors::yellow(), Colors::reset());
}
// Show asterisks
print!("{}", Colors::cyan());
for _ in 0..stars_to_show {
print!("*");
}
print!("{}", Colors::reset());
let _ = io::stdout().flush();
match event::read() {
Ok(Event::Paste(pasted_text)) => {
// Handle paste event - add all characters at once
password.push_str(&pasted_text);
paste_buffer.clear();
}
Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) => {
let now = Instant::now();
let time_since_last = now.duration_since(last_char_time);
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
let _ = execute!(stdout(), DisableBracketedPaste);
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
// Flush any pending paste buffer
if !paste_buffer.is_empty() {
password.push_str(&paste_buffer);
paste_buffer.clear();
}
let trimmed = password.trim();
if required && trimmed.is_empty() {
show_required = true;
password.clear();
// Don't disable raw mode - continue the loop
continue;
}
print!("\r\n");
let _ = execute!(stdout(), DisableBracketedPaste);
disable_raw_mode().ok();
return NavResult::Forward(if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
});
}
KeyCode::Esc => {
print!("\r\n");
let _ = execute!(stdout(), DisableBracketedPaste);
disable_raw_mode().ok();
return NavResult::Back;
}
KeyCode::Backspace => {
if !paste_buffer.is_empty() {
paste_buffer.pop();
} else {
password.pop();
}
last_char_time = now;
}
KeyCode::Char(c) => {
// If characters are arriving rapidly, collect them as a paste
if time_since_last.as_millis() < PASTE_TIMEOUT_MS as u128 {
paste_buffer.push(c);
last_char_time = now;
// Try to read all remaining rapid characters
while let Ok(true) = event::poll(Duration::from_millis(10)) {
match event::read() {
Ok(Event::Key(KeyEvent {
code: KeyCode::Char(ch),
kind: KeyEventKind::Press,
..
})) => {
paste_buffer.push(ch);
last_char_time = Instant::now();
}
_ => break,
}
}
// Flush buffer to password
password.push_str(&paste_buffer);
paste_buffer.clear();
} else {
// Flush any pending paste buffer
if !paste_buffer.is_empty() {
password.push_str(&paste_buffer);
paste_buffer.clear();
}
password.push(c);
last_char_time = now;
}
}
_ => {}
}
}
_ => {
// Flush any pending paste buffer on other events
if !paste_buffer.is_empty() {
password.push_str(&paste_buffer);
paste_buffer.clear();
}
}
}
}
}
/// Prompt for yes/no confirmation
/// Returns NavResult to support back navigation
pub fn prompt_yes_no(prompt: &str, default: bool) -> NavResult<Option<bool>> {
let default_text = if default { "Y/n" } else { "y/N" };
let mut input = String::new();
if enable_raw_mode().is_err() {
return NavResult::Cancel;
}
loop {
// Clear the line and re-render prompt
print!("\r\x1b[K"); // Clear current line
print!(
"{}◆ {}{} ({}): ",
Colors::yellow(),
Colors::cyan(),
prompt,
default_text
);
print!("{}{}", Colors::cyan(), input);
let _ = io::stdout().flush();
if let Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) = event::read()
{
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
print!("\r\n");
disable_raw_mode().ok();
let trimmed = input.trim().to_lowercase();
let result = match trimmed.as_str() {
"y" | "yes" => Some(true),
"n" | "no" => Some(false),
"" => None, // Use default
_ => None, // Use default for invalid input
};
return NavResult::Forward(result);
}
KeyCode::Esc => {
print!("\r\n");
disable_raw_mode().ok();
return NavResult::Back;
}
KeyCode::Backspace => {
input.pop();
}
KeyCode::Char(c) => {
input.push(c);
}
_ => {}
}
}
}
}
/// Select profile interactively with scrolling (max 7 visible)
/// Returns Some(profile_name) or None if cancelled
/// Special return value "CREATE_NEW_PROFILE" indicates user wants to create new profile
pub async fn select_profile_interactive(config_path: Option<&std::path::Path>) -> Option<String> {
use crate::config::AppConfig;
// Get available profiles
let profiles = AppConfig::list_available_profiles(config_path).unwrap_or_default();
// Build options: "Create a new profile" first, then profiles
let mut options: Vec<(String, &str, bool)> = vec![(
"CREATE_NEW_PROFILE".to_string(),
"Create a new profile",
false,
)];
for profile in &profiles {
options.push((profile.clone(), profile.as_str(), false));
}
if options.len() == 1 {
// Only "Create a new profile" option, return it directly
return Some("CREATE_NEW_PROFILE".to_string());
}
// Use select_option but we need to customize it for scrolling
// For now, let's create a simplified version
select_profile_with_scrolling("Stakpak profiles", &options, config_path).await
}
/// Select profile with scrolling support (max 7 visible)
async fn select_profile_with_scrolling(
title: &str,
options: &[(String, &str, bool)],
_config_path: Option<&std::path::Path>,
) -> Option<String> {
let _ = _config_path; // Suppress unused parameter warning
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use std::io::{Write, stdout};
let mut selected = 0;
let mut search_input = String::new();
let mut scroll_offset = 0;
const MAX_VISIBLE: usize = 7;
if enable_raw_mode().is_err() {
return None;
}
styled_output::render_title(title);
print!("\r\n");
let mut previous_height = 0;
loop {
if previous_height > 0 {
print!("\x1b[{}A", previous_height);
print!("\x1b[0J");
}
let mut current_height = 0;
// Render search line
print!(
" {}Search: {}{}\r\n",
Colors::gray(),
search_input,
Colors::reset()
);
current_height += 1;
// Filter options
let filtered: Vec<_> = if search_input.is_empty() {
options.iter().collect()
} else {
options
.iter()
.filter(|(_, name, _)| name.to_lowercase().contains(&search_input.to_lowercase()))
.collect()
};
if !filtered.is_empty() {
if selected >= filtered.len() {
selected = filtered.len().saturating_sub(1);
}
// Calculate scroll window
let total = filtered.len();
let visible_start = if total <= MAX_VISIBLE {
0
} else if selected < scroll_offset {
selected.max(0)
} else if selected >= scroll_offset + MAX_VISIBLE {
selected.saturating_sub(MAX_VISIBLE - 1)
} else {
scroll_offset
};
let visible_end = (visible_start + MAX_VISIBLE).min(total);
let visible_items = &filtered[visible_start..visible_end];
// Show ◆ if there are items above
if visible_start > 0 {
let hidden_above = visible_start;
print!(
" {}◆ {} more above{}\r\n",
Colors::yellow(),
hidden_above,
Colors::reset()
);
current_height += 1;
}
// Render visible items with radio button circles
for (idx, (_, name, _)) in visible_items.iter().enumerate() {
let global_idx = visible_start + idx;
let is_selected = global_idx == selected;
if is_selected {
// Selected: green filled circle + white text
print!(
" {}●{} {}{}\r\n",
Colors::green(),
Colors::reset(),
Colors::white(),
name
);
print!("{}", Colors::reset());
} else {
// Unselected: gray circle border + gray text
print!(
" {}○{} {}{}\r\n",
Colors::gray(),
Colors::reset(),
Colors::gray(),
name
);
print!("{}", Colors::reset());
}
current_height += 1;
}
// Show ▼ if there are items below
if visible_end < total {
let hidden_below = total - visible_end;
print!(
" {}▼ {} more below{}\r\n",
Colors::gray(),
hidden_below,
Colors::reset()
);
current_height += 1;
}
} else {
print!(
" {}No matches found{}\r\n",
Colors::gray(),
Colors::reset()
);
current_height += 1;
}
print!("\r\n");
current_height += 1;
styled_output::render_footer_shortcuts();
current_height += 1;
let _ = stdout().flush();
previous_height = current_height;
if let Ok(Event::Key(KeyEvent {
code,
kind: KeyEventKind::Press,
modifiers,
..
})) = event::read()
{
match code {
KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
print!("\x1b[{}A", previous_height + 2);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
std::process::exit(130);
}
KeyCode::Enter => {
if !filtered.is_empty() {
print!("\x1b[{}A", previous_height + 2);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
return Some(filtered[selected].0.clone());
}
}
KeyCode::Up => {
if selected > 0 {
selected -= 1;
// Update scroll if needed
if selected < scroll_offset {
scroll_offset = selected;
}
}
}
KeyCode::Down => {
if selected < filtered.len().saturating_sub(1) {
selected += 1;
// Update scroll if needed
if selected >= scroll_offset + MAX_VISIBLE {
scroll_offset = selected.saturating_sub(MAX_VISIBLE - 1);
}
}
}
KeyCode::Char(c) => {
search_input.push(c);
selected = 0;
scroll_offset = 0;
}
KeyCode::Backspace => {
search_input.pop();
selected = 0;
scroll_offset = 0;
}
KeyCode::Esc => {
print!("\x1b[{}A", previous_height + 2);
print!("\x1b[0J");
let _ = stdout().flush();
disable_raw_mode().ok();
return None;
}
_ => {}
}
}
}
}