ratatui-interact 0.5.3

Interactive TUI components for ratatui with focus management and mouse support
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
//! Widget implementation for the hotkey dialog.
//!
//! This module provides the rendering logic for the hotkey dialog component.

use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};

use super::state::{HotkeyDialogState, HotkeyFocus};
use super::style::HotkeyDialogStyle;
use super::traits::{HotkeyCategory, HotkeyEntryData, HotkeyProvider};

/// A hotkey configuration dialog widget.
///
/// This widget renders a modal dialog for displaying and searching hotkeys.
/// It requires a state object and a provider for the hotkey data.
///
/// # Type Parameters
///
/// - `C`: The category type implementing `HotkeyCategory`
/// - `P`: The provider type implementing `HotkeyProvider<Category = C>`
///
/// # Example
///
/// ```rust,ignore
/// use ratatui_interact::components::hotkey_dialog::{
///     HotkeyDialog, HotkeyDialogState, HotkeyDialogStyle
/// };
///
/// let style = HotkeyDialogStyle::default();
/// let provider = MyHotkeyProvider;
///
/// HotkeyDialog::new(&mut state, &provider, &style)
///     .render(frame, frame.area());
/// ```
pub struct HotkeyDialog<'a, C: HotkeyCategory, P: HotkeyProvider<Category = C>> {
    state: &'a mut HotkeyDialogState<C>,
    provider: &'a P,
    style: &'a HotkeyDialogStyle,
}

impl<'a, C: HotkeyCategory, P: HotkeyProvider<Category = C>> HotkeyDialog<'a, C, P> {
    /// Create a new hotkey dialog widget.
    pub fn new(
        state: &'a mut HotkeyDialogState<C>,
        provider: &'a P,
        style: &'a HotkeyDialogStyle,
    ) -> Self {
        Self {
            state,
            provider,
            style,
        }
    }

    /// Render the dialog to the frame.
    pub fn render(mut self, frame: &mut Frame, _area: Rect) {
        let screen = frame.area();

        // Calculate modal dimensions
        let (x, y, modal_width, modal_height) =
            self.style.calculate_modal_area(screen.width, screen.height);
        let modal_area = Rect::new(x, y, modal_width, modal_height);

        // Clear background
        frame.render_widget(Clear, modal_area);

        // Outer border with title
        let border_color = ratatui::style::Color::Cyan;
        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(border_color))
            .title(self.style.title.as_str())
            .title_style(self.style.title_style());

        let inner = block.inner(modal_area);
        frame.render_widget(block, modal_area);

        // Clear click regions before rendering
        self.state.clear_click_regions();

        // Layout: Search bar | Main content | Footer
        let main_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(self.style.search_height),
                Constraint::Min(1),
                Constraint::Length(self.style.footer_height),
            ])
            .split(inner);

        // Render components
        self.render_search_bar(frame, main_chunks[0]);

        // Split main content: Categories | Hotkeys
        let content_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(self.style.category_width_percent),
                Constraint::Percentage(100 - self.style.category_width_percent),
            ])
            .split(main_chunks[1]);

        self.render_category_list(frame, content_chunks[0]);
        self.render_hotkey_list(frame, content_chunks[1]);
        self.render_footer(frame, main_chunks[2]);
    }

    /// Render the search bar.
    fn render_search_bar(&mut self, frame: &mut Frame, area: Rect) {
        let is_focused = self.state.focus == HotkeyFocus::SearchInput;
        let border_style = if is_focused {
            self.style.focused_border_style()
        } else {
            self.style.unfocused_border_style()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(" Search ");

        let inner = block.inner(area);
        frame.render_widget(block, area);

        // Build search text with cursor
        let text = if self.state.search_query.is_empty() && !is_focused {
            Line::from(Span::styled(
                &self.style.search_placeholder,
                self.style.placeholder_style(),
            ))
        } else {
            let before = self.state.text_before_cursor();
            let after = self.state.text_after_cursor();

            let mut spans = vec![Span::styled(before.to_string(), self.style.text_style())];

            if is_focused {
                spans.push(Span::styled("|", self.style.cursor_style()));
            }

            spans.push(Span::styled(after.to_string(), self.style.text_style()));

            Line::from(spans)
        };

        let paragraph = Paragraph::new(text);
        frame.render_widget(paragraph, inner);
    }

    /// Render the category list.
    fn render_category_list(&mut self, frame: &mut Frame, area: Rect) {
        let is_focused = self.state.focus == HotkeyFocus::CategoryList;
        let border_style = if is_focused {
            self.style.focused_border_style()
        } else {
            self.style.unfocused_border_style()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(" Categories ");

        let inner = block.inner(area);
        frame.render_widget(block, area);

        let categories = C::all();
        let mut lines = Vec::new();

        for (idx, category) in categories.iter().enumerate() {
            let is_selected =
                *category == self.state.selected_category && !self.state.is_searching();

            let prefix = if is_selected { "> " } else { "  " };
            let icon = category.icon();
            let name = category.display_name();
            let count = self.provider.entries_for_category(*category).len();

            let style = if is_selected {
                self.style.selected_style()
            } else {
                self.style.text_style()
            };

            let count_style = if is_selected {
                self.style.selected_text_style()
            } else {
                self.style.dim_style()
            };

            let line = Line::from(vec![
                Span::styled(prefix, style),
                Span::styled(format!("{} ", icon), style),
                Span::styled(name, style),
                Span::styled(format!(" ({})", count), count_style),
            ]);
            lines.push(line);

            // Register click region
            let row_y = inner.y + idx as u16;
            if row_y < inner.y + inner.height {
                self.state.add_category_click_region(
                    Rect::new(inner.x, row_y, inner.width, 1),
                    *category,
                );
            }
        }

        let paragraph = Paragraph::new(lines);
        frame.render_widget(paragraph, inner);
    }

    /// Render the hotkey list.
    fn render_hotkey_list(&mut self, frame: &mut Frame, area: Rect) {
        let is_focused = self.state.focus == HotkeyFocus::HotkeyList;
        let border_style = if is_focused {
            self.style.focused_border_style()
        } else {
            self.style.unfocused_border_style()
        };

        // Title shows category name or "Search Results"
        let title = if self.state.is_searching() {
            let count = self.state.get_search_results(self.provider).len();
            format!(" Search Results ({}) ", count)
        } else {
            format!(
                " {} {} ",
                self.state.selected_category.icon(),
                self.state.selected_category.display_name()
            )
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(title);

        let inner = block.inner(area);
        frame.render_widget(block, area);

        // Get entries to display
        let entries = self.state.get_current_entries(self.provider);
        let total_entries = entries.len();

        // Update cached entry count
        self.state.update_entry_count(total_entries);

        if entries.is_empty() {
            let msg = if self.state.is_searching() {
                "No matching hotkeys found"
            } else {
                "No hotkeys in this category"
            };
            let paragraph = Paragraph::new(Line::from(Span::styled(
                msg,
                self.style.placeholder_style(),
            )));
            frame.render_widget(paragraph, inner);
            return;
        }

        // Calculate column widths
        let max_key_len = entries
            .iter()
            .map(|e| e.key_combination.chars().count())
            .max()
            .unwrap_or(15)
            .max(15);

        // Visible height for scrolling
        let visible_height = inner.height as usize;

        // Ensure selected hotkey is visible
        self.state.ensure_hotkey_visible(visible_height);

        // Build lines with proper formatting
        let lines =
            self.build_hotkey_lines(&entries, max_key_len, is_focused, inner, visible_height);

        // Apply scroll
        let scroll = self
            .state
            .hotkey_scroll
            .min(total_entries.saturating_sub(1));

        let paragraph = Paragraph::new(lines).scroll((scroll as u16, 0));
        frame.render_widget(paragraph, inner);

        // Render scrollbar if needed
        if total_entries > visible_height {
            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some("^"))
                .end_symbol(Some("v"));

            let mut scrollbar_state = ScrollbarState::new(total_entries)
                .position(scroll)
                .viewport_content_length(visible_height);

            let scrollbar_area = Rect::new(
                area.x + area.width - 1,
                area.y + 1,
                1,
                area.height.saturating_sub(2),
            );

            frame.render_stateful_widget(scrollbar, scrollbar_area, &mut scrollbar_state);
        }
    }

    /// Build the lines for the hotkey list.
    fn build_hotkey_lines(
        &mut self,
        entries: &[HotkeyEntryData],
        max_key_len: usize,
        is_focused: bool,
        inner: Rect,
        visible_height: usize,
    ) -> Vec<Line<'static>> {
        let mut lines = Vec::new();

        for (idx, entry) in entries.iter().enumerate() {
            let is_selected = idx == self.state.selected_hotkey_idx && is_focused;

            // Key combination with fixed width
            let key_padded = format!("{:width$}", entry.key_combination, width = max_key_len);

            // Context indicator
            let context_str = if entry.is_global {
                self.style.global_indicator.clone()
            } else {
                format!("[{}]", entry.context.chars().next().unwrap_or('?'))
            };

            // Styles
            let (key_style, action_style, context_style) = if is_selected {
                (
                    self.style.selected_style(),
                    self.style.selected_text_style(),
                    self.style.selected_text_style(),
                )
            } else {
                let key_style = if entry.is_global {
                    self.style.global_key_style()
                } else {
                    self.style.local_key_style()
                };
                (key_style, self.style.text_style(), self.style.dim_style())
            };

            // Customizable indicator
            let lock_indicator = if entry.is_customizable {
                " "
            } else {
                &self.style.locked_indicator
            };
            let lock_style = if is_selected {
                self.style.selected_text_style()
            } else {
                self.style.locked_style()
            };

            let line = Line::from(vec![
                Span::styled(lock_indicator.to_string(), lock_style),
                Span::styled(" ", action_style),
                Span::styled(key_padded, key_style),
                Span::styled("  ", action_style),
                Span::styled(entry.action.clone(), action_style),
                Span::styled("  ", action_style),
                Span::styled(context_str, context_style),
            ]);
            lines.push(line);

            // Register click region (only for visible entries)
            let row_offset = idx.saturating_sub(self.state.hotkey_scroll);
            if idx >= self.state.hotkey_scroll && row_offset < visible_height {
                let row_y = inner.y + row_offset as u16;
                self.state
                    .add_hotkey_click_region(Rect::new(inner.x, row_y, inner.width, 1), idx);
            }
        }

        lines
    }

    /// Render the footer with key hints and legend.
    fn render_footer(&self, frame: &mut Frame, area: Rect) {
        let hints = match self.state.focus {
            HotkeyFocus::SearchInput => vec![
                ("Esc", "Clear/Close"),
                ("Tab", "Categories"),
                ("Type", "Filter"),
            ],
            HotkeyFocus::CategoryList => {
                vec![("Up/Dn", "Navigate"), ("Tab", "Hotkeys"), ("Esc", "Close")]
            }
            HotkeyFocus::HotkeyList => vec![
                ("Up/Dn", "Navigate"),
                ("PgUp/Dn", "Page"),
                ("Tab", "Search"),
                ("Esc", "Close"),
            ],
        };

        // Legend
        let mut spans = vec![
            Span::styled(
                &self.style.global_indicator,
                Style::default().fg(self.style.global_key_color),
            ),
            Span::styled("=Global ", self.style.dim_style()),
            Span::styled(&self.style.locked_indicator, self.style.locked_style()),
            Span::styled("=Locked  ", self.style.dim_style()),
            Span::raw("|  "),
        ];

        // Key hints
        for (idx, (key, desc)) in hints.iter().enumerate() {
            if idx > 0 {
                spans.push(Span::raw("  "));
            }
            spans.push(Span::styled(
                *key,
                Style::default().fg(self.style.global_key_color),
            ));
            spans.push(Span::raw(": "));
            spans.push(Span::styled(
                *desc,
                Style::default().fg(self.style.dim_color),
            ));
        }

        let line = Line::from(spans);
        let paragraph = Paragraph::new(line).block(
            Block::default()
                .borders(Borders::TOP)
                .border_style(self.style.unfocused_border_style()),
        );

        frame.render_widget(paragraph, area);
    }
}

/// Convenience function to render a hotkey dialog.
///
/// This is a simpler alternative to creating a `HotkeyDialog` widget manually.
pub fn render_hotkey_dialog<C: HotkeyCategory, P: HotkeyProvider<Category = C>>(
    frame: &mut Frame,
    state: &mut HotkeyDialogState<C>,
    provider: &P,
    style: &HotkeyDialogStyle,
) {
    let dialog = HotkeyDialog::new(state, provider, style);
    dialog.render(frame, frame.area());
}