|
| 1 | +use crossterm::{ |
| 2 | + cursor::{Hide, MoveTo, Show}, |
| 3 | + event::{self, Event, KeyCode}, |
| 4 | + terminal::{self, Clear, ClearType}, |
| 5 | + ExecutableCommand, |
| 6 | +}; |
| 7 | +use std::io::{self, Write}; |
| 8 | +use colored::Colorize; |
| 9 | + |
| 10 | +fn navigate_strings(strings: &[String]) -> Option<Vec<usize>>{ |
| 11 | + let mut stdout = io::stdout(); |
| 12 | + let mut current_index: usize = 0; |
| 13 | + let mut selected_indexes:Vec<usize> = Vec::new(); |
| 14 | + terminal::enable_raw_mode().unwrap(); |
| 15 | + stdout.execute(Hide).unwrap(); |
| 16 | + |
| 17 | + loop { |
| 18 | + stdout.execute(Clear(ClearType::All)).unwrap(); |
| 19 | + for (i, string) in strings.iter().enumerate() { |
| 20 | + let is_selected = selected_indexes.contains(&i); |
| 21 | + let is_current = i == current_index; |
| 22 | + let done_position = strings.len() - 1; |
| 23 | + stdout.execute(MoveTo(0, i as u16)).unwrap(); |
| 24 | + if is_current && is_selected { |
| 25 | + println!("-> [{}] {}", "✓".green(), string); |
| 26 | + } else if i == done_position && is_current { |
| 27 | + println!("-> {}", string.green()); |
| 28 | + } else if i == done_position { |
| 29 | + println!(" {}", string); |
| 30 | + } else if is_current { |
| 31 | + println!("-> [ ] {}", string); |
| 32 | + } else if is_selected { |
| 33 | + println!(" [{}] {}", "✓".green(), string); |
| 34 | + } else { |
| 35 | + println!(" [] {}", string); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if let Event::Key(key_event) = event::read().unwrap() { |
| 40 | + match key_event.code { |
| 41 | + KeyCode::Up => { |
| 42 | + if current_index > 0 { |
| 43 | + current_index -= 1; |
| 44 | + } else { |
| 45 | + current_index = strings.len() - 1; |
| 46 | + } |
| 47 | + } |
| 48 | + KeyCode::Down => { |
| 49 | + if current_index < strings.len() - 1 { |
| 50 | + current_index += 1; |
| 51 | + } else { |
| 52 | + current_index = 0; |
| 53 | + } |
| 54 | + } |
| 55 | + KeyCode::Esc => { |
| 56 | + break; |
| 57 | + } |
| 58 | + KeyCode::Enter => { |
| 59 | + |
| 60 | + // Operation is done, return to the calling thread |
| 61 | + if current_index == strings.len() - 1 { |
| 62 | + break; |
| 63 | + } |
| 64 | + |
| 65 | + let pos = selected_indexes.iter().position(|&x| x == current_index); |
| 66 | + |
| 67 | + match pos { |
| 68 | + Some(index) => { |
| 69 | + // If the current_index is found, remove it |
| 70 | + selected_indexes.remove(index); |
| 71 | + } |
| 72 | + None => { |
| 73 | + // If the current_index is not found, add it |
| 74 | + selected_indexes.push(current_index); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + _ => {} |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + stdout.execute(Show).unwrap(); |
| 84 | + terminal::disable_raw_mode().unwrap(); |
| 85 | + |
| 86 | + if selected_indexes.is_empty() { |
| 87 | + None |
| 88 | + } else { |
| 89 | + Some(selected_indexes) |
| 90 | + } |
| 91 | +} |
| 92 | + |
0 commit comments