ghtui 0.1.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
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
//! The diff screen: file tree plus diff, and its key handling.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::api::model::{NodeId, PatchFile, PrRef, RepoId, ReviewThread, ViewedFiles};
use crate::diff::anchor::{Commentable, Side};
use crate::diff::{FileDiff, Whitespace};
use crate::git::Oid;
use crate::git::repo::{Commit, PrRefs};
use crate::store::ReviewState;
use crate::ui::annotations::Annotation;
use crate::ui::bars::Notice;
use crate::ui::diff_doc::{Doc, DocInputs, Note, Pos, Row, ViewOptions, Viewed};
use crate::ui::file_tree::{TreeRow, row_of_file, tree_rows};
use crate::ui::pages::url as links;
use crate::ui::text::short_sha;
use ratatui::layout::Rect;

use crate::diff_job::{DiffFiles, JobId, JobMsg, next_job};
use crate::join;
use crate::keymap::Action;
use crate::notice::Notices;
use crate::picker;
use crate::review::{annotations, on_submitted};
use crate::state::{Api, Cmd, DiffMsg, Git, Overlay, Problem, State};

/// What GitHub says about your last submitted review of a PR.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum LastReview {
    /// Not asked yet.
    #[default]
    Unknown,
    /// You haven't submitted one.
    None,
    /// The head commit it was on.
    At(Oid),
    /// GitHub couldn't say, and why: asked again next time.
    Failed(String),
}

/// What a diff screen shows: a pull request's changes, or one commit's.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DiffOf {
    Pr(PrRef),
    /// A commit against its first parent.
    Commit(RepoId, Oid),
    /// From one commit to another, as `a..b`: a comparison's
    /// files, from the merge base its page found.
    Range(RepoId, Oid, Oid),
}

impl DiffOf {
    /// The pull request, for what only pull requests have: reviews,
    /// threads, viewed files.
    pub fn pr(&self) -> Option<&PrRef> {
        match self {
            DiffOf::Pr(pr) => Some(pr),
            DiffOf::Commit(..) | DiffOf::Range(..) => None,
        }
    }

    pub fn repo(&self) -> &RepoId {
        match self {
            DiffOf::Pr(pr) => &pr.repo,
            DiffOf::Commit(repo, _) | DiffOf::Range(repo, ..) => repo,
        }
    }

    /// Its files on GitHub: the one place a diff's link is written, and
    /// one that parses back to it.
    pub fn url(&self) -> String {
        match self {
            DiffOf::Pr(pr) => format!("{}/files", pr.url()),
            DiffOf::Commit(repo, oid) => format!("{}#files", links::commit(repo, oid)),
            DiffOf::Range(repo, from, to) => format!("{}#files", links::compare(repo, from, to)),
        }
    }
}

impl From<PrRef> for DiffOf {
    fn from(pr: PrRef) -> Self {
        DiffOf::Pr(pr)
    }
}

impl std::fmt::Display for DiffOf {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DiffOf::Pr(pr) => pr.fmt(f),
            DiffOf::Commit(repo, oid) => write!(f, "{repo}@{}", short_sha(oid)),
            DiffOf::Range(repo, from, to) => {
                write!(f, "{repo}@{}...{}", short_sha(from), short_sha(to))
            }
        }
    }
}

/// Split view turns on automatically from this diff-pane width.
pub const SPLIT_MIN_WIDTH: u16 = 160;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    Tree,
    Diff,
}

/// How a diff screen is asked to show diffs, whichever it shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiffPrefs {
    pub tree_visible: bool,
    /// `None` picks split or unified by width.
    pub split_override: Option<bool>,
    pub ignore_whitespace: bool,
}

impl DiffPrefs {
    /// What a new diff screen `width` wide starts with.
    pub fn fit(width: u16) -> Self {
        Self {
            tree_visible: width >= 100,
            split_override: None,
            ignore_whitespace: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffScreen {
    pub of: DiffOf,
    pub cursor: Pos,
    /// The half of split rows the cursor is on (the other when that one
    /// is empty); it follows the line held across view changes.
    pub half: Side,
    pub top: Pos,
    pub prefs: DiffPrefs,
    pub focus: Pane,
    pub tree_selected: usize,
    pub tree_scroll: usize,
    /// The last search query, for `n` / `N`.
    pub search: Option<String>,
    /// Where a visual line selection started.
    pub selection: Option<Pos>,
    /// What a link pointed at, to go to once it's loaded: a file
    /// (`diff-<hash>`, GitHub's SHA-256 of its path) or a review comment
    /// (`discussion_r<id>`, `r<id>`).
    pub anchor: Option<String>,
}

impl DiffScreen {
    pub fn new(of: DiffOf, prefs: DiffPrefs) -> Self {
        Self {
            of,
            cursor: Pos::default(),
            half: Side::Right,
            top: Pos::default(),
            prefs,
            focus: Pane::Diff,
            tree_selected: 0,
            tree_scroll: 0,
            search: None,
            selection: None,
            anchor: None,
        }
    }

    /// Starts over at the top, as for a new range, keeping the view prefs.
    pub fn restart(&mut self) {
        *self = Self::new(self.of.clone(), self.prefs);
    }

    /// The view options this screen wants at `content` size.
    pub fn options(&self, content: Rect) -> ViewOptions {
        let lay = layout(content, self.prefs.tree_visible);
        ViewOptions {
            split: self
                .prefs
                .split_override
                .unwrap_or(lay.diff.width >= SPLIT_MIN_WIDTH),
            whitespace: if self.prefs.ignore_whitespace {
                Whitespace::Ignore
            } else {
                Whitespace::Exact
            },
            // Thread cards start after the gutter; keep comments readable.
            wrap: lay.diff.width.saturating_sub(24).clamp(20, 100),
        }
    }
}

/// A commit range being viewed: label, from (exclusive), to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RangeView {
    pub label: String,
    pub from: String,
    pub to: String,
}

/// What GitHub and the saved review say of a PR's diff; it outlasts rebuilds.
#[derive(Debug, Default)]
pub struct DiffInputs {
    /// GitHub's viewed state and the PR's node ID.
    pub viewed: Option<ViewedFiles>,
    /// Locally persisted review marks and draft comments.
    pub review: ReviewState,
    /// The saved review state has been read (saving before that would
    /// overwrite it).
    pub review_loaded: bool,
    /// Review threads from GitHub.
    pub threads: Vec<ReviewThread>,
    /// Commentable ranges from GitHub's patches of the whole PR, by path.
    pub patches: Arc<HashMap<String, Commentable>>,
    /// Your last submitted review on GitHub.
    pub last_review: LastReview,
    /// The PR's commits, oldest first.
    pub commits: Vec<Commit>,
    /// The draft deleted last, for undo.
    pub deleted: Option<crate::store::DraftComment>,
}

impl DiffInputs {
    /// Notes `path`'s viewed state, once GitHub's are in.
    pub fn set_viewed(&mut self, path: String, viewed: Viewed) {
        if let Some(files) = &mut self.viewed {
            files.states.insert(path, viewed);
        }
    }

    /// Marks thread `id` resolved or not.
    pub fn set_resolved(&mut self, id: &NodeId, resolved: bool) {
        if let Some(t) = self.threads.iter_mut().find(|t| t.id == *id) {
            t.resolved = resolved;
        }
    }

    /// Takes in the saved review state, keeping whatever was done before
    /// it arrived. True if that left something new to save.
    pub fn merge_saved_review(&mut self, saved: ReviewState) -> bool {
        let early = std::mem::replace(&mut self.review, saved);
        let changed = early != ReviewState::default();
        let review = &mut self.review;
        for hunk in early.reviewed_hunks {
            if !review.reviewed_hunks.contains(&hunk) {
                review.reviewed_hunks.push(hunk);
            }
        }
        review.reviewed_hunks.sort();
        for mut draft in early.pending {
            draft.id = review.next_draft_id();
            review.pending.push(draft);
        }
        if early.last_reviewed_head.is_some() {
            review.last_reviewed_head = early.last_reviewed_head;
        }
        self.review_loaded = true;
        changed
    }
}

/// Everything known about one PR's diff: its inputs, and what a job made.
#[derive(Debug)]
pub struct DiffState {
    /// Changed only through [`DiffState::edit`], which shows the change.
    inputs: DiffInputs,
    pub doc: Doc,
    pub tree: Vec<TreeRow>,
    pub refs: Option<PrRefs>,
    /// What the background job is doing, while it works.
    pub progress: Option<String>,
    pub error: Option<String>,
    /// Outdated threads mapped onto this job's head (`None`: can't be).
    /// Changed only through [`DiffState::add_mapped`], which shows it.
    mapped: HashMap<NodeId, Option<u32>>,
    /// What the work that waits on several inputs last ran for.
    pub(crate) joins: join::Joins,
    /// "Since my last review" was asked for and is waiting on data.
    pub since_requested: bool,
    /// Showing a sub-range of commits instead of the whole PR.
    range: Option<RangeView>,
    /// Files we've already asked the job to prioritize.
    requested: HashSet<usize>,
    /// The diff job whose results this shows; older jobs' are ignored.
    pub job: JobId,
}

impl DiffState {
    /// A new diff of the whole PR that knows nothing yet: all is fetched again.
    pub fn fresh() -> Self {
        Self {
            inputs: DiffInputs::default(),
            doc: Doc::default(),
            tree: Vec::new(),
            refs: None,
            progress: Some("Preparing".into()),
            error: None,
            mapped: HashMap::new(),
            joins: join::Joins::default(),
            since_requested: false,
            range: None,
            requested: HashSet::new(),
            job: next_job(),
        }
    }

    /// Starts over for a different commit range, with the same inputs.
    pub fn restart(&mut self, range: Option<RangeView>) {
        *self = Self {
            inputs: std::mem::take(&mut self.inputs),
            range,
            ..Self::fresh()
        };
    }

    /// The commit range shown, if not the whole PR.
    pub fn range(&self) -> Option<&RangeView> {
        self.range.as_ref()
    }

    pub fn inputs(&self) -> &DiffInputs {
        &self.inputs
    }

    /// What the doc shows of the inputs and this job's mapping; GitHub's
    /// patches only on the whole PR's diff, whose lines they number.
    fn doc_inputs(&self) -> DocInputs {
        let i = &self.inputs;
        DocInputs {
            patches: if self.range.is_none() {
                Arc::clone(&i.patches)
            } else {
                Arc::default()
            },
            viewed: i.viewed.iter().flat_map(|v| v.states.clone()).collect(),
            reviewed: i.review.reviewed_hunks.iter().cloned().collect(),
            annotations: annotations(&i.threads, &self.mapped, &i.review.pending),
        }
    }

    /// Changes the inputs with `f` and shows the change.
    pub fn edit<R>(&mut self, f: impl FnOnce(&mut DiffInputs) -> R) -> R {
        let r = f(&mut self.inputs);
        self.doc.set_inputs(self.doc_inputs());
        r
    }

    /// Places outdated threads as this job's mapping says, and shows them.
    pub fn add_mapped(&mut self, mapped: impl IntoIterator<Item = (NodeId, Option<u32>)>) {
        self.mapped.extend(mapped);
        self.doc.set_inputs(self.doc_inputs());
    }

    /// Changes the review with `f`, shows the change, and saves it once
    /// the saved one has been read (saving before would overwrite it).
    #[must_use]
    pub fn edit_review(&mut self, pr: &PrRef, f: impl FnOnce(&mut DiffInputs)) -> Vec<Cmd> {
        self.edit(f);
        let i = &self.inputs;
        let save = || Cmd::SaveReview(pr.clone(), i.review.clone());
        i.review_loaded.then(save).into_iter().collect()
    }

    /// The file list has arrived.
    pub fn listed(&self) -> bool {
        self.refs.is_some()
    }

    /// The head commit the diff was computed at.
    pub fn head(&self) -> Option<Oid> {
        self.refs.as_ref().map(|r| r.head.clone())
    }

    /// Lists the job's files. The doc shows the inputs from the start, so
    /// whatever arrived before the files (GitHub's patches, say) applies.
    pub fn set_files(&mut self, files: DiffFiles) {
        self.doc = Doc::new(files.files, &files.generated, self.doc_inputs());
        self.tree = tree_rows(&self.doc);
        self.refs = Some(files.refs);
        self.progress = (!self.doc.is_empty()).then(|| "Computing diffs".into());
    }

    pub fn set_file(&mut self, index: usize, diff: Arc<FileDiff>) {
        self.doc.set_diff(index, diff);
        if self.doc.ready_count() == self.doc.files().len() {
            self.progress = None;
        }
    }

    pub fn status(&self) -> Option<String> {
        let progress = self.progress.as_ref()?;
        if self.listed() && !self.doc.is_empty() {
            Some(format!(
                "Diffing {}/{} files",
                self.doc.ready_count(),
                self.doc.files().len()
            ))
        } else {
            Some(progress.clone())
        }
    }
}

pub struct Layout {
    pub tree: Option<Rect>,
    pub diff: Rect,
}

/// Splits the content area; shared by the view and key handling so both
/// agree on viewport sizes.
pub fn layout(content: Rect, tree_visible: bool) -> Layout {
    if !tree_visible || content.width < 60 {
        return Layout {
            tree: None,
            diff: content,
        };
    }
    let width = (content.width / 4).clamp(24, 40);
    Layout {
        tree: Some(Rect { width, ..content }),
        diff: Rect {
            x: content.x + width,
            width: content.width - width,
            ..content
        },
    }
}

/// Rows of the tree list below its title.
fn tree_list_height(tree: Rect) -> usize {
    usize::from(tree.height.saturating_sub(3))
}

/// Runs `change` on the diff, keeping the cursor, the top of the view and
/// the selection on the same lines and threads.
pub fn preserving_position<R>(
    screen: &mut DiffScreen,
    diff: &mut DiffState,
    change: impl FnOnce(&mut DiffState) -> R,
) -> R {
    let doc = &diff.doc;
    let [cursor, top] = [screen.cursor, screen.top].map(|p| doc.anchor(p, screen.half));
    let selection = screen.selection.map(|p| doc.anchor(p, screen.half));
    let r = change(diff);
    let doc = &diff.doc;
    screen.half = cursor.side().unwrap_or(screen.half);
    screen.cursor = doc.locate(cursor);
    screen.top = doc.locate(top);
    screen.selection = selection.map(|a| doc.locate(a));
    r
}

/// Handles `action` on the diff screen. Those that don't work here say
/// where they do.
#[must_use]
pub fn apply(
    screen: &mut DiffScreen,
    state: &mut DiffState,
    action: Action,
    content: Rect,
    notice: &mut Notices,
) -> Vec<Cmd> {
    let lay = layout(content, screen.prefs.tree_visible);
    let half = (usize::from(lay.diff.height) / 2).max(1).cast_signed();
    let tree_focused = screen.focus == Pane::Tree && lay.tree.is_some();
    // While searching, n and p go through the matches.
    let action = match action {
        Action::NextHunk if screen.search.is_some() => Action::SearchNext,
        Action::PrevHunk if screen.search.is_some() => Action::SearchPrev,
        action => action,
    };
    let mut cmds = Vec::new();
    match action {
        // A page is two half pages, so the cursor keeps its place on screen.
        Action::PageDown | Action::PageUp => {
            let half = if action == Action::PageDown {
                Action::HalfPageDown
            } else {
                Action::HalfPageUp
            };
            cmds = apply(screen, state, half, content, notice);
            cmds.extend(apply(screen, state, half, content, notice));
        }
        Action::ToggleTree => {
            screen.prefs.tree_visible = !screen.prefs.tree_visible;
            if !screen.prefs.tree_visible {
                screen.focus = Pane::Diff;
            }
        }
        Action::SwitchPane => {
            if lay.tree.is_some() {
                screen.focus = match screen.focus {
                    Pane::Tree => Pane::Diff,
                    Pane::Diff => Pane::Tree,
                };
            }
        }
        Action::ToggleSplit => {
            screen.prefs.split_override = Some(!screen.options(content).split);
        }
        Action::IgnoreWhitespace => {
            screen.prefs.ignore_whitespace = !screen.prefs.ignore_whitespace;
            notice.info(if screen.prefs.ignore_whitespace {
                "Ignoring whitespace changes"
            } else {
                "Showing whitespace changes"
            });
        }
        // Moving in the file tree; everything else acts on the diff.
        Action::Open if tree_focused => screen.focus = Pane::Diff,
        Action::Down
        | Action::Up
        | Action::HalfPageDown
        | Action::HalfPageUp
        | Action::Top
        | Action::Bottom
            if tree_focused =>
        {
            let tree_half = (tree_list_height(lay.tree.unwrap_or_default()) / 2)
                .max(1)
                .cast_signed();
            let delta = match action {
                Action::Down => 1,
                Action::Up => -1,
                Action::HalfPageDown => tree_half,
                Action::HalfPageUp => -tree_half,
                Action::Top => isize::MIN,
                _ => isize::MAX,
            };
            let last = state.tree.len().saturating_sub(1);
            screen.tree_selected = screen.tree_selected.saturating_add_signed(delta).min(last);
            // The diff follows the tree selection.
            if let Some(TreeRow::File { index, .. }) = state.tree.get(screen.tree_selected) {
                jump(
                    screen,
                    Pos {
                        file: *index,
                        row: 0,
                    },
                );
            }
        }
        Action::Down => screen.cursor = state.doc.offset(screen.cursor, 1),
        Action::Up => screen.cursor = state.doc.offset(screen.cursor, -1),
        Action::HalfPageDown => {
            screen.cursor = state.doc.offset(screen.cursor, half);
            screen.top = state.doc.offset(screen.top, half);
        }
        Action::HalfPageUp => {
            screen.cursor = state.doc.offset(screen.cursor, -half);
            screen.top = state.doc.offset(screen.top, -half);
        }
        Action::Top => screen.cursor = Pos::default(),
        Action::Bottom => screen.cursor = state.doc.last(),
        Action::NextHunk
        | Action::PrevHunk
        | Action::NextFile
        | Action::PrevFile
        | Action::NextThread
        | Action::PrevThread => {
            let (doc, at) = (&state.doc, screen.cursor);
            let (found, none) = match action {
                Action::NextHunk => (doc.next_hunk(at), "No more changes"),
                Action::PrevHunk => (doc.prev_hunk(at), "No more changes"),
                Action::NextFile => (doc.next_file(at), "No more files"),
                Action::PrevFile => (doc.prev_file(at), "No more files"),
                Action::NextThread => (doc.next_thread(at), "No more unresolved threads"),
                _ => (doc.prev_thread(at), "No more unresolved threads"),
            };
            match found {
                // A file starts at the top of the view.
                Some(pos) if matches!(action, Action::NextFile | Action::PrevFile) => {
                    jump(screen, pos);
                }
                Some(pos) => {
                    screen.cursor = pos;
                    face_thread(screen, state);
                }
                None => notice.info(none),
            }
        }
        Action::VisualLines => {
            let (selection, what) = match screen.selection {
                Some(_) => (None, "Selection cleared"),
                None => (Some(screen.cursor), "Selecting lines"),
            };
            screen.selection = selection;
            notice.info(what);
        }
        Action::NextUnviewed => match state.doc.next_unviewed(screen.cursor) {
            Some(pos) => jump(screen, pos),
            None => notice.info("Every file is viewed"),
        },
        Action::ExpandContext => {
            let pos = screen.cursor;
            let rows = |doc: &Doc| doc.files().get(pos.file).map(|f| f.rows().len());
            let before = rows(&state.doc);
            preserving_position(screen, state, |d| d.doc.expand(pos));
            if rows(&state.doc) == before {
                notice.info("No more context here");
            }
        }
        Action::FullFile => {
            let file = screen.cursor.file;
            preserving_position(screen, state, |d| d.doc.toggle_full(file));
        }
        Action::OldSide | Action::NewSide if !state.doc.opts().split => {
            notice.info("Sides are split view's · S splits");
        }
        Action::OldSide => screen.half = Side::Left,
        Action::NewSide => screen.half = Side::Right,
        Action::JumpMove => match state.doc.move_at(screen.cursor, screen.half) {
            Some((mv, from)) => {
                if let Some(pos) = state.doc.move_target(mv, from) {
                    screen.cursor = pos;
                    // From removed lines to where they were added, and back.
                    screen.half = if from { Side::Right } else { Side::Left };
                }
            }
            None => notice.info("Not on moved code"),
        },
        Action::Open => match state.doc.row(screen.cursor) {
            Some(Row::Fold { .. }) => {
                let pos = screen.cursor;
                preserving_position(screen, state, |d| d.doc.unfold(pos));
            }
            Some(Row::Gap { .. }) => {
                let pos = screen.cursor;
                preserving_position(screen, state, |d| d.doc.expand(pos));
            }
            Some(Row::Header | Row::Note(Note::Collapsed | Note::Viewed))
                if state
                    .doc
                    .files()
                    .get(screen.cursor.file)
                    .is_some_and(|f| f.collapsed() || f.expanded) =>
            {
                let file = screen.cursor.file;
                state.doc.toggle_expanded(file);
                // Expanded files are diffed on demand.
                state.requested.remove(&file);
                screen.cursor.row = 0;
            }
            _ => notice.info("Nothing to open here"),
        },
        Action::ToggleViewed => cmds.extend(toggle_viewed(screen, state, notice)),
        Action::MarkReviewed => cmds.extend(toggle_reviewed(screen, state, notice)),
        Action::SearchNext | Action::SearchPrev => {
            let Some(query) = screen.search.clone() else {
                notice.info("No search yet");
                return Vec::new();
            };
            match state
                .doc
                .search(&query, screen.cursor, action == Action::SearchNext)
            {
                Some(pos) => screen.cursor = pos,
                None => notice.error(format!("No match for “{query}”")),
            }
        }
        _ => notice.info(action.not_here()),
    }
    cmds
}

/// Puts the cursor on the half of a split row where the thread under it
/// is, so `c` replies to it.
fn face_thread(screen: &mut DiffScreen, state: &DiffState) {
    let doc = &state.doc;
    let line = doc
        .annotation_at(screen.cursor)
        .and_then(|i| doc.annotations().get(i as usize))
        .and_then(Annotation::on_line);
    if let Some(line) = line {
        screen.half = line.side;
    }
}

/// Puts `pos` at the top of the view with the cursor on it.
fn jump(screen: &mut DiffScreen, pos: Pos) {
    screen.cursor = pos;
    screen.top = pos;
}

/// Starts a search from the cursor.
pub fn search(screen: &mut DiffScreen, state: &DiffState, query: String) -> Notice {
    let notice = match state.doc.search(&query, screen.cursor, true) {
        Some(pos) => {
            screen.cursor = pos;
            let n = state.doc.count_matches(&query);
            Notice::Info(format!(
                "{n} line{} match “{query}”",
                if n == 1 { "" } else { "s" }
            ))
        }
        None => Notice::Error(format!("No match for “{query}”")),
    };
    screen.search = Some(query);
    notice
}

#[must_use]
fn toggle_viewed(screen: &mut DiffScreen, state: &mut DiffState, notice: &mut Notices) -> Vec<Cmd> {
    let Some(pr) = screen.of.pr().cloned() else {
        notice.info("Viewed files are a pull request's");
        return Vec::new();
    };
    let Some(viewed) = &state.inputs().viewed else {
        notice.error("Viewed state hasn't loaded from GitHub yet");
        return Vec::new();
    };
    let index = screen.cursor.file;
    let Some(file) = state.doc.files().get(index) else {
        return Vec::new();
    };
    let (previous, path) = (file.viewed, file.meta.path().to_owned());
    let now = if previous == Viewed::Viewed {
        Viewed::Unviewed
    } else {
        Viewed::Viewed
    };
    let cmd = Cmd::Api(Api::SetViewed {
        pr,
        pull_request_id: viewed.pull_request_id.clone(),
        path: path.clone(),
        viewed: now == Viewed::Viewed,
        previous,
    });
    // Optimistic: show it now, roll back if GitHub refuses.
    state.edit(|i| i.set_viewed(path, now));
    screen.cursor = Pos {
        file: index,
        row: 0,
    };
    vec![cmd]
}

#[must_use]
fn toggle_reviewed(screen: &DiffScreen, state: &mut DiffState, notice: &mut Notices) -> Vec<Cmd> {
    let Some(pr) = screen.of.pr().cloned() else {
        notice.info("Reviewed marks are a pull request's");
        return Vec::new();
    };
    let Some(block) = state.doc.block_at(screen.cursor) else {
        notice.info("Move to a changed line to mark it reviewed");
        return Vec::new();
    };
    let hash = block.hash.clone();
    state.edit_review(&pr, |i| {
        let hunks = &mut i.review.reviewed_hunks;
        if let Some(i) = hunks.iter().position(|h| *h == hash) {
            hunks.remove(i);
        } else {
            hunks.push(hash);
            hunks.sort();
        }
    })
}

/// How GitHub names a file in its diffs' anchors: the SHA-256 of its path,
/// in hex.
pub fn path_hash(path: &str) -> String {
    use sha2::{Digest, Sha256};
    Sha256::digest(path.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// Where a link's anchor is in the diff: `Some(None)` when it isn't there,
/// `None` while the review threads it needs are still on their way.
fn anchor_pos(anchor: &str, state: &DiffState, pr: bool) -> Option<Option<Pos>> {
    let doc = &state.doc;
    if let Some(hash) = anchor.strip_prefix("diff-") {
        let hash = hash.get(..64).unwrap_or(hash);
        let file = doc
            .files()
            .iter()
            .position(|f| path_hash(f.meta.path()) == hash);
        return Some(file.map(|file| Pos { file, row: 0 }));
    }
    let Some(id) = anchor
        .strip_prefix("discussion_r")
        .or_else(|| anchor.strip_prefix('r'))
        .filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()))
    else {
        // Not something ghtui finds in a diff (`#files`).
        return Some(None);
    };
    // Only pull requests have review threads.
    if !pr {
        return Some(None);
    }
    let threads = &state.inputs().threads;
    if threads.is_empty() {
        return None;
    }
    let comment = format!("#discussion_r{id}");
    // Annotations list the threads first, in order.
    let Some((index, thread)) = threads
        .iter()
        .enumerate()
        .find(|(_, t)| t.comments.iter().any(|c| c.url.ends_with(&comment)))
    else {
        return Some(None);
    };
    if let Some(pos) = u32::try_from(index)
        .ok()
        .and_then(|i| doc.annotation_pos(i))
    {
        return Some(Some(pos));
    }
    // Its file shows no thread rows yet: wait while it's being diffed;
    // once it is (collapsed, say), go to the file.
    let Some(file) = doc
        .files()
        .iter()
        .position(|f| f.meta.path() == thread.path)
    else {
        return Some(None);
    };
    let diffed = doc.files().get(file).is_some_and(|f| f.diff.is_some());
    diffed.then_some(Some(Pos { file, row: 0 }))
}

/// Applies view options, clamps positions, keeps the cursor visible (clear
/// of the sticky header), syncs the tree with the diff, and asks the job to
/// prioritize files that are on screen but not diffed yet.
#[must_use]
pub fn settle(screen: &mut DiffScreen, state: &mut DiffState, content: Rect) -> Vec<Cmd> {
    let lay = layout(content, screen.prefs.tree_visible);
    if lay.tree.is_none() {
        screen.focus = Pane::Diff;
    }
    let opts = screen.options(content);
    if state.doc.opts() != opts {
        preserving_position(screen, state, |d| d.doc.set_options(opts));
    }
    let doc = &state.doc;
    if doc.is_empty() {
        return Vec::new();
    }
    if let Some(anchor) = screen.anchor.take() {
        match anchor_pos(&anchor, state, screen.of.pr().is_some()) {
            Some(Some(pos)) => {
                screen.cursor = pos;
                face_thread(screen, state);
            }
            // A review comment waits for the threads.
            None => screen.anchor = Some(anchor),
            Some(None) => {}
        }
    }
    let doc = &state.doc;
    screen.cursor = doc.clamp(screen.cursor);
    let height = usize::from(lay.diff.height).max(1);
    let total = doc.total_rows();
    let cursor = doc.to_global(screen.cursor);
    let mut top = doc.to_global(screen.top).min(total.saturating_sub(height));
    // Row 0 of the viewport is covered by the sticky header unless it's the
    // file's own header.
    let upper = if screen.cursor.row == 0 {
        cursor
    } else {
        cursor.saturating_sub(1)
    };
    if top > upper {
        top = upper;
    }
    if cursor >= top + height {
        top = cursor + 1 - height;
    }
    screen.top = doc.to_pos(top);

    if screen.focus == Pane::Diff
        && let Some(row) = row_of_file(&state.tree, screen.cursor.file)
    {
        screen.tree_selected = row;
    }
    if let Some(tree) = lay.tree {
        let rows = tree_list_height(tree).max(1);
        if screen.tree_selected < screen.tree_scroll {
            screen.tree_scroll = screen.tree_selected;
        } else if screen.tree_selected >= screen.tree_scroll + rows {
            screen.tree_scroll = screen.tree_selected + 1 - rows;
        }
    }

    let mut wanted = vec![screen.cursor.file];
    wanted.extend(doc.loading_in_view(screen.top, height));
    let wanted: Vec<usize> = wanted
        .into_iter()
        .filter(|f| {
            doc.files()
                .get(*f)
                .is_some_and(|file| file.diff.is_none() && !file.collapsed())
                && !state.requested.contains(f)
        })
        .collect();
    if wanted.is_empty() {
        return Vec::new();
    }
    state.requested.extend(wanted.iter().copied());
    vec![Cmd::Git(Git::Prioritize(screen.of.clone(), wanted))]
}

/// A message from a diff's current job.
#[must_use]
pub(crate) fn on_job(state: &mut State, of: &DiffOf, msg: JobMsg) -> Vec<Cmd> {
    match msg {
        JobMsg::Progress(line) => {
            if let Some(diff) = state.diffs.get_mut(of)
                && !diff.listed()
            {
                diff.progress = Some(line);
            }
        }
        // Only the file is kept: the new one has no lines yet.
        JobMsg::Files(files) => {
            change(state, of, |d| d.set_files(*files));
        }
        JobMsg::File(index, file) => {
            if let Some(diff) = state.diffs.get_mut(of) {
                diff.set_file(index, file);
            }
        }
        JobMsg::Moves(moves) => {
            change(state, of, |d| d.doc.set_moves(moves));
        }
        JobMsg::Mapped(mapped) => {
            change(state, of, |d| d.add_mapped(mapped));
        }
        JobMsg::Failed(error) => {
            if let Some(diff) = state.diffs.get_mut(of) {
                diff.progress = None;
                diff.error = Some(error.to_string());
            }
        }
        JobMsg::Since(old_head, Ok(hashes)) => {
            if let Some((screen, diff)) = state.diff_parts()
                && screen.of == *of
            {
                preserving_position(screen, diff, |d| d.doc.set_since(Some(hashes), true));
                state.info(format!(
                    "Showing changes since your review of {}",
                    short_sha(&old_head)
                ));
            }
        }
        JobMsg::Since(_, Err(err)) => {
            tracing::warn!(%of, ?err, "comparing with the last review failed");
            state.error(format!("Couldn't compare with your last review: {err}"));
        }
    }
    Vec::new()
}

/// Changes `of`'s diff, if it's still open; on screen, keeping the cursor
/// where it is.
fn change<R>(state: &mut State, of: &DiffOf, f: impl FnOnce(&mut DiffState) -> R) -> Option<R> {
    match state.diff_parts() {
        Some((screen, diff)) if screen.of == *of => Some(preserving_position(screen, diff, f)),
        _ => state.diffs.get_mut(of).map(f),
    }
}

/// Changes the inputs of `of`'s diff, if it's still open.
fn edit(state: &mut State, of: &DiffOf, f: impl FnOnce(&mut DiffInputs)) {
    change(state, of, |d| d.edit(f));
}

/// A message for a diff screen.
#[must_use]
pub(crate) fn update(state: &mut State, of: &DiffOf, msg: DiffMsg) -> Vec<Cmd> {
    if let DiffMsg::Job(job, msg) = msg {
        if state.diffs.get(of).is_some_and(|d| d.job == job) {
            return on_job(state, of, msg);
        }
        return Vec::new();
    }
    // The rest is about reviewing a pull request.
    let DiffOf::Pr(pr) = of.clone() else {
        return Vec::new();
    };
    match msg {
        DiffMsg::LastReview(result) => {
            if let Some(diff) = state.diffs.get_mut(of) {
                let last = match result {
                    Ok(None) => LastReview::None,
                    Ok(Some(commit)) => Oid::parse(&commit)
                        .map_or_else(|e| LastReview::Failed(e.to_string()), LastReview::At),
                    Err(err) => LastReview::Failed(err.to_string()),
                };
                diff.edit(|i| i.last_review = last);
            }
        }
        DiffMsg::CommitsListed(Ok(commits)) => {
            edit(state, of, |i| i.commits = commits);
            state.notices.dismiss();
            return state.open_picker(picker::Kind::Commits { mark: None });
        }
        DiffMsg::CommitsListed(Err(err)) => {
            tracing::warn!(%pr, ?err, "listing commits failed");
            state.error(format!("Couldn't list commits: {err}"));
        }
        DiffMsg::ViewedLoaded(result) => match *result {
            Ok(viewed) => {
                edit(state, of, |i| i.viewed = Some(viewed));
            }
            Err(err) => {
                tracing::warn!(%pr, %err, "viewed state fetch failed");
                state.error(format!("Couldn't load viewed files: {err}"));
            }
        },
        DiffMsg::ViewedSaved {
            path,
            previous,
            result,
        } => {
            if let Err(err) = result {
                tracing::warn!(%pr, %err, "viewed state update failed");
                edit(state, of, |i| i.set_viewed(path, previous));
                state.error(format!("GitHub didn't save “viewed”: {err}"));
            }
        }
        // Approving from the pull request's page: its drafts go with it.
        DiffMsg::ReviewLoaded(Ok(saved)) if !state.diffs.contains_key(of) => {
            if let Some(Overlay::Submit(dialog)) = &mut state.overlay
                && dialog.pr == pr
            {
                dialog.saved = Some(saved);
            }
        }
        DiffMsg::ReviewLoaded(Ok(saved)) => {
            // Anything done before it arrived is kept, and saved.
            let mut changed = false;
            let save = change(state, of, |d| {
                d.edit_review(&pr, |i| changed = i.merge_saved_review(saved))
            });
            return save.filter(|_| changed).unwrap_or_default();
        }
        DiffMsg::ReviewLoaded(Err(err)) => {
            tracing::warn!(%pr, ?err, "reading review state failed");
            state.problems.insert(
                Problem::Drafts,
                format!("Drafts for {pr} are not being saved: {err}"),
            );
        }
        DiffMsg::ThreadsLoaded(Ok(threads)) => {
            edit(state, of, |i| i.threads = threads);
        }
        DiffMsg::ThreadsLoaded(Err(err)) => {
            tracing::warn!(%pr, %err, "review threads fetch failed");
            state.error(format!("Couldn't load review threads: {err}"));
        }
        DiffMsg::PatchesLoaded(Ok(patches)) => {
            let commentable = |f: PatchFile| Some((f.filename, Commentable::from_patch(&f.patch?)));
            let patches = Arc::new(patches.into_iter().filter_map(commentable).collect());
            edit(state, of, |i| i.patches = patches);
        }
        // The local fallback covers commenting; just note it.
        DiffMsg::PatchesLoaded(Err(err)) => {
            tracing::warn!(%pr, %err, "GitHub patches unavailable; using local hunks");
        }
        DiffMsg::ResolvedSet {
            thread_id,
            resolved,
            result: Err(err),
        } => {
            edit(state, of, |i| i.set_resolved(&thread_id, !resolved));
            state.error(format!("GitHub didn't save that: {err}"));
        }
        // Jobs are handled above.
        DiffMsg::ResolvedSet { .. } | DiffMsg::Job(..) => {}
        DiffMsg::ReviewSubmitted(outcome) => return on_submitted(state, &pr, &outcome),
        DiffMsg::PendingReview(result) => match (result, &mut state.overlay) {
            (Ok(n), Some(Overlay::Submit(dialog))) if dialog.pr == pr => {
                dialog.on_github = Some(n);
            }
            (Ok(_), _) => {}
            // Submitting checks again, and says what it finds.
            (Err(err), _) => tracing::warn!(%pr, %err, "couldn't read the pending review"),
        },
    }
    Vec::new()
}

#[cfg(test)]
mod tests {
    use super::*;

    impl DiffState {
        /// Where this job's outdated threads are.
        pub(crate) fn mapped(&self) -> &HashMap<NodeId, Option<u32>> {
            &self.mapped
        }

        /// Lists `doc`'s files at `refs` and diffs them as it has, as if the
        /// job had sent them.
        pub(crate) fn with_doc(mut self, refs: PrRefs, doc: &Doc) -> Self {
            let files = doc.files().iter().map(|f| f.meta.clone()).collect();
            let generated = HashSet::new();
            self.set_files(DiffFiles {
                refs,
                files,
                generated,
            });
            for (i, f) in doc.files().iter().enumerate() {
                if let Some(diff) = &f.diff {
                    self.doc.set_diff(i, Arc::clone(diff));
                }
            }
            self.doc.set_moves(doc.moves().to_vec());
            self
        }
    }
}