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
//! Writing a wiki's pages: editing one (`,e` on it) or making one (`,W`),
//! in the composer or `$EDITOR`. The form is a page
//! ([`Route::WikiEdit`]); saving commits the page on the wiki's latest
//! and pushes it with your git credentials ([`super::save`]). A page
//! changed on GitHub since it was opened is never overwritten: saving
//! says so, and keeps your text.

use std::borrow::Cow;

use crate::api::browse::WikiPage;
use crate::api::model::RepoId;
use crate::create::templates;
use crate::route::{Route, wiki};
use crate::ui::page::{Link, Page};
use crate::ui::pages::{Mark, TextBox, WriteFormView};

use crate::data::DataKey;
use crate::follow::{Expectation, Shown};
use crate::forms::{Fields, say};
use crate::keymap::Action;
use crate::nav::{Doable, row};
use crate::state::{Cmd, State};
use crate::work::{self, Cx, Failure, Job};

/// Commits and pushes a wiki page; its form's page asked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Save {
    pub route: Route,
    pub save: crate::wiki::Save,
}

/// A page being written.
#[derive(Debug, Clone, Default)]
pub struct Form {
    /// A page's text; a new page's title on its first line, then its text.
    pub text: String,
    /// The page changed: its title, file, and the commit it was read at.
    pub page: Option<(String, String, String)>,
    /// Filled in, and the composer opened once.
    pub started: bool,
}

impl Fields for Form {
    fn text(&mut self, _: usize) -> Option<&mut String> {
        Some(&mut self.text)
    }

    fn title(&self, _: &Route, _: usize) -> String {
        match &self.page {
            Some((title, ..)) => format!("Edit the wiki page {title}"),
            None => "New wiki page: its title on the first line, then its text".into(),
        }
    }

    fn save(&self, _: &Route) -> &'static str {
        "save page"
    }
}

/// The wiki page being written on screen: its repository, the page (none
/// for a new one), and its form.
fn here(state: &State) -> Option<(Route, RepoId, Option<String>, Cow<'_, Form>)> {
    let route = state.route()?;
    let Route::Wiki(wiki::WikiEdit { repo, page }) = route else {
        return None;
    };
    let form = state.forms.shown(route);
    Some((route.clone(), repo.clone(), page.clone(), form))
}

/// What a wiki's pages add: making one, and editing the one on screen.
pub const FEATURE: crate::features::Feature = crate::features::Feature {
    owns: &[Action::NewWikiPage],
    takes: |state, action| {
        action == Action::EditComment
            && matches!(state.route(), Some(Route::Wiki(wiki::Wiki { .. })))
    },
    act: |state, action| match action {
        Action::NewWikiPage => open_new(state),
        _ => open_edit(state),
    },
    offers: doables,
    ..crate::features::Feature::NONE
};

/// What a form reads: the page, or for a new one the list of pages.
pub fn key(repo: &RepoId, page: Option<&String>) -> DataKey {
    let page = page.cloned().unwrap_or_else(|| "_pages".into());
    DataKey::Wiki(repo.clone(), Some(page))
}

/// The wiki page on screen, as read.
fn shown(state: &State) -> Option<(RepoId, &WikiPage)> {
    let Some(Route::Wiki(wiki::Wiki { repo, page })) = state.route() else {
        return None;
    };
    let w = state.picked::<WikiPage>(&DataKey::Wiki(repo.clone(), page.clone()))?;
    Some((repo.clone(), w))
}

/// Why the page on screen can't be edited here, if it can't.
fn uneditable(state: &State) -> Option<String> {
    let Some((_, w)) = shown(state) else {
        return Some("The page hasn't loaded yet".into());
    };
    match (&w.title, &w.file) {
        (Some(_), Some(_)) => None,
        _ => Some("This is the list of pages: open one to edit it".into()),
    }
}

/// `,e` on a wiki page: its form.
#[must_use]
pub fn open_edit(state: &mut State) -> Vec<Cmd> {
    if let Some(why) = uneditable(state) {
        return state.just_say(why);
    }
    let Some((repo, w)) = shown(state) else {
        return Vec::new();
    };
    let page = w.title.as_deref().map(crate::wiki::slug);
    let route = Route::Wiki(wiki::WikiEdit { repo, page });
    // Started again from what's read now.
    state.forms.take::<Form>(&route);
    let mut cmds = state.push(route);
    cmds.extend(follow(state));
    cmds
}

/// `,W`: a new page of the wiki on screen (or of the repository's).
#[must_use]
pub fn open_new(state: &mut State) -> Vec<Cmd> {
    let repo = match state.route() {
        Some(Route::Wiki(wiki::WikiEdit { page: None, .. })) => return compose(state),
        Some(route) => route.repo().cloned(),
        None => None,
    };
    let Some(repo) = repo else {
        return state.just_say("Open a repository's wiki first");
    };
    if state.overview(&repo).is_some_and(|o| !o.has_wiki) {
        return state.just_say(format!("{repo} has its wiki turned off"));
    }
    let mut cmds = state.push(Route::Wiki(wiki::WikiEdit { repo, page: None }));
    cmds.extend(follow(state));
    cmds
}

/// Brings the form on screen up to date: filled in from the page once
/// it's read, then the composer opens on it.
#[must_use]
fn follow(state: &mut State) -> Vec<Cmd> {
    let Some((route, repo, page, form)) = here(state) else {
        return Vec::new();
    };
    if form.started {
        return Vec::new();
    }
    let Some(w) = state
        .picked::<WikiPage>(&key(&repo, page.as_ref()))
        .cloned()
    else {
        return Vec::new();
    };
    let form = state.forms.edit::<Form>(&route);
    form.started = true;
    if page.is_some()
        && let (Some(title), Some(file), Some(commit)) = (w.title, w.file, w.commit)
    {
        form.text = w.text.unwrap_or_default();
        form.page = Some((title, file, commit));
    }
    if state.overlay.is_none() {
        return compose(state);
    }
    Vec::new()
}

/// The composer, on the page.
#[must_use]
fn compose(state: &mut State) -> Vec<Cmd> {
    let Some((route, _, page, form)) = here(state) else {
        return Vec::new();
    };
    if page.is_some() && form.page.is_none() {
        return state.just_say("The page hasn't loaded yet");
    }
    let top = [ratatui_textarea::CursorMove::Top];
    crate::forms::compose::<Form>(state, &route, 0, &top)
}

/// The page to save, or why it can't be.
fn to_save(state: &State, repo: &RepoId, form: &Form) -> Result<crate::wiki::Save, String> {
    let login = state.viewer.clone();
    match &form.page {
        Some((title, file, commit)) => Ok(crate::wiki::Save {
            repo: repo.clone(),
            title: title.clone(),
            file: Some(file.clone()),
            base: Some(commit.clone()),
            text: form.text.clone(),
            login,
        }),
        None => {
            let (title, text) = templates::split(&form.text);
            if title.is_empty() {
                return Err("Write the page's title first: it's the first line".into());
            }
            if title.contains(['/', '\\']) || title.chars().any(char::is_control) {
                return Err("A page's title can't have / or \\ in it".into());
            }
            Ok(crate::wiki::Save {
                repo: repo.clone(),
                title,
                file: None,
                base: None,
                text,
                login,
            })
        }
    }
}

/// `,s`, ctrl-s or its button: commits and pushes the page.
#[must_use]
fn submit(state: &mut State) -> Vec<Cmd> {
    let Some((route, repo, page, form)) = here(state) else {
        return Vec::new();
    };
    if page.is_some() && form.page.is_none() {
        return say(state, "The page hasn't loaded yet".into());
    }
    let save = match to_save(state, &repo, &form) {
        Ok(save) => save,
        Err(why) => {
            return say(state, why);
        }
    };
    crate::forms::form_sending(state, &route);
    state.info(format!("Saving {}…", save.title));
    work::start(Save { route, save })
}

/// A wiki page with this text, as its page's data is keyed.
#[derive(Debug)]
struct Saved(DataKey, String);

impl Expectation for Saved {
    fn waiting(&self) -> &'static str {
        "Waiting for GitHub to show the page"
    }

    fn shown(&self, state: &State, _: &Route) -> Shown {
        let text = |w: &WikiPage| w.text.as_deref().map(str::trim_end) == Some(self.1.trim_end());
        state.picked::<WikiPage>(&self.0).is_some_and(text).into()
    }
}

impl Job for Save {
    type Out = String;

    async fn run(&self, cx: &Cx) -> Result<String, Failure> {
        crate::wiki::save(&cx.git, &self.save)
            .await
            .map_err(Failure::msg)
    }

    /// Saved: the page opens (back on it, when it's the page before), and
    /// follows GitHub until it shows the text saved.
    fn done(self, state: &mut State, result: Result<String, Failure>) -> Vec<Cmd> {
        let route = &self.route;
        let Route::Wiki(wiki::WikiEdit { repo, .. }) = route else {
            return Vec::new();
        };
        match result {
            Ok(slug) => {
                let form: Form = crate::forms::done(state, route);
                let text = match &form.page {
                    Some(_) => form.text.clone(),
                    None => templates::split(&form.text).1,
                };
                state.info(match &form.page {
                    Some((title, ..)) => format!("Saved {title}"),
                    None => format!("Created {}", slug.replace('-', " ")),
                });
                if state.route() != Some(route) {
                    return Vec::new();
                }
                // Back on the page it was opened from, if it's that one.
                let below = state.screens.below().and_then(|s| match s {
                    crate::state::Screen::Page(p) => match &p.route {
                        Route::Wiki(wiki::Wiki { repo: r, page }) if r == repo => {
                            let title = (state
                                .picked::<WikiPage>(&DataKey::Wiki(r.clone(), page.clone())))
                            .and_then(|w| w.title.as_deref().map(crate::wiki::slug));
                            (title.as_deref() == Some(slug.as_str())).then(|| p.route.clone())
                        }
                        _ => None,
                    },
                    crate::state::Screen::Diff(_) => None,
                });
                let page = below.clone().unwrap_or_else(|| {
                    Route::Wiki(wiki::Wiki {
                        repo: repo.clone(),
                        page: Some(slug),
                    })
                });
                let Route::Wiki(wiki::Wiki { page: name, .. }) = &page else {
                    return Vec::new();
                };
                let shows = Saved(DataKey::Wiki(repo.clone(), name.clone()), text);
                crate::follow::expect(state, page.clone(), shows);
                if below.is_some() {
                    let mut cmds = state.back();
                    state.forward.clear();
                    cmds.extend(state.ensure_route(&page, true));
                    cmds
                } else {
                    state.replace(page, true, None)
                }
            }
            Err(why) => crate::forms::failed(state, route, why.to_string()),
        }
    }
}

/// What a wiki page's form does.
pub const FORM: crate::forms::Kind = crate::forms::Kind {
    compose: |state, _| compose(state),
    row: |_, _| Vec::new(),
    fill: |_, _, _, _| Vec::new(),
    submit,
    follow,
    offers,
};

/// The form's rows in the menu: writing it, and saving it.
fn offers(state: &State, out: &mut Vec<Doable>) {
    if let Some((_, repo, _, form)) = here(state) {
        let why = to_save(state, &repo, &form).err();
        let save = ("Save the page", "save");
        crate::forms::offer(state, Some("Write the page"), save, why, out);
    }
}

/// The menu's rows: editing the page on screen and making one.
fn doables(state: &State, out: &mut Vec<Doable>) {
    if let Some(Route::Wiki(wiki::Wiki { .. })) = state.route() {
        out.push(row(
            "Edit",
            Action::EditComment,
            "Edit this page",
            "edit",
            uneditable(state),
        ));
        out.push(row("New", Action::NewWikiPage, "New wiki page", "", None));
    }
}

/// The form's page.
pub fn build(state: &State, page: &mut Page, route: &Route) {
    let Route::Wiki(wiki::WikiEdit { repo, .. }) = route else {
        return;
    };
    let form = state.forms.shown::<Form>(route);
    let composing = crate::forms::composing(state, route, 0);
    let (heading, title, body, hint) = match &form.page {
        Some((title, file, _)) => (
            format!("Editing {title} in {repo}'s wiki"),
            title.clone(),
            form.text.clone(),
            format!("Saved as {file}: committed and pushed with your git credentials"),
        ),
        None => {
            let (title, body) = templates::split(&form.text);
            (
                format!("New page in {repo}'s wiki"),
                title,
                body,
                "The first line is the title; then the page, in Markdown (ctrl-e for $EDITOR)"
                    .to_owned(),
            )
        }
    };
    let markdown = form
        .page
        .as_ref()
        .is_none_or(|(_, file, _)| crate::ui::pages::is_markdown(file));
    let mut status = Vec::new();
    if let Some((_, _, commit)) = &form.page {
        let at = crate::ui::text::short_sha(commit);
        status.push((
            format!("As the wiki had it at {at}: if it changes meanwhile, saving says so"),
            Mark::Fine,
            None,
        ));
    }
    let write = state.first_key(Action::Comment);
    let save_key = state.first_key(Action::Create);
    let body = if composing { String::new() } else { body };
    let view = WriteFormView {
        heading,
        base: Some(crate::ui::markdown::LinkBase::wiki(repo)),
        rows: Vec::new(),
        status,
        boxes: vec![TextBox {
            title: if composing { String::new() } else { title },
            untitled: "Title",
            body: &body,
            markdown,
            empty: "Nothing written yet.",
            hint: &hint,
            link: Link::Form(crate::ui::form::Row::Text(0)),
            actions: Vec::new(),
        }],
        after: Vec::new(),
        write: &write,
        button: "Save page".into(),
        save_key: &save_key,
        why_not: to_save(state, repo, &form).err(),
        error: state.forms.sent(route).error.as_deref(),
    };
    crate::ui::pages::write_form(page, &view);
}