twc-rs 0.3.5

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
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
// SPDX-FileCopyrightText: 2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Main draw function — composes all widgets into the terminal layout.

use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, List, ListItem, ListState, Paragraph}
};
use rust_i18n::t;

use crate::tui::{
    app::{App, DrillView, Focus},
    themes::Palette,
    widgets::{
        Widget, account::AccountWidget, help::HelpWidget, resource_tabs::ResourceTabsWidget
    }
};

/// Renders the full dashboard into the given frame area.
///
/// Composes the layout into four sections: header (Account widget), resource
/// tabs, content (`ResourceList` and `Details` side by side), and status bar.
/// When help is requested, the Help widget is rendered as an overlay.
///
/// # Arguments
///
/// * `frame` - The render frame.
/// * `app` - The application state.
pub fn draw(frame: &mut Frame, app: &App) {
    let size = frame.area();
    let palette = app.theme.palette();

    let show_account = app.is_widget_enabled("account") && size.height >= 16;
    let show_events = app.is_widget_enabled("events") && size.height >= 24;

    let mut constraints = Vec::with_capacity(5);
    if show_account {
        constraints.push(Constraint::Length(3));
    }
    constraints.push(Constraint::Length(2));
    constraints.push(Constraint::Min(8));
    if show_events {
        constraints.push(Constraint::Length(7));
    }
    constraints.push(Constraint::Length(3));

    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(size);

    let mut idx = 0;
    if show_account {
        AccountWidget::new(true).render(frame, main_chunks[idx], app);
        idx += 1;
    }

    ResourceTabsWidget::new(true).render(frame, main_chunks[idx], app);
    idx += 1;

    render_content(frame, main_chunks[idx], app, &palette);
    idx += 1;

    if show_events {
        crate::tui::widgets::events::render(frame, main_chunks[idx], app);
        idx += 1;
    }

    render_status_bar(frame, main_chunks[idx], app, &palette);

    if app.show_help {
        HelpWidget::new().render(frame, size, app);
    }

    if app.action_menu_open() {
        render_action_menu(frame, size, app, &palette);
    }

    if app.awaiting_confirm() {
        render_confirm(frame, size, app, &palette);
    }

    if let Some(form) = app.create_form.as_ref() {
        render_create_form(frame, size, form, &palette);
    }

    if let Some(cp) = app.palette.as_ref() {
        crate::tui::command_palette::render(frame, size, &palette, cp);
    }
}

/// Renders the in-dashboard resource-creation form: a titled box with one
/// labelled input per field, the focused field highlighted, and a hint line.
fn render_create_form(
    frame: &mut Frame,
    area: Rect,
    form: &crate::tui::app::CreateForm,
    palette: &Palette
) {
    let width = 56u16.min(area.width.saturating_sub(4));
    let height = u16::try_from(form.fields.len()).unwrap_or(2) + 4;
    let popup = Rect {
        x: (area.width.saturating_sub(width)) / 2,
        y: (area.height.saturating_sub(height)) / 2,
        width,
        height
    };
    frame.render_widget(Clear, popup);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(palette.accent))
        .title(Line::from(Span::styled(
            format!(" {} ", form.title),
            Style::default()
                .fg(palette.title)
                .add_modifier(Modifier::BOLD)
        )));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    let mut constraints: Vec<Constraint> =
        form.fields.iter().map(|_| Constraint::Length(1)).collect();
    constraints.push(Constraint::Length(1));
    let rows = Layout::vertical(constraints).split(inner);

    for (i, field) in form.fields.iter().enumerate() {
        let focused = i == form.active;
        let marker = if focused { "" } else { "  " };
        let label = format!("{marker}{}: ", field.label);
        let value_style = if focused {
            Style::default()
                .fg(palette.fg)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
        } else {
            Style::default().fg(palette.dim)
        };
        let cursor = if focused { "" } else { "" };
        let line = Line::from(vec![
            Span::styled(label, Style::default().fg(palette.header)),
            Span::styled(format!("{}{cursor}", field.value), value_style),
        ]);
        if let Some(row) = rows.get(i) {
            frame.render_widget(Paragraph::new(line), *row);
        }
    }

    if let Some(hint_row) = rows.last() {
        let hint = Paragraph::new(Line::from(Span::styled(
            "Tab next · Enter create · Esc cancel",
            Style::default().fg(palette.dim)
        )));
        frame.render_widget(hint, *hint_row);
    }
}

/// Renders the context action menu for the selected server.
///
/// Lists the available actions with the highlighted one marked; destructive
/// actions are shown in the error color with a warning glyph.
fn render_action_menu(frame: &mut Frame, area: Rect, app: &App, palette: &Palette) {
    let Some(menu) = app.action_menu() else {
        return;
    };

    let lines: Vec<Line> = menu
        .actions
        .iter()
        .enumerate()
        .map(|(idx, action)| {
            let selected = idx == menu.selected;
            let marker = if selected { "\u{25B6} " } else { "  " };
            let color = if action.is_destructive() {
                palette.error
            } else if selected {
                palette.accent
            } else {
                palette.fg
            };
            let mut style = Style::default().fg(color);
            if selected {
                style = style.add_modifier(Modifier::BOLD);
            }
            let mut spans = vec![
                Span::styled(marker, Style::default().fg(palette.accent)),
                Span::styled(format!("{:<10}", action.display_label()), style),
            ];
            if action.is_destructive() {
                spans.push(Span::styled("\u{26A0}", Style::default().fg(palette.error)));
            }
            Line::from(spans)
        })
        .collect();

    let kind = menu.tab.display_name();
    let title = t!(
        "ui.action_menu_title",
        kind => kind,
        name => menu.resource_name,
        id => menu.resource_id
    )
    .to_string();
    let width = u16::try_from(title.len() + 4)
        .unwrap_or(40)
        .clamp(28, area.width.saturating_sub(4));
    let height = u16::try_from(menu.actions.len()).unwrap_or(5) + 2;
    let popup = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width,
        height
    };

    let paragraph = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(palette.accent))
                .title(Line::from(Span::styled(
                    title,
                    Style::default()
                        .fg(palette.title)
                        .add_modifier(Modifier::BOLD)
                )))
        )
        .alignment(Alignment::Left)
        .style(Style::default().bg(palette.bg));

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

/// Renders the action confirmation modal centered on screen.
///
/// Shows the verb, target server, an irreversibility warning for
/// destructive actions, and the confirm/cancel keys.
fn render_confirm(frame: &mut Frame, area: Rect, app: &App, palette: &Palette) {
    let Some(pending) = app.pending_action() else {
        return;
    };

    let accent = if pending.kind.is_destructive() {
        palette.error
    } else {
        palette.warning
    };

    let mut lines = vec![
        Line::from(Span::styled(
            t!(
                "ui.confirm_prompt",
                verb => pending.kind.display_label(),
                name => pending.resource_name,
                id => pending.resource_id
            )
            .to_string(),
            Style::default().fg(palette.fg).add_modifier(Modifier::BOLD)
        )),
        Line::from(""),
    ];
    if pending.kind.is_destructive() {
        lines.push(Line::from(Span::styled(
            t!("ui.confirm_irreversible").to_string(),
            Style::default().fg(palette.error)
        )));
        lines.push(Line::from(""));
    }
    lines.push(Line::from(vec![
        Span::styled(
            " [y] ",
            Style::default().fg(accent).add_modifier(Modifier::BOLD)
        ),
        Span::styled(
            format!("{}    ", t!("ui.confirm_yes")),
            Style::default().fg(palette.dim)
        ),
        Span::styled(
            "[n] ",
            Style::default().fg(palette.fg).add_modifier(Modifier::BOLD)
        ),
        Span::styled(
            t!("ui.confirm_no").to_string(),
            Style::default().fg(palette.dim)
        ),
    ]));

    let width = 54u16.min(area.width.saturating_sub(4));
    let height = u16::try_from(lines.len()).unwrap_or(4) + 2;
    let popup = Rect {
        x: area.width.saturating_sub(width) / 2,
        y: area.height.saturating_sub(height) / 2,
        width,
        height
    };

    let paragraph = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(accent))
                .title(Line::from(Span::styled(
                    t!("ui.confirm_title").to_string(),
                    Style::default()
                        .fg(palette.title)
                        .add_modifier(Modifier::BOLD)
                )))
        )
        .alignment(Alignment::Left)
        .style(Style::default().bg(palette.bg));

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

/// Renders the content area with resource list and details side by side.
///
/// The focused panel receives a highlighted border using `palette.accent`.
/// Non-focused panels use `palette.border`.
///
/// # Arguments
///
/// * `frame` - The render frame.
/// * `area` - The content area rectangle.
/// * `app` - The application state.
/// * `palette` - The theme color palette.
fn render_content(frame: &mut Frame, area: Rect, app: &App, palette: &Palette) {
    if let Some(view) = app.drill_view() {
        render_drill(frame, area, view, palette);
        return;
    }

    let list_pct = app.list_width_pct.clamp(20, 70);
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(list_pct),
            Constraint::Percentage(100 - list_pct)
        ])
        .split(area);

    if app.is_loading {
        crate::tui::widgets::skeleton::render(
            frame,
            chunks[0],
            palette,
            &t!("ui.skeleton_resources"),
            8,
            app.anim_tick
        );
        crate::tui::widgets::skeleton::render(
            frame,
            chunks[1],
            palette,
            &t!("ui.skeleton_details"),
            6,
            app.anim_tick
        );
        return;
    }

    let list_border_color = if app.focus == Focus::ResourceList {
        palette.accent
    } else {
        palette.border
    };
    let detail_border_color = if app.focus == Focus::Details {
        palette.accent
    } else {
        palette.border
    };

    if area.width < 56 {
        crate::tui::widgets::resource_list::render(frame, area, app, list_border_color);
        return;
    }

    let wide = area.width >= 100;
    let show_stats = wide && app.is_widget_enabled("stats");
    let show_token = wide && app.is_widget_enabled("token_info");

    crate::tui::widgets::resource_list::render(frame, chunks[0], app, list_border_color);

    if show_stats || show_token {
        let right = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(62), Constraint::Percentage(38)])
            .split(chunks[1]);
        crate::tui::widgets::details::render(frame, right[0], app, detail_border_color);
        render_info_column(frame, right[1], app, show_stats, show_token);
    } else {
        crate::tui::widgets::details::render(frame, chunks[1], app, detail_border_color);
    }
}

/// Renders the optional right-hand info column with the Stats and Token Info
/// widgets, stacked according to which are enabled.
fn render_info_column(frame: &mut Frame, area: Rect, app: &App, stats: bool, token: bool) {
    use crate::tui::widgets::{Widget, stats::StatsWidget, token_info::TokenInfoWidget};

    match (stats, token) {
        (true, true) => {
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])
                .split(area);
            StatsWidget::new(true).render(frame, rows[0], app);
            TokenInfoWidget::new(true).render(frame, rows[1], app);
        }
        (true, false) => StatsWidget::new(true).render(frame, area, app),
        (false, true) => TokenInfoWidget::new(true).render(frame, area, app),
        (false, false) => {}
    }
}

/// Renders the status bar with mode indicator and available keys.
///
/// # Arguments
///
/// * `frame` - The render frame.
/// * `area` - The status bar area rectangle.
/// * `app` - The application state.
/// * `palette` - The theme color palette.
fn render_status_bar(frame: &mut Frame, area: Rect, app: &App, palette: &Palette) {
    let tab = app.active_tab.display_name();

    let key = |k: &'static str| {
        Span::styled(
            k,
            Style::default()
                .fg(palette.accent)
                .add_modifier(Modifier::BOLD)
        )
    };
    let lbl = |t: String| Span::styled(t, Style::default().fg(palette.dim));

    let mut spans = vec![
        Span::styled(
            format!(" {tab} "),
            Style::default()
                .fg(palette.bg)
                .bg(palette.tab_active)
                .add_modifier(Modifier::BOLD)
        ),
        Span::raw("  "),
        key("h/l"),
        lbl(format!(" {}   ", t!("ui.status_tabs"))),
        key("j/k"),
        lbl(format!(" {}   ", t!("ui.status_move"))),
        key(""),
        lbl(format!(" {}   ", t!("ui.status_open"))),
        key("/"),
        lbl(format!(" {}   ", t!("ui.status_filter"))),
        key("^K"),
        lbl(format!(" {}   ", t!("ui.status_cmds"))),
        key("?"),
        lbl(format!(" {}   ", t!("ui.status_help"))),
        key("Q"),
        lbl(format!(" {}", t!("ui.status_quit"))),
    ];

    let message = match (&app.error_message, &app.status_message) {
        (Some(err), _) => Some((err.clone(), palette.error)),
        (_, Some(msg)) => Some((msg.clone(), palette.success)),
        _ => None
    };
    if let Some((text, color)) = message {
        spans.push(Span::raw("   "));
        spans.push(Span::styled("", Style::default().fg(color)));
        spans.push(Span::styled(text, Style::default().fg(color)));
    }

    let paragraph = Paragraph::new(Line::from(spans)).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(palette.border))
    );
    frame.render_widget(paragraph, area);
}

/// Renders the drill-in view listing the resources contained in a parent.
fn render_drill(frame: &mut Frame, area: Rect, view: &DrillView, palette: &Palette) {
    let items: Vec<ListItem> = if view.items.is_empty() {
        vec![ListItem::new(Line::from(Span::styled(
            t!("ui.drill_empty").to_string(),
            Style::default().fg(palette.dim)
        )))]
    } else {
        view.items
            .iter()
            .map(|item| {
                ListItem::new(Line::from(vec![
                    Span::styled(
                        format!("{:<11}", item.kind),
                        Style::default().fg(palette.dim)
                    ),
                    Span::styled(
                        item.name.clone(),
                        Style::default().fg(palette.fg).add_modifier(Modifier::BOLD)
                    ),
                    Span::raw("   "),
                    Span::styled(item.detail.clone(), Style::default().fg(palette.accent)),
                ]))
            })
            .collect()
    };

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(palette.accent))
                .title(Line::from(Span::styled(
                    t!("ui.drill_title", title => view.title).to_string(),
                    Style::default()
                        .fg(palette.title)
                        .add_modifier(Modifier::BOLD)
                )))
        )
        .highlight_style(
            Style::default()
                .fg(palette.bg)
                .bg(palette.accent)
                .add_modifier(Modifier::BOLD)
        )
        .highlight_symbol("\u{2503} ");

    let mut state = ListState::default();
    state.select(Some(view.selected));
    frame.render_stateful_widget(list, area, &mut state);
}