intelli-shell 3.4.0

Like IntelliSense, but for shells
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
use std::{borrow::Cow, collections::HashSet};

use ratatui::{
    buffer::Buffer,
    layout::{Rect, Size},
    prelude::StatefulWidget,
    style::{Style, Styled},
    widgets::{Block, Borders, Widget},
};
use tui_widget_list::{ListBuilder, ListState, ListView, ScrollAxis};
use unicode_width::UnicodeWidthStr;

use crate::config::Theme;

/// A trait for types that can be rendered inside a [`CustomList`]
pub trait CustomListItem {
    type Widget<'w>: Widget + 'w
    where
        Self: 'w;

    /// Converts the item into a ratatui widget and its size
    fn as_widget<'a>(
        &'a self,
        theme: &Theme,
        inline: bool,
        is_highlighted: bool,
        is_discarded: bool,
    ) -> (Self::Widget<'a>, Size);
}

/// Defines how a highlight symbol is rendered next to a list item
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HighlightSymbolMode {
    /// Appears only on the first line of the selected item
    First,
    /// Repeats on each line of the selected item
    Repeat,
    /// Appears only on the last line of the selected item
    Last,
}

/// A widget that displays a customizable list of items
pub struct CustomList<'a, T: CustomListItem> {
    /// Application theme
    theme: Theme,
    /// Whether the TUI is rendered inline or not
    inline: bool,
    /// An optional `Block` to surround the list
    block: Option<Block<'a>>,
    /// The scroll axis
    axis: ScrollAxis,
    /// The vector of items to be displayed in the list
    items: Vec<T>,
    /// Whether the list is focused or not
    focus: bool,
    /// The state of the list, managing selection and scrolling
    state: ListState,
    /// The indices of the items marked as discarded
    discarded_indices: HashSet<usize>,
    /// An optional symbol string to display in front of the selected item
    highlight_symbol: Option<String>,
    /// Determines how the `highlight_symbol` is rendered
    highlight_symbol_mode: HighlightSymbolMode,
    /// The `Style` to apply to the `highlight_symbol`
    highlight_symbol_style: Style,
    /// The `Style` to apply to the `highlight_symbol` when focused
    highlight_symbol_style_focused: Style,
}

impl<'a, T: CustomListItem> CustomList<'a, T> {
    /// Creates a new [`CustomList`]
    pub fn new(theme: Theme, inline: bool, items: Vec<T>) -> Self {
        let mut state = ListState::default();
        if !items.is_empty() {
            state.select(Some(0));
        }
        Self {
            block: (!inline).then(|| Block::default().borders(Borders::ALL).style(theme.primary)),
            axis: ScrollAxis::Vertical,
            items,
            focus: true,
            state,
            discarded_indices: HashSet::new(),
            highlight_symbol_style: theme.primary.into(),
            highlight_symbol_style_focused: theme.highlight_primary_full().into(),
            highlight_symbol: Some(theme.highlight_symbol.clone()).filter(|s| !s.trim().is_empty()),
            highlight_symbol_mode: HighlightSymbolMode::Last,
            theme,
            inline,
        }
    }

    /// Sets the scroll axis to horizontal
    pub fn horizontal(mut self) -> Self {
        self.axis = ScrollAxis::Horizontal;
        self
    }

    /// Sets the scroll axis to vertical (the default)
    pub fn vertical(mut self) -> Self {
        self.axis = ScrollAxis::Vertical;
        self
    }

    /// Sets the title for the list
    pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
        self.set_title(title);
        self
    }

    /// Sets the symbol to be displayed before the selected item
    pub fn highlight_symbol(mut self, highlight_symbol: String) -> Self {
        self.highlight_symbol = Some(highlight_symbol).filter(|s| !s.is_empty());
        self
    }

    /// Sets the rendering mode for the highlight symbol
    pub fn highlight_symbol_mode(mut self, highlight_symbol_mode: HighlightSymbolMode) -> Self {
        self.highlight_symbol_mode = highlight_symbol_mode;
        self
    }

    /// Sets the style for the highlight symbol
    pub fn highlight_symbol_style(mut self, highlight_symbol_style: Style) -> Self {
        self.highlight_symbol_style = highlight_symbol_style;
        self
    }

    /// Sets the style for the highlight symbol when focused
    pub fn highlight_symbol_style_focused(mut self, highlight_symbol_style_focused: Style) -> Self {
        self.highlight_symbol_style_focused = highlight_symbol_style_focused;
        self
    }

    /// Updates the title of the list
    pub fn set_title(&mut self, new_title: impl Into<Cow<'a, str>>) {
        if let Some(ref mut block) = self.block {
            *block = Block::default()
                .borders(Borders::ALL)
                .style(Styled::style(block))
                .title(new_title.into());
        }
    }

    /// Sets the focus state of the list
    pub fn set_focus(&mut self, focus: bool) {
        self.focus = focus;
    }

    /// Returns whether the text area is currently focused or not
    pub fn is_focused(&self) -> bool {
        self.focus
    }

    /// Returns the number of items in this list
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns `true` if the list contains no items
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Returns a reference to the inner items of the list
    pub fn items(&self) -> &Vec<T> {
        &self.items
    }

    /// Returns a mutable reference to the inner items of the list
    pub fn items_mut(&mut self) -> &mut Vec<T> {
        &mut self.items
    }

    /// Returns an iterator over the references to items that have not been discarded
    pub fn non_discarded_items(&self) -> impl Iterator<Item = &T> {
        self.items
            .iter()
            .enumerate()
            .filter_map(|(index, item)| if self.is_discarded(index) { None } else { Some(item) })
    }

    /// Checks if an item at a given index is discarded
    pub fn is_discarded(&self, index: usize) -> bool {
        self.discarded_indices.contains(&index)
    }

    /// Updates the items displayed in this list.
    ///
    /// The discarded state will always be reset.
    pub fn update_items(&mut self, items: Vec<T>, keep_selection: bool) {
        self.items = items;
        self.discarded_indices.clear();

        if keep_selection {
            if self.items.is_empty() {
                self.state.select(None);
            } else if let Some(selected) = self.state.selected {
                if selected > self.items.len() - 1 {
                    self.state.select(Some(self.items.len() - 1));
                }
            } else {
                self.state.select(Some(0));
            }
        } else {
            self.state = ListState::default();
            if !self.items.is_empty() {
                self.state.select(Some(0));
            }
        }
    }

    /// Selects the next item in the list, wrapping around to the beginning if at the end
    pub fn select_next(&mut self) {
        if self.focus
            && let Some(selected) = self.state.selected
        {
            if self.items.is_empty() {
                self.state.select(None);
            } else {
                let i = if selected >= self.items.len() - 1 {
                    0
                } else {
                    selected + 1
                };
                self.state.select(Some(i));
            }
        }
    }

    /// Selects the previous item in the list, wrapping around to the end if at the beginning
    pub fn select_prev(&mut self) {
        if self.focus
            && let Some(selected) = self.state.selected
        {
            if self.items.is_empty() {
                self.state.select(None);
            } else {
                let i = if selected == 0 {
                    self.items.len() - 1
                } else {
                    selected - 1
                };
                self.state.select(Some(i));
            }
        }
    }

    /// Selects the first item in the list
    pub fn select_first(&mut self) {
        if self.focus && !self.items.is_empty() {
            self.state.select(Some(0));
        }
    }

    /// Selects the last item in the list
    pub fn select_last(&mut self) {
        if self.focus && !self.items.is_empty() {
            let i = self.items.len() - 1;
            self.state.select(Some(i));
        }
    }

    /// Selects the first item that matches the given predicate
    pub fn select_matching<F>(&mut self, predicate: F) -> bool
    where
        F: FnMut(&T) -> bool,
    {
        if !self.items.is_empty()
            && let Some(index) = self.items.iter().position(predicate)
        {
            self.state.select(Some(index));
            true
        } else {
            false
        }
    }

    /// Selects the given index
    pub fn select(&mut self, index: usize) {
        if self.focus && index < self.items.len() {
            self.state.select(Some(index));
        }
    }

    /// Returns the index of the currently selected item
    pub fn selected_index(&self) -> Option<usize> {
        self.state.selected
    }

    /// Returns a mutable reference to the currently selected item and its index
    pub fn selected_mut(&mut self) -> Option<&mut T> {
        if let Some(selected) = self.state.selected {
            self.items.get_mut(selected)
        } else {
            None
        }
    }

    /// Returns a reference to the currently selected item and its index
    pub fn selected(&self) -> Option<&T> {
        if let Some(selected) = self.state.selected {
            self.items.get(selected)
        } else {
            None
        }
    }

    /// Returns a reference to the currently selected item and its index
    pub fn selected_with_index(&self) -> Option<(usize, &T)> {
        if let Some(selected) = self.state.selected {
            self.items.get(selected).map(|i| (selected, i))
        } else {
            None
        }
    }

    /// Deletes the currently selected item from the list and returns it (along with its index)
    pub fn delete_selected(&mut self) -> Option<(usize, T)> {
        if self.focus {
            let selected = self.state.selected?;
            let deleted = self.items.remove(selected);

            // Update discarded indices
            self.discarded_indices = self
                .discarded_indices
                .iter()
                .filter_map(|&idx| {
                    if idx < selected {
                        // Indices before the deleted one are unaffected
                        Some(idx)
                    } else if idx > selected {
                        // Indices after the deleted one must be decremented
                        Some(idx - 1)
                    } else {
                        // The deleted index itself is removed from the set
                        None
                    }
                })
                .collect();

            if self.items.is_empty() {
                self.state.select(None);
            } else if selected >= self.items.len() {
                self.state.select(Some(self.items.len() - 1));
            }

            Some((selected, deleted))
        } else {
            None
        }
    }

    /// Toggles the discarded state of the currently selected item
    pub fn toggle_discard_selected(&mut self) {
        if let Some(selected) = self.state.selected
            && !self.discarded_indices.remove(&selected)
        {
            self.discarded_indices.insert(selected);
        }
    }

    /// Toggles the discarded state for all items
    pub fn toggle_discard_all(&mut self) {
        if self.items.is_empty() {
            return;
        }
        // If all items are already discarded
        if self.discarded_indices.len() == self.items.len() {
            // Clear the set
            self.discarded_indices.clear();
        } else {
            // Otherwise, discard all
            self.discarded_indices.extend(0..self.items.len());
        }
    }
}

impl<'a, T: CustomListItem> Widget for &mut CustomList<'a, T> {
    fn render(self, area: Rect, buf: &mut Buffer)
    where
        Self: Sized,
    {
        if let Some(ref highlight_symbol) = self.highlight_symbol {
            // Render items with the highlight symbol
            render_list_view(
                ListBuilder::new(|ctx| {
                    let is_highlighted = self.focus && ctx.is_selected;
                    let is_discarded = self.discarded_indices.contains(&ctx.index);
                    // Get the base widget and its height from the item
                    let (item_widget, item_size) =
                        self.items[ctx.index].as_widget(&self.theme, self.inline, is_highlighted, is_discarded);

                    // Wrap the widget with a symbol
                    let item = SymbolAndWidget {
                        content: item_widget,
                        content_height: item_size.height,
                        symbol: if ctx.is_selected { highlight_symbol.as_str() } else { "" },
                        symbol_width: highlight_symbol.width() as u16,
                        symbol_mode: self.highlight_symbol_mode,
                        symbol_style: if self.focus {
                            self.highlight_symbol_style_focused
                        } else {
                            self.highlight_symbol_style
                        },
                    };

                    let main_axis_size = match ctx.scroll_axis {
                        ScrollAxis::Vertical => item_size.height,
                        ScrollAxis::Horizontal => item_size.width + 1,
                    };

                    (item, main_axis_size)
                }),
                self.axis,
                self.block.is_none(),
                self.items.len(),
                self.block.clone(),
                &mut self.state,
                area,
                buf,
            );
        } else {
            // No highlight symbol, render items directly
            render_list_view(
                ListBuilder::new(|ctx| {
                    let is_highlighted = ctx.is_selected;
                    let is_discarded = self.discarded_indices.contains(&ctx.index);
                    let (item_widget, item_size) =
                        self.items[ctx.index].as_widget(&self.theme, self.inline, is_highlighted, is_discarded);
                    let main_axis_size = match ctx.scroll_axis {
                        ScrollAxis::Vertical => item_size.height,
                        ScrollAxis::Horizontal => item_size.width + 1,
                    };
                    (item_widget, main_axis_size)
                }),
                self.axis,
                self.block.is_none(),
                self.items.len(),
                self.block.clone(),
                &mut self.state,
                area,
                buf,
            );
        }
    }
}

/// Internal helper function to render a list view using a generic builder
#[allow(clippy::too_many_arguments)]
fn render_list_view<'a, W: Widget>(
    builder: ListBuilder<'a, W>,
    axis: ScrollAxis,
    inline: bool,
    item_count: usize,
    block: Option<Block<'a>>,
    state: &mut ListState,
    area: Rect,
    buf: &mut Buffer,
) {
    let mut view = ListView::new(builder, item_count)
        .scroll_axis(axis)
        .infinite_scrolling(false)
        .scroll_padding(1 + (!inline as u16));
    if let Some(block) = block {
        view = view.block(block);
    }
    view.render(area, buf, state)
}

/// Internal helper widget to render an item prefixed with a highlight symbol
struct SymbolAndWidget<'a, W: Widget> {
    /// The widget to be rendered as the main content next to the symbol
    content: W,
    /// Height of the `content` widget in rows
    content_height: u16,
    /// The actual symbol string to render (e.g., " > ", " ✔ ").
    symbol: &'a str,
    /// The pre-calculated width of the `symbol` string
    symbol_width: u16,
    /// Specifies how the `symbol` should be rendered relative to the `content`
    symbol_mode: HighlightSymbolMode,
    /// The `Style` to be applied to the `symbol` when rendering.
    symbol_style: Style,
}

impl<'a, W: Widget> Widget for SymbolAndWidget<'a, W> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let mut content_area = area;
        let mut symbol_area = Rect::default();

        // Calculate the area for the symbol string
        if self.symbol_width > 0 && area.width > 0 {
            symbol_area = Rect {
                x: area.x,
                y: area.y,
                width: self.symbol_width.min(area.width),
                height: area.height,
            };

            // Adjust content area to be to the right of the symbol area
            content_area.x = area.x.saturating_add(symbol_area.width);
            content_area.width = area.width.saturating_sub(symbol_area.width);
        }

        // Render the actual item content widget
        if content_area.width > 0 && content_area.height > 0 {
            self.content.render(content_area, buf);
        }

        // Render the highlight symbol
        if !self.symbol.is_empty() && symbol_area.width > 0 && symbol_area.height > 0 {
            // Fill the entire symbol_area with the background style
            if let Some(bg_color) = self.symbol_style.bg {
                for y_coord in symbol_area.top()..symbol_area.bottom() {
                    for x_coord in symbol_area.left()..symbol_area.right() {
                        if let Some(cell) = buf.cell_mut((x_coord, y_coord)) {
                            cell.set_bg(bg_color);
                        }
                    }
                }
            }
            // Render the symbol
            match self.symbol_mode {
                HighlightSymbolMode::First => {
                    // Render on the first line of the symbol's allocated area
                    buf.set_stringn(
                        symbol_area.x,
                        symbol_area.y,
                        self.symbol,
                        symbol_area.width as usize,
                        self.symbol_style,
                    );
                }
                HighlightSymbolMode::Repeat => {
                    // Repeat for each line of the content, up to content_height or available symbol area height
                    for i in 0..self.content_height {
                        let y_pos = symbol_area.y + i;
                        // Ensure we are within the bounds of the symbol_area
                        if y_pos < symbol_area.bottom() && i < symbol_area.height {
                            buf.set_stringn(
                                symbol_area.x,
                                y_pos,
                                self.symbol,
                                symbol_area.width as usize,
                                self.symbol_style,
                            );
                        } else {
                            // Stop if we go beyond the symbol area's height
                            break;
                        }
                    }
                }
                HighlightSymbolMode::Last => {
                    // Render on the last line occupied by the content, if space permits
                    if self.content_height > 0 {
                        let y_pos = symbol_area.y + self.content_height - 1;
                        // Ensure the calculated y_pos is within the symbol_area
                        if y_pos < symbol_area.bottom() && (self.content_height - 1) < symbol_area.height {
                            buf.set_stringn(
                                symbol_area.x,
                                y_pos,
                                self.symbol,
                                symbol_area.width as usize,
                                self.symbol_style,
                            );
                        }
                    }
                }
            }
        }
    }
}