ichoose 0.3.0

Interactive terminal list selection (lib+bin)
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
use {
    ratatui::{
        crossterm::{
            event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
            execute,
            terminal::{
                disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
            },
        },
        prelude::*,
        symbols::border,
        widgets::{
            block::{Position, Title},
            Block, List, ListState, Padding, Paragraph, Scrollbar, ScrollbarOrientation,
            ScrollbarState, Wrap,
        },
        Terminal,
    },
    std::{collections::BTreeSet, io},
    tap::Tap,
};

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone)]
pub struct ListEntry<K> {
    pub key: K,
    pub name: String,
    /// Optional description shown as dim text after the name.
    pub description: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct ListSearchExtra<'k, K> {
    /// Title of the box.
    pub title: String,
    /// Text displayed at the top of the box, usually giving context for the selection.
    pub text: String,
    /// Is multiselection enabled.
    pub multi_select: bool,
    /// List showed if the search input is empty (history for iforgor).
    pub empty_search_list: Option<&'k [ListEntry<K>]>,
    /// Initial selection for multi-select mode. Keys that match entries will be pre-selected.
    pub initial_selection: BTreeSet<K>,
    /// If true, preserve the original item order instead of sorting alphabetically.
    pub preserve_order: bool,
    /// Custom key bindings that exit the picker with an action name.
    /// The currently highlighted item (if any) is included in `selected`.
    pub action_keys: Vec<(ActionKey, String)>,
}

/// Keys that can be used as action keys without conflicting with search or navigation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionKey {
    F(u8),
    Ctrl(char),
    Alt(char),
    Insert,
    Delete,
    Home,
    End,
    PageUp,
    PageDown,
}

impl ActionKey {
    fn matches(&self, event: &KeyEvent) -> bool {
        use ratatui::crossterm::event::KeyModifiers;
        match (self, event.code) {
            (ActionKey::F(n), KeyCode::F(m)) => *n == m,
            (ActionKey::Ctrl(c), KeyCode::Char(k)) => {
                *c == k && event.modifiers.contains(KeyModifiers::CONTROL)
            }
            (ActionKey::Alt(c), KeyCode::Char(k)) => {
                *c == k && event.modifiers.contains(KeyModifiers::ALT)
            }
            (ActionKey::Insert, KeyCode::Insert) => true,
            (ActionKey::Delete, KeyCode::Delete) => true,
            (ActionKey::Home, KeyCode::Home) => true,
            (ActionKey::End, KeyCode::End) => true,
            (ActionKey::PageUp, KeyCode::PageUp) => true,
            (ActionKey::PageDown, KeyCode::PageDown) => true,
            _ => false,
        }
    }

    fn label(&self) -> String {
        match self {
            ActionKey::F(n) => format!("F{n}"),
            ActionKey::Ctrl(c) => format!("Ctrl+{}", c.to_uppercase()),
            ActionKey::Alt(c) => format!("Alt+{}", c.to_uppercase()),
            ActionKey::Insert => "Ins".into(),
            ActionKey::Delete => "Del".into(),
            ActionKey::Home => "Home".into(),
            ActionKey::End => "End".into(),
            ActionKey::PageUp => "PgUp".into(),
            ActionKey::PageDown => "PgDn".into(),
        }
    }
}

/// Result returned by the list search picker.
#[derive(Debug, Clone)]
pub struct SelectionResult<K> {
    pub selected: BTreeSet<K>,
    /// Set when a custom action key was pressed.
    pub action: Option<String>,
}

/// Callback to handle `key:value` filter terms.
/// Given a key, value, and the entry, returns true if it matches.
#[allow(clippy::type_complexity)]
pub type FilterCallback<K> = Box<dyn Fn(&str, &str, &ListEntry<K>) -> bool>;

/// Callback to get preview text for an entry.
/// Given a key, returns the text to display in the preview pane.
pub type PreviewCallback<K> = Box<dyn Fn(&K) -> Option<String>>;

/// Main type to setup the list search.
///
/// ```no_run
/// # fn main() -> std::io::Result<()> {
/// let list: Vec<_> = ["Alpha", "Beta", "Omega"]
///     .into_iter()
///     .enumerate()
///     .map(|(index, item)| ichoose::ListEntry {
///         key: index.to_string(),
///         name: item.to_string(),
///         description: None,
///     })
///     .collect();
///
/// let choices = ichoose::ListSearch {
///    items: &list,
///    extra: ichoose::ListSearchExtra {
///        title: "Exemple title".to_string(),
///        ..Default::default()
///    },
///    filter_callback: None,
///    preview_callback: None,
/// }
/// .run()?;
///
/// println!("{choices:?}");
/// # Ok(())
/// # }
/// ```
pub struct ListSearch<'k, K> {
    /// Customization options.
    pub extra: ListSearchExtra<'k, K>,
    /// The main list we want to search into.
    pub items: &'k [ListEntry<K>],
    /// Optional callback for `key:value` filter terms.
    pub filter_callback: Option<FilterCallback<K>>,
    /// Optional callback to get preview text for the highlighted entry.
    /// When set, Tab toggles a preview pane.
    pub preview_callback: Option<PreviewCallback<K>>,
}

struct ListSearchRunner<'c, 'k, K> {
    config: &'c ListSearch<'k, K>,

    /// List currently being displayed (filtered by search).
    displayed_list: Vec<&'k ListEntry<K>>,
    /// Content of the search input field.
    search_input: String,
    /// Set of selected items.
    selected_items: BTreeSet<K>,
    /// State of the TUI List.
    ui_list_state: ListState,
    /// Should the TUI exit?
    exit: bool,
    /// Is the preview pane visible?
    show_preview: bool,
    /// Action triggered by a custom key.
    action: Option<String>,
}

impl<'k, K: Ord + Clone> ListSearch<'k, K> {
    pub fn run(&self) -> io::Result<SelectionResult<K>> {
        ListSearchRunner {
            config: self,
            displayed_list: Vec::new(),
            search_input: String::new(),
            selected_items: self.extra.initial_selection.clone(),
            ui_list_state: ListState::default().tap_mut(|v| v.select(Some(0))),
            exit: false,
            show_preview: false,
            action: None,
        }
        .run()
    }
}

impl<'c, 'k, K: Ord + Clone> ListSearchRunner<'c, 'k, K> {
    fn update_displayed_list(&mut self) {
        if let Some(alt_list) = self.config.extra.empty_search_list {
            if self.search_input.is_empty() {
                self.displayed_list = alt_list.iter().collect();
                return;
            }
        }

        let search = self.search_input.to_lowercase();
        let terms: Vec<_> = search.split(',').map(|s| s.trim()).collect();

        self.displayed_list = self
            .config
            .items
            .iter()
            .filter(|item| search_filter(item, &terms, self.config.filter_callback.as_deref()))
            .collect::<Vec<_>>()
            .tap_mut(|v| {
                if !self.config.extra.preserve_order {
                    v.sort_by_key(|item| &item.name);
                }
            });
    }

    /// Get the currently highlighted entry's key.
    fn selected_key(&self) -> Option<&K> {
        let idx = self.ui_list_state.selected()?;
        self.displayed_list.get(idx).map(|e| &e.key)
    }

    pub fn run(self) -> io::Result<SelectionResult<K>> {
        let mut stderr = io::stderr();

        execute!(stderr, EnterAlternateScreen)?;
        enable_raw_mode()?;

        let mut terminal = Terminal::new(CrosstermBackend::new(stderr.lock()))?;

        let output = self.run_inner(&mut terminal);

        execute!(stderr, LeaveAlternateScreen)?;
        disable_raw_mode()?;
        output
    }

    fn run_inner<T: ratatui::backend::Backend>(
        mut self,
        terminal: &mut Terminal<T>,
    ) -> io::Result<SelectionResult<K>> {
        self.update_displayed_list();

        while !self.exit {
            terminal.draw(|frame| self.render_frame(frame))?;
            self.handle_events()?;
        }

        Ok(SelectionResult {
            selected: self.selected_items,
            action: self.action,
        })
    }

    fn render_frame(&mut self, frame: &mut Frame) {
        frame.render_widget(self, frame.size());
    }

    fn handle_events(&mut self) -> io::Result<()> {
        match event::read()? {
            Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
                self.handle_key_event(key_event)
            }
            _ => {}
        };
        Ok(())
    }

    fn handle_key_event(&mut self, key_event: KeyEvent) {
        // Check custom action keys.
        if let Some((_, action_name)) = self
            .config
            .extra
            .action_keys
            .iter()
            .find(|(ak, _)| ak.matches(&key_event))
        {
            self.action = Some(action_name.clone());
            if let Some(key) = self.selected_key().cloned() {
                self.selected_items.insert(key);
            }
            self.exit = true;
            return;
        }

        match key_event.code {
            KeyCode::Esc => {
                self.selected_items = BTreeSet::new();
                self.exit = true;
            }
            KeyCode::Enter => {
                self.exit = true;

                if self.config.extra.multi_select {
                    return;
                }

                let Some(selected_index) = self.ui_list_state.selected() else {
                    return;
                };

                let Some(item) = self.displayed_list.get(selected_index) else {
                    return;
                };

                self.selected_items.insert(item.key.clone());
            }
            KeyCode::Tab if self.config.preview_callback.is_some() => {
                self.show_preview = !self.show_preview;
            }
            KeyCode::Char(c)
                if !key_event.modifiers.intersects(
                    ratatui::crossterm::event::KeyModifiers::CONTROL
                        | ratatui::crossterm::event::KeyModifiers::ALT,
                ) =>
            {
                self.search_input.push(c);
                self.ui_list_state.select(Some(0));
                self.update_displayed_list();
            }
            KeyCode::Backspace => {
                self.search_input.pop();
                self.ui_list_state.select(Some(0));
                self.update_displayed_list();
            }
            KeyCode::Up => {
                self.ui_list_state.select_previous();
            }
            KeyCode::Down => {
                self.ui_list_state.select_next();
            }
            KeyCode::Left if self.config.extra.multi_select => {
                if self
                    .displayed_list
                    .iter()
                    .any(|item| self.selected_items.contains(&item.key))
                {
                    for item in self.displayed_list.iter() {
                        self.selected_items.remove(&item.key);
                    }
                } else {
                    for item in self.displayed_list.iter() {
                        self.selected_items.insert(item.key.clone());
                    }
                }
            }
            KeyCode::Right if self.config.extra.multi_select => {
                let Some(selected_index) = self.ui_list_state.selected() else {
                    return;
                };

                let Some(item) = self.displayed_list.get(selected_index) else {
                    return;
                };

                if self.selected_items.contains(&item.key) {
                    self.selected_items.remove(&item.key);
                } else {
                    self.selected_items.insert(item.key.clone());
                }
            }
            _ => {}
        }
    }
}

impl<'c, 'k, K: Ord + Clone> Widget for &mut ListSearchRunner<'c, 'k, K> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // Display outer block
        // Build title with item count.
        let total = self.config.items.len();
        let shown = self.displayed_list.len();
        let count_str = if shown == total {
            format!(" ({total}) ")
        } else {
            format!(" ({shown}/{total}) ")
        };
        let title = Title::from(vec![
            self.config.extra.title.as_str().bold().magenta(),
            count_str.dim(),
        ]);

        let mut instructions = Vec::new();
        instructions.add_instruction("Change Line", "Up/Down");

        if self.config.extra.multi_select {
            instructions.add_instruction("Toggle select", "Right");
            instructions.add_instruction("Toggle all", "Left");
        }

        if self.config.preview_callback.is_some() {
            instructions.add_instruction("Preview", "Tab");
        }

        for (key, name) in &self.config.extra.action_keys {
            instructions.add_instruction(name, &key.label());
        }

        instructions.add_instruction("Confirm", "Enter");
        instructions.add_instruction("Quit", "Esc");

        instructions.push(" ".into());

        let instructions = Title::from(instructions);
        let block = Block::bordered()
            .title(title.alignment(Alignment::Center))
            .title(
                instructions
                    .alignment(Alignment::Center)
                    .position(Position::Bottom),
            )
            .border_set(border::ROUNDED)
            .padding(Padding::horizontal(1));

        let inner = block.inner(area);

        // If preview is active, split horizontally.
        let (main_area, preview_area) = if self.show_preview {
            let chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
                .split(inner);
            (chunks[0], Some(chunks[1]))
        } else {
            (inner, None)
        };

        // Main area layout
        let [search_bar, separator, list_area, extra_text] = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1),
                Constraint::Length(1),
                Constraint::Min(3),
                Constraint::Max(3),
            ])
            .areas(main_area);

        let [search_label, search_area] = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(9), Constraint::Min(10)])
            .areas(search_bar);

        // Render search bar
        Line::from("Search :").render(search_label, buf);

        // Search input with block cursor
        let mut search_spans = vec![Span::styled(
            self.search_input.as_str(),
            Style::new().underlined(),
        )];
        search_spans.push(Span::styled("â–ˆ", Style::new().dim()));
        Line::from(search_spans).render(search_area, buf);

        // Separator line
        let sep = "─".repeat(separator.width as usize);
        Line::from(sep)
            .style(Style::new().dark_gray())
            .render(separator, buf);

        // Render list
        let list: Vec<_> = self
            .displayed_list
            .iter()
            .map(|item| {
                let mut spans = Vec::new();

                if self.config.extra.multi_select {
                    let c = if self.selected_items.contains(&item.key) {
                        "â—‰ "
                    } else {
                        "â—‹ "
                    };
                    spans.push(Span::raw(c));
                }

                spans.push(Span::raw(&item.name));

                if let Some(ref desc) = item.description {
                    spans.push(Span::styled(
                        format!("  {desc}"),
                        Style::new().dim().italic(),
                    ));
                }

                Line::from(spans)
            })
            .collect();

        let list_len = list.len();
        let list = List::new(list)
            .highlight_style(Style::new().bold().reversed())
            .scroll_padding(1);
        StatefulWidget::render(&list, list_area, buf, &mut self.ui_list_state);

        // Scrollbar (only when list overflows visible area)
        let visible_height = list_area.height as usize;
        if list_len > visible_height {
            let mut scrollbar_state =
                ScrollbarState::new(list_len).position(self.ui_list_state.selected().unwrap_or(0));
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .render(list_area, buf, &mut scrollbar_state);
        }

        // Render extra text
        Paragraph::new(self.config.extra.text.as_str())
            .wrap(Wrap { trim: true })
            .style(Style::new().dark_gray().italic())
            .render(extra_text, buf);

        // Render preview pane
        if let Some(preview_area) = preview_area {
            let preview_text = self
                .selected_key()
                .and_then(|key| self.config.preview_callback.as_ref().and_then(|cb| cb(key)))
                .unwrap_or_default();

            let preview_block = Block::bordered()
                .title(" Preview ".bold().cyan())
                .border_set(border::ROUNDED)
                .padding(Padding::horizontal(1));

            Paragraph::new(preview_text)
                .wrap(Wrap { trim: false })
                .block(preview_block)
                .render(preview_area, buf);
        }

        // Render block
        block.render(area, buf);
    }
}

/// Filter an entry against search terms.
/// Terms are comma-separated. Each term must match (AND).
/// A term like `key:value` is delegated to the filter_callback if provided.
/// Plain terms match against name and description (case-insensitive substring).
#[allow(clippy::type_complexity)]
fn search_filter<K>(
    entry: &ListEntry<K>,
    search_terms: &[&str],
    filter_callback: Option<&dyn Fn(&str, &str, &ListEntry<K>) -> bool>,
) -> bool {
    let name_lower = entry.name.to_lowercase();
    let desc_lower = entry.description.as_ref().map(|d| d.to_lowercase());

    for term in search_terms {
        // Check for key:value filter syntax.
        if let Some((key, value)) = term.split_once(':') {
            if let Some(cb) = filter_callback {
                if !cb(key.trim(), value.trim(), entry) {
                    return false;
                }
                continue;
            }
            // No callback: fall through to plain text match.
        }

        // Plain text: match against name or description.
        let in_name = name_lower.contains(term);
        let in_desc = desc_lower.as_ref().is_some_and(|d| d.contains(term));
        if !in_name && !in_desc {
            return false;
        }
    }

    true
}

trait AddInstruction {
    fn add_instruction(&mut self, name: &str, keys: &str);
}

impl<'k> AddInstruction for Vec<Span<'k>> {
    fn add_instruction(&mut self, name: &str, keys: &str) {
        self.push(format!(" {name} ").dim());
        self.push(format!("<{keys}>").blue().bold());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(name: &str, desc: Option<&str>) -> ListEntry<String> {
        ListEntry {
            key: name.to_string(),
            name: name.to_string(),
            description: desc.map(String::from),
        }
    }

    #[test]
    fn plain_term_matches_name() {
        let e = entry("docker-deploy", None);
        assert!(search_filter(&e, &["docker"], None));
    }

    #[test]
    fn plain_term_matches_description() {
        let e = entry("deploy", Some("runs docker containers"));
        assert!(search_filter(&e, &["docker"], None));
    }

    #[test]
    fn plain_term_matches_neither() {
        let e = entry("deploy", Some("runs containers"));
        assert!(!search_filter(&e, &["docker"], None));
    }

    #[test]
    fn multiple_terms_all_match() {
        let e = entry("docker-deploy", Some("production"));
        assert!(search_filter(&e, &["docker", "production"], None));
    }

    #[test]
    fn multiple_terms_one_fails() {
        let e = entry("docker-deploy", None);
        assert!(!search_filter(&e, &["docker", "missing"], None));
    }

    #[test]
    fn case_insensitive() {
        let e = entry("Docker-Deploy", None);
        assert!(search_filter(&e, &["docker"], None));
    }

    #[test]
    fn key_value_with_callback() {
        let e = entry("deploy", None);
        let cb = |key: &str, value: &str, _: &ListEntry<String>| -> bool {
            key == "tag" && value == "prod"
        };
        assert!(search_filter(&e, &["tag:prod"], Some(&cb)));
    }

    #[test]
    fn key_value_callback_rejects() {
        let e = entry("deploy", None);
        let cb = |_: &str, _: &str, _: &ListEntry<String>| -> bool { false };
        assert!(!search_filter(&e, &["tag:prod"], Some(&cb)));
    }

    #[test]
    fn key_value_without_callback_falls_through() {
        // "tag:prod" treated as plain text, no match in name
        let e = entry("deploy", None);
        assert!(!search_filter(&e, &["tag:prod"], None));
    }

    #[test]
    fn key_value_without_callback_matches_as_text() {
        // "tag:prod" treated as plain text, matches in name
        let e = entry("tag:prod-deploy", None);
        assert!(search_filter(&e, &["tag:prod"], None));
    }

    #[test]
    fn empty_search_matches_all() {
        let e = entry("anything", None);
        assert!(search_filter(&e, &[""], None));
    }
}