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
//! Reading offline. There's no separate offline mode: a page shows what
//! the cache has first, and GitHub refreshes it, so when GitHub can't be
//! reached the page is simply the cache's, marked offline with its age,
//! and code comes from the clones. What's offline here:
//! - whether GitHub can be reached ([`crate::api::reach`]): the header
//!   says so, once, and requests fail at once instead of loading;
//! - writes that waited for it ([`queue`]): shown on their pages as
//!   queued, sent in order once it's back, a refused one kept;
//! - repositories kept to read offline ([`keep`]), fetched ahead.
//!
//! The Offline page (`:offline`, or the header's link) lists both.

pub mod keep;
mod page;
pub mod queue;

use crate::act::By;
use crate::api::ApiError;
use crate::api::change::Change;
use crate::api::model::PrRef;
use crate::keymap::Action;
use crate::route::{Dest, Route, app};
use crate::state::{Cmd as Do, Overlay, Screen, State, Timer};
use crate::ui::page::Link;

pub use page::{build, queued_here};

/// What the background says.
#[derive(Debug)]
pub enum Msg {
    /// GitHub became unreachable (since when), or reachable again.
    Reach(Option<u64>),
    /// A probe was answered (or wasn't).
    Probed(bool),
    Queue(queue::Told),
    /// The kept repositories, and how big the cache is.
    Kept(Vec<keep::Kept>, Option<u64>),
}

/// What's asked of the background.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cmd {
    /// Ask whether GitHub's there.
    Probe,
    Queue(queue::Op),
    Keep(keep::Op),
}

/// What the page knows of all that.
#[derive(Debug, Default)]
pub struct Offline {
    /// Since when GitHub has been unreachable, if it is.
    pub since: Option<u64>,
    /// The queued writes, as the queue said last.
    pub queue: Vec<queue::Entry>,
    /// The kept repositories, as the keeper said last.
    pub kept: Vec<keep::Kept>,
    /// How big the cache is.
    pub cache: Option<u64>,
    pub limits: keep::Limits,
    /// How long until the next probe (ms), while one's scheduled.
    probe: Option<u64>,
    /// The write thrown away last, to bring back.
    discarded: Option<queue::Entry>,
}

/// How soon GitHub is asked again after it went away, and the most.
const PROBE_FIRST: u64 = 2_000;
const PROBE_MOST: u64 = 30_000;

impl Offline {
    /// The writes still waiting (queued, or on their way).
    pub fn waiting(&self) -> usize {
        (self.queue.iter())
            .filter(|e| matches!(e.status, queue::Status::Queued | queue::Status::Sending))
            .count()
    }

    /// The writes GitHub didn't take, or that may not have reached it.
    pub fn unsent(&self) -> usize {
        self.queue.len() - self.waiting()
    }

    pub fn keeps(&self, repo: &crate::api::model::RepoId) -> Option<&keep::Kept> {
        self.kept.iter().find(|k| k.repo == *repo)
    }
}

#[must_use]
pub fn on_msg(state: &mut State, msg: Msg) -> Vec<Do> {
    // Pages show whether GitHub can be reached, the queue and what's
    // kept; not how often it's asked.
    if !matches!(msg, Msg::Probed(_)) {
        state.shown_gen += 1;
    }
    match msg {
        Msg::Reach(Some(since)) => {
            state.offline.since = Some(since);
            return schedule(state);
        }
        Msg::Reach(None) => {
            if state.offline.since.take().is_none() {
                return Vec::new();
            }
            state.info("GitHub is back");
            let mut cmds = vec![
                Do::Offline(Cmd::Queue(queue::Op::Flush)),
                Do::Offline(Cmd::Keep(keep::Op::Now)),
            ];
            cmds.extend(state.load_visible(false));
            return cmds;
        }
        Msg::Probed(true) => state.offline.probe = None,
        Msg::Probed(false) => {
            let off = &mut state.offline;
            let wait = off.probe.map_or(PROBE_FIRST, |w| (w * 2).min(PROBE_MOST));
            off.probe = Some(wait);
            if off.since.is_some() {
                return vec![Do::Timer(Timer::Probe, wait)];
            }
        }
        Msg::Queue(queue::Told::All(entries)) => state.offline.queue = entries,
        Msg::Queue(queue::Told::Taken(entry)) => {
            state.info(format!(
                "Sent to GitHub: {} on {}",
                entry.write.what(),
                entry.title
            ));
            // What it changed shows (it's a write: everything's stale).
            return state.load_visible(false);
        }
        Msg::Kept(kept, cache) => (state.offline.kept, state.offline.cache) = (kept, cache),
    }
    Vec::new()
}

/// The first probe after GitHub went away.
fn schedule(state: &mut State) -> Vec<Do> {
    if state.offline.probe.is_some() {
        return Vec::new();
    }
    state.offline.probe = Some(PROBE_FIRST);
    vec![Do::Timer(Timer::Probe, PROBE_FIRST)]
}

/// It's time to ask whether GitHub's back.
#[must_use]
pub fn on_timer(state: &mut State) -> Vec<Do> {
    if state.offline.since.is_none() {
        state.offline.probe = None;
        return Vec::new();
    }
    vec![Do::Offline(Cmd::Probe)]
}

/// Queues a change GitHub couldn't be reached for, if it can wait:
/// what sent it closes, and the page shows it queued. `None` when it
/// can't wait (or it reached GitHub after all).
#[must_use]
pub fn queue_change(
    state: &mut State,
    change: &Change,
    by: &By,
    err: &crate::work::Failure,
    sender: bool,
) -> Option<Vec<Do>> {
    let Some(ApiError::Offline(_)) = err.api() else {
        return None;
    };
    let write = queue::Write::of(change)?;
    let route = match by {
        By::Reply(pr) => Some(Route::pr(pr.clone())),
        _ => here(state),
    };
    // What sent it is done with it: it's in the queue now.
    if sender && matches!(state.overlay, Some(Overlay::Compose(_) | Overlay::Ask(_))) {
        state.overlay = None;
    }
    state.info(format!(
        "GitHub can't be reached: {} is queued, to send when it's back",
        write.what().to_lowercase()
    ));
    Some(vec![add(state, write, route)])
}

/// A review GitHub couldn't be reached for: queued, its comments with it.
#[must_use]
pub fn queue_review(state: &mut State, review: &queue::Review) -> Do {
    let route = Route::pr(review.pr.clone());
    state.info("GitHub can't be reached: your review is queued, to send when it's back");
    add(state, queue::Write::Review(review.clone()), Some(route))
}

fn add(state: &State, write: queue::Write, route: Option<Route>) -> Do {
    let (page, title) = route.map_or_else(
        || (String::new(), "GitHub".to_owned()),
        |r| (r.url(), r.title()),
    );
    let entry = queue::Entry {
        id: 0,
        at: (state.clock)(),
        write,
        page,
        title,
        status: queue::Status::Queued,
    };
    Do::Offline(Cmd::Queue(queue::Op::Add(Box::new(entry))))
}

/// The page a write is made on: the page on screen, or a pull request's
/// conversation for its diff.
fn here(state: &State) -> Option<Route> {
    match state.screen() {
        Screen::Page(p) => Some(p.route.clone()),
        Screen::Diff(d) => match &d.of {
            crate::diff_screen::DiffOf::Pr(pr) => Some(Route::pr(PrRef::clone(pr))),
            _ => None,
        },
    }
}

/// What the header says: GitHub can't be reached, and what waits for it;
/// or what it didn't take.
/// Short, most important first: on a narrow header, what doesn't fit is
/// left out from the last.
pub fn header(state: &State) -> Vec<String> {
    let off = &state.offline;
    let waiting = off.waiting();
    let mut said = Vec::new();
    if off.since.is_some() {
        said.push("⚠ Offline".to_owned());
    }
    match (off.since, waiting, off.unsent()) {
        (Some(_), 0, _) | (None, 0, 0) => {}
        (Some(_), n, _) => said.push(format!("{n} queued")),
        (None, 0, n) => said.push(format!("⚠ {n} not sent")),
        (None, n, _) => said.push(format!("Sending {n}")),
    }
    said
}

/// The banner over a page showing the cache's copy because GitHub can't
/// be reached.
pub fn banner(state: &State, when: &str) -> Option<String> {
    state
        .offline
        .since
        .map(|_| format!("Offline: showing what was loaded {when}."))
}

/// The queued write a row is, if it's one.
fn selected(state: &State) -> Option<&queue::Entry> {
    let Screen::Page(p) = state.screen() else {
        return None;
    };
    let Some(Link::Queued(id)) = p.selected_link() else {
        return None;
    };
    state.offline.queue.iter().find(|e| e.id == *id)
}

/// Whether `action` is offline's here.
/// What working offline adds: its own actions, and on the Offline page
/// and while GitHub can't be reached, others' (refreshing, copying).
pub const FEATURE: crate::features::Feature = crate::features::Feature {
    owns: &[Action::Offline, Action::KeepOffline],
    takes,
    act,
    offers: doables,
    ..crate::features::Feature::NONE
};

fn takes(state: &State, action: Action) -> bool {
    match action {
        Action::Refresh => state.offline.since.is_some(),
        // Where the write was thrown away: elsewhere, it's a draft's or a
        // Home section's.
        Action::UndoDelete => state.offline.discarded.as_ref().is_some_and(|e| {
            let here = state.route();
            here == Some(&Route::App(app::Offline)) || here.is_some_and(|r| r.url() == e.page)
        }),
        Action::Rerun | Action::Delete | Action::Copy => selected(state).is_some(),
        _ => false,
    }
}

#[must_use]
pub fn act(state: &mut State, action: Action) -> Vec<Do> {
    match action {
        Action::Offline if state.route() == Some(&Route::App(app::Offline)) => {
            state.just_say("This is the Offline page")
        }
        Action::Offline => state.push(Route::App(app::Offline)),
        Action::KeepOffline => keep(state),
        // Asked now, besides fetching again.
        Action::Refresh => {
            let mut cmds = state.load_visible(true);
            cmds.push(Do::Offline(Cmd::Probe));
            state.info("Asking whether GitHub's back…");
            cmds
        }
        Action::UndoDelete => match state.offline.discarded.take() {
            Some(entry) => {
                state.info(format!("Brought back: {}", entry.write.what()));
                vec![Do::Offline(Cmd::Queue(queue::Op::Add(Box::new(entry))))]
            }
            None => Vec::new(),
        },
        _ => {
            let Some(entry) = selected(state).cloned() else {
                return Vec::new();
            };
            on_entry(state, action, entry)
        }
    }
}

/// `action` on a queued write's row.
fn on_entry(state: &mut State, action: Action, entry: queue::Entry) -> Vec<Do> {
    let what = entry.write.what();
    match action {
        Action::Copy => match entry.write.text() {
            Some(text) => {
                state.info(format!("Copied the text of {}", what.to_lowercase()));
                vec![Do::Copy(text)]
            }
            None => state.just_say(format!("{what} has no text to copy")),
        },
        Action::Rerun => match entry.status {
            queue::Status::Refused(_) | queue::Status::Unsure(_) => {
                state.info(format!("Sending again: {what}"));
                vec![Do::Offline(Cmd::Queue(queue::Op::Retry(entry.id)))]
            }
            queue::Status::Queued | queue::Status::Sending => {
                state.just_say(format!("{what} is queued already"))
            }
        },
        Action::Delete if entry.status == queue::Status::Sending => {
            state.just_say(format!("{what} is on its way to GitHub"))
        }
        Action::Delete => {
            let undo = state.first_key(Action::UndoDelete);
            state.info(format!("Threw away: {what} · {undo} brings it back"));
            let id = entry.id;
            state.offline.discarded = Some(entry);
            vec![Do::Offline(Cmd::Queue(queue::Op::Discard(id)))]
        }
        _ => Vec::new(),
    }
}

/// Keeps the repository on screen to read offline, or stops.
fn keep(state: &mut State) -> Vec<Do> {
    let Some(repo) = state.route().and_then(Route::repo).cloned() else {
        return state.just_say("Keep offline works on a repository's pages");
    };
    if state.offline.keeps(&repo).is_some() {
        state.offline.kept.retain(|k| k.repo != repo);
        state.info(format!(
            "No longer keeping {repo} offline (what the cache has stays until it's replaced)"
        ));
    } else {
        state.info(format!("Keeping {repo} to read offline: fetching it ahead"));
    }
    vec![Do::Offline(Cmd::Keep(keep::Op::Toggle(repo)))]
}

/// Following a queued write's row: its page (from the Offline page).
#[must_use]
pub fn follow(state: &mut State, id: u64) -> Vec<Do> {
    let Some(entry) = state.offline.queue.iter().find(|e| e.id == id) else {
        return Vec::new();
    };
    let here = state.route().map(Route::url);
    if entry.page.is_empty() || here.as_deref() == Some(entry.page.as_str()) {
        let (retry, copy) = (
            state.first_key(Action::Rerun),
            state.first_key(Action::Copy),
        );
        return state.just_say(format!(
            "{} · {retry} sends a refused one again · {copy} copies its text",
            entry.write.what()
        ));
    }
    let page = entry.page.clone();
    state.go(Dest::from_url(&page))
}

/// The Space menu's offline rows.
pub fn doables(state: &State, out: &mut Vec<crate::nav::Doable>) {
    let row = |action, label| crate::nav::row("Offline", action, label, "", None);
    if let Some(entry) = selected(state) {
        let what = entry.write.what().to_lowercase();
        let mut again = row(Action::Rerun, format!("Send {what} again"));
        if matches!(entry.status, queue::Status::Queued | queue::Status::Sending) {
            again.unavailable = Some("it's queued".into());
        }
        out.push(again);
        out.push(row(Action::Delete, format!("Throw away {what}")));
        let mut copy = row(Action::Copy, format!("Copy the text of {what}"));
        if entry.write.text().is_none() {
            copy.unavailable = Some("it has no text".into());
        }
        out.push(copy);
    }
    if let Some(repo) = state.route().and_then(Route::repo) {
        let label = match state.offline.keeps(repo) {
            Some(_) => format!("Stop keeping {repo} offline"),
            None => format!("Keep {repo} to read offline"),
        };
        out.push(row(Action::KeepOffline, label));
    }
    // First of the menu's Go rows, which follow.
    if state.route() != Some(&Route::App(app::Offline)) {
        let label = "Offline: what's queued for GitHub, and what's kept";
        out.push(crate::nav::row("Go", Action::Offline, label, "", None));
    }
}