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
//! Key-event handlers for every focus state.
use crossterm::event::{KeyCode, KeyModifiers};
use crate::ui::pr_detail::DetailSection;
use super::actions::Action;
use super::state::App;
use super::types::{DetailKind, Focus, RepoPickerMode};
fn detail_section_shortcut(key: crossterm::event::KeyEvent) -> Option<(DetailSection, bool)> {
let section = match key.code {
KeyCode::Char('!') => DetailSection::Description,
KeyCode::Char('@') => DetailSection::Checks,
KeyCode::Char('#') => DetailSection::Reviews,
KeyCode::Char('$') => DetailSection::Files,
KeyCode::Char('%') => DetailSection::Comments,
// `C` avoids dead-key caret layouts; caret variants stay supported
// when terminals send them directly for Shift+6.
KeyCode::Char('C' | '^' | 'ˆ' | '^' | '˄' | '\u{0302}') => DetailSection::Commits,
// Other terminals keep the digit and attach modifier bits. Match any
// event containing SHIFT so layout-added ALT/CTRL bits don't make
// Shift+6 fall through to the modifier blocker.
KeyCode::Char(ch @ '1'..='6') if key.modifiers.contains(KeyModifiers::SHIFT) => {
let idx = (ch as usize) - ('1' as usize);
DetailSection::ALL[idx]
}
_ => return None,
};
Some((section, section == DetailSection::Files))
}
impl App {
/// Translate a raw key event into an [`Action`] based on current focus.
pub(super) fn handle_key(&mut self, key: crossterm::event::KeyEvent) {
// Global bindings that work in any focus state. Repo-tab switching
// takes priority even inside the detail view: switching from detail
// pops back to the dashboard so the new tab's content is visible
// (see `leave_detail_after_tab_switch`). The section-picker keys in
// the detail view are the SHIFT-variants (`!@#$%`, `F`) precisely so
// unshifted digits / Tab remain available here for tab switching.
let typing_in_input = (self.focus == Focus::RepoPicker
&& self.repo_picker_mode == RepoPickerMode::Input)
|| self.focus == Focus::Composer;
if key.modifiers == KeyModifiers::NONE && !typing_in_input {
match key.code {
KeyCode::Char('q') => {
self.running = false;
return;
}
KeyCode::Char('?') => {
self.handle_action(Action::OpenHelp);
return;
}
KeyCode::Tab => {
self.handle_action(Action::NextTab);
return;
}
// `[` / `]` switch repo tabs everywhere EXCEPT Detail focus,
// where they resize the sidebar (see `handle_key_detail`).
KeyCode::Char(']') if !typing_in_input && self.focus != Focus::Detail => {
self.handle_action(Action::NextTab);
return;
}
KeyCode::Char('[') if !typing_in_input && self.focus != Focus::Detail => {
self.handle_action(Action::PrevTab);
return;
}
_ => {}
}
}
if key.modifiers == KeyModifiers::SHIFT && key.code == KeyCode::BackTab {
self.handle_action(Action::PrevTab);
return;
}
// Digit keys 1–9 jump to the corresponding repo tab (1-based).
// Suppressed only when the user is typing into the repo-picker Add
// field. In detail focus the digits still dispatch SwitchTab — the
// section-picker uses the SHIFT-variants (`!@#$%`) to avoid the
// clash that bit us in Phase 1.
if !typing_in_input
&& key.modifiers == KeyModifiers::NONE
&& let KeyCode::Char(ch) = key.code
&& let Some(digit) = ch.to_digit(10)
{
// digit==0 maps to tab index 9 (vim convention: 0 = 10th tab).
let idx = if digit == 0 { 9 } else { (digit as usize) - 1 };
self.handle_action(Action::SwitchTab(idx));
return;
}
// Help overlay steals all other keys — Esc, '?', or 'q' closes it.
if self.focus == Focus::Help {
match key.code {
KeyCode::Esc | KeyCode::Char('?' | 'q') => {
self.show_help = false;
self.focus = Focus::Dashboard;
}
_ => {}
}
return;
}
// Per-focus dispatch.
match self.focus {
Focus::Dashboard => self.handle_key_dashboard(key),
Focus::FirstRun => self.handle_key_first_run(key),
Focus::Detail => self.handle_key_detail(key),
Focus::RepoPicker => self.handle_key_repo_picker(key),
Focus::Confirm => self.handle_key_confirm(key),
Focus::Composer => self.handle_key_composer(key),
Focus::ThemePicker => self.handle_key_theme_picker(key),
Focus::Help => {
// Handled above; unreachable here.
}
}
}
/// Key handler for the first-run welcome wizard.
///
/// Bindings:
/// - `j` / `Down`: move cursor down (clamped).
/// - `k` / `Up`: move cursor up (saturating).
/// - `g g` (vim chord via `pending_g`): jump to top.
/// - `G`: jump to bottom.
/// - `Space`: toggle selected state of the cursor row.
/// - `a`: open the repo-picker in Input mode so the user can add a custom repo.
/// - `Enter`: commit all selected suggestions to config, then go to Dashboard.
/// - `Esc`: skip wizard without committing, go to Dashboard.
/// - `?`: toggle help overlay.
/// - `q`: quit.
pub(super) fn handle_key_first_run(&mut self, key: crossterm::event::KeyEvent) {
// Ignore key combos with modifiers (consistent with other handlers).
if key.modifiers != KeyModifiers::NONE {
self.pending_g = false;
return;
}
let len = self.first_run_suggestions.len();
match key.code {
KeyCode::Char('q') => {
self.pending_g = false;
self.running = false;
}
KeyCode::Char('?') => {
self.pending_g = false;
self.handle_action(Action::OpenHelp);
}
KeyCode::Char('j') | KeyCode::Down => {
self.pending_g = false;
if len > 0 {
self.first_run_cursor = (self.first_run_cursor + 1).min(len - 1);
}
}
KeyCode::Char('k') | KeyCode::Up => {
self.pending_g = false;
self.first_run_cursor = self.first_run_cursor.saturating_sub(1);
}
KeyCode::Char('g') => {
if self.pending_g {
// Second `g` in vim chord — jump to top.
self.pending_g = false;
self.first_run_cursor = 0;
} else {
self.pending_g = true;
}
}
KeyCode::Char('G') => {
self.pending_g = false;
if len > 0 {
self.first_run_cursor = len - 1;
}
}
KeyCode::Char(' ') => {
self.pending_g = false;
if len > 0 {
let idx = self.first_run_cursor.min(len - 1);
self.first_run_suggestions[idx].selected =
!self.first_run_suggestions[idx].selected;
}
}
KeyCode::Char('a') => {
// Open the repo-picker in Input mode so the user can add a
// custom repo not present in the suggestions list.
self.pending_g = false;
self.repo_picker_list_cursor = 0;
self.repo_picker_input.clear();
self.repo_picker_mode = RepoPickerMode::Input;
// Return to FirstRun (not Dashboard) when the picker closes,
// so the wizard can stay open for any remaining suggestions.
self.repo_picker_return_focus = Focus::FirstRun;
self.focus = Focus::RepoPicker;
}
KeyCode::Enter => {
self.pending_g = false;
self.commit_first_run();
}
KeyCode::Esc => {
// Skip without committing.
self.pending_g = false;
self.first_run_suggestions.clear();
self.first_run_cursor = 0;
self.focus = Focus::Dashboard;
self.show_flash(
"Press `p` any time to add repos",
std::time::Duration::from_secs(2),
);
}
_ => {
self.pending_g = false;
}
}
}
/// Commit the user's selections from the first-run wizard to
/// `config.repos`, save, and return to the dashboard.
///
/// If nothing is selected, flashes a hint and keeps the wizard open
/// rather than closing silently (users often hit Enter accidentally).
pub(super) fn commit_first_run(&mut self) {
// Collect the chosen slugs first so the mutation loop below does not
// also need to borrow `first_run_suggestions`.
let selected: Vec<String> = self
.first_run_suggestions
.iter()
.filter(|s| s.selected)
.map(|s| s.repo.clone())
.collect();
if selected.is_empty() {
self.show_flash(
"Nothing selected — press Space to pick repos, or Esc to skip",
std::time::Duration::from_secs(3),
);
return;
}
// Explicit loop (not an iterator with side-effects in its closure) so
// that the `added` count cannot silently desync from the `push` calls
// if the deduplication logic is refactored later.
let mut added: usize = 0;
for repo in selected {
if !self.config.repos.contains(&repo) {
self.config.repos.push(repo);
added += 1;
}
}
self.config.save();
self.sync_tabs_to_config();
self.first_run_suggestions.clear();
self.first_run_cursor = 0;
self.focus = Focus::Dashboard;
self.show_flash(
format!("Added {added} repositor{}", if added == 1 { "y" } else { "ies" }),
std::time::Duration::from_secs(2),
);
}
/// Key handler for the PR/issue detail focus.
#[allow(clippy::too_many_lines)]
pub(super) fn handle_key_detail(&mut self, key: crossterm::event::KeyEvent) {
// When copy mode is active, it owns the entire keymap for this focus.
if self.copy_mode.active {
self.handle_key_detail_copy_mode(key);
return;
}
// Section picker: `!@#$%^` for Description/Checks/Reviews/Files/
// Comments/Commits. Match the final character before filtering
// modifiers because non-US layouts often emit symbols like `@` or
// `#` with AltGr/Option modifiers attached.
if let Some((sec, files_overview)) = detail_section_shortcut(key) {
self.detail_pending_g = false;
self.pr_detail_selected_section = sec;
if files_overview {
self.pr_detail_files_show_diff = false;
}
self.copy_mode.h_scroll = 0;
return;
}
// Allow SHIFT so the section-picker keys (`F`, and `!@#$%` on US
// keyboards / SHIFT+digit on those that send it unshifted) reach
// the match arms. Reject Ctrl / Alt / Super as before.
let blocked_mods = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER;
if key.modifiers.intersects(blocked_mods) {
self.detail_pending_g = false;
return;
}
match key.code {
KeyCode::Esc | KeyCode::Char('b')
if self.pr_detail_selected_section == DetailSection::Files
&& self.selected_commit.is_some() =>
{
self.detail_pending_g = false;
if let Some(idx) = self.selected_commit {
self.commits_cursor = idx;
}
self.pr_detail_selected_section = DetailSection::Commits;
self.copy_mode.h_scroll = 0;
}
KeyCode::Esc | KeyCode::Char('b')
if self.pr_detail_selected_section == DetailSection::Files
&& self.pr_detail_files_show_diff =>
{
self.detail_pending_g = false;
self.pr_detail_files_show_diff = false;
self.copy_mode.h_scroll = 0;
}
KeyCode::Esc | KeyCode::Char('b') => {
self.detail_pending_g = false;
self.back_to_dashboard();
}
KeyCode::Char('q') => {
self.detail_pending_g = false;
self.running = false;
}
KeyCode::Char('?') => {
self.detail_pending_g = false;
self.handle_action(Action::OpenHelp);
}
// Commits section: j/k move the cursor; G jumps bottom; Enter scopes.
// These guards must appear BEFORE the unconditional j/k/G scroll arms
// so that match short-circuits here when in the Commits section.
KeyCode::Char('j') | KeyCode::Down
if self.pr_detail_selected_section == DetailSection::Commits =>
{
self.detail_pending_g = false;
if let Some(detail) = &self.pr_detail {
let last = detail.commits.len().saturating_sub(1);
self.commits_cursor = (self.commits_cursor + 1).min(last);
}
}
KeyCode::Char('k') | KeyCode::Up
if self.pr_detail_selected_section == DetailSection::Commits =>
{
self.detail_pending_g = false;
self.commits_cursor = self.commits_cursor.saturating_sub(1);
}
KeyCode::Char('G') if self.pr_detail_selected_section == DetailSection::Commits => {
self.detail_pending_g = false;
if let Some(detail) = &self.pr_detail {
let last = detail.commits.len().saturating_sub(1);
self.commits_cursor = last;
}
}
KeyCode::Down
if self.pr_detail_selected_section == DetailSection::Files
&& !self.pr_detail_files_show_diff =>
{
self.detail_pending_g = false;
self.cycle_files_cursor(1);
}
KeyCode::Up
if self.pr_detail_selected_section == DetailSection::Files
&& !self.pr_detail_files_show_diff =>
{
self.detail_pending_g = false;
self.cycle_files_cursor(-1);
}
// General j/k scroll (not in Commits section, which is handled above).
KeyCode::Char('j') | KeyCode::Down => {
self.detail_pending_g = false;
let next = self.right_pane_scroll().saturating_add(1);
*self.right_pane_scroll_mut() = next;
}
KeyCode::Char('k') | KeyCode::Up => {
self.detail_pending_g = false;
let next = self.right_pane_scroll().saturating_sub(1);
*self.right_pane_scroll_mut() = next;
}
KeyCode::Char('d') => {
self.detail_pending_g = false;
let next = self.right_pane_scroll().saturating_add(10);
*self.right_pane_scroll_mut() = next;
}
KeyCode::Char('u') => {
self.detail_pending_g = false;
let next = self.right_pane_scroll().saturating_sub(10);
*self.right_pane_scroll_mut() = next;
}
KeyCode::Char('g') => {
if self.detail_pending_g {
self.detail_pending_g = false;
// gg in Commits section jumps cursor to top; elsewhere scrolls to top.
if self.pr_detail_selected_section == DetailSection::Commits {
self.commits_cursor = 0;
} else {
*self.right_pane_scroll_mut() = 0;
}
} else {
self.detail_pending_g = true;
}
}
KeyCode::Char('G') => {
self.detail_pending_g = false;
// Set to a large value; the renderer clamps to valid range.
*self.right_pane_scroll_mut() = u16::MAX;
}
// J / K cycle the file cursor when the Files section is active.
// Matches the "shift = bigger hop" vim convention: unshifted j/k
// scroll within the current diff, shifted jumps to the next file.
KeyCode::Char('J') if self.pr_detail_selected_section == DetailSection::Files => {
self.detail_pending_g = false;
self.cycle_files_cursor(1);
}
KeyCode::Char('K') if self.pr_detail_selected_section == DetailSection::Files => {
self.detail_pending_g = false;
self.cycle_files_cursor(-1);
}
KeyCode::Enter if self.pr_detail_selected_section == DetailSection::Commits => {
self.detail_pending_g = false;
let Some(detail) = self.pr_detail.as_ref() else {
return;
};
if detail.commits.get(self.commits_cursor).is_none() {
return;
}
// Scope the Files section to the highlighted commit's delta.
// Intentionally clear thread expansion and diff cursor state
// when switching scope — threads are anchored to HEAD-view line
// numbers and become meaningless under a per-commit diff view.
self.pr_detail_expanded_threads.clear();
*self.pr_detail_diff_cursor.borrow_mut() = None;
self.selected_commit = Some(self.commits_cursor);
self.pr_detail_selected_section = DetailSection::Files;
self.pr_detail_files_show_diff = true;
self.pr_detail_files_cursor = 0;
self.copy_mode.h_scroll = 0;
// Kick a background fetch for the commit's patch if the eager
// PR-load prefetch has not already cached or started it.
let Some((repo, sha)) = self.pr_detail.as_ref().and_then(|detail| {
detail
.commits
.get(self.commits_cursor)
.map(|commit| (detail.repo.clone(), commit.sha.clone()))
}) else {
return;
};
self.request_commit_diff_fetch(repo, sha);
}
// H (capital): return to HEAD cumulative view from any scoped state.
// Guard: only fires when actually scoped (selected_commit.is_some())
// so we don't accidentally shadow vim-style `H` for non-scoped usage.
KeyCode::Char('H') if self.selected_commit.is_some() => {
self.detail_pending_g = false;
// Intentionally clear thread expansion and diff cursor when
// returning to HEAD — same reasoning as scoping into a commit.
self.pr_detail_expanded_threads.clear();
*self.pr_detail_diff_cursor.borrow_mut() = None;
self.selected_commit = None;
self.show_flash("Returned to HEAD", std::time::Duration::from_millis(1500));
}
KeyCode::Char('F') => {
// `F` jumps to Files in diff mode (drill-in gesture).
self.detail_pending_g = false;
self.pr_detail_selected_section = DetailSection::Files;
self.pr_detail_files_show_diff = true;
self.copy_mode.h_scroll = 0;
}
// Sidebar resize: `[` narrows (min 20), `]` widens (max 60).
KeyCode::Char('[') if !self.sidebar_hidden => {
self.detail_pending_g = false;
self.sidebar_width = self.sidebar_width.saturating_sub(2).max(20);
}
KeyCode::Char(']') => {
self.detail_pending_g = false;
self.sidebar_width = self.sidebar_width.saturating_add(2).min(60);
}
// Toggle sidebar visibility.
KeyCode::Char('\\') => {
self.detail_pending_g = false;
self.sidebar_hidden = !self.sidebar_hidden;
let msg = if self.sidebar_hidden { "Sidebar hidden" } else { "Sidebar shown" };
self.show_flash(msg, std::time::Duration::from_millis(1500));
}
KeyCode::Char('f') => {
self.detail_pending_g = false;
self.pr_detail_files_expanded = !self.pr_detail_files_expanded;
}
KeyCode::Char('m') => {
self.detail_pending_g = false;
self.detail_comments_expanded = !self.detail_comments_expanded;
}
KeyCode::Char('z') => {
// Toggle outdated-thread visibility in the Comments section.
// Default is visible-but-muted; pressing `z` collapses them
// into a single disclosure row so the list reads clean while
// still surfacing that outdated threads exist.
self.detail_pending_g = false;
self.detail_show_outdated = !self.detail_show_outdated;
}
KeyCode::Char('o') => {
self.detail_pending_g = false;
if let Some(url) = self.active_detail_url() {
let result = crate::actions_util::open_url_in_browser(&url);
self.flash_result(result, "Opened in browser", "Open failed");
}
}
KeyCode::Char('y') => {
self.detail_pending_g = false;
if let Some(url) = self.active_detail_url() {
let result = crate::actions_util::copy_to_clipboard(&url);
self.flash_result(result, "URL copied", "Copy failed");
}
}
KeyCode::Char('c') => {
self.detail_pending_g = false;
self.handle_action(Action::CheckoutBranch);
}
KeyCode::Char('M') => {
self.detail_pending_g = false;
self.handle_action(Action::BeginMergePullRequest(
crate::github::mutations::MergeMethod::Merge,
));
}
KeyCode::Char('S') => {
self.detail_pending_g = false;
self.handle_action(Action::BeginMergePullRequest(
crate::github::mutations::MergeMethod::Squash,
));
}
KeyCode::Char('A') => {
self.detail_pending_g = false;
if let Some(target) = self.top_level_comment_target() {
self.handle_action(Action::OpenCommentComposer(target));
}
}
KeyCode::Char('R') => {
self.detail_pending_g = false;
if let Some(target) = self.focused_review_thread_reply_target() {
self.handle_action(Action::OpenCommentComposer(target));
} else {
self.show_flash(
"Move to a review thread in the Files diff before replying",
std::time::Duration::from_secs(3),
);
}
}
KeyCode::Char('v') => {
self.detail_pending_g = false;
// Enter copy mode at the top of the current viewport. Clamp
// to the last real line so the cursor never strands on a
// non-existent row.
let lines = self.current_detail_lines();
let last_row = lines.len().saturating_sub(1);
let scroll = self.scroll_for(self.pr_detail_selected_section);
let row = (scroll as usize).min(last_row);
self.copy_mode.enter(row, 0);
}
// Toggle inline thread expansion at the current diff cursor position.
// Only active when the Files section is showing a diff so unrelated
// `t` presses (e.g. while scrolling Description) are no-ops.
KeyCode::Char('t')
if self.pr_detail_selected_section == DetailSection::Files
&& self.pr_detail_files_show_diff =>
{
self.detail_pending_g = false;
// Rebuild the current section's line buffer before reading
// the render-owned cursor. This makes `t` work immediately
// after a cached detail restore or programmatic file jump,
// before the next frame has had a chance to redraw.
let _ = self.current_detail_lines();
// `borrow()` is safe here — no other borrow is live across
// this synchronous path.
let cursor = self.pr_detail_diff_cursor.borrow().clone();
if let Some(anchor) = cursor {
if self.pr_detail_expanded_threads.contains(&anchor) {
self.pr_detail_expanded_threads.remove(&anchor);
} else {
self.pr_detail_expanded_threads.insert(anchor);
}
} else {
self.show_flash(
"No review thread at the current diff position",
std::time::Duration::from_secs(2),
);
}
}
// Collapse all expanded thread cards at once (does NOT reset scroll).
KeyCode::Char('T')
if self.pr_detail_selected_section == DetailSection::Files
&& self.pr_detail_files_show_diff =>
{
self.detail_pending_g = false;
self.pr_detail_expanded_threads.clear();
}
KeyCode::Char('r') => {
self.detail_pending_g = false;
// Manual refresh bypasses the cache. Invalidate the entry so
// the next restore is a cold miss (spinner) rather than a
// stale-while-revalidate serve. `spawn_detail_fetch` owns the
// `detail_fetching` guard — setting it externally would cause
// the guard to skip the fetch.
let target: Option<(DetailKind, String, u32)> =
if let Some(detail) = &self.pr_detail {
Some((DetailKind::Pr, detail.repo.clone(), detail.number))
} else {
self.issue_detail
.as_ref()
.map(|detail| (DetailKind::Issue, detail.repo.clone(), detail.number))
};
if let Some((kind, repo, number)) = target {
match kind {
DetailKind::Pr => self.detail_cache.invalidate_pr(&repo, number),
DetailKind::Issue => self.detail_cache.invalidate_issue(&repo, number),
}
self.clear_detail_state();
if let Some(tx) = self.action_tx.clone() {
self.spawn_detail_fetch(kind, repo, number, tx);
}
}
}
_ => {
self.detail_pending_g = false;
}
}
}
/// Key handler active only while `self.copy_mode.active` is `true`.
///
/// The copy-mode keymap is a separate modal layer: it owns `h`/`j`/`k`/`l`
/// and arrows for cursor movement, `V` to toggle the selection anchor,
/// `y` to yank the selection, and `Esc` to exit without copying.
///
/// Any key not listed here is intentionally swallowed so the user cannot
/// accidentally trigger destructive actions (like checkout) while trying
/// to copy text.
pub(super) fn handle_key_detail_copy_mode(&mut self, key: crossterm::event::KeyEvent) {
let lines = self.current_detail_lines();
match key.code {
KeyCode::Esc => {
self.copy_mode.exit();
}
KeyCode::Char('q') => {
self.copy_mode.exit();
self.running = false;
}
KeyCode::Char('h') | KeyCode::Left => {
self.copy_mode.move_cursor(-1, 0, &lines);
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('l') | KeyCode::Right => {
self.copy_mode.move_cursor(1, 0, &lines);
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('j') | KeyCode::Down => {
self.copy_mode.move_cursor(0, 1, &lines);
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('k') | KeyCode::Up => {
self.copy_mode.move_cursor(0, -1, &lines);
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('g') => {
self.copy_mode.jump_top();
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('G') => {
self.copy_mode.jump_bottom(&lines);
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('V' | 'v') => {
self.copy_mode.toggle_selection();
}
KeyCode::Char('0') | KeyCode::Home => {
self.copy_mode.cursor.col = 0;
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('$') | KeyCode::End => {
// Jump to the last character on the current row. Falls back to
// 0 when the row is empty so the cursor never falls off the
// end. Combined with `Y` below, this is the fastest path to
// copy a long error message that overflows the viewport.
let row = self.copy_mode.cursor.row;
let last_col = lines
.get(row)
.map_or(0, |l| l.spans.iter().map(|s| s.content.chars().count()).sum::<usize>())
.saturating_sub(1);
self.copy_mode.cursor.col = last_col;
self.ensure_cursor_visible(&lines);
}
KeyCode::Char('Y') => {
// One-shot "yank the current logical line to clipboard" —
// huge QoL win for copying long error strings that wrap off
// the right edge, where navigating `V` then `$` then `y` is
// five keys for what should be one.
let row = self.copy_mode.cursor.row;
if let Some(line) = lines.get(row) {
let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
Self::yank_and_flash(&mut self.flash, &text);
self.copy_mode.exit();
}
}
KeyCode::Char('y') => {
if let Some(text) = self.copy_mode.selected_text(&lines) {
Self::yank_and_flash(&mut self.flash, &text);
self.copy_mode.exit();
} else {
self.show_flash(
"No selection (press V to start, Y to yank whole line)",
std::time::Duration::from_secs(2),
);
}
}
_ => {}
}
}
/// Move the Files-sidebar cursor by `delta` rows, clamped to the PR's
/// file list. Also nudges `pr_detail_sidebar_scroll` so the newly-
/// selected file stays visible in the sidebar pane (best-effort —
/// viewport height isn't cached for the sidebar, so we use a
/// conservative default of 10 visible rows).
pub(super) fn cycle_files_cursor(&mut self, delta: i32) {
let Some(detail) = self.pr_detail.as_ref() else { return };
if detail.files.is_empty() {
return;
}
let last = detail.files.len().saturating_sub(1);
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
let current = self.pr_detail_files_cursor as i32;
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
let last_i = last as i32;
let next = current.saturating_add(delta).clamp(0, last_i);
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
{
self.pr_detail_files_cursor = next as usize;
}
// Nudge sidebar scroll so cursor stays roughly centred.
#[allow(clippy::cast_possible_truncation)]
let cursor_u16 = self.pr_detail_files_cursor as u16;
let visible = 10u16;
if cursor_u16 < self.pr_detail_sidebar_scroll {
self.pr_detail_sidebar_scroll = cursor_u16;
} else if cursor_u16 >= self.pr_detail_sidebar_scroll.saturating_add(visible) {
self.pr_detail_sidebar_scroll = cursor_u16.saturating_sub(visible).saturating_add(1);
}
}
// ── Repo picker ──────────────────────────────────────────────────────────
/// Close the repo picker and sync tabs to the current config.
///
/// Also resets picker state so the next `p` press starts fresh.
pub(super) fn close_repo_picker(&mut self) {
self.focus = self.repo_picker_return_focus;
self.repo_picker_input.clear();
self.repo_picker_mode = RepoPickerMode::List;
self.sync_tabs_to_config();
}
/// Ensure `App::tabs` mirrors `config.repos`: open any newly-added repos,
/// close any removed repos, and preserve the active tab where possible.
///
/// Also drops stale entries from the `selection` map: a repo that has been
/// removed from the config must not continue to hold a per-repo cursor
/// index, or long-running sessions would accumulate dead entries.
pub(super) fn sync_tabs_to_config(&mut self) {
// Close tabs whose repos are no longer in the config and drop any
// per-repo state that only makes sense for a tracked repo.
let removed: Vec<(crate::ui::tabs::TabId, String)> = self
.tabs
.tabs
.iter()
.filter(|t| !self.config.repos.contains(&t.repo))
.map(|t| (t.id, t.repo.clone()))
.collect();
for (id, repo) in removed {
self.tabs.close(id);
self.selection.remove(&repo);
}
// Open tabs for repos not yet represented.
for repo in &self.config.repos {
self.tabs.open_or_focus(repo);
}
// Restore cursor within bounds.
let max_idx = self.config.repos.len().saturating_sub(1);
if self.repo_picker_list_cursor > max_idx {
self.repo_picker_list_cursor = max_idx;
}
}
/// Key handler for the repo picker overlay.
pub(super) fn handle_key_repo_picker(&mut self, key: crossterm::event::KeyEvent) {
match self.repo_picker_mode {
RepoPickerMode::List => self.handle_repo_picker_list_key(key),
RepoPickerMode::Input => self.handle_repo_picker_input_key(key),
}
}
/// Key handler for repo picker List mode.
pub(super) fn handle_repo_picker_list_key(&mut self, key: crossterm::event::KeyEvent) {
if key.modifiers != KeyModifiers::NONE {
return;
}
let repo_count = self.config.repos.len();
match key.code {
KeyCode::Esc => {
self.close_repo_picker();
}
KeyCode::Char('j') | KeyCode::Down if repo_count > 0 => {
self.repo_picker_list_cursor =
(self.repo_picker_list_cursor + 1).min(repo_count - 1);
}
KeyCode::Char('k') | KeyCode::Up => {
self.repo_picker_list_cursor = self.repo_picker_list_cursor.saturating_sub(1);
}
KeyCode::Char('d') | KeyCode::Backspace if !self.config.repos.is_empty() => {
let idx = self.repo_picker_list_cursor.min(repo_count - 1);
self.config.repos.remove(idx);
self.config.save();
// Clamp cursor after removal.
let new_len = self.config.repos.len();
if new_len > 0 && self.repo_picker_list_cursor >= new_len {
self.repo_picker_list_cursor = new_len - 1;
} else if new_len == 0 {
self.repo_picker_list_cursor = 0;
}
self.sync_tabs_to_config();
}
KeyCode::Char('a' | 'i') => {
self.repo_picker_mode = RepoPickerMode::Input;
}
KeyCode::Enter if repo_count > 0 => {
// Focus the selected repo's tab and close the picker.
let idx = self.repo_picker_list_cursor.min(repo_count - 1);
let repo = self.config.repos[idx].clone();
self.tabs.open_or_focus(&repo);
self.close_repo_picker();
}
_ => {}
}
}
/// Key handler for repo picker Input mode.
pub(super) fn handle_repo_picker_input_key(&mut self, key: crossterm::event::KeyEvent) {
// Allow SHIFT (for uppercase letters in `0xIntuition`-style slugs).
// Reject only Ctrl / Alt / Meta, which are not expected inside a
// text field and would otherwise insert garbage characters on some
// terminals.
let blocked_mods = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER;
if key.modifiers.intersects(blocked_mods) {
return;
}
match key.code {
KeyCode::Esc => {
self.repo_picker_mode = RepoPickerMode::List;
self.repo_picker_input.clear();
}
KeyCode::Backspace => {
self.repo_picker_input.pop();
}
KeyCode::Enter => {
let slug = self.repo_picker_input.trim().to_owned();
if !crate::ui::repo_picker::is_valid_repo_slug(&slug) {
self.show_flash(
format!("Invalid repo slug: \"{slug}\". Use owner/name format."),
std::time::Duration::from_secs(3),
);
return;
}
// Dedup: silently ignore if already tracked.
if !self.config.repos.contains(&slug) {
self.config.repos.push(slug.clone());
self.config.save();
self.tabs.open_or_focus(&slug);
self.show_flash(format!("Added {slug}"), std::time::Duration::from_secs(2));
}
self.repo_picker_input.clear();
// Stay in Input mode so the user can add more repos.
}
KeyCode::Char(c) => {
self.repo_picker_input.push(c);
}
_ => {}
}
}
/// Key handler for the confirmation overlay.
pub(super) fn handle_key_confirm(&mut self, key: crossterm::event::KeyEvent) {
if key.modifiers != KeyModifiers::NONE {
return;
}
match key.code {
KeyCode::Char('y') => {
self.handle_action(Action::ConfirmPending(true));
}
KeyCode::Char('n' | 'N') | KeyCode::Esc => {
self.handle_action(Action::ConfirmPending(false));
}
_ => {}
}
}
/// Key handler for the markdown composer overlay.
pub(super) fn handle_key_composer(&mut self, key: crossterm::event::KeyEvent) {
if key.modifiers == KeyModifiers::CONTROL && matches!(key.code, KeyCode::Char('s' | 'S')) {
self.handle_action(Action::SubmitCommentComposer);
return;
}
let Some(composer) = self.composer.as_mut() else {
self.focus = self.composer_return_focus;
return;
};
match key.code {
KeyCode::Esc => {
self.composer = None;
self.focus = self.composer_return_focus;
}
KeyCode::Backspace => {
composer.body.pop();
}
KeyCode::Enter => {
composer.body.push('\n');
}
KeyCode::Char(ch)
if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT =>
{
composer.body.push(ch);
}
_ => {}
}
}
/// Open the theme picker overlay, recording the current theme so `Esc` can
/// revert it.
///
/// Initialises `theme_picker_cursor` to the index of the currently active
/// theme so the highlight starts on the user's existing choice.
pub fn open_theme_picker(&mut self) {
use crate::theme::Theme;
// Find the index of the current theme in the ordered list; default 0.
let current_idx = Theme::ALL.iter().position(|&t| t == self.config.theme).unwrap_or(0);
self.theme_picker_original = self.config.theme;
self.theme_picker_cursor = current_idx;
self.theme_picker_return_focus = self.focus;
self.focus = Focus::ThemePicker;
}
/// Key handler for the theme picker overlay ([`Focus::ThemePicker`]).
///
/// Bindings:
/// - `j` / `Down`: move cursor down (wraps around).
/// - `k` / `Up`: move cursor up (wraps around).
/// - `Enter`: apply the highlighted theme, persist config, close.
/// - `Esc`: restore the original theme (in-memory, no save), close.
pub(super) fn handle_key_theme_picker(&mut self, key: crossterm::event::KeyEvent) {
use crate::theme::{Palette, Theme};
if key.modifiers != KeyModifiers::NONE {
return;
}
let count = Theme::ALL.len();
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
// Wrap: last item → first item.
self.theme_picker_cursor = (self.theme_picker_cursor + 1) % count;
// Live preview.
self.palette = Palette::from_theme(Theme::ALL[self.theme_picker_cursor]);
}
KeyCode::Char('k') | KeyCode::Up => {
// Wrap: first item → last item.
self.theme_picker_cursor = (self.theme_picker_cursor + count - 1) % count;
// Live preview.
self.palette = Palette::from_theme(Theme::ALL[self.theme_picker_cursor]);
}
KeyCode::Enter => {
// Apply and persist.
let chosen = Theme::ALL[self.theme_picker_cursor];
self.config.theme = chosen;
self.palette = Palette::from_theme(chosen);
self.config.save();
self.focus = self.theme_picker_return_focus;
self.show_flash(
format!("Theme applied: {}", chosen.label()),
std::time::Duration::from_secs(3),
);
}
KeyCode::Esc => {
// Revert to the original theme (in-memory only; no save).
let original = self.theme_picker_original;
self.palette = Palette::from_theme(original);
// config.theme was never written, so it still holds the original
// value — no assignment needed here.
self.focus = self.theme_picker_return_focus;
self.show_flash("Theme change cancelled", std::time::Duration::from_secs(2));
}
_ => {}
}
}
/// Key handler for the dashboard (PR/issue list) focus.
#[allow(clippy::too_many_lines)] // dispatcher: each arm is one key binding
pub(super) fn handle_key_dashboard(&mut self, key: crossterm::event::KeyEvent) {
// Allow SHIFT (used for `A`, `G`, `R`, `N`) but reject Ctrl/Alt/Super
// so a stray `Ctrl+c` or `Alt+j` can't silently trigger list moves.
let blocked_mods = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER;
if key.modifiers.intersects(blocked_mods) {
self.pending_g = false;
return;
}
// Resolve active repo slug once.
let active_repo = self.tabs.active_tab().map(|t| t.repo.clone());
match key.code {
KeyCode::Char('j') | KeyCode::Down => {
self.pending_g = false;
if let Some(repo) = active_repo {
let len = self.active_list_len();
if len > 0 {
let sel = self.selection.entry(repo).or_insert(0);
*sel = (*sel + 1).min(len - 1);
}
}
}
KeyCode::Char('k') | KeyCode::Up => {
self.pending_g = false;
if let Some(repo) = active_repo {
let sel = self.selection.entry(repo).or_insert(0);
*sel = sel.saturating_sub(1);
}
}
KeyCode::Char('g') => {
if self.pending_g {
// Second `g` — jump to top.
self.pending_g = false;
if let Some(repo) = active_repo {
self.selection.insert(repo, 0);
}
} else {
self.pending_g = true;
}
}
KeyCode::Char('G') => {
self.pending_g = false;
if let Some(repo) = active_repo {
let len = self.active_list_len();
let bottom = if len > 0 { len - 1 } else { 0 };
self.selection.insert(repo, bottom);
}
}
KeyCode::Char('i') => {
self.pending_g = false;
self.handle_action(Action::ToggleView);
}
KeyCode::Char('r') => {
self.pending_g = false;
self.handle_action(Action::Refresh);
}
KeyCode::Char('R') => {
self.pending_g = false;
self.handle_action(Action::RefreshAll);
}
KeyCode::Enter => {
self.pending_g = false;
self.open_detail_for_selection();
}
KeyCode::Char('o') => {
self.pending_g = false;
if let Some(url) = self.dashboard_selected_url() {
let result = crate::actions_util::open_url_in_browser(&url);
self.flash_result(result, "Opened in browser", "Open failed");
}
}
KeyCode::Char('y') => {
self.pending_g = false;
if let Some(url) = self.dashboard_selected_url() {
let result = crate::actions_util::copy_to_clipboard(&url);
self.flash_result(result, "URL copied", "Copy failed");
}
}
KeyCode::Char('c') => {
self.pending_g = false;
// Open the theme picker. The checkout action is available in
// the detail view where `c` retains its original binding.
self.open_theme_picker();
}
KeyCode::Char('p') => {
tracing::debug!("dashboard: 'p' pressed — dispatching OpenRepoPicker");
self.pending_g = false;
self.handle_action(Action::OpenRepoPicker);
}
KeyCode::Char('A') => {
self.pending_g = false;
self.handle_action(Action::ToggleShowAll);
}
KeyCode::Char('f') => {
self.pending_g = false;
tracing::info!("Phase 4: not yet implemented — filter");
}
KeyCode::Char('n') => {
self.pending_g = false;
tracing::info!("Phase 4: not yet implemented — next match");
}
KeyCode::Char('N') => {
self.pending_g = false;
tracing::info!("Phase 4: not yet implemented — prev match");
}
KeyCode::Char('b') => {
self.pending_g = false;
tracing::info!("Phase 4: not yet implemented — back");
}
// All other keys (including Esc) cancel any pending chord.
_ => {
self.pending_g = false;
}
}
}
// ── Detail-view helpers ────────────────────────────────────────────────────
/// Return the URL of whichever detail object is currently loaded (PR first,
/// issue as fallback). `None` when neither is populated — which can happen
/// if the user hits a URL-consuming key before the first detail fetch
/// lands.
fn active_detail_url(&self) -> Option<String> {
self.pr_detail
.as_ref()
.map(|d| d.url.clone())
.or_else(|| self.issue_detail.as_ref().map(|d| d.url.clone()))
}
/// Resolve the review thread currently selected by the Files diff cursor.
fn focused_review_thread_reply_target(&self) -> Option<super::types::CommentComposerTarget> {
if self.pr_detail_selected_section != DetailSection::Files
|| !self.pr_detail_files_show_diff
|| self.selected_commit.is_some()
{
return None;
}
let detail = self.pr_detail.as_ref()?;
let cursor = self.pr_detail_diff_cursor.borrow().clone()?;
let thread_index = self.thread_index.as_ref()?;
let thread_idx = *thread_index.active_at(&cursor.0, cursor.1).first()?;
let thread = detail.review_threads.get(thread_idx)?;
Some(super::types::CommentComposerTarget::ReviewThreadReply {
repo: detail.repo.clone(),
number: detail.number,
thread_id: thread.node_id.clone(),
path: thread.path.clone(),
line: thread.line,
})
}
/// Return the URL of the PR or issue currently highlighted on the
/// dashboard. `None` when no inbox is loaded, no tab is active, or the
/// selection index is out of range.
fn dashboard_selected_url(&self) -> Option<String> {
let repo = self.tabs.active_tab()?.repo.clone();
let inbox = self.inbox.as_ref()?;
let sel = self.selection.get(&repo).copied().unwrap_or(0);
match self.session.view_mode(&repo) {
crate::state::ViewMode::Prs => crate::github::types::sorted_prs_for_repo(inbox, &repo)
.get(sel)
.map(|pr| pr.url.clone()),
crate::state::ViewMode::Issues => {
crate::github::types::sorted_issues_for_repo(inbox, &repo)
.get(sel)
.map(|i| i.url.clone())
}
}
}
/// Show a status-bar flash for a `Result<()>` OS action. The success
/// message gets a 2s duration; the error message gets 3s so users have
/// time to read the wrapped error detail.
fn flash_result(&mut self, result: anyhow::Result<()>, ok_msg: &str, err_prefix: &str) {
match result {
Ok(()) => self.show_flash(ok_msg.to_owned(), std::time::Duration::from_secs(2)),
Err(e) => {
self.show_flash(format!("{err_prefix}: {e}"), std::time::Duration::from_secs(3));
}
}
}
/// Reset every per-detail scroll / payload / refresh-flag field. Shared
/// by the `'r'` manual-refresh path so a future detail kind doesn't
/// silently skip part of the reset.
fn clear_detail_state(&mut self) {
self.detail_refreshing = None;
self.pr_detail = None;
self.issue_detail = None;
self.detail_error = None;
self.pr_detail_scroll.clear();
self.pr_detail_diff_scroll.clear();
// Critical: invalidate the thread index together with `pr_detail`.
// If we didn't, a brief race between `r` and the refetch would let
// the Files overview read a stale index keyed to the old PR's
// threads.
self.thread_index = None;
// Clear ephemeral thread expansion state alongside the index.
self.pr_detail_expanded_threads.clear();
*self.pr_detail_diff_cursor.borrow_mut() = None;
// Clear commit-scope state so a manual refresh always starts unscoped.
self.selected_commit = None;
self.commits_cursor = 0;
}
}