Skip to main content

mermaid_cli/render/widgets/
slash_palette.rs

1//! Slash-command palette widget — renders a filter-as-you-type list of
2//! available commands with the selected row highlighted. Visible
3//! whenever the input starts with `/`; replaces the bottom status bar
4//! while open (same screen region — see `render.rs::render_ui`).
5//!
6//! Keyboard handling lives in `event_handler.rs::handle_palette_key`.
7//! This widget is purely presentational — it consumes a pre-filtered
8//! slice and a selection index.
9
10use ratatui::{
11    buffer::Buffer,
12    layout::Rect,
13    style::{Modifier, Style},
14    text::{Line, Span},
15    widgets::{Block, Borders, Paragraph, Widget},
16};
17
18use crate::render::theme::Theme;
19use mermaid_domain::slash_commands::PaletteEntry;
20
21/// Hard cap on visible rows — anything beyond is hidden until the user
22/// narrows the filter. Current registry has 9 entries; cap at 8 means
23/// at most one row is hidden when filter is empty. If the registry
24/// grows past ~12 we should add scrolling.
25const MAX_VISIBLE_ROWS: usize = 8;
26
27pub struct SlashPaletteWidget<'a> {
28    pub theme: &'a Theme,
29    /// Already-filtered (and ordered) list of rows to display — built-ins
30    /// plus plugin prompt commands, from `filter_entries` so indices agree
31    /// with the reducer's cursor.
32    pub entries: Vec<PaletteEntry<'a>>,
33    /// Index into `commands` of the highlighted row. `render` clamps it to
34    /// the valid range (or 0 when empty), so an out-of-range value from the
35    /// caller can't panic the row slice (#103).
36    pub selected_index: usize,
37}
38
39impl<'a> Widget for SlashPaletteWidget<'a> {
40    fn render(self, area: Rect, buf: &mut Buffer) {
41        // Scroll window: when selected row falls outside the visible
42        // 8-row band, slide the window so selected stays in view.
43        // "Anchor at bottom" — once selected goes past row 7, the
44        // selection sits at the bottom row of the visible window. Same
45        // pattern as most terminal palettes (fzf, less +F).
46        let total = self.entries.len();
47        // Clamp defensively: an out-of-range `selected_index` would drive
48        // `scroll_offset` past `visible_end` and panic the
49        // `commands[scroll_offset..visible_end]` slice below (#103).
50        let selected = self.selected_index.min(total.saturating_sub(1));
51        let scroll_offset = if selected >= MAX_VISIBLE_ROWS {
52            selected + 1 - MAX_VISIBLE_ROWS
53        } else {
54            0
55        };
56        let visible_end = (scroll_offset + MAX_VISIBLE_ROWS).min(total);
57
58        // Title: show total count + indicator when scrolled, so users
59        // know there's content above/below the visible window.
60        let title = if total > MAX_VISIBLE_ROWS {
61            format!(
62                " Commands ({}-{} of {})  ↑↓ navigate · Tab complete · Esc dismiss ",
63                scroll_offset + 1,
64                visible_end,
65                total
66            )
67        } else {
68            format!(" Commands ({total})  ↑↓ navigate · Tab complete · Esc dismiss ")
69        };
70
71        let block = Block::default()
72            .borders(Borders::ALL)
73            .border_style(Style::new().fg(self.theme.colors.border.to_color()))
74            .title(title);
75
76        // Empty filter result: render one line of explanatory text so
77        // the user understands their typed prefix matched nothing.
78        if self.entries.is_empty() {
79            let line = Line::from(vec![Span::styled(
80                "  No matching commands",
81                Style::new().fg(self.theme.colors.text_disabled.to_color()),
82            )]);
83            Paragraph::new(vec![line]).block(block).render(area, buf);
84            return;
85        }
86
87        let mut lines: Vec<Line> = Vec::with_capacity(MAX_VISIBLE_ROWS);
88        for (offset, entry) in self.entries[scroll_offset..visible_end].iter().enumerate() {
89            // Recover the absolute index for selection comparison.
90            let absolute_index = scroll_offset + offset;
91            let is_selected = absolute_index == selected;
92
93            // Build the `/name [arg_hint]` chunk. The arg_hint is in a
94            // softer color so the eye lands on the command name first.
95            let mut name_part = format!("/{}", entry.name());
96            if let Some(hint) = entry.arg_hint() {
97                name_part.push(' ');
98                name_part.push_str(hint);
99            }
100
101            let name_style = if is_selected {
102                Style::new()
103                    .fg(self.theme.colors.text_highlight.to_color())
104                    .add_modifier(Modifier::BOLD | Modifier::REVERSED)
105            } else {
106                Style::new()
107                    .fg(self.theme.colors.info.to_color())
108                    .add_modifier(Modifier::BOLD)
109            };
110            let desc_style = if is_selected {
111                Style::new()
112                    .fg(self.theme.colors.text_primary.to_color())
113                    .add_modifier(Modifier::REVERSED)
114            } else {
115                Style::new().fg(self.theme.colors.text_secondary.to_color())
116            };
117
118            // Pad command column so descriptions align.
119            let padded_name = format!(" {name_part:<22}");
120            lines.push(Line::from(vec![
121                Span::styled(padded_name, name_style),
122                Span::styled(format!(" {}", entry.description()), desc_style),
123            ]));
124        }
125
126        Paragraph::new(lines).block(block).render(area, buf);
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use ratatui::Terminal;
134    use ratatui::backend::TestBackend;
135    use ratatui::layout::Rect;
136
137    #[test]
138    fn out_of_bounds_selection_does_not_panic() {
139        // #103: a caller that lets `selected_index` exceed the filtered list
140        // must not panic the `commands[scroll_offset..visible_end]` slice.
141        let theme = Theme::dark();
142        let entries = mermaid_domain::slash_commands::filter_entries("", &[]);
143        assert!(!entries.is_empty(), "registry should expose commands");
144        let widget = SlashPaletteWidget {
145            theme: &theme,
146            entries,
147            selected_index: 9999,
148        };
149        let backend = TestBackend::new(80, 12);
150        let mut term = Terminal::new(backend).expect("terminal");
151        term.draw(|f| f.render_widget(widget, Rect::new(0, 0, 80, 12)))
152            .expect("render must not panic on OOB selection");
153    }
154}