cli_prompts/prompts/options/
mod.rs

1pub mod multiselect;
2pub mod selection;
3pub mod multioption_prompt;
4
5/// A helper struct for the multi-option prompts
6pub struct Options<T> {
7    all_options: Vec<T>,
8    transformed_options: Vec<String>,
9    filtered_options: Vec<usize>,
10}
11
12impl<T> Options<T>
13where
14    T: Into<String> + Clone,
15{
16    /// Create `Options` from an iterator over a type that is convertable to `String`
17    pub fn from_iter<I>(iter: I) -> Self
18    where
19        I: Iterator<Item = T>,
20    {
21        let options: Vec<T> = iter.collect();
22        let options_count = options.len();
23        Options {
24            all_options: options.clone(),
25            transformed_options: options.into_iter().map(|s| s.into()).collect(),
26            filtered_options: (0..options_count).collect(),
27        }
28    }
29}
30
31impl<T> Options<T> {
32    /// Create `Options` from an arbitrary type using provided transformation function to `String`
33    pub fn from_iter_transformed<I, F>(iter: I, transformation: F) -> Self
34    where
35        I: Iterator<Item = T>,
36        F: Fn(&T) -> String,
37    {
38        let all_options: Vec<T> = iter.collect();
39        let transformed_options: Vec<String> = all_options.iter().map(transformation).collect();
40        let options_count = all_options.len();
41
42        Options {
43            all_options,
44            transformed_options,
45            filtered_options: (0..options_count).collect(),
46        }
47    }
48
49    /// Filter options using provided string slice
50    pub fn filter(&mut self, filter: &str) {
51        self.filtered_options.clear();
52        for (index, option) in self.transformed_options.iter().enumerate() {
53            if option.contains(filter) {
54                self.filtered_options.push(index);
55            }
56        }
57    }
58
59    /// Retrieve the indices of all options that satisfy the last applied filter
60    pub fn filtered_options(&self) -> &[usize] {
61        &self.filtered_options
62    }
63
64    /// Get a mutable reference to the vector all available options
65    pub fn all_options_mut(&mut self) -> &mut Vec<T> {
66        &mut self.all_options
67    }
68
69    /// Get a reference to all options in their string representation
70    pub fn transformed_options(&self) -> &[String] {
71        &self.transformed_options
72    }
73}