cruftkill 0.3.2

Polyglot dev-cache reaper — find and delete node_modules, .venv, target, DerivedData and the rest of your build cruft from a fast terminal UI
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! ratatui draw functions. Stateless: take `AppState`, write to a Frame.
//!
//! Visual goals: give the TUI personality without depending on Nerd Font or
//! wide emoji that breaks alignment. We use BMP-range Unicode glyphs that
//! all monospace fonts ship — box-drawing, geometric shapes, braille
//! patterns for the spinner.
//!
//! Layout (top to bottom):
//! ```text
//! ▓▓ cft  ⟶  /home/me/projects                        [dry-run]
//!   ◆ 12 found   ▼ 1.20 GB total   ⠋ scanning   sort: ▼ size
//! ──────────────────────────────────────────────────────────────
//! ▶ ⚠  /home/me/proj-a/node_modules           1.20 GB   2d
//!   ·  /home/me/proj-b/node_modules           250 MB    1w
//!   ✗  /home/me/proj-c/node_modules           120 MB    —
//! ──────────────────────────────────────────────────────────────
//!  ↑↓ nav  d delete  s/n/m sort  r rescan  q quit
//! ```
//!
//! When the user requests a delete, a double-bordered modal overlays.

use std::time::{SystemTime, UNIX_EPOCH};

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Cell, Clear, Paragraph, Row, Table, TableState,
};

use crate::core::types::{FolderResult, SortBy};
use crate::tui::app::{AppState, Mode};

/// Braille-pattern spinner frames (smoother than ASCII /-\|).
const SPINNER: &[&str] = &["", "", "", "", "", "", "", "", "", ""];

/// "CFT" rendered in ANSI Shadow figlet font. Used as a splash logo while
/// the scan is still empty.
const LOGO: &[&str] = &[
    " ██████╗███████╗████████╗",
    "██╔════╝██╔════╝╚══██╔══╝",
    "██║     █████╗     ██║   ",
    "██║     ██╔══╝     ██║   ",
    "╚██████╗██║        ██║   ",
    " ╚═════╝╚═╝        ╚═╝   ",
];

/// Width (in display columns) of the LOGO above. All ANSI-shadow chars are
/// single-cell, so this equals the character count of the longest line.
const LOGO_WIDTH: u16 = 25;

pub fn draw(frame: &mut Frame<'_>, state: &AppState) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(3), Constraint::Length(1)])
        .split(area);

    draw_header(frame, chunks[0], state);
    draw_table(frame, chunks[1], state);
    draw_status(frame, chunks[2], state);

    match &state.mode {
        Mode::Confirm(paths) => {
            draw_confirm_modal(frame, area, state, paths);
        }
        Mode::Deleting(progress) => {
            draw_deleting_modal(frame, area, state, progress);
        }
        Mode::Browse => {}
    }
}

// ─── Header ──────────────────────────────────────────────────────────────────

fn draw_header(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let logo =
        Span::styled(" ▓▓ cft", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD));
    let arrow = Span::styled("", Style::default().fg(Color::DarkGray));
    let path = Span::styled(state.root.display().to_string(), Style::default().fg(Color::White));
    let mut title_spans = vec![logo, arrow, path];
    if state.dry_run {
        title_spans.push(Span::styled(
            "   [dry-run]",
            Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD | Modifier::REVERSED),
        ));
    }
    let title = Line::from(title_spans);

    let (state_icon, state_label, state_style) = if state.scan_finished {
        ("", "done", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD))
    } else {
        (spinner_frame(), "scanning", Style::default().fg(Color::Yellow))
    };
    let sort_label = match state.sort {
        SortBy::Path => "name",
        SortBy::Size => "size",
        SortBy::Age => "last-used",
    };
    let dim = Style::default().fg(Color::DarkGray);
    let bold_white = Style::default().fg(Color::White).add_modifier(Modifier::BOLD);
    let mut stat_spans = vec![
        Span::raw("  "),
        Span::styled("", Style::default().fg(Color::Cyan)),
        Span::styled(format!("{}", state.results.len()), bold_white),
        Span::styled(" found", dim),
        Span::styled("    ", dim),
        Span::styled("", Style::default().fg(Color::Cyan)),
        Span::styled(human_bytes(state.releasable_bytes()), bold_white),
        Span::styled(" releasable", dim),
    ];
    if state.saved_bytes() > 0 {
        stat_spans.extend([
            Span::styled("    ", dim),
            Span::styled("", Style::default().fg(Color::Green)),
            Span::styled(
                human_bytes(state.saved_bytes()),
                Style::default().fg(Color::Green).add_modifier(Modifier::BOLD),
            ),
            Span::styled(" saved", dim),
        ]);
    }
    stat_spans.extend([
        Span::styled("    ", dim),
        Span::styled(format!("{state_icon} "), state_style),
        Span::styled(state_label, state_style),
        Span::styled(format!(" · {} dirs", state.dirs_scanned), dim),
        Span::styled("    ", dim),
        Span::styled("sort ", dim),
        Span::styled(
            format!("{} {sort_label}", state.sort_direction.indicator()),
            Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
        ),
    ]);
    let stats = Line::from(stat_spans);

    let p = Paragraph::new(vec![title, stats]).block(
        Block::default()
            .borders(Borders::BOTTOM)
            .border_style(Style::default().fg(Color::DarkGray)),
    );
    frame.render_widget(p, area);
}

// ─── Results table / empty state ─────────────────────────────────────────────

fn draw_table(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    if state.results.is_empty() {
        draw_empty_state(frame, area, state);
        return;
    }
    let header_style = Style::default().fg(Color::DarkGray).add_modifier(Modifier::BOLD);
    let header = Row::new(vec![
        Cell::from(""),
        Cell::from(""),
        Cell::from(Span::styled("PATH", header_style)),
        Cell::from(Span::styled("SIZE", header_style)),
        Cell::from(Span::styled("AGE", header_style)),
    ])
    .height(1);

    let rows: Vec<Row> = state
        .results
        .iter()
        .map(|r| {
            let select_marker = if r.selected {
                Span::styled("", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
            } else {
                Span::styled(" ", Style::default())
            };
            let risk_marker = if r.deleted {
                Span::styled("", Style::default().fg(Color::DarkGray))
            } else {
                match &r.risk {
                    Some(a) if a.is_sensitive => Span::styled(
                        "",
                        Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD),
                    ),
                    _ => Span::styled("·", Style::default().fg(Color::DarkGray)),
                }
            };

            let path_style = if r.deleted {
                Style::default().fg(Color::DarkGray).add_modifier(Modifier::CROSSED_OUT)
            } else if r.selected {
                Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            let path_span = Span::styled(r.path.display().to_string(), path_style);

            let (size_text, size_style_v) = match r.size_bytes {
                Some(b) => (human_bytes(b), size_style(b)),
                None => ("".to_string(), Style::default().fg(Color::DarkGray)),
            };

            let age_text = human_age(r.last_modified);
            let age_style = if r.last_modified.is_some() {
                Style::default().fg(Color::Gray)
            } else {
                Style::default().fg(Color::DarkGray)
            };

            Row::new(vec![
                Cell::from(select_marker),
                Cell::from(risk_marker),
                Cell::from(path_span),
                Cell::from(Span::styled(size_text, size_style_v)),
                Cell::from(Span::styled(age_text, age_style)),
            ])
        })
        .collect();

    let widths = [
        Constraint::Length(1),  // selected marker
        Constraint::Length(2),  // risk marker
        Constraint::Min(30),    // path
        Constraint::Length(10), // size
        Constraint::Length(6),  // age
    ];

    let table = Table::new(rows, widths)
        .header(header)
        .column_spacing(2)
        .block(Block::default().borders(Borders::NONE))
        .row_highlight_style(
            Style::default().fg(Color::Black).bg(Color::Cyan).add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("");

    let mut t_state = TableState::default();
    if !state.results.is_empty() {
        t_state.select(Some(state.cursor.min(state.results.len() - 1)));
    }

    frame.render_stateful_widget(table, area, &mut t_state);
}

/// Centred ASCII logo + tagline shown while no targets have been found yet.
fn draw_empty_state(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let logo_height = LOGO.len() as u16;
    // Logo + blank line + tagline + blank line + hint = logo_height + 4 rows.
    let block_height = logo_height + 4;
    if area.height < block_height + 2 {
        // Terminal too small for the splash; just bail out — the header
        // already shows progress and the table area will be blank.
        return;
    }

    let logo_style = Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD);
    let logo_x = area.x + area.width.saturating_sub(LOGO_WIDTH) / 2;
    let top_y = area.y + area.height.saturating_sub(block_height) / 2;
    for (i, line) in LOGO.iter().enumerate() {
        let rect = Rect { x: logo_x, y: top_y + i as u16, width: LOGO_WIDTH, height: 1 };
        frame.render_widget(Paragraph::new(Span::styled(*line, logo_style)), rect);
    }

    let tagline_y = top_y + logo_height + 1;
    let (tagline, tagline_style) = if state.scan_finished {
        ("no matching folders found".to_string(), Style::default().fg(Color::DarkGray))
    } else if state.dirs_scanned == 0 {
        ("warming up the scanner…".to_string(), Style::default().fg(Color::Yellow))
    } else {
        (
            format!("{} dirs scanned, still looking…", state.dirs_scanned),
            Style::default().fg(Color::Yellow),
        )
    };
    let tagline_rect = Rect { x: area.x, y: tagline_y, width: area.width, height: 1 };
    frame.render_widget(
        Paragraph::new(Span::styled(tagline, tagline_style)).alignment(Alignment::Center),
        tagline_rect,
    );

    let hint_y = tagline_y + 2;
    if hint_y < area.y + area.height {
        let hint_rect = Rect { x: area.x, y: hint_y, width: area.width, height: 1 };
        let hint_style = Style::default().fg(Color::DarkGray);
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled("scanning ", hint_style),
                Span::styled(
                    state.root.display().to_string(),
                    Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
                ),
            ]))
            .alignment(Alignment::Center),
            hint_rect,
        );
    }
}

// ─── Status bar ──────────────────────────────────────────────────────────────

fn draw_status(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let mut spans = match state.mode {
        Mode::Browse => {
            let sel = state.selection_count();
            if sel > 0 {
                vec![
                    Span::styled(
                        format!("{sel} selected · {} ", human_bytes(state.selection_bytes())),
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    ),
                    label_span("  "),
                    key_span("⏎/d "),
                    label_span("delete  "),
                    key_span("Space "),
                    label_span("toggle  "),
                    key_span("Esc "),
                    label_span("clear  "),
                    key_span("q "),
                    label_span("quit"),
                ]
            } else {
                vec![
                    key_span(" ↑↓ "),
                    label_span("nav  "),
                    key_span("Space "),
                    label_span("select  "),
                    key_span("⏎/d "),
                    label_span("delete  "),
                    key_span("s/n/m "),
                    label_span("sort  "),
                    key_span("r "),
                    label_span("rescan  "),
                    key_span("q "),
                    label_span("quit"),
                ]
            }
        }
        Mode::Confirm(_) => {
            vec![key_span(" y "), label_span("delete  "), key_span("n/Esc "), label_span("cancel")]
        }
        Mode::Deleting(_) => vec![
            Span::styled(
                format!(" {} deleting…", spinner_frame()),
                Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD),
            ),
            label_span("   keys locked until done"),
        ],
    };
    if let Some(msg) = &state.last_message {
        spans.push(Span::raw("    "));
        spans.push(Span::styled(
            msg.clone(),
            Style::default().fg(Color::Green).add_modifier(Modifier::BOLD),
        ));
    }
    let line = Line::from(spans);
    frame.render_widget(Paragraph::new(line).alignment(Alignment::Left), area);
}

fn key_span(s: &'static str) -> Span<'static> {
    Span::styled(s, Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
}

fn label_span(s: &'static str) -> Span<'static> {
    Span::styled(s, Style::default().fg(Color::DarkGray))
}

// ─── Confirm modal ───────────────────────────────────────────────────────────

fn draw_confirm_modal(
    frame: &mut Frame<'_>,
    area: Rect,
    state: &AppState,
    paths: &[std::path::PathBuf],
) {
    let mut width = area.width.saturating_mul(3) / 5;
    width = width.clamp(54, area.width.saturating_sub(4).max(54));
    let max_listed = 4usize;
    let listed = paths.len().min(max_listed) as u16;
    let extra_rows = if paths.len() > max_listed { 1 } else { 0 };
    let height = (9 + listed + extra_rows).min(area.height);
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height) / 2;
    let modal = Rect { x, y, width, height };

    frame.render_widget(Clear, modal);

    // Resolve each path back to its FolderResult so we can show size + risk.
    let rows: Vec<&FolderResult> =
        paths.iter().filter_map(|p| state.results.iter().find(|r| &r.path == p)).collect();
    let total_bytes: u64 = rows.iter().filter_map(|r| r.size_bytes).sum();
    let any_sensitive = rows.iter().any(|r| r.risk.as_ref().is_some_and(|a| a.is_sensitive));

    let title_color = if state.dry_run { Color::Magenta } else { Color::Red };
    let title_style = Style::default().fg(title_color).add_modifier(Modifier::BOLD);
    let title = if state.dry_run {
        format!(" ⚠  DRY-RUN — preview {} folders  ⚠ ", paths.len())
    } else {
        format!(" ⚠  CONFIRM DELETE — {} folder(s)  ⚠ ", paths.len())
    };

    let dim = Style::default().fg(Color::DarkGray);
    let bold_white = Style::default().fg(Color::White).add_modifier(Modifier::BOLD);
    let mut body = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled("total  ", dim),
            Span::styled(human_bytes(total_bytes), bold_white),
            Span::styled("    across  ", dim),
            Span::styled(format!("{}", paths.len()), bold_white),
            Span::styled("  folder(s)", dim),
        ]),
        Line::from(""),
    ];
    for p in paths.iter().take(max_listed) {
        body.push(Line::from(Span::styled(
            p.display().to_string(),
            Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
        )));
    }
    if paths.len() > max_listed {
        body.push(Line::from(Span::styled(
            format!("… and {} more", paths.len() - max_listed),
            dim,
        )));
    }
    body.push(Line::from(""));
    if any_sensitive {
        body.push(Line::from(vec![
            Span::styled("", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)),
            Span::styled(
                "some paths are flagged sensitive — review before confirming",
                Style::default().fg(Color::Yellow),
            ),
        ]));
    } else {
        body.push(Line::from(if state.dry_run {
            Span::styled(
                "Dry-run mode — filesystem is NOT touched.",
                Style::default().fg(Color::Magenta),
            )
        } else {
            Span::styled(
                "This will be permanently removed.",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            )
        }));
    }
    body.push(Line::from(""));
    body.push(Line::from(vec![
        Span::styled("press ", dim),
        Span::styled(
            " y ",
            Style::default().fg(Color::Black).bg(Color::Green).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" confirm  ·  ", dim),
        Span::styled(
            " n / Esc ",
            Style::default().fg(Color::Black).bg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" cancel", dim),
    ]));

    let block = Block::default()
        .title(Span::styled(title, title_style))
        .title_alignment(Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Double)
        .border_style(title_style);
    let p = Paragraph::new(body).alignment(Alignment::Center).block(block);
    frame.render_widget(p, modal);
}

/// Loading overlay shown while a (batch) delete is in flight. Shows live
/// progress so the user knows the app is working — large trees can take
/// many seconds, and a batch can span several of them.
fn draw_deleting_modal(
    frame: &mut Frame<'_>,
    area: Rect,
    state: &AppState,
    progress: &crate::tui::app::DeleteProgress,
) {
    let mut width = area.width.saturating_mul(3) / 5;
    width = width.clamp(54, area.width.saturating_sub(4).max(54));
    let height = 11u16.min(area.height);
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height) / 2;
    let modal = Rect { x, y, width, height };

    frame.render_widget(Clear, modal);

    let accent_color = if state.dry_run { Color::Magenta } else { Color::Yellow };
    let title_style = Style::default().fg(accent_color).add_modifier(Modifier::BOLD);
    let title = format!(" {} DELETING…  ", spinner_frame());

    let dim = Style::default().fg(Color::DarkGray);
    let bold_white = Style::default().fg(Color::White).add_modifier(Modifier::BOLD);
    let done = progress.completed + progress.failed;

    // Render a 20-char ASCII progress bar that fills as outcomes arrive.
    let bar_width = 30usize;
    let filled = if progress.total == 0 { 0 } else { bar_width * done / progress.total };
    let bar: String = std::iter::repeat_n('', filled)
        .chain(std::iter::repeat_n('', bar_width - filled))
        .collect();

    let body = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled(format!("{}/{}", done, progress.total), bold_white),
            Span::styled(" folders  ·  ", dim),
            Span::styled(human_bytes(progress.bytes_done), bold_white),
            Span::styled(" reclaimed", dim),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            bar,
            Style::default().fg(accent_color).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(if progress.failed > 0 {
            Span::styled(
                format!("{} failed so far", progress.failed),
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            )
        } else if state.dry_run {
            Span::styled("(dry-run — no filesystem mutation)", Style::default().fg(Color::Magenta))
        } else {
            Span::styled("do not interrupt; large trees can take seconds", dim)
        }),
    ];

    let block = Block::default()
        .title(Span::styled(title, title_style))
        .title_alignment(Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Double)
        .border_style(title_style);
    let p = Paragraph::new(body).alignment(Alignment::Center).block(block);
    frame.render_widget(p, modal);
}

// ─── Formatting helpers ──────────────────────────────────────────────────────

/// Format bytes as npkill-style human-readable (KB/MB/GB).
fn human_bytes(b: u64) -> String {
    const KB: f64 = 1024.0;
    const MB: f64 = KB * 1024.0;
    const GB: f64 = MB * 1024.0;
    let b = b as f64;
    if b < MB {
        format!("{:.0} KB", b / KB)
    } else if b < GB {
        format!("{:.1} MB", b / MB)
    } else {
        format!("{:.2} GB", b / GB)
    }
}

/// Color-code a size by magnitude — quick scan tells you where the wins are.
fn size_style(b: u64) -> Style {
    if b >= 1_073_741_824 {
        // ≥ 1 GiB — red bold (biggest wins)
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    } else if b >= 104_857_600 {
        // ≥ 100 MiB — yellow bold
        Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
    } else if b >= 10_485_760 {
        // ≥ 10 MiB — white
        Style::default().fg(Color::White)
    } else {
        // tiny — gray
        Style::default().fg(Color::Gray)
    }
}

/// Human-friendly relative age: `30s`, `2m`, `3h`, `5d`, `2w`, `4mo`, `1y`.
fn human_age(t: Option<SystemTime>) -> String {
    let Some(t) = t else {
        return "".into();
    };
    let Ok(elapsed) = SystemTime::now().duration_since(t) else {
        return "".into();
    };
    let secs = elapsed.as_secs();
    const MIN: u64 = 60;
    const HOUR: u64 = 60 * MIN;
    const DAY: u64 = 24 * HOUR;
    const WEEK: u64 = 7 * DAY;
    const MONTH: u64 = 30 * DAY;
    const YEAR: u64 = 365 * DAY;
    if secs < MIN {
        format!("{secs}s")
    } else if secs < HOUR {
        format!("{}m", secs / MIN)
    } else if secs < DAY {
        format!("{}h", secs / HOUR)
    } else if secs < WEEK {
        format!("{}d", secs / DAY)
    } else if secs < MONTH {
        format!("{}w", secs / WEEK)
    } else if secs < YEAR {
        format!("{}mo", secs / MONTH)
    } else {
        format!("{}y", secs / YEAR)
    }
}

/// Pick a braille spinner frame from the current wall-clock time. Frames
/// change roughly every 80 ms — pleasant motion without flicker.
fn spinner_frame() -> &'static str {
    let ms = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
    SPINNER[((ms / 80) as usize) % SPINNER.len()]
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn human_bytes_kb_range() {
        assert!(human_bytes(0).ends_with("KB"));
        assert!(human_bytes(50 * 1024).ends_with("KB"));
    }

    #[test]
    fn human_bytes_mb_range() {
        let s = human_bytes(5 * 1024 * 1024);
        assert!(s.ends_with("MB"), "got {s}");
    }

    #[test]
    fn human_bytes_gb_range() {
        let s = human_bytes(3 * 1024 * 1024 * 1024);
        assert!(s.ends_with("GB"), "got {s}");
    }

    #[test]
    fn human_age_none_is_dash() {
        assert_eq!(human_age(None), "");
    }

    #[test]
    fn human_age_unit_suffixes() {
        let now = SystemTime::now();
        assert!(human_age(Some(now - Duration::from_secs(30))).ends_with('s'));
        assert!(human_age(Some(now - Duration::from_secs(120))).ends_with('m'));
        assert!(human_age(Some(now - Duration::from_secs(7200))).ends_with('h'));
        assert!(human_age(Some(now - Duration::from_secs(86_400 * 2))).ends_with('d'));
        assert!(human_age(Some(now - Duration::from_secs(86_400 * 14))).ends_with('w'));
        let mo = human_age(Some(now - Duration::from_secs(86_400 * 60)));
        assert!(mo.ends_with("mo"), "got {mo}");
        let y = human_age(Some(now - Duration::from_secs(86_400 * 400)));
        assert!(y.ends_with('y'), "got {y}");
    }

    #[test]
    fn size_style_distinct_at_boundaries() {
        // Visual styles differ at the four magnitude tiers; we don't pin
        // specific colors (those are display preferences), only that the
        // smallest and largest produce different styles.
        assert_ne!(size_style(0), size_style(50 * 1024 * 1024 * 1024));
    }

    #[test]
    fn spinner_frame_is_one_of_set() {
        let frame = spinner_frame();
        assert!(SPINNER.contains(&frame));
    }
}