rs-hop 0.4.1

Fuzzy-finder TUI to jump between git repositories and folders
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
//! Renders the Files tab as a `List` of section-header bars and entry rows.
//!
//! Unlike the git table, sections interleave non-selectable header rows with
//! entry rows, so a `Table` cannot carry the cursor cleanly. Following mdtask's
//! finder, the scroll offset is kept across frames (`offset`) so the cursor
//! pages within the viewport and the list only scrolls at the edges; the
//! cursor itself is an entry display position (headers are purely visual).

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use chrono::{DateTime, Local};
use ratada::text::truncate;
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{List, ListItem, ListState, Paragraph};
use unicode_width::UnicodeWidthStr;

use crate::config::Config;
use crate::domain::filter::{Tab, TabKind};
use crate::domain::repo::Repo;
use crate::domain::sections::SectionGroup;
use crate::domain::stats::{CodeEntry, GitStats};
use crate::theme::Skin;
use crate::tui::columns::{ColumnSet, StatColumn, stat_columns};
use crate::tui::git_columns::{
    branch_text, effective_info, github_text, status_display, zip_date_text,
};
use crate::tui::list_layout::{
    ListScroll, SLUG_HEADER, settled_offset, slug_column_width,
};
use crate::tui::presentation::{IconSet, slug_style, status_span};
use crate::tui::row_cells::{
    GlyphContext, StatContext, fav_span, marker_span, type_label,
};
use crate::tui::skin::Colors;

/// The lower and upper bound for the auto-sized name column.
const NAME_MIN: usize = 4;
const NAME_MAX: usize = 30;
/// Fixed width of the type column (git / folder / file).
const TYPE_WIDTH: usize = 6;
/// Fixed width of the ZIP Backup column (fits a `YYYY-MM-DD` date).
const ZIP_WIDTH: usize = 10;
/// Lower and upper bounds for the git branch column.
const BRANCH_MIN: usize = 6;
const BRANCH_MAX: usize = 20;
/// Lower and upper bounds for the git status column (the floor fits the
/// "Status" header).
const STATUS_MIN: usize = 6;
const STATUS_MAX: usize = 12;
/// The styling context for a sectioned render, bundled to keep the parameter
/// count low.
pub struct SectionedView<'a> {
    /// The active tab (decides the git vs files column layout).
    pub tab: Tab,
    /// The display-ordered sections with their entry service indices.
    pub groups: &'a [SectionGroup],
    /// All service entries (indexed by the groups' items).
    pub repos: &'a [Repo],
    /// The resolved settings (branch column cap).
    pub config: &'a Config,
    /// Whether to show example git info instead of live status.
    pub example_mode: bool,
    /// The glyph set.
    pub icons: &'a IconSet,
    /// The active theme, for the scrollbar.
    pub skin: &'a Skin,
    /// The colour roles resolved from the active theme.
    pub colors: &'a Colors,
    /// Service indices that are part of the multi-selection.
    pub selected: &'a HashSet<usize>,
    /// Whether a multi-selection is active (shows the leading marker column).
    pub has_selection: bool,
    /// Paths flagged missing by the on-demand existence check.
    pub missing: &'a HashSet<PathBuf>,
    /// Whether to show each entry's slug (dim, italic) after its name.
    pub show_slugs: bool,
    /// Last ZIP-backup time per entry path, for the "ZIP Backup" column.
    pub zip_backups: &'a HashMap<PathBuf, DateTime<Local>>,
    /// The scroll offset carried across frames.
    pub offset: &'a Cell<usize>,
    /// Which columns to show.
    pub columns: ColumnSet,
    /// Cached code and size statistics, keyed by entry path.
    pub code: &'a HashMap<PathBuf, CodeEntry>,
    /// Cached history statistics, keyed by entry path.
    pub git: &'a HashMap<PathBuf, GitStats>,
    /// Paths a statistics worker has not reported yet.
    pub computing: &'a HashSet<PathBuf>,
    /// While a refresh runs: the still-in-flight paths and the current spinner
    /// glyph. Rows whose path is in the set show the spinner. `None` outside a
    /// run.
    pub spinner: Option<(&'a HashSet<PathBuf>, &'a str)>,
    /// The reference time for ages, in unix seconds.
    pub now: i64,
}

impl SectionedView<'_> {
    /// What the shared statistics cells read from.
    fn stats(&self) -> StatContext<'_> {
        StatContext {
            code: self.code,
            git: self.git,
            computing: self.computing,
            spinner: self.spinner,
            now: self.now,
        }
    }

    /// What the shared leading glyphs read from.
    fn glyphs(&self) -> GlyphContext<'_> {
        GlyphContext {
            example_mode: self.example_mode,
            missing: self.missing,
            icons: self.icons,
            colors: self.colors,
        }
    }

    /// The rendered text of one statistics cell.
    fn stat_text(&self, repo: &Repo, column: StatColumn) -> String {
        self.stats().text(repo, column)
    }

    /// The current spinner glyph, or a dash outside a run.
    fn spinner_glyph(&self) -> &str {
        self.stats().spinner_glyph()
    }

    /// Whether `repo` is still in flight in the running refresh.
    fn is_in_flight(&self, repo: &Repo) -> bool {
        self.stats().is_in_flight(repo)
    }
}

/// Renders the sectioned list into `area`, highlighting the entry at display
/// position `cursor`.
pub fn render(
    frame: &mut Frame,
    area: Rect,
    cursor: usize,
    view: &SectionedView,
) {
    // A column-header row plus a blank spacer sit above the list (the sectioned
    // list has no header of its own); reserve them, then the list and its
    // scrollbar take the rest.
    let header_h: u16 = if area.height > 1 { 1 } else { 0 };
    let header_area = (header_h > 0).then_some(Rect { height: 1, ..area });
    let list_full = Rect {
        y: area.y + header_h,
        height: area.height - header_h,
        ..area
    };

    let row_count = view.groups.len() + entry_count(view.groups);
    let viewport = list_full.height as usize;
    let overflow = viewport > 0 && row_count > viewport;
    // Reserve the rightmost column for the scrollbar when the list overflows.
    let list_area = if overflow {
        Rect {
            width: list_full.width.saturating_sub(1),
            ..list_full
        }
    } else {
        list_full
    };
    let content_width = list_area.width as usize;

    if let Some(header_area) = header_area {
        render_column_header(frame, header_area, view, content_width);
    }

    let (items, cursor_row, first_entry_row) =
        build_items(view, cursor, content_width);

    let offset = settled_offset(&ListScroll {
        saved: view.offset.get(),
        cursor: cursor_row,
        row_count,
        viewport,
        first_entry_row: Some(first_entry_row),
    });
    view.offset.set(offset);

    let list = List::new(items).highlight_style(view.colors.selection_style());
    let mut state = ListState::default();
    *state.offset_mut() = offset;
    state.select(Some(cursor_row));
    frame.render_stateful_widget(list, list_area, &mut state);

    if overflow {
        ratada::scroll::render_scrollbar(
            frame,
            list_full,
            view.skin,
            ratada::nav::ScrollView {
                total: row_count,
                offset,
                viewport,
            },
        );
    }
}

/// The total number of entry rows across `groups`.
fn entry_count(groups: &[SectionGroup]) -> usize {
    groups.iter().map(|group| group.items.len()).sum()
}

/// Builds the list items and returns them with the cursor's row index and the
/// first entry row index (used to snap the offset to the very top).
fn build_items<'a>(
    view: &SectionedView,
    cursor: usize,
    width: usize,
) -> (Vec<ListItem<'a>>, usize, usize) {
    let name_width = name_width(view);
    let mut items: Vec<ListItem> = Vec::new();
    let mut cursor_row = 0;
    let mut first_entry_row = 0;
    let mut entry_pos = 0;
    let mut seen_entry = false;
    for group in view.groups {
        items.push(header_item(&group.label, width, view.colors));
        for &index in &group.items {
            let row = items.len();
            if !seen_entry {
                first_entry_row = row;
                seen_entry = true;
            }
            if entry_pos == cursor {
                cursor_row = row;
            }
            items.push(entry_item(view, index, name_width, width));
            entry_pos += 1;
        }
    }
    (items, cursor_row, first_entry_row)
}

/// The column-title row drawn above the sectioned list. Its columns are sized
/// exactly like the entry rows (same width helpers) so the titles line up.
fn render_column_header(
    frame: &mut Frame,
    area: Rect,
    view: &SectionedView,
    width: usize,
) {
    let row = Rect { height: 1, ..area };
    frame.render_widget(
        Paragraph::new(Line::from(header_spans(view, width)))
            .style(view.colors.header_style()),
        row,
    );
}

/// The header spans: the shared name/slug prefix, then the set-specific columns
/// (statistics titles, or the git/files Standard columns).
fn header_spans(view: &SectionedView, width: usize) -> Vec<Span<'static>> {
    let name_w = name_width(view);
    let mut spans = vec![Span::raw("     "), Span::raw(pad("Name", name_w))];
    if view.show_slugs {
        spans.push(Span::raw("  "));
        spans.push(Span::raw(pad(SLUG_HEADER, slug_col_width(view))));
    }
    if view.columns.is_statistics() {
        for column in stat_columns(view.columns) {
            spans.push(Span::raw("  "));
            spans.push(Span::raw(format!(
                "{:>w$}",
                column.title(),
                w = column.width() as usize
            )));
        }
        return spans;
    }
    let prefix = content_prefix(view, name_w);
    match view.tab.kind() {
        TabKind::Files => {
            spans.push(Span::raw("  "));
            spans.push(Span::raw(pad("Type", TYPE_WIDTH)));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(pad("Path", files_path_width(prefix, width))));
        }
        TabKind::Git => {
            let (branch_w, status_w, github_w) =
                git_column_widths(view, prefix, width);
            spans.push(Span::raw("  "));
            spans.push(Span::raw(pad("Branch", branch_w)));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(pad("Status", status_w)));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(pad("GitHub", github_w)));
        }
    }
    spans.push(Span::raw("  "));
    spans.push(Span::raw(format!("{:>ZIP_WIDTH$}", "ZIP Backup")));
    spans
}

/// The statistics cells of one entry, right-aligned under their headers.
fn stat_spans(view: &SectionedView, repo: &Repo) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    for column in stat_columns(view.columns) {
        let text = view.stat_text(repo, *column);
        let width = column.width() as usize;
        let cell = if column.is_numeric() {
            format!("{text:>width$}")
        } else {
            pad(&text, width)
        };
        spans.push(Span::raw("  "));
        spans.push(Span::styled(
            cell,
            Style::default().fg(view.colors.foreground),
        ));
    }
    spans
}

/// A full-width section-header bar: the bold accent label then a dim rule.
fn header_item<'a>(label: &str, width: usize, colors: &Colors) -> ListItem<'a> {
    let title = format!(" {label} ");
    let used = UnicodeWidthStr::width(title.as_str());
    let rule = "\u{2500}".repeat(width.saturating_sub(used));
    ListItem::new(Line::from(vec![
        Span::styled(
            title,
            Style::default()
                .fg(colors.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(rule, Style::default().fg(colors.dim)),
    ]))
}

/// One entry row: a shared marker/fav/name prefix, then the git or files
/// columns, tinted when part of the multi-selection.
fn entry_item<'a>(
    view: &SectionedView,
    index: usize,
    name_width: usize,
    width: usize,
) -> ListItem<'a> {
    let repo = &view.repos[index];
    let selected = view.selected.contains(&index);
    // A 2-cell lead: the selection marker when a selection is active.
    let lead = if view.has_selection && selected {
        Span::styled(
            "\u{25b8} ",
            Style::default()
                .fg(view.colors.accent)
                .add_modifier(Modifier::BOLD),
        )
    } else {
        Span::raw("  ")
    };
    let name_field = name_field_spans(&repo.display_name(), name_width);
    let glyphs = view.glyphs();
    let mut spans = vec![
        lead,
        marker_span(repo, &glyphs),
        fav_span(repo, &glyphs),
        Span::raw(" "),
    ];
    spans.extend(name_field);
    // The slug is its own dim-italic column right after the name.
    if view.show_slugs {
        spans.push(Span::raw("  "));
        spans.push(Span::styled(
            pad(shown_slug(view, repo).unwrap_or(""), slug_col_width(view)),
            slug_style(view.colors),
        ));
    }
    // The prefix the kind columns start after (name + optional slug), so the
    // flexible path/github columns still fit.
    let prefix = content_prefix(view, name_width);
    if view.columns.is_statistics() {
        spans.extend(stat_spans(view, repo));
    } else {
        match view.tab.kind() {
            TabKind::Files => {
                spans.extend(files_spans(repo, view, prefix, width))
            }
            TabKind::Git => spans.extend(git_spans(repo, view, prefix, width)),
        }
    }
    let item = ListItem::new(Line::from(spans));
    if selected {
        item.style(Style::default().bg(view.colors.multi_select_bg))
    } else {
        item
    }
}

/// The Files-tab columns after the name/slug prefix: type, the dim path and the
/// ZIP date. `prefix` is the name column plus the optional slug column.
fn files_spans(
    repo: &Repo,
    view: &SectionedView,
    prefix: usize,
    width: usize,
) -> Vec<Span<'static>> {
    let kind = pad(type_label(repo), TYPE_WIDTH);
    let path = pad(
        &repo.path.to_string_lossy(),
        files_path_width(prefix, width),
    );
    let zip = format!("{:>ZIP_WIDTH$}", zip_cell_text(repo, view));
    vec![
        Span::raw("  "),
        Span::raw(kind),
        Span::raw("  "),
        Span::styled(path, Style::default().fg(view.colors.dim)),
        Span::raw("  "),
        Span::styled(zip, Style::default().fg(view.colors.dim)),
    ]
}

/// The git-tab columns after the name: branch and GitHub name in the foreground
/// (like the name), the coloured status, and the dim ZIP date. GitHub flexes
/// into the leftover width.
fn git_spans(
    repo: &Repo,
    view: &SectionedView,
    prefix: usize,
    width: usize,
) -> Vec<Span<'static>> {
    let (branch_w, status_w, github_w) = git_column_widths(view, prefix, width);
    let info = effective_info(repo, view.example_mode);
    let branch = pad(&branch_text(info), branch_w);
    let github = pad(&github_text(info), github_w);
    let zip = format!("{:>ZIP_WIDTH$}", zip_cell_text(repo, view));
    let fg = Style::default().fg(view.colors.foreground);
    let mut spans =
        vec![Span::raw("  "), Span::styled(branch, fg), Span::raw("  ")];
    spans.extend(git_status_spans(repo, view, info, status_w));
    spans.extend([
        Span::raw("  "),
        Span::styled(github, fg),
        Span::raw("  "),
        Span::styled(zip, Style::default().fg(view.colors.dim)),
    ]);
    spans
}

/// The status spans padded to `width`: the spinner while the row is in flight,
/// otherwise the shared coloured status followed by padding.
fn git_status_spans(
    repo: &Repo,
    view: &SectionedView,
    info: Option<&crate::domain::repo::GitInfo>,
    width: usize,
) -> Vec<Span<'static>> {
    if view.is_in_flight(repo) {
        return vec![Span::styled(
            pad(view.spinner_glyph(), width),
            Style::default().fg(view.colors.accent),
        )];
    }
    let text = status_display(info, view.icons);
    let used = UnicodeWidthStr::width(text.as_str()).min(width);
    vec![
        status_span(info, view.icons, view.colors),
        Span::raw(" ".repeat(width.saturating_sub(used))),
    ]
}

/// The git columns' widths: branch and status sized to their bounded content,
/// GitHub taking the leftover width (so the row fills without overflowing).
fn git_column_widths(
    view: &SectionedView,
    prefix: usize,
    width: usize,
) -> (usize, usize, usize) {
    let branch = col_content(view, |r| {
        branch_text(effective_info(r, view.example_mode))
    })
    .clamp(BRANCH_MIN, BRANCH_MAX);
    let status = col_content(view, |r| {
        status_display(effective_info(r, view.example_mode), view.icons)
    })
    .clamp(STATUS_MIN, STATUS_MAX);
    // lead(2) + marker(1) + fav(1) + space(1) + prefix + gap(2) + branch + gap(2)
    // + status + gap(2) + github + gap(2) + ZIP; GitHub flexes into the rest.
    // `prefix` = the name column plus the optional slug column.
    let used =
        2 + 1 + 1 + 1 + prefix + 2 + branch + 2 + status + 2 + 2 + ZIP_WIDTH;
    let github = width.saturating_sub(used);
    (branch, status, github)
}

/// The widest rendered cell (display columns) over every entry for one column.
fn col_content<F>(view: &SectionedView, cell: F) -> usize
where
    F: Fn(&Repo) -> String,
{
    view.groups
        .iter()
        .flat_map(|group| group.items.iter())
        .map(|&index| UnicodeWidthStr::width(cell(&view.repos[index]).as_str()))
        .max()
        .unwrap_or(0)
}

/// The auto-sized name column width: the widest display name, bounded.
fn name_width(view: &SectionedView) -> usize {
    view.groups
        .iter()
        .flat_map(|group| group.items.iter())
        .map(|&index| {
            UnicodeWidthStr::width(view.repos[index].display_name().as_str())
        })
        .max()
        .unwrap_or(NAME_MIN)
        .clamp(NAME_MIN, NAME_MAX)
}

/// The Slug column width: the widest entry slug, bounded by the shared rule, or
/// 0 when slugs are hidden.
fn slug_col_width(view: &SectionedView) -> usize {
    if !view.show_slugs {
        return 0;
    }
    let widest = view
        .groups
        .iter()
        .flat_map(|group| group.items.iter())
        .map(|&index| {
            view.repos[index]
                .slug
                .as_deref()
                .map_or(0, UnicodeWidthStr::width)
        })
        .max()
        .unwrap_or(0);
    slug_column_width(widest)
}

/// The row prefix width before the kind columns: the name column plus the
/// optional slug column (its 2-cell gap + width). Shared by the entry rows and
/// the column header so they align.
fn content_prefix(view: &SectionedView, name_width: usize) -> usize {
    let slug = if view.show_slugs {
        2 + slug_col_width(view)
    } else {
        0
    };
    name_width + slug
}

/// The Files-tab path column width: the leftover after the fixed columns, so the
/// row fills to `width` without overflowing. Shared by the rows and the header.
fn files_path_width(prefix: usize, width: usize) -> usize {
    // lead(5) + prefix + gap(2) + type + gap(2) + path + gap(2) + ZIP.
    let used = 2 + 1 + 1 + 1 + prefix + 2 + TYPE_WIDTH + 2 + 2 + ZIP_WIDTH;
    width.saturating_sub(used)
}

/// The slug to display for `repo`, or `None` when slugs are hidden.
fn shown_slug<'a>(view: &SectionedView, repo: &'a Repo) -> Option<&'a str> {
    repo.slug.as_deref().filter(|_| view.show_slugs)
}

/// The name-column spans: the name, padded to `width`.
fn name_field_spans(name: &str, width: usize) -> Vec<Span<'static>> {
    vec![Span::raw(pad(name, width))]
}

/// Pads `text` with trailing spaces to `width`, truncating when it is longer.
fn pad(text: &str, width: usize) -> String {
    let len = UnicodeWidthStr::width(text);
    if len >= width {
        truncate(text, width)
    } else {
        format!("{text}{}", " ".repeat(width - len))
    }
}

/// The ZIP Backup cell text for `repo` (the shared git-columns helper).
fn zip_cell_text(repo: &Repo, view: &SectionedView) -> String {
    zip_date_text(repo, view.icons, view.zip_backups)
}

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

    #[test]
    fn pad_fills_or_truncates() {
        assert_eq!(pad("ab", 5), "ab   ");
        assert_eq!(pad("abcdef", 4), "abc…");
    }

    #[test]
    fn name_field_spans_pads_the_name() {
        // The slug is its own column now; the name field is a single padded
        // span sized to the name column width.
        let spans = name_field_spans("hop", 10);
        assert_eq!(spans.len(), 1);
    }
}