ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
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
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
//! An issue's or pull request's timeline: its comments, reviews and
//! events in GitHub's own order (`timelineItems`), and how it connects to
//! other issues and pull requests.
//!
//! The wire types are typed against GitHub's schema; the models before
//! them are what the app renders and caches.

use serde::{Deserialize, Serialize};

use crate::api::browse::{
    BotLogin, Comment, CommitCard, CommitInfo, RequestedReviewer, Reviewer, StateReason, UserLogin,
    WireComment, WireIssueState, comment,
};
use crate::api::edit::{Editable, WireReactionGroup, reactions};
use crate::api::model::{
    Capped, IssueState, Label, PrState, PrStatus, RepoId, ReviewState, Status, author, count,
};
use crate::api::queries::{
    Actor, BigInt, CommitOid, DateTime, PageVariablesFields, RepositoryName, fragments, nodes,
};
use crate::schema::schema;

// ---- models ------------------------------------------------------------------

/// One entry of a conversation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Item {
    Comment(Comment),
    Review(Review),
    Event(Event),
}

impl Item {
    /// When it happened (ISO 8601).
    pub fn at(&self) -> &str {
        match self {
            Item::Comment(c) => &c.created_at,
            Item::Review(r) => &r.at,
            Item::Event(e) => &e.at,
        }
    }
}

/// A pull request's review: what its author decided and said.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Review {
    /// GitHub's number for it, which its link's anchor uses
    /// (`#pullrequestreview-…`) and its comments name.
    pub id: Option<u64>,
    pub author: String,
    pub state: ReviewState,
    /// Its summary, as Markdown.
    pub body: String,
    /// When it was submitted (ISO 8601); a pending review's, when it was
    /// started.
    pub at: String,
    /// The head it reviewed.
    pub commit: Option<String>,
    /// How many comments it made on lines and files.
    pub comments: u64,
    /// What edits name it by (its summary), what GitHub lets you do to
    /// it, and its reactions.
    pub editable: Editable,
}

impl Review {
    /// Its anchor in the conversation.
    pub fn anchor(&self) -> Option<String> {
        self.id.map(|id| format!("pullrequestreview-{id}"))
    }
}

/// Something that happened to an issue or pull request, by someone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
    pub actor: String,
    /// ISO 8601.
    pub at: String,
    pub what: What,
}

/// An issue or pull request named by an event or a sidebar.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Linked {
    pub repo: RepoId,
    pub number: u64,
    pub title: String,
    pub state: LinkedState,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LinkedState {
    Issue(IssueState),
    Pr(PrState),
}

impl Linked {
    pub fn status(&self) -> Status {
        match self.state {
            LinkedState::Issue(s) => Status::Issue(s),
            LinkedState::Pr(s) => Status::Pr(s),
        }
    }

    pub fn is_pr(&self) -> bool {
        matches!(self.state, LinkedState::Pr(_))
    }

    /// `#12`, or `owner/name#12` from elsewhere than `here`.
    pub fn name(&self, here: &RepoId) -> String {
        if self.repo == *here {
            format!("#{}", self.number)
        } else {
            format!("{}#{}", self.repo, self.number)
        }
    }

    /// Its page on GitHub.
    pub fn url(&self) -> String {
        let kind = if self.is_pr() { "pull" } else { "issues" };
        format!(
            "{}/{}/{kind}/{}",
            crate::host::current().web(),
            self.repo,
            self.number
        )
    }
}

/// What closed an issue or pull request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Closer {
    Commit(String),
    Pr(Linked),
}

/// What an event was.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum What {
    Closed {
        by: Option<Closer>,
        /// An issue's: completed, not planned, a duplicate.
        reason: Option<IssueState>,
        duplicate: bool,
    },
    Reopened,
    Merged {
        commit: Option<String>,
        into: String,
    },
    /// Mentioned from another issue or pull request.
    CrossReferenced {
        from: Linked,
        will_close: bool,
    },
    /// Mentioned by a commit's message.
    Referenced {
        commit: String,
        repo: Option<RepoId>,
    },
    Labeled {
        label: Label,
        added: bool,
    },
    Assigned {
        who: String,
        added: bool,
    },
    Milestoned {
        title: String,
        added: bool,
    },
    /// Added to or removed from a project.
    Project {
        added: bool,
    },
    /// Moved between a project's statuses.
    ProjectStatus {
        from: String,
        to: String,
    },
    ReviewRequested {
        who: Option<Reviewer>,
        added: bool,
    },
    ReviewDismissed {
        /// Whose review.
        of: Option<String>,
        message: String,
    },
    Renamed {
        from: String,
        to: String,
    },
    ReadyForReview,
    ConvertedToDraft,
    /// A commit added to a pull request.
    Committed(CommitInfo),
    /// The head (or base) branch force-pushed, old head to new.
    ForcePushed {
        base: bool,
        before: Option<String>,
        after: Option<String>,
    },
    BranchDeleted {
        name: String,
    },
    BranchRestored,
    BaseChanged {
        from: String,
        to: String,
    },
    Locked {
        reason: Option<String>,
    },
    Unlocked,
    Pinned {
        pinned: bool,
    },
    Transferred {
        from: Option<String>,
    },
    MarkedDuplicate {
        of: Option<Linked>,
        undone: bool,
    },
    AutoMerge {
        on: bool,
    },
    MergeQueue {
        added: bool,
        reason: Option<String>,
    },
    SubIssue {
        issue: Option<Linked>,
        added: bool,
    },
    Parent {
        issue: Option<Linked>,
        added: bool,
    },
    IssueType {
        from: Option<String>,
        to: Option<String>,
    },
    ConvertedToDiscussion,
}

impl What {
    /// Which run of events it folds into: events of one kind by one
    /// person, one after another, read as one line.
    pub fn kind(&self) -> &'static str {
        match self {
            What::Closed { .. } => "closed",
            What::Reopened => "reopened",
            What::Merged { .. } => "merged",
            What::CrossReferenced { .. } => "referenced",
            What::Referenced { .. } => "commit",
            What::Labeled { .. } => "labels",
            What::Assigned { .. } => "assignees",
            What::Milestoned { .. } => "milestone",
            What::Project { .. } | What::ProjectStatus { .. } => "project",
            What::ReviewRequested { .. } => "reviewers",
            What::ReviewDismissed { .. } => "dismissed",
            What::Renamed { .. } => "title",
            What::ReadyForReview | What::ConvertedToDraft => "draft",
            What::Committed(_) => "commits",
            What::ForcePushed { .. } => "force",
            What::BranchDeleted { .. } | What::BranchRestored => "branch",
            What::BaseChanged { .. } => "base",
            What::Locked { .. } | What::Unlocked => "lock",
            What::Pinned { .. } => "pin",
            What::Transferred { .. } => "transfer",
            What::MarkedDuplicate { .. } => "duplicate",
            What::AutoMerge { .. } => "auto-merge",
            What::MergeQueue { .. } => "queue",
            What::SubIssue { .. } => "sub-issues",
            What::Parent { .. } => "parent",
            What::IssueType { .. } => "type",
            What::ConvertedToDiscussion => "discussion",
        }
    }
}

/// How an issue's sub-issues are coming along.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Progress {
    pub done: u64,
    pub total: u64,
}

/// The latest review of one reviewer, as the sidebar lists them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Latest {
    pub author: String,
    pub state: ReviewState,
    pub id: Option<u64>,
    /// ISO 8601.
    pub at: String,
    /// The head it reviewed: an approval of an older one came before the
    /// last push.
    pub commit: Option<String>,
    /// Teams it was given for (`org/slug`).
    pub for_teams: Vec<String>,
}

/// Someone asked for a review who hasn't given one since.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Requested {
    pub who: Reviewer,
    /// Asked because they own code it changes (CODEOWNERS).
    pub code_owner: bool,
}

// ---- wire: the items -------------------------------------------------------------

/// Events that are only who and when.
macro_rules! bare_events {
    ($($name:ident = $graphql:literal),* $(,)?) => {$(
        #[derive(cynic::QueryFragment, Debug)]
        #[cynic(graphql_type = $graphql)]
        pub struct $name {
            pub actor: Option<Actor>,
            pub created_at: DateTime,
        }
    )*};
}

bare_events! {
    ReopenedEv = "ReopenedEvent",
    ReadyEv = "ReadyForReviewEvent",
    DraftEv = "ConvertToDraftEvent",
    RestoredEv = "HeadRefRestoredEvent",
    UnlockedEv = "UnlockedEvent",
    PinnedEv = "PinnedEvent",
    UnpinnedEv = "UnpinnedEvent",
    AutoMergeOnEv = "AutoMergeEnabledEvent",
    AutoMergeOffEv = "AutoMergeDisabledEvent",
    QueuedEv = "AddedToMergeQueueEvent",
    DiscussionEv = "ConvertedToDiscussionEvent",
    ProjectAddedEv = "AddedToProjectV2Event",
    ProjectRemovedEv = "RemovedFromProjectV2Event",
}

/// An issue a timeline names.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "Issue")]
pub struct LinkedIssue {
    pub number: i32,
    pub title: String,
    pub state: WireIssueState,
    pub state_reason: Option<StateReason>,
    pub repository: RepositoryName,
}

/// A pull request a timeline names.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequest")]
pub struct LinkedPr {
    pub number: i32,
    pub title: String,
    #[cynic(spread)]
    pub status: PrStatus,
    pub repository: RepositoryName,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "ReferencedSubject")]
pub enum Subject {
    Issue(LinkedIssue),
    PullRequest(LinkedPr),
    #[cynic(fallback)]
    Other,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "IssueOrPullRequest")]
pub enum IssueOrPrLink {
    Issue(LinkedIssue),
    PullRequest(LinkedPr),
    #[cynic(fallback)]
    Other,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "Closer")]
pub enum WireCloser {
    Commit(CommitOid),
    PullRequest(LinkedPr),
    #[cynic(fallback)]
    Other,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "Assignee")]
pub enum WireAssignee {
    User(UserLogin),
    Bot(BotLogin),
    #[cynic(fallback)]
    Other,
}

#[derive(cynic::Enum, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LockReason {
    OffTopic,
    Resolved,
    Spam,
    TooHeated,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "IssueType")]
pub struct TypeName {
    pub name: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ClosedEvent")]
pub struct ClosedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub closer: Option<WireCloser>,
    pub state_reason: Option<StateReason>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "MergedEvent")]
pub struct MergedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub commit: Option<CommitOid>,
    pub merge_ref_name: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "CrossReferencedEvent")]
pub struct CrossReferencedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub source: Subject,
    pub will_close_target: bool,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ReferencedEvent")]
pub struct ReferencedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub commit: Option<CommitOid>,
    pub commit_repository: RepositoryName,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "LabeledEvent")]
pub struct LabeledEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub label: crate::api::queries::Label,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "UnlabeledEvent")]
pub struct UnlabeledEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub label: crate::api::queries::Label,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "AssignedEvent")]
pub struct AssignedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub assignee: Option<WireAssignee>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "UnassignedEvent")]
pub struct UnassignedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub assignee: Option<WireAssignee>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "MilestonedEvent")]
pub struct MilestonedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub milestone_title: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "DemilestonedEvent")]
pub struct DemilestonedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub milestone_title: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ProjectV2ItemStatusChangedEvent")]
pub struct StatusChangedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub previous_status: String,
    pub status: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ReviewRequestedEvent")]
pub struct ReviewRequestedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub requested_reviewer: Option<RequestedReviewer>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ReviewRequestRemovedEvent")]
pub struct ReviewUnrequestedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub requested_reviewer: Option<RequestedReviewer>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestReview")]
pub struct ReviewAuthor {
    pub author: Option<Actor>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ReviewDismissedEvent")]
pub struct DismissedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub dismissal_message: Option<String>,
    pub review: Option<ReviewAuthor>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "RenamedTitleEvent")]
pub struct RenamedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub previous_title: String,
    pub current_title: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "HeadRefForcePushedEvent")]
pub struct HeadPushedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub before_commit: Option<CommitOid>,
    pub after_commit: Option<CommitOid>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "BaseRefForcePushedEvent")]
pub struct BasePushedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub before_commit: Option<CommitOid>,
    pub after_commit: Option<CommitOid>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "HeadRefDeletedEvent")]
pub struct DeletedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub head_ref_name: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "BaseRefChangedEvent")]
pub struct BaseChangedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub previous_ref_name: String,
    pub current_ref_name: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "LockedEvent")]
pub struct LockedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub lock_reason: Option<LockReason>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "TransferredEvent")]
pub struct TransferredEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub from_repository: Option<RepositoryName>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "MarkedAsDuplicateEvent")]
pub struct DuplicateEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub canonical: Option<IssueOrPrLink>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "UnmarkedAsDuplicateEvent")]
pub struct NotDuplicateEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub canonical: Option<IssueOrPrLink>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "RemovedFromMergeQueueEvent")]
pub struct DequeuedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub reason: Option<String>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "SubIssueAddedEvent")]
pub struct SubAddedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub sub_issue: Option<LinkedIssue>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "SubIssueRemovedEvent")]
pub struct SubRemovedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub sub_issue: Option<LinkedIssue>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ParentIssueAddedEvent")]
pub struct ParentAddedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub parent: Option<LinkedIssue>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ParentIssueRemovedEvent")]
pub struct ParentRemovedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub parent: Option<LinkedIssue>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "IssueTypeAddedEvent")]
pub struct TypeAddedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub issue_type: Option<TypeName>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "IssueTypeChangedEvent")]
pub struct TypeChangedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub issue_type: Option<TypeName>,
    pub prev_issue_type: Option<TypeName>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "IssueTypeRemovedEvent")]
pub struct TypeRemovedEv {
    pub actor: Option<Actor>,
    pub created_at: DateTime,
    pub issue_type: Option<TypeName>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestCommit")]
pub struct CommitEv {
    pub commit: CommitCard,
}

/// A review, as the timeline and the list of reviews have it.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestReview")]
pub struct WireReview {
    pub id: cynic::Id,
    /// `databaseId` overflows GraphQL's `Int` on newer reviews.
    pub full_database_id: Option<BigInt>,
    pub author: Option<Actor>,
    pub state: ReviewState,
    pub body: String,
    pub submitted_at: Option<DateTime>,
    pub created_at: DateTime,
    pub commit: Option<CommitOid>,
    #[arguments(first: 0)]
    pub comments: crate::api::queries::ReviewCommentCount,
    pub viewer_can_update: bool,
    pub viewer_can_delete: bool,
    pub viewer_can_react: bool,
    pub reaction_groups: Option<Vec<WireReactionGroup>>,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "PullRequestTimelineItems")]
pub enum PrItem {
    IssueComment(Box<WireComment>),
    PullRequestReview(Box<WireReview>),
    PullRequestCommit(CommitEv),
    ClosedEvent(ClosedEv),
    ReopenedEvent(ReopenedEv),
    MergedEvent(MergedEv),
    CrossReferencedEvent(CrossReferencedEv),
    ReferencedEvent(ReferencedEv),
    LabeledEvent(LabeledEv),
    UnlabeledEvent(UnlabeledEv),
    AssignedEvent(AssignedEv),
    UnassignedEvent(UnassignedEv),
    MilestonedEvent(MilestonedEv),
    DemilestonedEvent(DemilestonedEv),
    AddedToProjectV2Event(ProjectAddedEv),
    RemovedFromProjectV2Event(ProjectRemovedEv),
    ProjectV2ItemStatusChangedEvent(StatusChangedEv),
    ReviewRequestedEvent(ReviewRequestedEv),
    ReviewRequestRemovedEvent(ReviewUnrequestedEv),
    ReviewDismissedEvent(DismissedEv),
    RenamedTitleEvent(RenamedEv),
    ReadyForReviewEvent(ReadyEv),
    ConvertToDraftEvent(DraftEv),
    HeadRefForcePushedEvent(HeadPushedEv),
    BaseRefForcePushedEvent(BasePushedEv),
    HeadRefDeletedEvent(DeletedEv),
    HeadRefRestoredEvent(RestoredEv),
    BaseRefChangedEvent(BaseChangedEv),
    LockedEvent(LockedEv),
    UnlockedEvent(UnlockedEv),
    MarkedAsDuplicateEvent(DuplicateEv),
    UnmarkedAsDuplicateEvent(NotDuplicateEv),
    AutoMergeEnabledEvent(AutoMergeOnEv),
    AutoMergeDisabledEvent(AutoMergeOffEv),
    AddedToMergeQueueEvent(QueuedEv),
    RemovedFromMergeQueueEvent(DequeuedEv),
    #[cynic(fallback)]
    Other,
}

#[derive(cynic::InlineFragments, Debug)]
#[cynic(graphql_type = "IssueTimelineItems")]
pub enum IssueItem {
    IssueComment(Box<WireComment>),
    ClosedEvent(ClosedEv),
    ReopenedEvent(ReopenedEv),
    CrossReferencedEvent(CrossReferencedEv),
    ReferencedEvent(ReferencedEv),
    LabeledEvent(LabeledEv),
    UnlabeledEvent(UnlabeledEv),
    AssignedEvent(AssignedEv),
    UnassignedEvent(UnassignedEv),
    MilestonedEvent(MilestonedEv),
    DemilestonedEvent(DemilestonedEv),
    AddedToProjectV2Event(ProjectAddedEv),
    RemovedFromProjectV2Event(ProjectRemovedEv),
    ProjectV2ItemStatusChangedEvent(StatusChangedEv),
    RenamedTitleEvent(RenamedEv),
    LockedEvent(LockedEv),
    UnlockedEvent(UnlockedEv),
    PinnedEvent(PinnedEv),
    UnpinnedEvent(UnpinnedEv),
    TransferredEvent(TransferredEv),
    MarkedAsDuplicateEvent(DuplicateEv),
    UnmarkedAsDuplicateEvent(NotDuplicateEv),
    SubIssueAddedEvent(SubAddedEv),
    SubIssueRemovedEvent(SubRemovedEv),
    ParentIssueAddedEvent(ParentAddedEv),
    ParentIssueRemovedEvent(ParentRemovedEv),
    IssueTypeAddedEvent(TypeAddedEv),
    IssueTypeChangedEvent(TypeChangedEv),
    IssueTypeRemovedEvent(TypeRemovedEv),
    ConvertedToDiscussionEvent(DiscussionEv),
    #[cynic(fallback)]
    Other,
}

fragments! {
    counted:
    PrTimeline = "PullRequestTimelineItemsConnection" => PrItem,
    IssueTimeline = "IssueTimelineItemsConnection" => IssueItem,
    Closing = "IssueConnection" => LinkedIssue,
    ClosedBy = "PullRequestConnection" => LinkedPr,
    SubIssues = "IssueConnection" => LinkedIssue,
    Branches = "LinkedBranchConnection" => WireLinkedBranch,
    LatestReviews = "PullRequestReviewConnection" => WireLatest,
    Requests = "ReviewRequestConnection" => WireRequest,
    PendingReviews = "PullRequestReviewConnection" => WireReview,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "LinkedBranch")]
pub struct WireLinkedBranch {
    #[cynic(rename = "ref")]
    pub branch: Option<RefName>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "Ref")]
pub struct RefName {
    pub name: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "SubIssuesSummary")]
pub struct WireProgress {
    pub completed: i32,
    pub total: i32,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "Team")]
pub struct TeamName {
    /// `org/slug`.
    pub combined_slug: String,
}

fragments! {
    counted:
    OnBehalfOf = "TeamConnection" => TeamName,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestReview")]
pub struct WireLatest {
    pub full_database_id: Option<BigInt>,
    pub author: Option<Actor>,
    pub state: ReviewState,
    pub submitted_at: Option<DateTime>,
    pub commit: Option<CommitOid>,
    #[arguments(first: 10)]
    pub on_behalf_of: OnBehalfOf,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestReview")]
pub struct Opinion {
    pub state: ReviewState,
}

fragments! {
    counted:
    Opinions = "PullRequestReviewConnection" => Opinion,
}

#[derive(cynic::QueryFragment, Debug)]
pub struct PinnedIssue {
    pub issue: LinkedIssue,
}

fragments! {
    counted:
    PinnedIssues = "PinnedIssueConnection" => PinnedIssue,
}

/// A repository's pinned issues.
pub(crate) fn pinned_issues(p: PinnedIssues) -> Capped<Linked> {
    let items = nodes(p.nodes).filter_map(|p| p.issue.into_linked());
    Capped::new(items.collect(), count(p.total_count))
}

/// How many reviewers' latest word is an approval.
pub(crate) fn approvals(o: Option<Opinions>) -> u64 {
    let approved = o.map(|o| nodes(o.nodes).filter(|r| r.state == ReviewState::Approved));
    approved.map_or(0, |a| a.count() as u64)
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "ReviewRequest")]
pub struct WireRequest {
    pub as_code_owner: bool,
    pub requested_reviewer: Option<RequestedReviewer>,
}

// ---- from the wire ---------------------------------------------------------------

fn actor(a: Option<Actor>) -> String {
    author(a)
}

fn event(actor_: Option<Actor>, at: DateTime, what: What) -> Item {
    Item::Event(Event {
        actor: actor(actor_),
        at: at.0,
        what,
    })
}

fn oid(c: Option<CommitOid>) -> Option<String> {
    c.map(|c| c.oid.0)
}

fn database_id(id: Option<BigInt>) -> Option<u64> {
    id.and_then(|id| id.0.parse().ok())
}

impl LinkedIssue {
    pub(crate) fn into_linked(self) -> Option<Linked> {
        Some(Linked {
            repo: RepoId::parse(&self.repository.name_with_owner)?,
            number: count(self.number),
            title: self.title,
            state: LinkedState::Issue(crate::api::browse::issue_state(
                self.state,
                self.state_reason,
            )),
        })
    }
}

impl LinkedPr {
    pub(crate) fn into_linked(self) -> Option<Linked> {
        Some(Linked {
            repo: RepoId::parse(&self.repository.name_with_owner)?,
            number: count(self.number),
            title: self.title,
            state: LinkedState::Pr(self.status.into()),
        })
    }
}

impl Subject {
    fn into_linked(self) -> Option<Linked> {
        match self {
            Subject::Issue(i) => i.into_linked(),
            Subject::PullRequest(p) => p.into_linked(),
            Subject::Other => None,
        }
    }
}

impl IssueOrPrLink {
    fn into_linked(self) -> Option<Linked> {
        match self {
            IssueOrPrLink::Issue(i) => i.into_linked(),
            IssueOrPrLink::PullRequest(p) => p.into_linked(),
            IssueOrPrLink::Other => None,
        }
    }
}

fn assignee(a: Option<WireAssignee>) -> String {
    match a {
        Some(WireAssignee::User(u)) => u.login,
        Some(WireAssignee::Bot(b)) => b.login,
        _ => "ghost".to_owned(),
    }
}

pub(crate) fn reviewer(r: Option<RequestedReviewer>) -> Option<Reviewer> {
    match r? {
        RequestedReviewer::User(u) => Some(Reviewer::User(u.login)),
        RequestedReviewer::Bot(b) => Some(Reviewer::User(b.login)),
        RequestedReviewer::Team(t) => Some(Reviewer::Team(t.combined_slug)),
        RequestedReviewer::Other => None,
    }
}

impl WireReview {
    pub(crate) fn into_review(self) -> Review {
        Review {
            id: database_id(self.full_database_id),
            author: author(self.author),
            state: self.state,
            body: self.body,
            at: self.submitted_at.unwrap_or(self.created_at).0,
            commit: oid(self.commit),
            comments: count(self.comments.total_count),
            editable: Editable {
                id: self.id.into(),
                can_update: self.viewer_can_update,
                can_delete: self.viewer_can_delete,
                can_react: self.viewer_can_react,
                reactions: reactions(self.reaction_groups),
            },
        }
    }
}

/// The events both kinds of timeline have, made into items.
macro_rules! shared_events {
    ($item:expr, $ty:ident, $($extra:tt)*) => {
        match $item {
            $ty::IssueComment(c) => Some(Item::Comment(comment(*c))),
            $ty::ClosedEvent(e) => {
                let by = match e.closer {
                    Some(WireCloser::Commit(c)) => Some(Closer::Commit(c.oid.0)),
                    Some(WireCloser::PullRequest(p)) => p.into_linked().map(Closer::Pr),
                    _ => None,
                };
                let reason = e.state_reason.map(|r| match r {
                    StateReason::NotPlanned => IssueState::NotPlanned,
                    _ => IssueState::Closed,
                });
                let duplicate = e.state_reason == Some(StateReason::Duplicate);
                Some(event(e.actor, e.created_at, What::Closed { by, reason, duplicate }))
            }
            $ty::ReopenedEvent(e) => Some(event(e.actor, e.created_at, What::Reopened)),
            $ty::CrossReferencedEvent(e) => {
                let from = e.source.into_linked()?;
                let will_close = e.will_close_target;
                Some(event(e.actor, e.created_at, What::CrossReferenced { from, will_close }))
            }
            $ty::ReferencedEvent(e) => {
                let commit = oid(e.commit)?;
                let repo = RepoId::parse(&e.commit_repository.name_with_owner);
                Some(event(e.actor, e.created_at, What::Referenced { commit, repo }))
            }
            $ty::LabeledEvent(e) => {
                let label = Label { name: e.label.name, color: e.label.color };
                Some(event(e.actor, e.created_at, What::Labeled { label, added: true }))
            }
            $ty::UnlabeledEvent(e) => {
                let label = Label { name: e.label.name, color: e.label.color };
                Some(event(e.actor, e.created_at, What::Labeled { label, added: false }))
            }
            $ty::AssignedEvent(e) => {
                let who = assignee(e.assignee);
                Some(event(e.actor, e.created_at, What::Assigned { who, added: true }))
            }
            $ty::UnassignedEvent(e) => {
                let who = assignee(e.assignee);
                Some(event(e.actor, e.created_at, What::Assigned { who, added: false }))
            }
            $ty::MilestonedEvent(e) => {
                let title = e.milestone_title;
                Some(event(e.actor, e.created_at, What::Milestoned { title, added: true }))
            }
            $ty::DemilestonedEvent(e) => {
                let title = e.milestone_title;
                Some(event(e.actor, e.created_at, What::Milestoned { title, added: false }))
            }
            $ty::AddedToProjectV2Event(e) => {
                Some(event(e.actor, e.created_at, What::Project { added: true }))
            }
            $ty::RemovedFromProjectV2Event(e) => {
                Some(event(e.actor, e.created_at, What::Project { added: false }))
            }
            $ty::ProjectV2ItemStatusChangedEvent(e) => {
                let what = What::ProjectStatus { from: e.previous_status, to: e.status };
                Some(event(e.actor, e.created_at, what))
            }
            $ty::RenamedTitleEvent(e) => {
                let what = What::Renamed { from: e.previous_title, to: e.current_title };
                Some(event(e.actor, e.created_at, what))
            }
            $ty::LockedEvent(e) => {
                let reason = e.lock_reason.map(|r| crate::api::manage::lock_said(r).to_owned());
                Some(event(e.actor, e.created_at, What::Locked { reason }))
            }
            $ty::UnlockedEvent(e) => Some(event(e.actor, e.created_at, What::Unlocked)),
            $ty::MarkedAsDuplicateEvent(e) => {
                let of = e.canonical.and_then(IssueOrPrLink::into_linked);
                Some(event(e.actor, e.created_at, What::MarkedDuplicate { of, undone: false }))
            }
            $ty::UnmarkedAsDuplicateEvent(e) => {
                let of = e.canonical.and_then(IssueOrPrLink::into_linked);
                Some(event(e.actor, e.created_at, What::MarkedDuplicate { of, undone: true }))
            }
            $($extra)*
        }
    };
}

impl PrItem {
    pub(crate) fn into_item(self) -> Option<Item> {
        shared_events!(self, PrItem,
            PrItem::PullRequestReview(r) => Some(Item::Review(r.into_review())),
            PrItem::PullRequestCommit(c) => {
                let at = c.commit.committed_date.0.clone();
                let info = c.commit.into_info();
                let actor = info.author.login().unwrap_or_default().to_owned();
                Some(Item::Event(Event { actor, at, what: What::Committed(info) }))
            }
            PrItem::MergedEvent(e) => {
                let what = What::Merged { commit: oid(e.commit), into: e.merge_ref_name };
                Some(event(e.actor, e.created_at, what))
            }
            PrItem::ReviewRequestedEvent(e) => {
                let who = reviewer(e.requested_reviewer);
                Some(event(e.actor, e.created_at, What::ReviewRequested { who, added: true }))
            }
            PrItem::ReviewRequestRemovedEvent(e) => {
                let who = reviewer(e.requested_reviewer);
                Some(event(e.actor, e.created_at, What::ReviewRequested { who, added: false }))
            }
            PrItem::ReviewDismissedEvent(e) => {
                let of = e.review.map(|r| author(r.author));
                let message = e.dismissal_message.unwrap_or_default();
                Some(event(e.actor, e.created_at, What::ReviewDismissed { of, message }))
            }
            PrItem::ReadyForReviewEvent(e) => Some(event(e.actor, e.created_at, What::ReadyForReview)),
            PrItem::ConvertToDraftEvent(e) => Some(event(e.actor, e.created_at, What::ConvertedToDraft)),
            PrItem::HeadRefForcePushedEvent(e) => {
                let what = What::ForcePushed {
                    base: false,
                    before: oid(e.before_commit),
                    after: oid(e.after_commit),
                };
                Some(event(e.actor, e.created_at, what))
            }
            PrItem::BaseRefForcePushedEvent(e) => {
                let what = What::ForcePushed {
                    base: true,
                    before: oid(e.before_commit),
                    after: oid(e.after_commit),
                };
                Some(event(e.actor, e.created_at, what))
            }
            PrItem::HeadRefDeletedEvent(e) => {
                let what = What::BranchDeleted { name: e.head_ref_name };
                Some(event(e.actor, e.created_at, what))
            }
            PrItem::HeadRefRestoredEvent(e) => Some(event(e.actor, e.created_at, What::BranchRestored)),
            PrItem::BaseRefChangedEvent(e) => {
                let what = What::BaseChanged { from: e.previous_ref_name, to: e.current_ref_name };
                Some(event(e.actor, e.created_at, what))
            }
            PrItem::AutoMergeEnabledEvent(e) => Some(event(e.actor, e.created_at, What::AutoMerge { on: true })),
            PrItem::AutoMergeDisabledEvent(e) => Some(event(e.actor, e.created_at, What::AutoMerge { on: false })),
            PrItem::AddedToMergeQueueEvent(e) => {
                Some(event(e.actor, e.created_at, What::MergeQueue { added: true, reason: None }))
            }
            PrItem::RemovedFromMergeQueueEvent(e) => {
                let reason = e.reason.filter(|r| !r.trim().is_empty());
                Some(event(e.actor, e.created_at, What::MergeQueue { added: false, reason }))
            }
            PrItem::Other => None,
        )
    }
}

impl IssueItem {
    pub(crate) fn into_item(self) -> Option<Item> {
        shared_events!(self, IssueItem,
            IssueItem::PinnedEvent(e) => Some(event(e.actor, e.created_at, What::Pinned { pinned: true })),
            IssueItem::UnpinnedEvent(e) => Some(event(e.actor, e.created_at, What::Pinned { pinned: false })),
            IssueItem::TransferredEvent(e) => {
                let from = e.from_repository.map(|r| r.name_with_owner);
                Some(event(e.actor, e.created_at, What::Transferred { from }))
            }
            IssueItem::SubIssueAddedEvent(e) => {
                let issue = e.sub_issue.and_then(LinkedIssue::into_linked);
                Some(event(e.actor, e.created_at, What::SubIssue { issue, added: true }))
            }
            IssueItem::SubIssueRemovedEvent(e) => {
                let issue = e.sub_issue.and_then(LinkedIssue::into_linked);
                Some(event(e.actor, e.created_at, What::SubIssue { issue, added: false }))
            }
            IssueItem::ParentIssueAddedEvent(e) => {
                let issue = e.parent.and_then(LinkedIssue::into_linked);
                Some(event(e.actor, e.created_at, What::Parent { issue, added: true }))
            }
            IssueItem::ParentIssueRemovedEvent(e) => {
                let issue = e.parent.and_then(LinkedIssue::into_linked);
                Some(event(e.actor, e.created_at, What::Parent { issue, added: false }))
            }
            IssueItem::IssueTypeAddedEvent(e) => {
                let what = What::IssueType { from: None, to: e.issue_type.map(|t| t.name) };
                Some(event(e.actor, e.created_at, what))
            }
            IssueItem::IssueTypeChangedEvent(e) => {
                let what = What::IssueType {
                    from: e.prev_issue_type.map(|t| t.name),
                    to: e.issue_type.map(|t| t.name),
                };
                Some(event(e.actor, e.created_at, what))
            }
            IssueItem::IssueTypeRemovedEvent(e) => {
                let what = What::IssueType { from: e.issue_type.map(|t| t.name), to: None };
                Some(event(e.actor, e.created_at, what))
            }
            IssueItem::ConvertedToDiscussionEvent(e) => {
                Some(event(e.actor, e.created_at, What::ConvertedToDiscussion))
            }
            IssueItem::Other => None,
        )
    }
}

/// A timeline's items, oldest first, of how many there are in all.
/// Your pending review, which the timeline may not have, comes last.
pub(crate) fn pr_timeline(t: PrTimeline, pending: Option<PendingReviews>) -> Capped<Item> {
    let fetched = t.nodes.as_ref().map_or(0, Vec::len) as u64;
    let mut items: Vec<Item> = nodes(t.nodes).filter_map(PrItem::into_item).collect();
    // What ghtui doesn't show isn't left out.
    let unshown = fetched.saturating_sub(items.len() as u64);
    let total = count(t.total_count).saturating_sub(unshown);
    let has_pending = items
        .iter()
        .any(|i| matches!(i, Item::Review(r) if r.state == ReviewState::Pending));
    let pending = pending.and_then(|p| nodes(p.nodes).next());
    if let Some(p) = pending.filter(|_| !has_pending) {
        items.push(Item::Review(p.into_review()));
        return Capped::new(items, total + 1);
    }
    Capped::new(items, total)
}

pub(crate) fn issue_timeline(t: IssueTimeline) -> Capped<Item> {
    let fetched = t.nodes.as_ref().map_or(0, Vec::len) as u64;
    let items: Vec<Item> = nodes(t.nodes).filter_map(IssueItem::into_item).collect();
    let unshown = fetched.saturating_sub(items.len() as u64);
    Capped::new(items, count(t.total_count).saturating_sub(unshown))
}

pub(crate) fn linked_issues(c: Closing) -> Capped<Linked> {
    let items = nodes(c.nodes)
        .filter_map(LinkedIssue::into_linked)
        .collect();
    Capped::new(items, count(c.total_count))
}

pub(crate) fn sub_issues(c: SubIssues) -> Capped<Linked> {
    let items = nodes(c.nodes)
        .filter_map(LinkedIssue::into_linked)
        .collect();
    Capped::new(items, count(c.total_count))
}

pub(crate) fn linked_prs(c: ClosedBy) -> Capped<Linked> {
    let items = nodes(c.nodes).filter_map(LinkedPr::into_linked).collect();
    Capped::new(items, count(c.total_count))
}

pub(crate) fn branches(b: Branches) -> Capped<String> {
    let items = nodes(b.nodes)
        .filter_map(|b| Some(b.branch?.name))
        .collect();
    Capped::new(items, count(b.total_count))
}

pub(crate) fn progress(p: &WireProgress) -> Option<Progress> {
    (p.total > 0).then(|| Progress {
        done: count(p.completed),
        total: count(p.total),
    })
}

pub(crate) fn latest(l: Option<LatestReviews>) -> Capped<Latest> {
    let Some(l) = l else {
        return Capped::default();
    };
    Capped::from_nodes(l.total_count, l.nodes, |r| Latest {
        author: author(r.author),
        state: r.state,
        id: database_id(r.full_database_id),
        at: r.submitted_at.map(|d| d.0).unwrap_or_default(),
        commit: oid(r.commit),
        for_teams: nodes(r.on_behalf_of.nodes)
            .map(|t| t.combined_slug)
            .collect(),
    })
}

/// Who a pull request's review requests name; one GitHub's types don't
/// cover (an enterprise team) counts as left out.
pub(crate) fn requested(r: Option<Requests>) -> Capped<Requested> {
    let Some(r) = r else {
        return Capped::default();
    };
    let named = nodes(r.nodes).filter_map(|r| {
        Some(Requested {
            who: reviewer(r.requested_reviewer)?,
            code_owner: r.as_code_owner,
        })
    });
    Capped::new(named.collect(), count(r.total_count))
}

// ---- a pull request's reviews ----------------------------------------------------------

/// A page of a pull request's reviews, oldest first.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "Query", variables = "PageVariables")]
pub struct ReviewsQuery {
    #[arguments(owner: $owner, name: $name)]
    pub repository: Option<RepoReviews>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "Repository", variables = "PageVariables")]
pub struct RepoReviews {
    #[arguments(number: $number)]
    pub pull_request: Option<PrReviews>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequest", variables = "PageVariables")]
pub struct PrReviews {
    #[arguments(first: 100, after: $after)]
    pub reviews: Option<ReviewsPage>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(graphql_type = "PullRequestReviewConnection")]
pub struct ReviewsPage {
    pub page_info: crate::api::queries::PageInfo,
    pub nodes: Option<Vec<Option<WireReview>>>,
}

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

    fn decode<T: serde::de::DeserializeOwned>(json: serde_json::Value) -> T {
        serde_json::from_value(json).unwrap_or_else(|e| panic!("{e}"))
    }

    /// A pull request's timeline keeps GitHub's order and states (a
    /// dismissed review reads as dismissed, as the conversation shows it),
    /// and what ghtui doesn't show isn't counted as left out.
    #[test]
    fn a_timeline_keeps_order_and_counts_only_what_it_shows() {
        let review = |state: &str| {
            serde_json::json!({"__typename": "PullRequestReview", "id": "PRR_1",
                "fullDatabaseId": "7", "author": {"login": "hubot"}, "state": state,
                "body": "", "submittedAt": "2026-10-01T00:00:00Z",
                "createdAt": "2026-10-01T00:00:00Z", "commit": {"oid": "abc"},
                "comments": {"totalCount": 2}, "viewerCanUpdate": false,
                "viewerCanDelete": false, "viewerCanReact": true, "reactionGroups": []})
        };
        let wire: crate::api::browse::WirePrActivity = decode(serde_json::json!({
            "id": "PR_1",
            "comments": {"totalCount": 0},
            "timelineItems": {"totalCount": 5, "nodes": [
                review("DISMISSED"),
                {"__typename": "SomethingNew"},
                {"__typename": "ReadyForReviewEvent", "actor": null,
                 "createdAt": "2026-10-02T00:00:00Z"},
            ]},
            "commits": {"totalCount": 0, "nodes": []},
            "reviewRequests": {"totalCount": 1, "nodes": [
                {"asCodeOwner": true, "requestedReviewer": {"__typename": "Team", "combinedSlug": "o/core"}}
            ]},
            "latestReviews": null,
            "closingIssuesReferences": null,
            "mergeCommit": null,
            "pending_review": {"totalCount": 1, "nodes": [review("PENDING")]},
        }));
        let a = wire.into_activity();
        let [Item::Review(r), Item::Event(e), Item::Review(mine)] = a.timeline.items.as_slice()
        else {
            panic!("{:?}", a.timeline);
        };
        assert_eq!(
            (r.state, r.id, r.comments),
            (ReviewState::Dismissed, Some(7), 2)
        );
        assert_eq!(
            (e.actor.as_str(), &e.what),
            ("ghost", &What::ReadyForReview)
        );
        assert_eq!(
            mine.state,
            ReviewState::Pending,
            "your pending review comes last"
        );
        assert_eq!(a.timeline.left_out(), 2);
        assert!(a.requested.first().is_some_and(|r| r.code_owner));
    }

    #[test]
    fn a_closing_commit_and_a_will_close_reference_read_as_github_says_them() {
        let items: Vec<PrItem> = decode(serde_json::json!([
            {"__typename": "CrossReferencedEvent", "actor": {"login": "bob"},
             "createdAt": "2026-01-01T00:00:00Z", "willCloseTarget": true,
             "source": {"__typename": "PullRequest", "number": 5, "title": "Fix",
                        "isDraft": false, "state": "OPEN",
                        "repository": {"nameWithOwner": "o/r"}}},
            {"__typename": "ClosedEvent", "actor": {"login": "alice"},
             "createdAt": "2026-01-02T00:00:00Z", "stateReason": null,
             "closer": {"__typename": "Commit", "oid": "abc"}},
            {"__typename": "SomethingNew"}
        ]));
        let items: Vec<Item> = items.into_iter().filter_map(PrItem::into_item).collect();
        let [Item::Event(refd), Item::Event(closed)] = items.as_slice() else {
            panic!("{items:?}");
        };
        let What::CrossReferenced { from, will_close } = &refd.what else {
            panic!("{refd:?}");
        };
        assert!(*will_close && from.is_pr() && from.name(&RepoId::new("o", "r")) == "#5");
        assert_eq!(closed.actor, "alice");
        assert!(matches!(
            &closed.what,
            What::Closed { by: Some(Closer::Commit(c)), .. } if c == "abc"
        ));
    }
}