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
//! Pages the website has beyond code and conversations: a repository's
//! Insights (contributors and commit activity, counted with git; traffic;
//! the dependency graph), Explore and topics, starred lists, packages;
//! and saved replies for the comment composer.
//!
//! They're one [`Route::Site`](crate::route::Route::Site): this module
//! says what each is (its URL, title, needs and how it's built), and its
//! submodules how it's changed.

#[cfg(test)]
pub(crate) mod fixtures;
pub mod insights;
pub mod lists;
pub mod packages;
pub mod replies;

use crate::api::browse::SearchKind;
use crate::api::explore::{Since, Topic};
use crate::api::lists::ListPage;
use crate::api::model::RepoId;
use crate::api::packages::{Kind, PackageRef, PackagesOf};
use crate::route::{Family, Route, Target, app, code, people};
use crate::ui::pages::url as links;

use crate::browse::{Build, Width};
use crate::chrome::{Chrome, Section};
use crate::data::DataKey;
use crate::state::State;
use crate::ui::pages::{InsightsTab, ProfileTab};

/// One of these pages.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Page {
    /// A repository's Insights, at a tab.
    Insights { repo: RepoId, tab: InsightsTab },
    /// New repositories, most starred (the nearest the API comes to
    /// Trending), in a language if given, and GitHub's featured topics.
    Explore {
        language: Option<String>,
        since: Since,
    },
    /// A topic and its repositories.
    Topic(String),
    /// One of someone's starred lists.
    StarList { login: String, slug: String },
    /// An owner's packages, or a repository's.
    Packages(PackagesOf),
    /// A package and its versions, at one of them (else its newest).
    Package {
        at: PackageRef,
        version: Option<u64>,
    },
}

impl Family for Page {
    fn url(&self) -> String {
        match self {
            Page::Insights { repo, tab } => links::insights(repo, *tab),
            Page::Explore { language, since } => links::explore(language.as_deref(), *since),
            Page::Topic(name) => links::topic(name),
            Page::StarList { login, slug } => links::star_list(login, slug),
            Page::Packages(of) => links::packages(of),
            Page::Package { at, version } => links::package(at, *version),
        }
    }

    fn title(&self) -> String {
        match self {
            Page::Insights { repo, tab } => format!("{repo} · {}", tab.name()),
            Page::Explore { language: None, .. } => "Explore".to_owned(),
            Page::Explore {
                language: Some(l), ..
            } => format!("Explore · {l}"),
            Page::Topic(name) => format!("Topic: {name}"),
            Page::StarList { login, slug } => format!("@{login}'s list {slug}"),
            Page::Packages(PackagesOf::Owner(login)) => format!("@{login} · Packages"),
            Page::Packages(PackagesOf::Repo(repo)) => format!("{repo} · Packages"),
            Page::Package { at, .. } => format!("Package {}", at.name),
        }
    }

    fn repo(&self) -> Option<&RepoId> {
        match self {
            Page::Insights { repo, .. } | Page::Packages(PackagesOf::Repo(repo)) => Some(repo),
            _ => None,
        }
    }

    fn up(&self, _: &State) -> Option<Route> {
        Some(match self {
            Page::Insights { repo, .. } | Page::Packages(PackagesOf::Repo(repo)) => {
                Route::Code(code::Repo(repo.clone()))
            }
            Page::Explore { .. } | Page::Topic(_) => Route::App(app::Home),
            Page::StarList { login, .. } => Route::People(people::User {
                login: login.clone(),
                tab: crate::ui::pages::ProfileTab::Stars,
            }),
            Page::Packages(PackagesOf::Owner(login)) => Route::user(login),
            Page::Package { at, version: None } => {
                Route::Site(Page::Packages(PackagesOf::Owner(at.owner.clone())))
            }
            Page::Package { at, .. } => Route::Site(Page::Package {
                at: at.clone(),
                version: None,
            }),
        })
    }

    /// Explore's search is from a day, today.
    fn paged(&self) -> Option<DataKey> {
        Some(match self {
            Page::Explore { language, since } => DataKey::Search(
                SearchKind::Repos,
                crate::api::explore::new_and_starred(
                    language.as_deref(),
                    *since,
                    crate::store::now(),
                ),
            ),
            Page::Topic(name) => {
                DataKey::Search(SearchKind::Repos, crate::api::explore::topic_repos(name))
            }
            Page::StarList { login, slug } => DataKey::StarList(login.to_lowercase(), slug.clone()),
            Page::Package { at, .. } => DataKey::Package(at.clone()),
            _ => return None,
        })
    }

    fn needs(&self) -> Vec<DataKey> {
        let data = |key| key;
        let header = |repo: &RepoId| DataKey::Repo(repo.clone());
        let paged = self.paged();
        match self {
            Page::Insights { repo, tab } => {
                let own = match tab {
                    InsightsTab::Contributors | InsightsTab::Commits => {
                        DataKey::Activity(repo.clone())
                    }
                    InsightsTab::Traffic => DataKey::Traffic(repo.clone()),
                    InsightsTab::Dependencies => DataKey::Dependencies(repo.clone()),
                };
                vec![header(repo), data(own)]
            }
            Page::Explore { .. } => paged.into_iter().chain([data(DataKey::Featured)]).collect(),
            Page::Topic(name) => std::iter::once(data(DataKey::Topic(name.to_lowercase())))
                .chain(paged)
                .collect(),
            Page::StarList { login, .. } => {
                let profile = DataKey::Profile(login.to_lowercase());
                std::iter::once(profile).chain(paged).collect()
            }
            Page::Packages(of) => {
                let own = data(DataKey::Packages(of.clone()));
                match of {
                    PackagesOf::Repo(repo) => vec![header(repo), own],
                    PackagesOf::Owner(login) => {
                        vec![DataKey::Profile(login.to_lowercase()), own]
                    }
                }
            }
            Page::Package { .. } => paged.into_iter().collect(),
        }
    }

    fn width(&self) -> Width {
        Width::Lists
    }

    fn shown_source(&self) -> Option<DataKey> {
        match self {
            Page::Insights {
                repo,
                tab: InsightsTab::Contributors | InsightsTab::Commits,
            } => Some(DataKey::Activity(repo.clone())),
            _ => None,
        }
    }

    fn section(&self) -> Section {
        match self {
            Page::Insights { .. } => Section::Insights,
            _ => Section::Code,
        }
    }

    fn chrome(&self, state: &State, c: &mut Chrome) {
        let explore = || {
            Target::Page(Route::Site(Page::Explore {
                language: None,
                since: crate::api::explore::Since::default(),
            }))
        };
        let user = |login: &str| Some(Target::Page(Route::user(login)));
        match self {
            Page::Explore { .. } => c.crumb("Explore", None),
            Page::Topic(name) => {
                c.crumb("Explore", Some(explore()));
                c.crumb(&format!("#{name}"), None);
            }
            Page::StarList { login, .. } => {
                c.crumb(login, user(login));
                let stars = Route::People(people::User {
                    login: login.clone(),
                    tab: ProfileTab::Stars,
                });
                c.crumb("Stars", Some(Target::Page(stars)));
                let list = (self.paged())
                    .and_then(|k| state.picked::<ListPage>(&k))
                    .map_or_else(|| "List".to_owned(), |l| l.list.name.clone());
                c.crumb(&list, None);
            }
            Page::Packages(PackagesOf::Repo(repo)) => state.repo_chrome(repo, Section::Code, c),
            Page::Packages(of) => {
                let login = of.owner();
                c.crumb(login, None);
                state.profile_tabs(login, None, None, c);
                let here = Target::Page(Route::Site(self.clone()));
                c.active = c.tabs.iter().position(|(_, t)| *t == here);
            }
            Page::Package { at, .. } => {
                c.crumb(&at.owner, user(&at.owner));
                let list = Route::Site(Page::Packages(PackagesOf::Owner(at.owner.clone())));
                c.crumb("Packages", Some(Target::Page(list)));
                c.crumb(&at.name, None);
            }
            Page::Insights { repo, .. } => state.repo_chrome(repo, Section::Insights, c),
        }
    }

    fn build(&self, b: Build<'_>, page: &mut crate::ui::page::Page) {
        use crate::ui::pages;
        let now = b.cx.now;
        match self {
            Page::Insights { repo, tab } => {
                pages::insights_nav(page, repo, *tab);
                match tab {
                    InsightsTab::Contributors | InsightsTab::Commits => {
                        let key = DataKey::Activity(repo.clone());
                        let f = b.get(&key);
                        if let Some(a) = f.show(page, "the commits") {
                            if *tab == InsightsTab::Contributors {
                                pages::contributors(page, repo, a);
                            } else {
                                pages::commit_activity(page, a);
                            }
                        }
                    }
                    InsightsTab::Traffic => {
                        let key = DataKey::Traffic(repo.clone());
                        let f = b.get(&key);
                        if let Some(t) = f.show(page, "the traffic") {
                            pages::traffic(page, t);
                        }
                    }
                    InsightsTab::Dependencies => {
                        pages::dependents_note(page, repo);
                        let key = DataKey::Dependencies(repo.clone());
                        let f = b.get(&key);
                        if let Some(d) = f.show(page, "the dependency graph") {
                            pages::dependencies(page, d);
                        }
                    }
                }
            }
            Page::Explore { language, since } => {
                let topics = b.get(&DataKey::Featured);
                if let Some(key) = self.paged() {
                    let repos = b.get(&key);
                    pages::explore(page, language.as_deref(), *since, repos, topics, b.cx);
                }
            }
            Page::Topic(name) => {
                let topic = b.get::<Topic>(&DataKey::Topic(name.to_lowercase()));
                if let (Some(t), Some(key)) = (topic.show(page, "the topic"), self.paged()) {
                    let repos = b.get(&key);
                    pages::topic(page, t, repos, now);
                }
            }
            Page::StarList { login, .. } => {
                let Some(key) = self.paged() else {
                    return;
                };
                if let Some(l) = b.get(&key).show(page, "the list") {
                    pages::star_list(page, login, l, now);
                }
            }
            Page::Packages(of) => {
                let f = b.get(&DataKey::Packages(of.clone()));
                if let Some(list) = f.show(page, "the packages") {
                    pages::packages(page, of, list, now);
                }
            }
            Page::Package { at, version } => {
                let f = b.get(&DataKey::Package(at.clone()));
                if let Some(d) = f.show(page, "the package") {
                    let delete = b.state.first_key(crate::keymap::Action::DeleteComment);
                    pages::package(page, d, *version, &delete, now);
                }
            }
        }
    }
}

/// A language from a Trending URL.
fn language_of(slug: &str) -> String {
    slug.replace('-', " ")
}

/// The page a GitHub URL's path (`segments`) names, if it's one of these.
pub fn parse(segments: &[&str], param: impl Fn(&str) -> Option<String>) -> Option<Page> {
    let valid = crate::route::valid_login;
    let owner = |s: &str| RepoId::parse(&format!("{s}/x")).is_some();
    Some(match segments {
        ["explore"] | ["trending"] => Page::Explore {
            language: None,
            since: since(&param),
        },
        ["trending", language] => Page::Explore {
            language: Some(language_of(language)),
            since: since(&param),
        },
        ["topics"] => Page::Explore {
            language: None,
            since: Since::Daily,
        },
        ["topics", name] if valid_topic(name) => Page::Topic((*name).to_lowercase()),
        ["stars", login, "lists", slug] if valid(login) && !slug.is_empty() => Page::StarList {
            login: (*login).to_owned(),
            slug: (*slug).to_owned(),
        },
        ["orgs" | "users", login, "packages"] if valid(login) => {
            Page::Packages(PackagesOf::Owner((*login).to_owned()))
        }
        // A package's owner is as its repository's is: one a repository
        // path accepts.
        ["orgs" | "users", login, "packages", kind, "package", name] if owner(login) => {
            Page::Package {
                at: PackageRef {
                    owner: (*login).to_owned(),
                    kind: Kind::from_slug(kind)?,
                    name: (*name).to_owned(),
                },
                version: None,
            }
        }
        // One of its versions.
        ["orgs" | "users", login, "packages", kind, name, id] if owner(login) => Page::Package {
            at: PackageRef {
                owner: (*login).to_owned(),
                kind: Kind::from_slug(kind)?,
                name: (*name).to_owned(),
            },
            version: Some(id.parse().ok()?),
        },
        [login] if param("tab").as_deref() == Some("packages") && valid(login) => {
            Page::Packages(PackagesOf::Owner((*login).to_owned()))
        }
        [o, r, rest @ ..] if !crate::route::is_reserved(o) => {
            let repo = RepoId::parse(&format!("{o}/{r}"))?;
            let tab = |tab| Page::Insights {
                repo: repo.clone(),
                tab,
            };
            match rest {
                ["graphs", "contributors"] => tab(InsightsTab::Contributors),
                ["graphs", "commit-activity"] => tab(InsightsTab::Commits),
                ["graphs", "traffic"] => tab(InsightsTab::Traffic),
                ["network", "dependencies"] => tab(InsightsTab::Dependencies),
                ["packages"] => Page::Packages(PackagesOf::Repo(repo)),
                ["pkgs", kind, name] => Page::Package {
                    at: PackageRef {
                        owner: repo.owner,
                        kind: Kind::from_slug(kind)?,
                        name: (*name).to_owned(),
                    },
                    version: None,
                },
                _ => return None,
            }
        }
        _ => return None,
    })
}

fn since(param: &impl Fn(&str) -> Option<String>) -> Since {
    param("since")
        .and_then(|s| Since::from_slug(&s))
        .unwrap_or_default()
}

/// A topic's name, as GitHub allows them: lowercase letters, digits and
/// hyphens.
fn valid_topic(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 50
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '+' || c == '#')
}

#[cfg(test)]
pub(crate) fn arb() -> impl proptest::strategy::Strategy<Value = Route> {
    use crate::route::arb::{login, repo};
    use proptest::prelude::*;
    let package = (
        login(),
        prop::sample::select(Kind::ALL.to_vec()),
        "[a-z0-9][a-z0-9._-]{0,11}",
    )
        .prop_map(|(owner, kind, name)| PackageRef { owner, kind, name });
    let page = prop_oneof![
        (repo(), prop::sample::select(InsightsTab::ALL.to_vec()))
            .prop_map(|(repo, tab)| Page::Insights { repo, tab }),
        (
            prop::option::of("[a-z0-9+#]{1,10}"),
            prop::sample::select(Since::ALL.to_vec())
        )
            .prop_map(|(language, since)| Page::Explore { language, since }),
        "[a-z0-9][a-z0-9-]{0,15}".prop_map(Page::Topic),
        (login(), "[a-z0-9][a-z0-9-]{0,15}")
            .prop_map(|(login, slug)| Page::StarList { login, slug }),
        login().prop_map(|l| Page::Packages(PackagesOf::Owner(l))),
        repo().prop_map(|r| Page::Packages(PackagesOf::Repo(r))),
        (package, prop::option::of(1..u64::MAX))
            .prop_map(|(at, version)| Page::Package { at, version }),
    ];
    page.prop_map(Route::Site)
}

/// Answers to these pages' questions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Answer {
    DeleteList,
    /// Delete the version with this ID.
    DeleteVersion(u64),
}

impl Answer {
    pub fn busy(self) -> &'static str {
        match self {
            Answer::DeleteList => "Deleting the list…",
            Answer::DeleteVersion(_) => "Deleting the version…",
        }
    }
}

/// The question about `route` was answered.
#[must_use]
pub fn answer(
    state: &mut crate::state::State,
    route: &crate::route::Route,
    answer: Answer,
) -> Vec<crate::state::Cmd> {
    match answer {
        Answer::DeleteList => lists::delete(state, route),
        Answer::DeleteVersion(id) => packages::delete(state, route, id),
    }
}

/// These pages' pickers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pick {
    /// Your lists, for a repository.
    Lists(RepoId),
}

impl Pick {
    pub fn title(&self) -> &'static str {
        match self {
            Pick::Lists(_) => "Your lists",
        }
    }

    pub fn placeholder(&self) -> &'static str {
        match self {
            Pick::Lists(_) => "Filter, or type a new list's name · ↵ adds or takes out",
        }
    }

    pub fn need(&self) -> Option<DataKey> {
        match self {
            Pick::Lists(repo) => Some(DataKey::MyLists(repo.clone())),
        }
    }
}

pub fn rows(state: &crate::state::State, pick: &Pick, q: &str) -> crate::picker::Rows {
    match pick {
        Pick::Lists(repo) => lists::rows(state, repo, q),
    }
}

/// The menu's rows on these pages.
pub fn doables(
    state: &crate::state::State,
    route: &crate::route::Route,
    out: &mut Vec<crate::nav::Doable>,
) {
    lists::doables(state, route, out);
    packages::doables(state, route, out);
}

/// What the site's pages add: your starred lists, and deleting a list or
/// a package's version on its page.
pub const FEATURE: crate::features::Feature = crate::features::Feature {
    owns: &[crate::keymap::Action::Lists],
    takes: |state, action| {
        action == crate::keymap::Action::DeleteComment
            && matches!(
                state.route(),
                Some(crate::route::Route::Site(
                    Page::Package { .. } | Page::StarList { .. }
                ))
            )
    },
    act: |state, action| match action {
        crate::keymap::Action::Lists => lists::open(state),
        _ => ask_delete(state),
    },
    offers: |state, out| {
        if let Some(route) = state.route() {
            doables(state, route, out);
        }
        out.extend(lists::doable(state));
    },
    ..crate::features::Feature::NONE
};

/// `,D` here.
#[must_use]
pub fn ask_delete(state: &mut crate::state::State) -> Vec<crate::state::Cmd> {
    match state.route() {
        Some(crate::route::Route::Site(Page::StarList { .. })) => lists::ask_delete(state),
        _ => packages::ask_delete(state),
    }
}