eddacraft-tui 0.2.3

Shared Ratatui component library for the eddacraft product family
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use std::fmt;
use std::time::{Duration, Instant};

use animate::Animate;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, StatefulWidget, Widget};
use unicode_width::UnicodeWidthChar;

use crate::theme::Theme;
use crate::widgets::spinner::SpinnerPreset;
use crate::widgets::{AnimatedU8, animated_u8};

const FRACTION_BLOCKS: [char; 8] = ['', '', '', '', '', '', '', ''];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckStatus {
    Pending,
    Running,
    Passed,
    Failed,
    Skipped,
    Cached,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CheckProgress {
    pub id: String,
    pub name: String,
    pub status: CheckStatus,
    pub progress: u8,
    pub start_time: Option<Instant>,
    pub end_time: Option<Instant>,
    pub duration_ms: Option<u64>,
    pub message: Option<String>,
}

impl CheckProgress {
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            status: CheckStatus::Pending,
            progress: 0,
            start_time: None,
            end_time: None,
            duration_ms: None,
            message: None,
        }
    }
}

#[non_exhaustive]
pub struct ParallelProgressState {
    pub checks: Vec<CheckProgress>,
    pub start_time: Option<Instant>,
    anim_overall: AnimatedU8,
    anim_overall_target: u8,
}

impl Default for ParallelProgressState {
    fn default() -> Self {
        Self {
            checks: Vec::new(),
            start_time: None,
            anim_overall: animated_u8(0),
            anim_overall_target: 0,
        }
    }
}

impl fmt::Debug for ParallelProgressState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ParallelProgressState")
            .field("checks", &self.checks)
            .field("start_time", &self.start_time)
            .finish_non_exhaustive()
    }
}

#[must_use]
pub fn calculate_overall_progress(checks: &[CheckProgress]) -> u8 {
    if checks.is_empty() {
        return 0;
    }

    let total: u64 = checks
        .iter()
        .map(|check| u64::from(effective_progress(check)))
        .sum();

    #[allow(clippy::cast_possible_truncation)]
    {
        (total / checks.len() as u64) as u8
    }
}

#[must_use]
pub fn calculate_eta(checks: &[CheckProgress], elapsed: Duration) -> Option<Duration> {
    let progress = calculate_overall_progress(checks);
    if progress == 0 || progress >= 100 {
        return None;
    }

    let elapsed_ms = elapsed.as_millis();
    let remaining_ratio = u128::from(100_u8.saturating_sub(progress));
    let progress_ratio = u128::from(progress);
    let remaining_ms = elapsed_ms.saturating_mul(remaining_ratio) / progress_ratio;

    #[allow(clippy::cast_possible_truncation)]
    Some(Duration::from_millis(remaining_ms as u64))
}

#[must_use]
pub fn format_duration(duration_ms: u64) -> String {
    if duration_ms < 1_000 {
        return format!("{duration_ms}ms");
    }

    let total_seconds = duration_ms / 1_000;
    let minutes = total_seconds / 60;
    let seconds = total_seconds % 60;

    if minutes == 0 {
        format!("{seconds}s")
    } else {
        format!("{minutes}m {seconds}s")
    }
}

pub struct ParallelProgress<'a, T: Theme> {
    theme: &'a T,
    block: Option<Block<'a>>,
    title: &'a str,
    show_eta: bool,
    show_overall: bool,
    compact: bool,
}

impl<'a, T: Theme> ParallelProgress<'a, T> {
    pub fn new(theme: &'a T) -> Self {
        Self {
            theme,
            block: None,
            title: "Parallel Progress",
            show_eta: true,
            show_overall: true,
            compact: false,
        }
    }

    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = block.into();
        self
    }

    #[must_use]
    pub fn title(mut self, title: &'a str) -> Self {
        self.title = title;
        self
    }

    #[must_use]
    pub fn show_eta(mut self, show_eta: bool) -> Self {
        self.show_eta = show_eta;
        self
    }

    #[must_use]
    pub fn show_overall(mut self, show_overall: bool) -> Self {
        self.show_overall = show_overall;
        self
    }

    #[must_use]
    pub fn compact(mut self, compact: bool) -> Self {
        self.compact = compact;
        self
    }
}

impl<T: Theme> StatefulWidget for ParallelProgress<'_, T> {
    type State = ParallelProgressState;

    #[allow(clippy::too_many_lines)]
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        if area.width == 0 || area.height == 0 {
            return;
        }

        let complete = state
            .checks
            .iter()
            .filter(|check| {
                matches!(
                    check.status,
                    CheckStatus::Passed
                        | CheckStatus::Failed
                        | CheckStatus::Skipped
                        | CheckStatus::Cached
                )
            })
            .count();

        let mut block = self
            .block
            .unwrap_or_else(|| Block::default().borders(Borders::ALL));
        block = block
            .border_style(self.theme.border_focused())
            .title(Line::styled(
                format!("{} ({}/{})", self.title, complete, state.checks.len()),
                self.theme.title(),
            ));

        let inner = block.inner(area);
        block.render(area, buf);

        if inner.width == 0 || inner.height == 0 {
            return;
        }

        let mut constraints = vec![Constraint::Min(1)];
        if self.show_overall {
            constraints.push(Constraint::Length(1));
        }
        if self.show_eta {
            constraints.push(Constraint::Length(1));
        }
        let chunks = Layout::vertical(constraints).split(inner);

        let checks_area = chunks[0];
        let check_rows = usize::from(checks_area.height);

        for (row_index, check) in state.checks.iter().take(check_rows).enumerate() {
            #[allow(clippy::cast_possible_truncation)]
            let y = checks_area.y.saturating_add(row_index as u16);
            if y >= checks_area.y.saturating_add(checks_area.height) {
                break;
            }
            let row_area = Rect::new(checks_area.x, y, checks_area.width, 1);
            let row_chunks = Layout::horizontal([
                Constraint::Length(14),
                Constraint::Min(8),
                Constraint::Length(9),
            ])
            .split(row_area);

            let name = truncate_name(&check.name, usize::from(row_chunks[0].width));
            Line::styled(name, self.theme.base()).render(row_chunks[0], buf);

            let status_style = status_style(check.status, self.theme);
            let status_icon = status_icon(check);
            let progress_text = if self.compact || !matches!(check.status, CheckStatus::Running) {
                if let Some(message) = &check.message {
                    format!("{status_icon} {message}")
                } else {
                    format!("{status_icon} {}%", effective_progress(check))
                }
            } else {
                let bar_width = usize::from(row_chunks[1].width).saturating_sub(5);
                let bar = render_fractional_bar(bar_width, effective_progress(check));
                format!("{bar} {:>3}%", effective_progress(check))
            };
            Line::styled(progress_text, status_style).render(row_chunks[1], buf);

            let duration =
                resolve_duration(check).map_or_else(|| "--".to_string(), format_duration);
            Line::styled(duration, self.theme.disabled()).render(row_chunks[2], buf);
        }

        let mut cursor = 1;
        if self.show_overall {
            let raw_overall = calculate_overall_progress(&state.checks);
            if raw_overall != state.anim_overall_target {
                state.anim_overall.set(raw_overall);
                state.anim_overall_target = raw_overall;
            }
            state.anim_overall.update();
            let overall = *state.anim_overall;

            let line = format!(
                "Overall {} {:>3}%",
                render_fractional_bar(
                    usize::from(chunks[cursor].width).saturating_sub(13),
                    overall
                ),
                overall
            );
            Line::styled(line, self.theme.base()).render(chunks[cursor], buf);
            cursor += 1;
        }

        if self.show_eta {
            let eta_line = if let Some(started) = state.start_time {
                let elapsed = Instant::now().saturating_duration_since(started);
                calculate_eta(&state.checks, elapsed).map_or_else(
                    || "ETA: --".to_string(),
                    |eta| {
                        let eta_ms = u64::try_from(eta.as_millis()).unwrap_or(u64::MAX);
                        format!("ETA: {}", format_duration(eta_ms))
                    },
                )
            } else {
                "ETA: --".to_string()
            };
            Line::styled(eta_line, self.theme.disabled()).render(chunks[cursor], buf);
        }
    }
}

fn effective_progress(check: &CheckProgress) -> u8 {
    match check.status {
        CheckStatus::Pending => 0,
        CheckStatus::Running => check.progress.min(100),
        CheckStatus::Passed | CheckStatus::Failed | CheckStatus::Skipped | CheckStatus::Cached => {
            100
        }
    }
}

fn status_icon(check: &CheckProgress) -> &'static str {
    match check.status {
        CheckStatus::Passed => "",
        CheckStatus::Failed => "",
        CheckStatus::Running => SpinnerPreset::Anvil.frame(running_frame_index(check.start_time)),
        CheckStatus::Pending | CheckStatus::Skipped => "",
        CheckStatus::Cached => "",
    }
}

fn running_frame_index(start_time: Option<Instant>) -> usize {
    let interval_ms = SpinnerPreset::Anvil.interval().as_millis().max(1);
    let elapsed_ms = start_time.map_or(0, |started| {
        Instant::now()
            .saturating_duration_since(started)
            .as_millis()
    });
    usize::try_from(elapsed_ms / interval_ms).unwrap_or(0)
}

fn status_style<T: Theme>(status: CheckStatus, theme: &T) -> Style {
    match status {
        CheckStatus::Passed | CheckStatus::Cached => Style::default().fg(theme.success()),
        CheckStatus::Failed => Style::default().fg(theme.error()),
        CheckStatus::Running => Style::default().fg(theme.accent()),
        CheckStatus::Pending => theme.disabled(),
        CheckStatus::Skipped => Style::default().fg(theme.muted()),
    }
}

#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]
fn render_fractional_bar(width: usize, progress: u8) -> String {
    if width == 0 {
        return String::new();
    }

    let total_eighths = width * 8;
    let filled_eighths = (total_eighths * usize::from(progress)) / 100;
    let full_blocks = filled_eighths / 8;
    let remainder = filled_eighths % 8;

    let mut bar = String::new();
    bar.push_str(&"".repeat(full_blocks));
    if remainder > 0 {
        bar.push(FRACTION_BLOCKS[remainder - 1]);
    }

    let used = full_blocks + usize::from(remainder > 0);
    bar.push_str(&"".repeat(width.saturating_sub(used)));
    bar
}

fn truncate_name(name: &str, width: usize) -> String {
    if width == 0 {
        return String::new();
    }

    let mut output = String::new();
    let mut used = 0;
    for ch in name.chars() {
        let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + cw > width {
            break;
        }
        output.push(ch);
        used += cw;
    }

    if used < width {
        output.push_str(&" ".repeat(width - used));
    }

    output
}

#[allow(clippy::cast_possible_truncation)]
fn resolve_duration(check: &CheckProgress) -> Option<u64> {
    if let Some(duration) = check.duration_ms {
        return Some(duration);
    }

    match (check.start_time, check.end_time) {
        (Some(start), Some(end)) => Some(end.saturating_duration_since(start).as_millis() as u64),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use ratatui::widgets::StatefulWidget;

    use super::*;

    #[test]
    fn overall_progress_uses_weighted_status_progress() {
        let checks = vec![
            CheckProgress {
                id: "a".to_string(),
                name: "lint".to_string(),
                status: CheckStatus::Passed,
                progress: 100,
                start_time: None,
                end_time: None,
                duration_ms: Some(1_000),
                message: None,
            },
            CheckProgress {
                id: "b".to_string(),
                name: "tests".to_string(),
                status: CheckStatus::Running,
                progress: 50,
                start_time: None,
                end_time: None,
                duration_ms: None,
                message: None,
            },
        ];

        assert_eq!(calculate_overall_progress(&checks), 75);
    }

    #[test]
    fn eta_scales_from_elapsed_and_progress() {
        let checks = vec![CheckProgress {
            id: "a".to_string(),
            name: "lint".to_string(),
            status: CheckStatus::Running,
            progress: 50,
            start_time: None,
            end_time: None,
            duration_ms: None,
            message: None,
        }];

        let eta = calculate_eta(&checks, Duration::from_secs(10));
        assert_eq!(eta, Some(Duration::from_secs(10)));
    }

    #[test]
    fn format_duration_handles_milliseconds_seconds_and_minutes() {
        assert_eq!(format_duration(512), "512ms");
        assert_eq!(format_duration(12_000), "12s");
        assert_eq!(format_duration(61_000), "1m 1s");
    }

    #[test]
    fn overall_progress_animates_toward_target() {
        use crate::widgets::ANIM_DURATION_MS;

        let theme = crate::theme::EddaCraftTheme;
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);
        let mut state = ParallelProgressState {
            checks: vec![CheckProgress {
                id: "a".to_string(),
                name: "lint".to_string(),
                status: CheckStatus::Passed,
                progress: 100,
                start_time: None,
                end_time: None,
                duration_ms: Some(100),
                message: None,
            }],
            start_time: None,
            ..Default::default()
        };

        // First render primes the animation toward overall=100.
        ParallelProgress::new(&theme).render(area, &mut buf, &mut state);
        let first = *state.anim_overall;
        assert!(
            first <= 100,
            "animation should start within [0, 100], got {first}"
        );

        // Advance past the configured animation duration and re-render.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let advance = ANIM_DURATION_MS as usize + 1;
        animate::tick(advance);
        ParallelProgress::new(&theme).render(area, &mut buf, &mut state);

        assert_eq!(
            *state.anim_overall, 100,
            "expected anim_overall to converge to target after full duration"
        );
    }

    #[test]
    fn compact_running_check_renders_spinner_frame() {
        let theme = crate::theme::EddaCraftTheme;
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);
        // Pin start_time so `running_frame_index` lands on frame 3 (the final
        // build-up glyph "‡"), letting us assert against a single distinctive
        // character that doesn't collide with the ETA dashes.
        let interval_ms = SpinnerPreset::Anvil.interval();
        let started = Instant::now()
            .checked_sub(interval_ms * 3 + Duration::from_millis(10))
            .expect("Instant arithmetic underflow");
        let mut state = ParallelProgressState {
            checks: vec![CheckProgress {
                id: "a".to_string(),
                name: "forge".to_string(),
                status: CheckStatus::Running,
                progress: 42,
                start_time: Some(started),
                end_time: None,
                duration_ms: None,
                message: Some("Forging".to_string()),
            }],
            start_time: None,
            ..Default::default()
        };

        ParallelProgress::new(&theme)
            .compact(true)
            .render(area, &mut buf, &mut state);

        let row: String = (0..40).map(|x| buf[(x, 1)].symbol().to_string()).collect();
        assert!(
            row.contains(""),
            "expected the final anvil spinner frame (‡) in row {row:?}"
        );
    }
}