twc-rs 0.5.0

Fast single-binary CLI and interactive TUI dashboard for Timeweb Cloud
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
// SPDX-FileCopyrightText: 2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Help widget — displays keyboard shortcuts and widget toggle status.

use ratatui::{
    Frame,
    layout::{Alignment, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph}
};
use rust_i18n::t;

use crate::tui::app::App;

/// Renders the help overlay with keyboard shortcuts and widget toggles.
///
/// # Overview
///
/// Displays a centered popup containing all keyboard shortcuts,
/// a separator, and the current enabled/disabled status of every
/// registered dashboard widget.
///
/// The widget is always considered "enabled" because it is an
/// overlay — it does not participate in the grid layout.
///
/// # Example
///
/// ```ignore
/// let mut registry = WidgetRegistry::new();
/// registry.register(Box::new(help::HelpWidget::new()));
/// ```
pub struct HelpWidget;

impl HelpWidget {
    /// Creates a new help widget.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// Builds the help text lines for the overlay.
    ///
    /// # Arguments
    ///
    /// * `palette` - The theme color palette.
    /// * `widget_names` - Names of all registered widgets with their enabled
    ///   state.
    ///
    /// # Returns
    ///
    /// A vector of styled `Line` values representing the full help content.
    fn build_lines(
        palette: crate::tui::themes::Palette,
        widget_names: &[(String, bool)]
    ) -> Vec<Line<'static>> {
        let mut lines = Vec::new();

        lines.push(Line::from(Span::styled(
            t!("help.title").to_string(),
            Style::default()
                .fg(palette.title)
                .add_modifier(Modifier::BOLD)
        )));

        lines.push(Line::from(Span::styled(
            " ".repeat(60),
            Style::default().fg(palette.border)
        )));

        let shortcuts = [
            ("h/l", t!("help.shortcut_tab")),
            ("j/k", t!("help.shortcut_move")),
            ("g/G", t!("help.shortcut_jump")),
            ("Enter", t!("help.shortcut_enter")),
            ("n", t!("help.shortcut_new")),
            ("/", t!("help.shortcut_filter")),
            ("Ctrl+K", t!("help.shortcut_palette")),
            ("p", t!("help.shortcut_profile")),
            ("r", t!("help.shortcut_refresh")),
            ("Esc", t!("help.shortcut_esc")),
            ("?", t!("help.shortcut_toggle_help")),
            ("Q", t!("help.shortcut_quit"))
        ];

        for (key, desc) in shortcuts {
            lines.push(Self::make_shortcut_line(key, desc.as_ref(), palette));
        }

        lines.push(Line::from(Span::styled(
            " ".repeat(60),
            Style::default().fg(palette.border)
        )));

        lines.push(Line::from(Span::styled(
            t!("help.widgets_header").to_string(),
            Style::default()
                .fg(palette.title)
                .add_modifier(Modifier::BOLD)
        )));

        for (name, enabled) in widget_names {
            let status = if *enabled {
                Line::from(vec![
                    Span::styled("[x] ", Style::default().fg(palette.success)),
                    Span::styled(name.clone(), Style::default().fg(palette.fg)),
                ])
            } else {
                Line::from(vec![
                    Span::styled("[ ] ", Style::default().fg(palette.dim)),
                    Span::styled(name.clone(), Style::default().fg(palette.dim)),
                ])
            };
            lines.push(status);
        }

        lines
    }

    /// Formats a single shortcut line with key and description.
    ///
    /// # Arguments
    ///
    /// * `key` - The keyboard key or key combination.
    /// * `desc` - Human-readable description of the action.
    /// * `palette` - The theme color palette.
    ///
    /// # Returns
    ///
    /// A styled `Line` with the key in bold accent color and description in
    /// dim.
    fn make_shortcut_line(
        key: &str,
        desc: &str,
        palette: crate::tui::themes::Palette
    ) -> Line<'static> {
        let key_len = u16::try_from(key.len()).unwrap_or(0);
        let padding = 8u16.saturating_sub(key_len);
        let pad_str = " ".repeat(padding as usize);

        Line::from(vec![
            Span::styled(
                key.to_string(),
                Style::default()
                    .fg(palette.accent)
                    .add_modifier(Modifier::BOLD)
            ),
            Span::raw(pad_str),
            Span::styled(desc.to_string(), Style::default().fg(palette.dim)),
        ])
    }

    /// Collects widget names and enabled states from the registry.
    ///
    /// # Arguments
    ///
    /// * `widgets` - The widget registry to inspect.
    ///
    /// # Returns
    ///
    /// A vector of `(name, enabled)` tuples for all registered widgets.
    fn collect_widget_status(
        widgets: &crate::tui::widgets::WidgetRegistry
    ) -> Vec<(String, bool)> {
        let mut status = Vec::new();

        let all_widgets: Vec<&(dyn crate::tui::widgets::Widget + Send)> = widgets
            .widgets
            .iter()
            .map(std::convert::AsRef::as_ref)
            .collect();

        for w in all_widgets {
            status.push((w.name().to_string(), w.enabled()));
        }

        status
    }

    /// Renders the help overlay centered in the given area.
    ///
    /// # Arguments
    ///
    /// * `frame` - The render frame.
    /// * `area` - The total terminal area.
    /// * `app` - The application state containing widgets and theme.
    fn render_overlay(frame: &mut Frame, area: Rect, app: &App) {
        let palette = app.theme.palette();
        let widget_names = Self::collect_widget_status(&app.widgets);
        let content = Self::build_lines(palette, &widget_names);

        let paragraph = Paragraph::new(content)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(palette.accent))
            )
            .alignment(Alignment::Left)
            .style(Style::default().bg(palette.bg));

        let popup_area = Rect {
            x:      area.width / 4,
            y:      area.height / 4,
            width:  area.width / 2,
            height: area.height / 2
        };

        frame.render_widget(Clear, popup_area);
        frame.render_widget(paragraph, popup_area);
    }
}

impl crate::tui::widgets::Widget for HelpWidget {
    fn id(&self) -> &'static str {
        "help"
    }

    fn name(&self) -> &'static str {
        "Help"
    }

    fn enabled(&self) -> bool {
        true
    }

    fn toggle(&mut self) {}

    fn render(&self, frame: &mut Frame, area: Rect, app: &App) {
        Self::render_overlay(frame, area, app);
    }
}

impl Default for HelpWidget {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use ratatui::style::Color;

    use super::*;
    use crate::tui::{themes::Theme, widgets::Widget};

    #[test]
    fn widget_id_is_help() {
        let widget = HelpWidget::new();
        assert_eq!(widget.id(), "help");
    }

    #[test]
    fn widget_name_is_help() {
        let widget = HelpWidget::new();
        assert_eq!(widget.name(), "Help");
    }

    #[test]
    fn widget_is_always_enabled() {
        let widget = HelpWidget::new();
        assert!(widget.enabled());
    }

    #[test]
    fn widget_toggle_does_nothing() {
        let mut widget = HelpWidget::new();
        widget.toggle();
        assert!(widget.enabled());
    }

    #[test]
    fn default_is_new() {
        let widget = HelpWidget;
        assert_eq!(widget.id(), "help");
    }

    #[test]
    fn build_lines_contains_shortcuts() {
        let palette = Theme::GruvboxDark.palette();
        let lines = HelpWidget::build_lines(palette, &[]);

        let text: String = lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect::<Vec<_>>()
            .join(" ");

        assert!(text.contains("Quit"));
        assert!(text.contains("Refresh now"));
        assert!(text.contains("Toggle this help"));
    }

    #[test]
    fn build_lines_contains_widget_section() {
        let palette = Theme::GruvboxDark.palette();
        let widgets = vec![
            ("Account".to_string(), true),
            ("Resources".to_string(), false),
        ];
        let lines = HelpWidget::build_lines(palette, &widgets);

        let text: String = lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect::<Vec<_>>()
            .join(" ");

        assert!(text.contains("[x]"));
        assert!(text.contains("[ ]"));
        assert!(text.contains("Account"));
        assert!(text.contains("Resources"));
    }

    #[test]
    fn build_lines_empty_widgets_no_panic() {
        let palette = Theme::GruvboxDark.palette();
        let lines = HelpWidget::build_lines(palette, &[]);
        assert!(!lines.is_empty());
    }

    #[test]
    fn make_shortcut_line_produces_correct_format() {
        let palette = Theme::CatppuccinMocha.palette();
        let line = HelpWidget::make_shortcut_line("q", "Quit", palette);

        assert_eq!(line.spans.len(), 3);
        assert!(line.spans[0].content.contains('q'));
    }

    #[test]
    fn make_shortcut_line_handles_long_keys() {
        let palette = Theme::GruvboxLight.palette();
        let line = HelpWidget::make_shortcut_line("Tab", "Cycle tabs", palette);

        assert_eq!(line.spans.len(), 3);
    }

    #[test]
    fn collect_widget_status_returns_widget_info() {
        let registry = crate::tui::widgets::WidgetRegistry::new();
        let status = HelpWidget::collect_widget_status(&registry);

        assert!(!status.is_empty());
        assert!(status.iter().any(|(name, _)| name == "Account"));
    }

    #[test]
    fn collect_widget_status_preserves_enabled_state() {
        let registry = crate::tui::widgets::WidgetRegistry::new();
        let status = HelpWidget::collect_widget_status(&registry);

        for (_, enabled) in &status {
            assert!(*enabled);
        }
    }

    #[test]
    fn widget_trait_object_is_send() {
        let widget: Box<dyn Widget + Send> = Box::new(HelpWidget::new());
        assert_eq!(widget.id(), "help");
    }

    #[test]
    fn build_lines_with_disabled_widgets() {
        let palette = Theme::GruvboxDark.palette();
        let widgets = vec![("Account".to_string(), true), ("Stats".to_string(), false)];
        let lines = HelpWidget::build_lines(palette, &widgets);

        let text: String = lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect::<Vec<_>>()
            .join(" ");

        let account_idx = text.find("Account").expect("account entry present");
        let stats_idx = text.find("Stats").expect("stats entry present");
        assert!(account_idx < stats_idx);
        assert!(text.contains("[x]"));
        assert!(text.contains("[ ]"));
    }

    #[test]
    fn build_lines_palette_applied() {
        let palette = Theme::CatppuccinLatte.palette();
        let lines = HelpWidget::build_lines(palette, &[]);

        let title_line = &lines[0];
        let span = title_line.spans.first().expect("title span");
        assert!(matches!(span.style.fg, Some(Color::Rgb(183, 108, 7))));
    }
}