Repository navigation
Expand file tree
/
Copy pathmulti.rs
More file actions
110 lines (95 loc) · 3.21 KB
/
Copy pathmulti.rs
File metadata and controls
110 lines (95 loc) · 3.21 KB
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
use std::io::IsTerminal;
use anyhow::Result;
use console::strip_ansi_codes;
use fzf_wrapped::{Fzf, Layout};
use crate::select::{indexed_items, parse_fzf_index};
/// Builder for multi-select prompts.
pub struct MultiSelectBuilder<T> {
pub(crate) message: String,
pub(crate) options: Vec<T>,
}
impl<T> MultiSelectBuilder<T> {
/// Execute multi-select prompt.
///
/// # Returns
///
/// - `Ok(Some(Vec<T>))` - User selected one or more options
/// - `Ok(None)` - No options available or user cancelled (ESC / Ctrl+C)
///
/// # Errors
///
/// Returns an error if the fzf process fails to start or interact
pub fn prompt(self) -> Result<Option<Vec<T>>>
where
T: std::fmt::Display + Clone,
{
// Bail immediately when stdin is not a terminal to prevent the process
// from blocking indefinitely on a detached or non-interactive session.
if !std::io::stdin().is_terminal() {
return Ok(None);
}
if self.options.is_empty() {
return Ok(None);
}
let display_options: Vec<String> = self
.options
.iter()
.map(|item| strip_ansi_codes(&item.to_string()).trim().to_string())
.collect();
let fzf = build_multi_fzf(&self.message);
let mut fzf = fzf;
fzf.run()
.map_err(|e| anyhow::anyhow!("Failed to start fzf: {e}"))?;
fzf.add_items(indexed_items(&display_options))
.map_err(|e| anyhow::anyhow!("Failed to add items to fzf: {e}"))?;
let raw_output = fzf.output();
match raw_output {
None => Ok(None),
Some(output) => {
let selected_items: Vec<T> = output
.lines()
.filter(|line| !line.trim().is_empty())
.filter_map(|line| {
parse_fzf_index(line).and_then(|index| self.options.get(index).cloned())
})
.collect();
if selected_items.is_empty() {
Ok(None)
} else {
Ok(Some(selected_items))
}
}
}
}
}
/// Builds an `Fzf` instance for multi-select prompts.
fn build_multi_fzf(message: &str) -> Fzf {
let mut builder = Fzf::builder();
builder.layout(Layout::Reverse);
builder.no_scrollbar(true);
builder.prompt(format!("{} ❯ ", message));
builder.custom_args(vec![
"--height=80%".to_string(),
"--exact".to_string(),
"--cycle".to_string(),
"--color=dark,header:bold".to_string(),
"--pointer=▌".to_string(),
"--delimiter=\t".to_string(),
"--with-nth=2..".to_string(),
"--multi".to_string(),
]);
builder
.build()
.expect("fzf builder should always succeed with default options")
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use crate::ForgeWidget;
#[test]
fn test_multi_select_builder_creates() {
let builder = ForgeWidget::multi_select("Select options:", vec!["a", "b", "c"]);
assert_eq!(builder.message, "Select options:");
assert_eq!(builder.options, vec!["a", "b", "c"]);
}
}