ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
//! Conversations: issues and discussions.

use super::*;
use crate::api::browse::DiscussionComment;
use crate::api::edit::Reaction;
use crate::ui::page::ReviewLink;
use std::collections::HashSet;

/// What the comment boxes of a conversation share.
pub(super) struct Conversation<'a> {
    pub(super) base: LinkBase,
    /// Who opened it.
    pub(super) op: &'a str,
    pub(super) now: u64,
    /// Hidden comments (and long reviews) you unfolded, by their anchors.
    pub(super) unfolded: &'a HashSet<String>,
}

impl Conversation<'_> {
    /// A comment box: `╭─ author commented 3d ago ─── Author ─╮`, the
    /// Markdown body, its reactions, `╰──╯`. `verb` is "commented",
    /// "opened"...
    #[expect(clippy::too_many_arguments, reason = "the parts of a comment box")]
    pub(super) fn said(
        &self,
        page: &mut Page,
        author: &str,
        verb: &str,
        when: &str,
        body: &str,
        badge: bool,
        reactions: &[Reaction],
    ) {
        self.said_at(
            page,
            None,
            author,
            verb,
            when,
            body,
            badge.then(|| chip("Author", Bg::SecondaryContainer)),
            reactions,
        );
    }

    /// A comment box, named `anchor` for links to it, with `chip` on its
    /// right (Author, Answer).
    #[expect(clippy::too_many_arguments, reason = "the parts of a comment box")]
    pub(super) fn said_at(
        &self,
        page: &mut Page,
        anchor: Option<String>,
        author: &str,
        verb: &str,
        when: &str,
        body: &str,
        chip: Option<Seg>,
        reactions: &[Reaction],
    ) {
        if let Some(anchor) = anchor {
            page.anchor(anchor);
        }
        let start = page.lines.len();
        let who = login_seg(page, author, Role::Strong);
        let ago = time::ago_iso(when, self.now);
        let right = Vec::from_iter(chip);
        page.box_top(
            vec![who, Seg::new(format!(" {verb} {ago}"), Role::Meta)],
            right,
        );
        if body.trim().is_empty() {
            empty_row(page, "No description provided.");
        } else {
            markdown::render(page, body, Some(&self.base), Frame::Body);
        }
        reaction_chips(page, reactions);
        page.box_bottom();
        // The whole comment is a row: Enter quote-replies, as GitHub's `r` does.
        let quote = page.link(Link::Quote {
            author: author.to_owned(),
            at: when.to_owned(),
            body: body.to_owned(),
        });
        page.item(start, quote);
    }

    /// A comment, badged when it's `new` (it came in since you started
    /// looking), or else when it's by whoever opened the conversation.
    pub(super) fn comment(&self, page: &mut Page, c: &Comment, new: bool) {
        let anchor = c.id.map(|id| format!("issuecomment-{id}"));
        let badge = if new {
            Some(chip("New", Bg::TertiaryContainer))
        } else {
            (c.author == self.op).then(|| chip("Author", Bg::SecondaryContainer))
        };
        self.said_comment(page, anchor, c, "commented", badge);
    }

    /// A comment's box; a hidden one folded, as GitHub shows it, saying
    /// why, until it's unfolded (its anchor names it), and then saying
    /// it's hidden under it.
    pub(super) fn said_comment(
        &self,
        page: &mut Page,
        anchor: Option<String>,
        c: &Comment,
        verb: &str,
        badge: Option<Seg>,
    ) {
        let hidden = c.hiding.reason.as_deref().map(|r| match r.trim() {
            "" => "Hidden".to_owned(),
            r => format!("Hidden as {}", r.replace('_', "-").to_lowercase()),
        });
        let (Some(hidden), Some(anchor)) = (hidden, anchor.clone()) else {
            let reactions = c.editable.as_ref().map_or(&[][..], |e| &e.reactions);
            let (author, at, body) = (&c.author, &c.created_at, &c.body);
            self.said_at(page, anchor, author, verb, at, body, badge, reactions);
            return;
        };
        let fold = Link::Review(ReviewLink::Fold(anchor.clone()));
        if self.unfolded.contains(&anchor) {
            let reactions = c.editable.as_ref().map_or(&[][..], |e| &e.reactions);
            let (author, at, body) = (&c.author, &c.created_at, &c.body);
            self.said_at(page, Some(anchor), author, verb, at, body, badge, reactions);
            item(page, fold, |page, link| {
                let segs = vec![
                    Seg::linked(format!("▾ {hidden}"), Role::Link, link),
                    Seg::new(" · ↵ folds it", Role::Meta),
                ];
                page.add(Frame::None, 2, segs, Vec::new());
            });
            return;
        }
        page.anchor(anchor);
        item(page, fold, |page, link| {
            let who = login_seg(page, &c.author, Role::Strong);
            let ago = time::ago_iso(&c.created_at, self.now);
            page.box_top(
                vec![who, Seg::new(format!(" {verb} {ago}"), Role::Meta)],
                Vec::new(),
            );
            let segs = vec![
                Seg::linked(format!("▸ {hidden}"), Role::Link, link),
                Seg::new(" · ↵ shows it", Role::Meta),
            ];
            body(page, segs);
            page.box_bottom();
        });
    }
}

/// "Locked as off-topic".
pub(super) fn locked_said(locked: crate::api::manage::Locked) -> String {
    match locked.reason {
        Some(reason) => format!("Locked as {}", crate::api::manage::lock_said(reason)),
        None => "Locked".to_owned(),
    }
}

/// The reactions under a comment, as GitHub shows them: each one's emoji
/// and count, the ones you gave marked.
pub(super) fn reaction_chips(page: &mut Page, reactions: &[Reaction]) {
    if reactions.is_empty() {
        return;
    }
    let mut segs = Vec::new();
    for r in reactions {
        if !segs.is_empty() {
            segs.push(space());
        }
        let text = format!("{} {}", r.content.emoji(), r.count);
        segs.push(chip(text, crate::ui::chips::reaction_fill(r.mine)));
    }
    body(page, Vec::new());
    body(page, segs);
}

/// The line between timeline entries.
pub(super) fn connector(page: &mut Page) {
    page.add(Frame::None, 3, vec![Seg::new("│", Role::Meta)], Vec::new());
}

/// The comment box at the end of a conversation.
pub(super) fn add_comment(page: &mut Page, keys: Keys<'_>) {
    connector(page);
    item(page, Link::Comment, |page, link| {
        page.box_top(
            vec![Seg::linked("Add a comment", Role::Strong, link)],
            Vec::new(),
        );
        let press = format!(
            "Press {} to write a comment (Markdown; ctrl-e for $EDITOR)",
            keys.comment
        );
        body(page, vec![Seg::linked(press, Role::Meta, link)]);
        page.box_bottom();
    });
}

/// The sidebar's list of people; `more` says who else there may be.
pub(super) fn people(
    page: &mut Page,
    heading: &str,
    logins: &[String],
    more: Option<String>,
    none: &str,
) {
    aside_heading(page, heading);
    if logins.is_empty() && more.is_none() {
        page.wrapped(vec![Seg::new(none, Role::Meta)], 0, Frame::None);
    }
    for login in logins {
        let login = login_seg(page, login, Role::Link);
        page.wrapped(vec![login], 0, Frame::None);
    }
    if let Some(more) = more {
        page.wrapped(vec![Seg::new(more, Role::Meta)], 0, Frame::None);
    }
}

/// For people found in a conversation's comments, when its earlier ones
/// weren't loaded.
pub(super) fn maybe_others(earlier: bool) -> Option<String> {
    earlier.then(|| "and maybe others, earlier on GitHub".to_owned())
}

/// The sidebar's milestone, linked to its page.
pub(super) fn milestone_aside(page: &mut Page, repo: &RepoId, m: Option<&MilestoneRef>) {
    aside_heading(page, "Milestone");
    match m {
        Some(m) => {
            let target = format!("{}/milestone/{}", url::repo(repo), m.number);
            let title = link_seg(page, m.title.clone(), target, Role::Link);
            page.wrapped(vec![title], 0, Frame::None);
        }
        None => page.line(vec![Seg::new("No milestone", Role::Meta)]),
    }
}

pub(super) fn label_list(page: &mut Page, l: &Capped<Label>) {
    aside_heading(page, "Labels");
    if l.is_empty() {
        page.line(vec![Seg::new("None yet", Role::Meta)]);
    } else {
        let mut segs = Vec::new();
        labels(&mut segs, l);
        page.wrapped(segs, 0, Frame::None);
    }
}

pub fn issue(
    page: &mut Page,
    d: &IssueDetail,
    projects: Fetched<'_, Capped<crate::api::project::InProject>>,
    marks: Marks<'_>,
    cx: PageCtx<'_>,
) {
    let PageCtx { icons, keys, now } = cx;
    let participants = unique(std::iter::once(&d.author).chain(d.comments().map(|c| &c.author)));
    let aside = page.build_aside(|a| {
        people(
            a,
            "Assignees",
            &d.assignees,
            (d.assignees.left_out() > 0)
                .then(|| left_out_text(d.assignees.left_out(), "more", "more")),
            "No one assigned",
        );
        label_list(a, &d.labels);
        milestone_aside(a, &d.repo, d.milestone.as_ref());
        timeline::relations_aside(a, icons, d);
        timeline::projects_aside(a, projects);
        let earlier = d.timeline.left_out() > 0;
        people(a, "Participants", &participants, maybe_others(earlier), "");
    });
    page.wrapped(
        vec![
            Seg::new(d.title.clone(), Role::Title),
            Seg::new(format!("  #{}", d.number), Role::Meta),
        ],
        0,
        Frame::None,
    );
    let author = login_seg(page, &d.author, Role::Strong);
    let mut segs = vec![
        state_chip(Status::Issue(d.state), icons),
        Seg::new("  ", Role::Body),
        author,
        Seg::new(
            format!(
                " opened this issue {} · {}",
                time::ago_iso(&d.created_at, now),
                plural(d.comment_count, "comment")
            ),
            Role::Meta,
        ),
    ];
    if d.pinned {
        segs.push(Seg::new("  ", Role::Body));
        segs.push(chip("Pinned", Bg::SecondaryContainer));
    }
    if let Some(locked) = d.locked {
        segs.push(Seg::new("  ", Role::Body));
        segs.push(chip(locked_said(locked), Bg::TertiaryContainer));
    }
    if !aside {
        labels(&mut segs, &d.labels);
        if let Some(m) = &d.milestone {
            let target = format!("{}/milestone/{}", url::repo(&d.repo), m.number);
            segs.push(Seg::new("  ", Role::Meta));
            segs.push(link_seg(page, format!("◷ {}", m.title), target, Role::Link));
        }
    }
    page.wrapped(segs, 0, Frame::None);
    if aside || d.assignees.is_empty() {
        page.rule(0, Frame::None);
    }
    if !aside && !d.assignees.is_empty() {
        let mut segs = vec![Seg::new("Assignees: ", Role::Meta)];
        for (i, a) in d.assignees.iter().enumerate() {
            if i > 0 {
                segs.push(Seg::new(", ", Role::Meta));
            }
            segs.push(login_seg(page, a, Role::Link));
        }
        more_chips(&mut segs, &d.assignees);
        page.line(segs);
    }
    if !aside {
        timeline::relations_inline(page, icons, d);
        timeline::projects_inline(page, projects);
    }
    let talk = Conversation {
        base: LinkBase::new(&d.repo, "HEAD", ""),
        op: &d.author,
        now,
        unfolded: marks.unfolded,
    };
    let reactions = &d.editable.reactions;
    talk.said(
        page,
        &d.author,
        "opened",
        &d.created_at,
        &d.body,
        true,
        reactions,
    );
    earlier_here(page, &d.timeline, "comment or event", "comments and events");
    let place = timeline::Place {
        repo: &d.repo,
        pr: None,
        threads: &[],
        icons,
    };
    timeline::entries(page, &talk, &place, &d.timeline, marks);
    add_comment(page, keys);
}

/// A list of discussions: the categories to filter by (`base` is the
/// list's URL), then the discussions, most recently updated first.
pub fn discussions(
    page: &mut Page,
    base: &str,
    list: Fetched<'_, DiscussionList>,
    category: Option<&str>,
    now: u64,
) {
    let Some(l) = list.show(page, "discussions") else {
        return;
    };
    if !l.categories.is_empty() {
        let mut segs = Vec::new();
        let all = category.is_none();
        segs.push(link_seg(
            page,
            "All",
            base.to_owned(),
            if all { Role::Strong } else { Role::Link },
        ));
        for c in &l.categories {
            segs.push(Seg::new(" · ", Role::Meta));
            let target = format!("{base}/categories/{}", c.slug);
            let role = if category == Some(c.slug.as_str()) {
                Role::Strong
            } else {
                Role::Link
            };
            segs.push(link_seg(page, c.name.clone(), target, role));
        }
        more_chips(&mut segs, &l.categories);
        page.wrapped(segs, 0, Frame::None);
        page.blank();
    }
    let r = &l.results;
    let title = vec![Seg::new(
        format!("Discussions  {}", count_of(r)),
        Role::Strong,
    )];
    list_box(
        page,
        title,
        Vec::new(),
        r,
        "No discussions yet.",
        |page, d| {
            item(page, format!("{base}/{}", d.number), |page, link| {
                let mut segs = vec![Seg::linked(d.title.clone(), Role::Strong, link)];
                if d.answered {
                    segs.push(space());
                    segs.push(chip("✓ Answered", Bg::SuccessContainer));
                }
                body(page, segs);
                let meta = format!(
                    "#{} · {} · {} · {} · ▲ {} · updated {}",
                    d.number,
                    d.category,
                    d.author,
                    plural(d.comments, "comment"),
                    d.upvotes,
                    time::ago_iso(&d.updated_at, now)
                );
                body(page, vec![Seg::new(meta, Role::Meta)]);
            });
        },
    );
}

/// A discussion: its post, the answer at the top as GitHub shows it, then
/// its comments (the answer marked) with their replies, each named for
/// links to it (`#discussioncomment-…`), and the box to write in. Those
/// in `fresh` (by GitHub's number) came in since you started looking.
pub fn discussion(
    page: &mut Page,
    d: &DiscussionDetail,
    fresh: &HashSet<u64>,
    unfolded: &HashSet<String>,
    cx: PageCtx<'_>,
) {
    page.wrapped(
        vec![
            Seg::new(d.title.clone(), Role::Title),
            Seg::new(format!("  #{}", d.number), Role::Meta),
        ],
        0,
        Frame::None,
    );
    let mut segs = vec![chip(d.category.clone(), Bg::SecondaryContainer)];
    if d.answered {
        segs.push(space());
        segs.push(chip("✓ Answered", Bg::SuccessContainer));
    }
    match d.closed {
        Some(Some(reason)) => {
            segs.push(space());
            let said = format!("Closed as {}", reason.said());
            segs.push(chip(said, Bg::ContainerHigh));
        }
        Some(None) => {
            segs.push(space());
            segs.push(chip("Closed", Bg::ContainerHigh));
        }
        None => {}
    }
    if let Some(locked) = d.locked {
        segs.push(space());
        segs.push(chip(locked_said(locked), Bg::TertiaryContainer));
    }
    segs.push(Seg::new(
        format!(
            "  ▲ {} · {}",
            d.upvotes,
            plural(d.comments.total(), "comment")
        ),
        Role::Meta,
    ));
    page.wrapped(segs, 0, Frame::None);
    page.rule(0, Frame::None);
    let talk = Conversation {
        base: LinkBase::new(&d.repo, "HEAD", ""),
        op: &d.author,
        now: cx.now,
        unfolded,
    };
    talk.said(
        page,
        &d.author,
        "started",
        &d.created_at,
        &d.body,
        true,
        &d.editable.reactions,
    );
    let anchor = |c: &Comment| c.id.map(|id| format!("discussioncomment-{id}"));
    let new = |c: &Comment| c.id.is_some_and(|id| fresh.contains(&id));
    let comment = |page: &mut Page, c: &DiscussionComment, anchored: bool| {
        let badge = if new(&c.comment) && anchored {
            Some(chip("New", Bg::TertiaryContainer))
        } else if c.answer {
            Some(chip("✓ Answer", Bg::SuccessContainer))
        } else {
            (c.comment.author == d.author).then(|| chip("Author", Bg::SecondaryContainer))
        };
        let verb = if d.answerable {
            "answered"
        } else {
            "commented"
        };
        let said = &c.comment;
        let verb = format!("{verb} · ▲ {}", c.upvotes);
        let anchor = anchored.then(|| anchor(said)).flatten();
        talk.said_comment(page, anchor, said, &verb, badge);
    };
    // The answer, at the top; it's in its place below too.
    if let Some(answer) = &d.answer {
        connector(page);
        let mut segs = vec![Seg::new("✓ ", Role::Success)];
        match &d.answer_by {
            Some(by) => {
                segs.push(Seg::new("Answer selected by ", Role::Meta));
                segs.push(login_seg(page, by, Role::Strong));
            }
            None => segs.push(Seg::new("Answer selected", Role::Meta)),
        }
        page.add(Frame::None, 2, segs, Vec::new());
        comment(page, answer, false);
    }
    for c in &d.comments {
        connector(page);
        comment(page, c, true);
        for r in &c.replies {
            let badge = if new(r) {
                Some(chip("New", Bg::TertiaryContainer))
            } else {
                (r.author == d.author).then(|| chip("Author", Bg::SecondaryContainer))
            };
            talk.said_comment(page, anchor(r), r, "replied", badge);
        }
        more_here(page, &c.replies, "reply", "replies");
    }
    more_here(page, &d.comments, "comment", "comments");
    // Where to write: an answer, in a category that takes them.
    connector(page);
    let (title, what) = if d.answerable {
        ("Write an answer", "an answer")
    } else {
        ("Add a comment", "a comment")
    };
    item(page, Link::Comment, |page, link| {
        page.box_top(vec![Seg::linked(title, Role::Strong, link)], Vec::new());
        let keys = cx.keys;
        let mut press = format!(
            "Press {} to write {what}, or on a comment to reply in its thread",
            keys.comment
        );
        if d.locked.is_some() {
            press.push_str(" (it's locked: only those with write access can)");
        }
        body(page, vec![Seg::linked(press, Role::Meta, link)]);
        page.box_bottom();
    });
}