sluuz 0.10.5

git, but it sleuths - a git superset with cross-repo search, secret scanning, and multi-repo management
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! Rendering. Two panes on every level: the current list on top, the level
//! below it underneath, and the file diff in place of that list at the bottom
//! of the drill.

use super::{App, Level, Pane, Sel, branches, commits, repos, tags};
use crate::git::RepoStatus;
use crate::git::load::{Remote, RemoteTags, Tag, TagState};
use crate::tui::input::{CTRL_X_MOVE, CTRL_Y_MOVE, X_MOVE, Y_MOVE};
use crate::tui::widgets::{
    CREATE, DEL, EDIT, FILTER_KEYS, FIND, HELP, HelpSection, Modal, QUIT, REFRESH, commit_item,
    confirm_popup, diff_hscrollbar, diff_scrollbar, file_item, key_footer, list_scrollbar,
    pane_block, scope_tabs, typed_popup,
};
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{List, ListItem, Paragraph};

/// Width the branch name column is padded to, and the cap on the repo one,
/// which grows to fit the paths actually on screen.
const NAME_W: usize = 28;
const REPO_NAME_MAX: usize = 40;
/// Cap on the origin column, which is the first thing to give when the terminal
/// is narrow: it identifies a repo, it is not what you came to read.
const ORIGIN_MAX: usize = 38;
/// Cap on a remote's URL column, wider than a repo's origin since on the
/// remotes screen it is half of what a row is about.
const REMOTE_URL_MAX: usize = 44;

pub(super) fn draw(frame: &mut Frame, app: &mut App) {
    let [panes, footer_row] =
        Layout::vertical([Constraint::Min(2), Constraint::Length(1)]).areas(frame.area());
    let [top, bottom] =
        Layout::vertical([Constraint::Percentage(40), Constraint::Percentage(60)]).areas(panes);

    // Which of the two panes a typed filter is going into. Only one at a time,
    // and it is the pane's own title that shows it, so `/` and `ctrl-f` can
    // never be confused for each other.
    let (edit_top, edit_bot) = (
        app.editing == Some(Pane::Top),
        app.editing == Some(Pane::Bottom),
    );

    match app.level {
        // Repos on top, the selected repo's branches below.
        Level::Repos => {
            let labels = stops(&repos::SCOPES, repos::Scope::label);
            let scope = Some((labels.as_slice(), app.rsel.scope));
            let items = repo_items(app);
            let top_title = title("repos", scope, &app.rsel, false, Pane::Top, edit_top, true);
            list(frame, top, items, top_title, true, &mut app.rsel);

            let items = branch_items(app);
            let slow = app.bfeed.slow();
            let bot_title = title(
                "branches",
                None,
                &app.bsel,
                slow,
                Pane::Bottom,
                edit_bot,
                true,
            );
            list(frame, bottom, items, bot_title, true, &mut app.bsel);
        }

        // Remotes on top, the selected remote's branches below.
        Level::Remotes => {
            let items = remote_items(app);
            let top_title = title("remotes", None, &app.msel, false, Pane::Top, edit_top, true);
            list(frame, top, items, top_title, true, &mut app.msel);

            let items = branch_items(app);
            let slow = app.bfeed.slow();
            let name = branches_label(app);
            let bot_title = title(&name, None, &app.bsel, slow, Pane::Bottom, edit_bot, true);
            list(frame, bottom, items, bot_title, true, &mut app.bsel);
        }

        // Branches on top, the selected branch's commits below.
        Level::Branches => {
            let labels = stops(&branches::SCOPES, branches::Scope::label);
            let scope = (!app.remote_branches()).then_some((labels.as_slice(), app.bsel.scope));
            let items = branch_items(app);
            let slow = app.bfeed.slow();
            let name = branches_label(app);
            let top_title = title(&name, scope, &app.bsel, slow, Pane::Top, edit_top, true);
            list(frame, top, items, top_title, true, &mut app.bsel);

            let items = commit_items(app, bottom.width);
            let slow = app.cfeed.slow();
            let bot_title = title(
                "commits",
                None,
                &app.csel,
                slow,
                Pane::Bottom,
                edit_bot,
                true,
            );
            list(frame, bottom, items, bot_title, true, &mut app.csel);
        }

        // Tags on top, the commits each one added below.
        Level::Tags => {
            let labels = stops(&tags::SCOPES, tags::Scope::label);
            let scope = Some((labels.as_slice(), app.tsel.scope));
            let items = tag_items(app);
            let slow = app.rfeed.slow();
            let (name, status) = tags_label(app);
            let mut top_title = title(&name, scope, &app.tsel, slow, Pane::Top, edit_top, true);
            // What the remote is up to changes while you look, so it goes after
            // everything else and never shifts the tabs along.
            if let Some(status) = status {
                let at = top_title.spans.len() - 1;
                let dim = Style::default().add_modifier(Modifier::DIM);
                top_title
                    .spans
                    .insert(at, Span::styled(format!("   {status}"), dim));
            }
            list(frame, top, items, top_title, true, &mut app.tsel);

            let items = commit_items(app, bottom.width);
            // A tag only the remote has names a commit this clone may not have,
            // and "(none)" would read as a tag with nothing in it.
            let unfetched = app.csel.is_empty()
                && !app.cfeed.loading
                && app
                    .tsel
                    .idx()
                    .is_some_and(|i| app.tags[i].state == TagState::Remote);
            let name = if unfetched {
                "commits · not in this clone until a fetch".to_string()
            } else {
                app.range_label()
            };
            let slow = app.cfeed.slow();
            let bot_title = title(&name, None, &app.csel, slow, Pane::Bottom, edit_bot, true);
            list(frame, bottom, items, bot_title, true, &mut app.csel);
        }

        // Commits on top, the selected commit's files below.
        Level::Commits => {
            let labels = stops(&commits::SCOPES, commits::Scope::label);
            let scope = (!app.stashes).then_some((labels.as_slice(), app.csel.scope));
            let items = commit_items(app, top.width);
            let slow = app.cfeed.slow();
            let top_title = title(
                &commits_label(app),
                scope,
                &app.csel,
                slow,
                Pane::Top,
                edit_top,
                true,
            );
            list(frame, top, items, top_title, true, &mut app.csel);

            let items = file_items(app);
            let slow = app.ffeed.slow();
            let bot_title = title("files", None, &app.fsel, slow, Pane::Bottom, edit_bot, true);
            list(frame, bottom, items, bot_title, true, &mut app.fsel);
        }

        // The commit list stays up as context; the diff takes the bottom pane.
        Level::Diff => {
            let labels = stops(&commits::SCOPES, commits::Scope::label);
            let scope = (!app.stashes).then_some((labels.as_slice(), app.csel.scope));
            let items = commit_items(app, top.width);
            let slow = app.cfeed.slow();
            let top_title = title(
                &commits_label(app),
                scope,
                &app.csel,
                slow,
                Pane::Top,
                false,
                false,
            );
            list(frame, top, items, top_title, false, &mut app.csel);
            app.diff_rows = bottom.height.saturating_sub(2).max(1);
            diff(frame, bottom, app);
        }
    }
    // Every letter but `?` goes into a filter being typed, so its footer offers
    // only keys that are not letters.
    let (mut keys, help): (Vec<&str>, _) = match app.editing {
        Some(_) => (FILTER_KEYS.to_vec(), HELP),
        None => (actions(app), HELP),
    };
    let job = app.repo_job.as_ref().map(|job| job.line());
    if let Some(job) = &job {
        keys.insert(0, job);
    }
    frame.render_widget(
        key_footer(
            &keys,
            app.note.as_ref(),
            app.command.as_ref(),
            Some(help),
            footer_row.width,
        ),
        footer_row,
    );

    if let Some(c) = &app.confirm
        && c.target.typed()
    {
        typed_popup(
            frame,
            panes,
            &c.target.title(),
            c.target.note().as_deref(),
            &c.target.name(),
            &c.typed,
            c.target.verb(),
        );
    } else if let Some(c) = &app.confirm {
        confirm_popup(
            frame,
            panes,
            c.target.colour(),
            &c.target.title(),
            &c.target.name(),
            c.target.note().as_deref(),
            c.yes,
        );
    }
    if let Some(f) = &app.form {
        f.form.draw(frame, panes);
    }
    if let Some(modal) = &mut app.modal {
        modal.draw(frame, panes);
    }
}

/// The footer's share of a level's keys: what it can *do*, in the house order
/// (`↵`, the level's own keys, `d del`, then `/ find · r refresh · q quit`), so
/// a narrow window loses the least used. Moving is left out, since motions are
/// tried rather than read, and `? help` lists everything, movement included.
fn actions(app: &App) -> Vec<&'static str> {
    let mut keys = vec![match app.level {
        Level::Commits => "↵ diff",
        Level::Diff => "↵ difftool",
        _ => "↵ open",
    }];
    let undo = |branch: bool| app.undo.as_ref().is_some_and(|u| u.branch == branch);
    let mut del = false;
    match app.level {
        Level::Repos => keys.extend(["s sync all", "S pull all"]),
        Level::Remotes => {
            if app.can_push() {
                keys.push("p push");
            }
            if app.remote().is_some() {
                keys.extend(["s sync", "S pull"]);
            }
        }
        Level::Branches => {
            keys.extend(["s sync", "S pull"]);
            if undo(true) {
                keys.push("u undo");
            }
            del = true;
        }
        Level::Tags => {
            if app.can_track() {
                keys.push("t track");
            }
            if undo(false) {
                keys.push("u undo");
            }
            del = true;
        }
        Level::Commits if app.stashes => {
            keys.extend(["a apply", "p pop"]);
            del = true;
        }
        _ => {}
    }
    keys.push("K inspect");
    if app.level == Level::Remotes {
        keys.push(CREATE);
        if app.remote().is_some() {
            keys.extend([EDIT, DEL]);
        }
    }
    if del {
        keys.push(DEL);
    }
    // the diff has no list of its own for `/` to narrow
    if app.level != Level::Diff {
        keys.push(FIND);
    }
    keys.extend([REFRESH, QUIT]);
    keys
}

/// The motions every level shares. The stash has no tabs to switch between,
/// so it gets the same group without `h/l`.
const MOVING: HelpSection = (
    "moving",
    &[
        (Y_MOVE, "move a row"),
        (X_MOVE, "the previous, next tab"),
        ("", "a held key speeds up"),
    ],
);
const MOVING_STASH: HelpSection = (
    "moving",
    &[(Y_MOVE, "move a row"), ("", "a held key speeds up")],
);
const BELOW: HelpSection = (
    "the pane below",
    &[(CTRL_Y_MOVE, "move in it"), ("ctrl-f", "find in it")],
);
const EVERYWHERE: HelpSection = (
    "every screen",
    &[
        ("↵", "open"),
        ("esc", "back"),
        ("/", "find"),
        ("K", "inspect the row"),
        ("r", "refresh"),
        (":", "a command (:q quits)"),
        ("?", "this help"),
        ("q", "quit"),
        ("ctrl-c", "quit, or esc in a box or a filter"),
    ],
);
const REPOS: HelpSection = (
    "repos",
    &[
        ("s", "sync every repo (fetch, prune)"),
        ("S", "sync and pull"),
    ],
);
const REMOTES: HelpSection = (
    "remotes",
    &[
        ("↵", "its branches"),
        ("p", "push this branch there, never forcing"),
        ("s", "sync it (fetch, prune)"),
        ("S", "sync, then fast-forward this branch to it"),
        ("c", "add a remote"),
        ("e", "change its name or URL"),
        ("d", "remove it from this clone, asking first"),
        ("", "↑↓ on a remote: this branch against its copy there"),
        (
            "",
            "↑↓ on its branches: the local branch tracking it, · if none",
        ),
    ],
);
const IN_A_FORM: HelpSection = (
    "in a form",
    &[
        ("type", "fill the field"),
        ("tab shift-tab", "the next, previous field"),
        (CTRL_Y_MOVE, "the next, previous field"),
        ("↵", "the next field, or submit on the last"),
        ("esc", "cancel"),
    ],
);
const BRANCHES: HelpSection = (
    "branches",
    &[
        ("s", "sync (fetch, prune)"),
        ("S", "sync and pull this one"),
        ("d", "delete, asking first"),
        ("u", "put back the last delete"),
    ],
);
const TAGS: HelpSection = (
    "tags",
    &[
        ("t", "keep a copy of the remote's tags"),
        ("d", "delete"),
        ("u", "put back the last delete"),
    ],
);
const COMMITS: HelpSection = ("commits", &[("↵", "the selected file's diff")]);
const STASHES: HelpSection = (
    "stashes",
    &[
        ("↵", "the selected file's diff"),
        ("a", "apply"),
        ("p", "pop"),
        ("d", "delete, asking its name first"),
    ],
);
const DIFF: HelpSection = (
    "diff",
    &[
        ("↵", "git difftool"),
        (CTRL_Y_MOVE, "scroll"),
        (CTRL_X_MOVE, "pan"),
    ],
);
const IN_A_BOX: HelpSection = (
    "in a box",
    &[
        ("y n", "answer"),
        (X_MOVE, "pick"),
        ("↵", "select"),
        (Y_MOVE, "scroll a long one"),
        ("esc", "cancel, or close a long one"),
    ],
);
const IN_A_FIND: HelpSection = (
    "in a find",
    &[
        ("type", "filter"),
        ("↵", "keep"),
        ("esc", "back"),
        ("?", "help"),
    ],
);
const IN_THIS_HELP: HelpSection = (
    "in this help",
    &[
        (Y_MOVE, "scroll"),
        ("ctrl-d ctrl-u", "half a page down, up"),
        ("g G", "the top, the bottom"),
        ("esc q ?", "close"),
    ],
);

/// Every key the app answers to, grouped by screen, for the reader `?` opens:
/// the keys every level shares, then each level this app can reach from where
/// it was entered, so `ilog` does not list the repos it never shows. The panel
/// scrolls, so a new row costs nothing but its line.
fn help(app: &App) -> Vec<HelpSection> {
    let moving = match app.stashes {
        true => MOVING_STASH,
        false => MOVING,
    };
    let mut sections = vec![moving, BELOW, EVERYWHERE];
    let reaches = |level: Level| match level {
        Level::Tags | Level::Remotes => app.start == level,
        Level::Repos => app.start == Level::Repos,
        Level::Commits => !app.stashes,
        level => app.start <= level,
    };
    if reaches(Level::Repos) {
        sections.push(REPOS);
    }
    if reaches(Level::Remotes) {
        sections.push(REMOTES);
    }
    if reaches(Level::Branches) {
        sections.push(BRANCHES);
    }
    if reaches(Level::Tags) {
        sections.push(TAGS);
    }
    if reaches(Level::Commits) {
        sections.push(COMMITS);
    }
    if app.stashes {
        sections.push(STASHES);
    }
    sections.extend([DIFF, IN_A_BOX]);
    if reaches(Level::Remotes) {
        sections.push(IN_A_FORM);
    }
    sections.extend([IN_A_FIND, IN_THIS_HELP]);
    sections
}

/// Render one list pane with its scrollbar.
fn list(
    frame: &mut Frame,
    area: Rect,
    items: Vec<ListItem<'static>>,
    title: Line<'static>,
    active: bool,
    sel: &mut Sel,
) {
    let widget = List::new(items)
        .block(pane_block(title, active))
        .highlight_style(Style::default().add_modifier(Modifier::REVERSED))
        .highlight_symbol("› ");
    frame.render_stateful_widget(widget, area, &mut sel.state);
    list_scrollbar(frame, area, sel.len(), sel.state.offset());
}

/// Render the diff pane.
fn diff(frame: &mut Frame, area: Rect, app: &App) {
    let title = format!(" {} ", app.file_path().unwrap_or(""));
    // An empty diff and one still being highlighted look identical, so say
    // which it is once the load has run long enough to be noticed.
    let body = if app.diff.lines.is_empty() && app.dfeed.slow() {
        Text::from(Line::from(Span::styled(
            "  loading…",
            Style::default().add_modifier(Modifier::DIM),
        )))
    } else {
        app.diff.clone()
    };
    let view = Paragraph::new(body)
        .block(pane_block(title, true))
        .scroll((app.diff_scroll, 0));
    frame.render_widget(view, area);
    diff_scrollbar(frame, area, app.diff.lines.len(), app.diff_scroll);
    let cell = app.prepared.cell_width(area.width.saturating_sub(2));
    diff_hscrollbar(frame, area, app.prepared.max_line(), cell, app.diff_hscroll);
}

/// `" <name>  <scope tabs>  <i>/<n>   <filter> "`, the title every pane wears. A pane
/// still being streamed into says so with a trailing `…`, so a list that is
/// merely short is never mistaken for one that has finished arriving - but only
/// once the load has run long enough to be noticed, or every keypress on a fast
/// repo would blink it on and off.
fn title(
    name: &str,
    scope: Option<(&[&str], usize)>,
    sel: &Sel,
    loading: bool,
    pane: Pane,
    editing: bool,
    filterable: bool,
) -> Line<'static> {
    // Each tab carries a space either side, so the gaps around the tabs are one
    // narrower than the ones around a title without them.
    let mut spans = vec![Span::raw(format!(" {name} "))];
    if let Some((labels, picked)) = scope {
        spans.extend(scope_tabs(labels, picked));
    }
    spans.push(Span::raw(" "));
    let count = if sel.is_empty() {
        let body = if loading { "…" } else { "(none)" };
        body.to_string()
    } else {
        let dots = if loading { "…" } else { "" };
        format!("{}/{}{dots}", sel.cur + 1, sel.len())
    };
    spans.push(Span::raw(count));
    // The key that would open a filter on this pane sits where the filter will
    // show once typed, rather than in the footer, which cannot say which pane.
    spans.extend(sel.query.title_span(pane.sigil(), editing, filterable));
    spans.push(Span::raw(" "));
    Line::from(spans)
}

/// A level's scope stops by name, for its tabs.
fn stops<T: Copy>(scopes: &[T], label: fn(T) -> &'static str) -> Vec<&'static str> {
    scopes.iter().map(|&s| label(s)).collect()
}

/// The tags pane's name, which says what the marks are read against and so
/// never changes while it is open, and what that remote is doing, which does.
fn tags_label(app: &App) -> (String, Option<String>) {
    let name = match &app.tag_remote {
        Some(remote) => format!("tags vs {remote}"),
        None => "tags".to_string(),
    };
    let status = match &app.remote {
        None => Some("asking the remote…".to_string()),
        Some(RemoteTags::NoRemote) => Some("no remote".to_string()),
        Some(RemoteTags::Unreachable(_)) => Some("unreachable".to_string()),
        Some(RemoteTags::Answered { fresh: true, .. }) => None,
        // git's copy, shown while the remote is asked again, or kept because it
        // could not be.
        Some(RemoteTags::Answered { .. }) if app.rfeed.loading => Some("refreshing…".to_string()),
        Some(RemoteTags::Answered { .. }) => Some("as of last fetch".to_string()),
    };
    (name, status)
}

/// The branch list's name: whose branches they are under `iremote`.
fn branches_label(app: &App) -> String {
    match (app.remote_branches(), app.branch_remote.as_str()) {
        (true, "") => "branches".to_string(),
        (true, remote) => format!("{remote} branches"),
        (false, _) => "branches".to_string(),
    }
}

/// The commits pane names the paths it was filtered to, or the tag range it
/// holds.
fn commits_label(app: &App) -> String {
    if app.stashes {
        "stashes".to_string()
    } else if app.start == Level::Tags {
        app.range_label()
    } else if app.paths.is_empty() {
        "commits".to_string()
    } else {
        format!("commits · {}", app.paths.join(" "))
    }
}

// ── row renderers ───────────────────────────────────────────────────────────

fn repo_items(app: &App) -> Vec<ListItem<'static>> {
    let name_w = app
        .rsel
        .visible
        .iter()
        .map(|&i| app.repos[i].name.chars().count())
        .max()
        .unwrap_or(0)
        .clamp(1, REPO_NAME_MAX);
    let branch_w = app
        .rsel
        .visible
        .iter()
        .map(|&i| app.repos[i].branch.chars().count())
        .max()
        .unwrap_or(0)
        .min(24);
    // Pad the state column so the origins line up in one readable column.
    let state_w = app
        .rsel
        .visible
        .iter()
        .map(|&i| state_width(&app.repos[i]))
        .max()
        .unwrap_or(0);
    app.rsel
        .visible
        .iter()
        .map(|&i| repo_item(&app.repos[i], name_w, branch_w, state_w))
        .collect()
}

/// Printed width of a repo's state flags, for padding the column.
fn state_width(r: &RepoStatus) -> usize {
    state_spans(r)
        .iter()
        .map(|s| s.content.chars().count())
        .sum()
}

/// `✚2 ↑1 ↓3` when there is something to report, else the clean marker.
fn state_spans(r: &RepoStatus) -> Vec<Span<'static>> {
    if !r.needs_attention() {
        return if r.has_upstream {
            vec![Span::styled("✓ clean", Style::default().fg(Color::Green))]
        } else {
            vec![Span::styled(
                "✓ clean (no upstream)",
                Style::default().add_modifier(Modifier::DIM),
            )]
        };
    }
    let mut spans = Vec::new();
    if r.dirty > 0 {
        spans.push(Span::styled(
            format!("✚{}", r.dirty),
            Style::default().fg(Color::Yellow),
        ));
    }
    if r.ahead > 0 {
        spans.push(Span::styled(
            format!("↑{}", r.ahead),
            Style::default().fg(Color::Green),
        ));
    }
    if r.behind > 0 {
        spans.push(Span::styled(
            format!("↓{}", r.behind),
            Style::default().fg(Color::Red),
        ));
    }
    // One space between flags, kept inside the spans so the width math is the
    // same arithmetic the renderer does.
    let last = spans.len().saturating_sub(1);
    for (i, span) in spans.iter_mut().enumerate() {
        if i != last {
            *span = Span::styled(format!("{} ", span.content), span.style);
        }
    }
    spans
}

/// Name, current branch, the same state flags `slu repos` prints, and where the
/// repo came from.
fn repo_item(r: &RepoStatus, name_w: usize, branch_w: usize, state_w: usize) -> ListItem<'static> {
    let mut spans = vec![
        Span::styled(
            format!("  {:<name_w$}", truncate(&r.name, name_w)),
            Style::default().add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  {:<branch_w$}", truncate(&r.branch, branch_w)),
            Style::default().fg(Color::Cyan),
        ),
        Span::raw("  "),
    ];

    let state = state_spans(r);
    let pad = state_w.saturating_sub(state.iter().map(|s| s.content.chars().count()).sum());
    spans.extend(state);
    spans.push(Span::raw(" ".repeat(pad)));

    if !r.origin.is_empty() {
        spans.push(Span::styled(
            format!("  {}", truncate(&r.origin, ORIGIN_MAX)),
            Style::default().fg(Color::DarkGray),
        ));
    }
    ListItem::new(Line::from(spans))
}

fn branch_items(app: &App) -> Vec<ListItem<'static>> {
    if app.bsel.is_empty() && app.bfeed.slow() {
        return loading_body();
    }
    let remote = app.remote_branches();
    app.bsel
        .visible
        .iter()
        .map(|&i| {
            let b = &app.branches[i];
            // A remote's branch reads as the local one that tracks it, since
            // that is what a push or a pull would move.
            let local = remote
                .then(|| {
                    app.branches
                        .iter()
                        .find(|l| !l.remote && l.upstream == b.name)
                })
                .map(|l| l.map_or("·".to_string(), branches::Branch::status));
            branch_item(b, local)
        })
        .collect()
}

/// `local` stands in for a remote branch's empty push state: where the local
/// branch tracking it stands, or `·` when none does.
fn branch_item(b: &branches::Branch, local: Option<String>) -> ListItem<'static> {
    let name_style = if b.is_head {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else if b.remote {
        Style::default().fg(Color::Magenta)
    } else {
        Style::default().fg(Color::Cyan)
    };
    let (mark, mark_style) = branch_mark(b);
    let status = local.unwrap_or_else(|| b.status());
    let status_style = match status.as_str() {
        "·" | "synced" => Style::default().fg(Color::DarkGray),
        s if s.contains('↑') => Style::default().fg(Color::Yellow),
        _ => mark_style,
    };
    ListItem::new(Line::from(vec![
        Span::raw(if b.is_head { "● " } else { "  " }),
        cell(format!("{mark:<2}"), mark_style),
        Span::styled(
            format!("{:<NAME_W$}", truncate(&b.name, NAME_W)),
            name_style,
        ),
        cell(format!("  {status:<10}"), status_style),
        Span::styled(
            format!("  {:<14}", b.rel),
            Style::default().fg(Color::Magenta),
        ),
        Span::styled(format!("  {}", b.author), Style::default().fg(Color::Blue)),
    ]))
}

/// Quick-scan glyph: `↑` (unpushed/ahead, yellow), `⚑` (upstream gone, red),
/// nothing for a remote branch or an in-sync local one.
fn branch_mark(b: &branches::Branch) -> (&'static str, Style) {
    if b.remote {
        return ("", Style::default().fg(Color::DarkGray));
    }
    if b.track.contains("gone") {
        return ("⚑", Style::default().fg(Color::Red));
    }
    if b.unpushed() {
        return (
            "↑",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
    }
    ("", Style::default().fg(Color::DarkGray))
}

fn remote_items(app: &App) -> Vec<ListItem<'static>> {
    let width = |f: fn(&Remote) -> usize, cap: usize| {
        app.msel
            .visible
            .iter()
            .map(|&i| f(&app.remotes[i]))
            .max()
            .unwrap_or(0)
            .clamp(1, cap)
    };
    let name_w = width(|r| r.name.chars().count(), NAME_W);
    let url_w = width(|r| r.url.chars().count(), REMOTE_URL_MAX);
    app.msel
        .visible
        .iter()
        .map(|&i| remote_item(&app.remotes[i], app.head.as_deref(), name_w, url_w))
        .collect()
}

/// Mark, name, where it lives, and the checked-out branch against its copy
/// there.
fn remote_item(r: &Remote, head: Option<&str>, name_w: usize, url_w: usize) -> ListItem<'static> {
    let ahead = r.ahead_behind.is_some_and(|(a, _)| a > 0);
    let mark = if ahead {
        cell(
            "↑ ".to_string(),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )
    } else {
        Span::raw("  ")
    };
    let mut spans = vec![
        Span::raw("  "),
        mark,
        Span::styled(
            format!("{:<name_w$}", truncate(&r.name, name_w)),
            Style::default().fg(Color::Cyan),
        ),
        Span::styled(
            format!("  {:<url_w$}", truncate(&r.url, url_w)),
            Style::default().fg(Color::DarkGray),
        ),
    ];
    let Some(branch) = head else {
        return ListItem::new(Line::from(spans));
    };
    spans.push(Span::styled(
        format!("  {branch} "),
        Style::default().fg(Color::Green),
    ));
    match r.ahead_behind {
        None => spans.push(Span::styled(
            format!("not on {}", r.name),
            Style::default().add_modifier(Modifier::DIM),
        )),
        Some((0, 0)) => spans.push(Span::styled(
            "in sync",
            Style::default().add_modifier(Modifier::DIM),
        )),
        Some((a, b)) => {
            if a > 0 {
                spans.push(Span::styled(
                    format!("↑{a} "),
                    Style::default().fg(Color::Green),
                ));
            }
            if b > 0 {
                spans.push(Span::styled(
                    format!("↓{b}"),
                    Style::default().fg(Color::Red),
                ));
            }
        }
    }
    ListItem::new(Line::from(spans))
}

fn tag_items(app: &App) -> Vec<ListItem<'static>> {
    let name_w = app
        .tsel
        .visible
        .iter()
        .map(|&i| app.tags[i].name.chars().count())
        .max()
        .unwrap_or(0)
        .clamp(1, NAME_W);
    let asking = app.remote.is_none();
    app.tsel
        .visible
        .iter()
        .map(|&i| tag_item(&app.tags[i], name_w, asking))
        .collect()
}

/// Mark, name, date, where it stands, its kind, and its message. A tag only the
/// remote has has no date or message here to show.
fn tag_item(t: &Tag, name_w: usize, asking: bool) -> ListItem<'static> {
    let (mark, mark_style) = tag_mark(t.state);
    let name_color = if t.state == TagState::Remote {
        Color::Magenta
    } else {
        Color::Cyan
    };
    let kind = if t.annotated {
        "annotated"
    } else {
        "lightweight"
    };
    ListItem::new(Line::from(vec![
        Span::raw("  "),
        cell(format!("{mark:<2}"), mark_style),
        Span::styled(
            format!("{:<name_w$}", truncate(&t.name, name_w)),
            Style::default().fg(name_color),
        ),
        cell(
            format!("  {:<16}", t.date),
            Style::default().fg(Color::Green),
        ),
        state_cell(t.state, asking, mark_style),
        Span::styled(
            format!("  {kind:<11}"),
            Style::default().add_modifier(Modifier::DIM),
        ),
        Span::raw(format!("  {}", t.subject)),
    ]))
}

/// Where a tag stands, or, while the remote is still being asked, that it is:
/// a blank there reads as "nothing to say" when the answer is simply not in.
fn state_cell(state: TagState, asking: bool, style: Style) -> Span<'static> {
    if asking && state == TagState::Unknown {
        return Span::styled(
            format!("  {:<11}", "checking…"),
            Style::default().add_modifier(Modifier::DIM),
        );
    }
    Span::styled(format!("  {:<11}", state.label()), style)
}

/// Quick-scan glyph: `↑` (not pushed, yellow), `⚑` (the two sides differ,
/// red), `↓` (only the remote has it, magenta), nothing once it is in step.
fn tag_mark(state: TagState) -> (&'static str, Style) {
    match state {
        TagState::Local => (
            "↑",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        TagState::Differs => ("⚑", Style::default().fg(Color::Red)),
        TagState::Remote => ("↓", Style::default().fg(Color::Magenta)),
        TagState::Pushed | TagState::Unknown => ("", Style::default().fg(Color::DarkGray)),
    }
}

/// The body of a pane with nothing in it yet. It is a whole row rather than a
/// mark on the border because a blank box reads as "there is nothing here",
/// which is the one thing it does not mean.
fn loading_body() -> Vec<ListItem<'static>> {
    vec![ListItem::new(Line::from(Span::styled(
        "  loading…",
        Style::default().add_modifier(Modifier::DIM),
    )))]
}

/// `width` is the pane's, which a row gives up two borders and the cursor to.
fn commit_items(app: &App, width: u16) -> Vec<ListItem<'static>> {
    if app.csel.is_empty() && app.cfeed.slow() {
        return loading_body();
    }
    let row = (width as usize).saturating_sub(4);
    app.csel
        .visible
        .iter()
        .map(|&i| {
            let c = &app.commits[i];
            commit_item(c, app.unpushed.contains(&c.hash), row)
        })
        .collect()
}

fn file_items(app: &App) -> Vec<ListItem<'static>> {
    if app.fsel.is_empty() && app.ffeed.slow() {
        return loading_body();
    }
    app.fsel
        .visible
        .iter()
        .map(|&i| file_item(&app.files[i]))
        .collect()
}

/// A padded column, without its colour when it holds nothing: the highlight
/// reverses each cell's colours, so a coloured blank comes out as a solid bar
/// on the selected row.
fn cell(text: String, style: Style) -> Span<'static> {
    if text.trim().is_empty() {
        Span::raw(text)
    } else {
        Span::styled(text, style)
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let kept: String = s.chars().take(max.saturating_sub(1)).collect();
    format!("{kept}…")
}

impl App {
    /// `?`: every key, in a reader over the panes.
    pub(super) fn help(&mut self) {
        self.modal = Some(Modal::help(&help(self)));
    }
}