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
use std::io::{self, Stdout};
use std::path::{Path, PathBuf};
use anyhow::Result;
use ratatui::backend::CrosstermBackend;
use ratatui::crossterm::event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
MouseEventKind,
};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::Terminal;
use turboreview::app::{App, CommentScope, Mode, Pane, Section, ViewMode};
use turboreview::comments;
use turboreview::git::Repo;
use turboreview::{review, storage, ui};
/// Rows moved per Shift+Up/Down (or J/K) fast-nav step.
const JUMP_STEP: isize = 10;
/// Copy text to the system clipboard. A fresh handle is created per call;
/// arboard advises against holding one long-term on some platforms.
fn copy_to_clipboard(text: &str) -> Result<(), String> {
arboard::Clipboard::new()
.and_then(|mut cb| cb.set_text(text.to_string()))
.map_err(|e| e.to_string())
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--skill") {
print!("{}", turboreview::skill::SKILL_DOC);
return Ok(());
}
let repo_arg = args
.iter()
.skip(1)
.find(|a| !a.starts_with("--"))
.cloned()
.unwrap_or_else(|| ".".to_string());
let repo = Repo::discover(&PathBuf::from(&repo_arg))?;
let root = repo.workdir()?;
let unstaged = repo.changed_files(Mode::Unstaged)?;
let staged = repo.changed_files(Mode::Staged)?;
let mut app = App::new(unstaged, staged, root.clone());
// Startup: load from worktree scope
let wt_dir = storage::worktree_dir(&root);
app.reviewed = review::load(&wt_dir).unwrap_or_default();
app.comments = comments::Comments::load(&wt_dir).unwrap_or_default();
// Auto-archive resolved comments older than 14 days on startup
let cutoff = storage::archive_cutoff_secs(storage::now_secs());
let old = app.comments.drain_resolved_older_than(cutoff);
if !old.is_empty() {
match storage::append_archive(&root, &old) {
Ok(()) => {
let _ = app.comments.save(&wt_dir);
}
Err(_) => {
// Archive write failed — put the drained comments back so they are not lost.
app.comments.items.extend(old);
}
}
}
app.commits = repo.log(app.commit_limit).unwrap_or_default();
// Load persisted theme preference
app.theme = storage::load_theme(&root);
app.split_diff = storage::load_split(&root);
refresh_diff(&repo, &mut app);
let mut terminal = setup_terminal()?;
let result = run(&mut terminal, &repo, &mut app);
let restore = restore_terminal(&mut terminal);
result.and(restore)
}
/// Load the comments and reviewed set for the current scope into `app`.
fn load_scope(repo_root: &Path, app: &mut App) {
let dir = storage::scope_dir(repo_root, &app.comment_scope);
app.comments = comments::Comments::load(&dir).unwrap_or_default();
app.reviewed = review::load(&dir).unwrap_or_default();
}
/// Re-sync the comment scope to the current history revision (or the baseline),
/// load that scope's comments/reviewed, and refresh the diff. Call after any
/// change to `history.idx`.
fn sync_history_scope(repo: &Repo, app: &mut App) {
let anchor = app.history_active().then(|| app.cursor_lineno()).flatten();
match app.history_current_commit() {
Some(commit) => app.comment_scope = CommentScope::Commit(commit.id.clone()),
None => {
// Back at baseline (idx 0): restore whatever scope History saved.
if let Some(h) = app.history.as_ref() {
app.comment_scope = h.baseline_scope.clone();
}
}
}
let root = app.repo_root.clone();
load_scope(&root, app);
refresh_diff_preserving_line(repo, app, anchor);
}
/// Reload the diff, keeping the cursor on `anchor` when possible. Increases context
/// in steps of 5 (up to [`App::MAX_CONTEXT_LINES`]), then full-file, until visible.
fn refresh_diff_preserving_line(repo: &Repo, app: &mut App, anchor: Option<u32>) {
let Some(lineno) = anchor else {
refresh_diff(repo, app);
return;
};
loop {
refresh_diff(repo, app);
if app.diff_has_lineno(lineno) {
app.move_cursor_to_lineno(lineno);
return;
}
if app.full_file {
app.move_cursor_to_lineno(lineno);
return;
}
if app.context_lines >= App::MAX_CONTEXT_LINES {
app.full_file = true;
continue;
}
app.context_lines = (app.context_lines + 5).min(App::MAX_CONTEXT_LINES);
}
}
fn refresh_diff(repo: &Repo, app: &mut App) {
// File-history overlay: when showing a past revision (idx >= 1), render that
// commit's diff for the history file. idx 0 falls through to the baseline branches.
if let Some(commit) = app.history_current_commit() {
let id = commit.id.clone();
let file = app.history.as_ref().unwrap().file.clone();
match repo.commit_diff_for(&id, &file, app.effective_context()) {
Ok(lines) => {
app.status_msg = None;
app.set_diff(lines);
let candidates: Vec<(u32, String)> = app
.diff
.iter()
.filter_map(|l| l.new_lineno.map(|n| (n, l.text.trim().to_string())))
.collect();
app.comments.relocate_file(&file, &candidates);
}
Err(e) => {
app.status_msg = Some(format!("diff error: {e}"));
app.set_diff(Vec::new());
}
}
return;
}
// Commit-detail: use commit_diff_for instead of working-tree diff.
if app.in_commit_detail() {
if let (Some(path), Some(id)) = (app.selected_path().cloned(), app.open_commit.clone()) {
match repo.commit_diff_for(&id, &path, app.effective_context()) {
Ok(lines) => {
app.status_msg = None;
app.set_diff(lines);
let candidates: Vec<(u32, String)> = app
.diff
.iter()
.filter_map(|l| l.new_lineno.map(|n| (n, l.text.trim().to_string())))
.collect();
app.comments.relocate_file(&path, &candidates);
}
Err(e) => {
app.status_msg = Some(format!("diff error: {e}"));
app.set_diff(Vec::new());
}
}
} else {
app.set_diff(Vec::new());
}
return;
}
// Working-tree diff.
match (app.selected_path(), app.selected_section()) {
(Some(path), Some(section)) => {
let path = path.clone();
let mode = match section {
Section::Unstaged => Mode::Unstaged,
Section::Staged => Mode::Staged,
Section::Commit => return, // unreachable in working-tree branch
};
match repo.diff_for(&path, mode, app.effective_context()) {
Ok(lines) => {
app.status_msg = None;
app.set_diff(lines);
// Relocate comments for this file against the fresh diff.
let candidates: Vec<(u32, String)> = app
.diff
.iter()
.filter_map(|l| l.new_lineno.map(|n| (n, l.text.trim().to_string())))
.collect();
app.comments.relocate_file(&path, &candidates);
}
Err(e) => {
app.status_msg = Some(format!("diff error: {e}"));
app.set_diff(Vec::new());
}
}
}
_ => app.set_diff(Vec::new()),
}
}
fn reload_all(repo: &Repo, app: &mut App) {
let unstaged = match repo.changed_files(Mode::Unstaged) {
Ok(f) => f,
Err(e) => {
app.status_msg = Some(format!("list error: {e}"));
return;
}
};
let staged = match repo.changed_files(Mode::Staged) {
Ok(f) => f,
Err(e) => {
app.status_msg = Some(format!("list error: {e}"));
return;
}
};
app.unstaged = unstaged;
app.staged = staged;
load_scope(&app.repo_root.clone(), app);
app.rebuild_rows();
refresh_diff(repo, app);
}
/// Reload everything from disk/git so new external changes appear.
fn reload_everything(repo: &Repo, app: &mut App) {
// Reload file lists (on error set status_msg but keep going)
match repo.changed_files(Mode::Unstaged) {
Ok(f) => app.unstaged = f,
Err(e) => app.status_msg = Some(format!("list error: {e}")),
}
match repo.changed_files(Mode::Staged) {
Ok(f) => app.staged = f,
Err(e) => app.status_msg = Some(format!("list error: {e}")),
}
// Reload commits (keep whatever page size the user has scrolled to).
app.commits = repo.log(app.commit_limit).unwrap_or_default();
app.commit_stats.clear();
// If in a commit detail view, refresh that commit's files
if app.in_commit_detail() {
if let Some(id) = app.open_commit.clone() {
app.commit_files = repo.commit_files(&id).unwrap_or_default();
}
}
// Reload reviewed set and comments from the CURRENT scope
load_scope(&app.repo_root.clone(), app);
// Clamp comment_selected so it can't dangle past a now-shorter comment list.
let clen = app.comment_rows().len();
app.comment_selected = app.comment_selected.min(clen.saturating_sub(1));
// Rebuild rows and refresh diff
app.rebuild_rows();
refresh_diff(repo, app);
app.status_msg = Some("refreshed".into());
}
fn run(
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
repo: &Repo,
app: &mut App,
) -> Result<()> {
let mut pending_g = false; // for the `gg` chord
let mut pending_q = false; // for the `qq` quit chord (avoid accidental quit on a stray q)
loop {
// Fill diff stats for the visible commit window before drawing (the
// renderer only has &App and no repo handle).
if app.view == ViewMode::Commits && app.open_commit.is_none() {
let h = terminal.size().map(|s| s.height as usize).unwrap_or(40);
ensure_visible_commit_stats(repo, app, h);
}
terminal.draw(|f| ui::render(f, app))?;
match event::read()? {
Event::Key(key) => {
if key.kind != KeyEventKind::Press {
continue;
}
// When the comment input modal is active, route all keys to the
// editor and skip normal key handling entirely.
if app.input_active() {
match key.code {
KeyCode::Esc => app.input_cancel(),
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
// FIX 4: anchor comes from CommittedComment (captured at start_comment time).
if let Some(committed) = app.input_commit() {
let trimmed = committed.text.trim().to_string();
let action = if trimmed.is_empty() { "remove" } else { "set" };
if trimmed.is_empty() {
app.comments.remove(&committed.file, committed.line);
} else {
app.comments.set(
committed.file.clone(),
committed.line,
committed.hunk.clone(),
trimmed,
committed.line_text.clone(),
committed.context_before.clone(),
committed.context_after.clone(),
storage::now_secs(),
);
}
// Save to the current scope directory
let scope_dir =
storage::scope_dir(&app.repo_root, &app.comment_scope);
if let Err(e) = app.comments.save(&scope_dir) {
app.status_msg = Some(format!("comment save error: {e}"));
}
// Append to the comment log (best-effort)
let scope_label = app.scope_label();
let _ = storage::append_comment_log(
&app.repo_root,
&committed.file,
committed.line,
&scope_label,
action,
);
}
}
KeyCode::Enter => app.input_newline(),
KeyCode::Backspace => app.input_backspace(),
KeyCode::Char(c) => app.input_push(c),
_ => {}
}
continue;
}
// When the search input line is open, route keys to it.
if app.search_input_active() {
match key.code {
KeyCode::Esc => app.search_input_cancel(),
KeyCode::Enter => {
if !app.search_commit() {
// search_commit already cleared `search`; tell the user.
app.status_msg = Some("no match".into());
}
}
KeyCode::Backspace => app.search_input_backspace(),
KeyCode::Char(c) => app.search_input_push(c),
_ => {}
}
continue;
}
// Help overlay: while open, any key closes it (swallow).
if app.show_help {
app.show_help = false;
continue;
}
// `qq` chord quits; a single `q` only arms the chord, so an
// accidental stray `q` does nothing.
if matches!(key.code, KeyCode::Char('q')) && key.modifiers.is_empty() {
if pending_q {
return Ok(());
}
pending_q = true;
app.status_msg = Some("Press q again to quit".into());
continue;
}
pending_q = false;
if matches!(key.code, KeyCode::Char('g')) && key.modifiers.is_empty() {
if pending_g {
if app.view == ViewMode::Commits
&& app.open_commit.is_none()
&& app.focus == Pane::Files
{
app.selected_commit = 0;
} else if app.focus == Pane::Comments {
app.comment_selected = 0;
} else {
app.to_top();
}
pending_g = false;
} else {
pending_g = true;
}
continue;
}
pending_g = false;
match (key.code, key.modifiers) {
(KeyCode::Char('c'), KeyModifiers::CONTROL) => return Ok(()),
(KeyCode::Tab, _) => app.toggle_focus(),
(KeyCode::Char('s'), _) => {
if app.focus == Pane::Files {
if let (Some(path), Some(section)) =
(app.selected_path().cloned(), app.selected_section())
{
let result = match section {
Section::Unstaged => repo.stage_file(&path),
Section::Staged => repo.unstage_file(&path),
// Commit-detail files cannot be staged/unstaged.
Section::Commit => continue,
};
match result {
Ok(()) => {
app.status_msg = None;
reload_all(repo, app);
}
Err(e) => {
app.status_msg = Some(format!("stage error: {e}"));
}
}
}
// If a Header or Dir is selected, s does nothing
}
// s in Diff pane is deferred (does nothing this phase)
}
(KeyCode::Char(' '), _) => {
// In Commits-list mode (not in detail), rows are stale working-tree rows;
// toggle_reviewed would act on the wrong file, so ignore.
if !(app.view == ViewMode::Commits && !app.in_commit_detail()) {
app.toggle_reviewed();
// Save reviewed to the current scope directory
let scope_dir = storage::scope_dir(&app.repo_root, &app.comment_scope);
if let Err(e) = review::save(&scope_dir, &app.reviewed) {
app.status_msg = Some(format!("save error: {e}"));
}
refresh_diff(repo, app);
}
}
(KeyCode::Char('G'), _) => {
if app.view == ViewMode::Commits
&& app.open_commit.is_none()
&& app.focus == Pane::Files
{
app.selected_commit = app.commits.len().saturating_sub(1);
} else if app.focus == Pane::Comments {
let len = app.comment_rows().len();
app.comment_selected = len.saturating_sub(1);
} else {
app.to_bottom();
}
}
(KeyCode::Char('L'), _) => {
if app.view == ViewMode::Commits
&& app.open_commit.is_none()
&& app.focus == Pane::Files
{
load_more_commits(repo, app);
}
}
(KeyCode::Char('C'), _) => app.toggle_comment_pane(),
(KeyCode::Char('R'), _) => {
app.toggle_hide_reviewed();
refresh_diff(repo, app);
}
// Shift+Up/Down (or K/J) jump by JUMP_STEP for faster scrolling.
(KeyCode::Up, KeyModifiers::SHIFT) | (KeyCode::Char('K'), _) => {
move_in_focus(repo, app, -JUMP_STEP)
}
(KeyCode::Down, KeyModifiers::SHIFT) | (KeyCode::Char('J'), _) => {
move_in_focus(repo, app, JUMP_STEP)
}
(KeyCode::Up, _) | (KeyCode::Char('k'), _) => move_in_focus(repo, app, -1),
(KeyCode::Down, _) | (KeyCode::Char('j'), _) => move_in_focus(repo, app, 1),
(KeyCode::Enter, _) => {
if app.focus == Pane::Comments {
// Jump to the selected comment's file and line in the diff.
if let Some(c) = app.selected_comment().cloned() {
if app.select_row_for_path(&c.file) {
refresh_diff(repo, app);
app.move_cursor_to_line(c.line);
app.focus = Pane::Diff;
} else {
app.status_msg =
Some("comment's file not in current view".into());
}
}
} else if app.focus == Pane::Files {
if app.view == ViewMode::Commits && !app.in_commit_detail() {
// Commit list: Enter drills into the selected commit.
if let Some(ci) = app.selected_commit_info() {
let id = ci.id.clone();
match repo.commit_files(&id) {
Ok(files) => {
app.status_msg = None;
app.open_commit(id.clone(), files);
// Load this commit's scope data
load_scope(&app.repo_root.clone(), app);
refresh_diff(repo, app);
}
Err(e) => {
app.status_msg =
Some(format!("commit files error: {e}"));
}
}
}
} else if app.selected_path().is_some() {
// File row (either Changes view or commit-detail): jump to diff.
app.focus = Pane::Diff;
} else {
// Dir/header row: fold/unfold.
app.toggle_collapse();
if app.selected_path().is_some() {
refresh_diff(repo, app);
}
}
}
}
(KeyCode::Char('V'), _) => {
if app.focus == Pane::Diff && !app.diff.is_empty() {
app.start_select();
}
}
(KeyCode::Char('y'), _) => {
if app.focus == Pane::Diff && !app.diff.is_empty() {
let (lo, hi) = app.select_range();
let n = hi - lo + 1;
match copy_to_clipboard(&app.selection_text()) {
Ok(()) => {
app.status_msg = Some(if n == 1 {
"copied line".into()
} else {
format!("copied {n} lines")
})
}
Err(e) => app.status_msg = Some(format!("copy error: {e}")),
}
app.cancel_select();
}
}
(KeyCode::Esc, _) => {
if app.select_active() {
app.cancel_select();
} else if app.history_active() && app.focus == Pane::Diff {
app.exit_history();
let root = app.repo_root.clone();
load_scope(&root, app);
refresh_diff(repo, app);
} else if app.in_commit_detail() && app.focus == Pane::Diff {
// Inside a commit's file diff: step back to that commit's
// file list, not all the way out to the commit list.
app.focus = Pane::Files;
} else if app.in_commit_detail() {
// On the commit's file list: back out to the commit list.
app.close_commit();
// Reload worktree scope after leaving commit detail
load_scope(&app.repo_root.clone(), app);
} else {
app.focus = Pane::Files;
}
}
(KeyCode::Char('F'), _) => {
app.toggle_full_file();
refresh_diff(repo, app);
}
(KeyCode::Char('H'), _) => {
if app.focus == Pane::Diff {
if app.history_active() {
// Toggle off: exit and reload baseline scope/diff.
app.exit_history();
let root = app.repo_root.clone();
load_scope(&root, app);
refresh_diff(repo, app);
} else if let Some(file) = app.selected_path().cloned() {
match repo.file_history(&file, App::MAX_FILE_HISTORY) {
Ok(commits) => {
if app.start_history(commits) {
sync_history_scope(repo, app);
} else {
app.status_msg =
Some(format!("no history for {}", file.display()));
}
}
Err(e) => {
app.status_msg = Some(format!("history error: {e}"));
}
}
}
}
}
(KeyCode::Char('{'), _) => {
if app.history_active() {
app.history_step(1); // older
sync_history_scope(repo, app);
}
}
(KeyCode::Char('}'), _) => {
if app.history_active() {
app.history_step(-1); // newer
sync_history_scope(repo, app);
}
}
(KeyCode::Char('l'), _) | (KeyCode::Right, _) => {
if app.focus == Pane::Diff {
app.scroll_h(1);
}
}
(KeyCode::Char('h'), _) | (KeyCode::Left, _) => {
if app.focus == Pane::Diff {
app.scroll_h(-1);
}
}
(KeyCode::Char('+'), _) | (KeyCode::Char('='), _) => {
app.inc_context();
refresh_diff(repo, app);
}
(KeyCode::Char('-'), _) => {
app.dec_context();
refresh_diff(repo, app);
}
(KeyCode::Char(']'), _) => {
if app.history_active() {
app.exit_history();
}
let was_in_commit = app.in_commit_detail();
app.next_view();
// If we were in a commit detail and left, reload worktree scope
if was_in_commit {
load_scope(&app.repo_root.clone(), app);
}
}
(KeyCode::Char('['), _) => {
if app.history_active() {
app.exit_history();
}
let was_in_commit = app.in_commit_detail();
app.prev_view();
// If we were in a commit detail and left, reload worktree scope
if was_in_commit {
load_scope(&app.repo_root.clone(), app);
}
}
// a — smart fold-all: collapse every dir, or expand all if all collapsed.
(KeyCode::Char('a'), _) => {
app.toggle_fold_all();
refresh_diff(repo, app);
}
(KeyCode::Char('z'), _) => app.toggle_files(),
(KeyCode::Char('>'), _) | (KeyCode::Char('.'), _) => app.widen_files(),
(KeyCode::Char('<'), _) | (KeyCode::Char(','), _) => app.narrow_files(),
// r (lowercase) refreshes everything from disk/git; R (uppercase) hides reviewed.
(KeyCode::Char('r'), KeyModifiers::NONE) => reload_everything(repo, app),
// T toggles light / dark theme and persists the choice
(KeyCode::Char('T'), _) => {
app.toggle_theme();
let _ = storage::save_theme(&app.repo_root, app.theme);
}
// v toggles side-by-side / unified diff and persists the choice
(KeyCode::Char('v'), _) => {
app.toggle_split();
let _ = storage::save_split(&app.repo_root, app.split_diff);
}
// A (capital) — archive all resolved comments in the current scope
(KeyCode::Char('A'), _) => {
// Peek the resolved comments WITHOUT draining yet.
let resolved: Vec<_> = app
.comments
.items
.iter()
.filter(|c| c.status == comments::CommentStatus::Resolved)
.cloned()
.collect();
if resolved.is_empty() {
app.status_msg = Some("no resolved comments to archive".into());
} else {
// Archive FIRST. Only mutate the active set if the archive write succeeded.
match storage::append_archive(&app.repo_root, &resolved) {
Ok(()) => {
let n = app.comments.drain_resolved().len();
let dir =
storage::scope_dir(&app.repo_root, &app.comment_scope);
match app.comments.save(&dir) {
Ok(()) => {
let clen = app.comment_rows().len();
app.comment_selected =
app.comment_selected.min(clen.saturating_sub(1));
app.status_msg =
Some(format!("archived {n} resolved comment(s)"));
}
Err(e) => {
app.status_msg =
Some(format!("archive save error: {e}"))
}
}
}
Err(e) => app.status_msg = Some(format!("archive error: {e}")),
}
}
}
// ? toggles the help overlay
(KeyCode::Char('?'), _) => app.toggle_help(),
(KeyCode::Char('/'), _) => {
if app.focus == Pane::Diff {
app.search_start();
}
}
(KeyCode::Char('n'), _) => {
if app.search_active() {
app.search_next(1);
}
}
(KeyCode::Char('N'), _) => {
if app.search_active() {
app.search_next(-1);
}
}
// c (no modifier) opens comment modal; Ctrl-C is already handled above.
// In Commits-list mode (not in detail), rows are stale; ignore.
(KeyCode::Char('c'), _) => {
if !(app.view == ViewMode::Commits && !app.in_commit_detail()) {
app.start_comment();
}
}
_ => {}
}
}
Event::Mouse(m) => match m.kind {
MouseEventKind::ScrollUp => move_in_focus(repo, app, -1),
MouseEventKind::ScrollDown => move_in_focus(repo, app, 1),
_ => {}
},
_ => {}
}
}
}
/// Compute and cache diff stats for the band of commits around the cursor
/// (`viewport_h` rows above and below), so the visible rows always have stats.
fn ensure_visible_commit_stats(repo: &Repo, app: &mut App, viewport_h: usize) {
if app.commits.is_empty() {
return;
}
let sel = app.selected_commit;
let lo = sel.saturating_sub(viewport_h);
let hi = (sel + viewport_h).min(app.commits.len().saturating_sub(1));
for i in lo..=hi {
let id = app.commits[i].id.clone();
if !app.commit_stats.contains_key(&id) {
if let Ok(stat) = repo.commit_stat(&id) {
app.commit_stats.insert(id, stat);
}
}
}
}
/// Grow the commit log by one page (`COMMIT_PAGE`) and report the result.
fn load_more_commits(repo: &Repo, app: &mut App) {
let before = app.commits.len();
app.commit_limit += turboreview::COMMIT_PAGE;
app.commits = repo.log(app.commit_limit).unwrap_or_default();
let loaded = app.commits.len();
if loaded > before {
app.status_msg = Some(format!("Loaded {} commits", loaded));
} else {
app.status_msg = Some("No more commits to load".into());
}
}
fn move_in_focus(repo: &Repo, app: &mut App, delta: isize) {
match app.focus {
Pane::Files => {
if app.view == ViewMode::Commits && app.open_commit.is_none() {
// Commit list: move commit selection. At the bottom, prompt to
// load more when the page may have been truncated.
let at_bottom = app.selected_commit + 1 >= app.commits.len();
let maybe_more = app.commits.len() == app.commit_limit;
if delta > 0 && at_bottom && maybe_more {
app.status_msg =
Some("End of loaded commits — press L to load more".into());
} else {
app.move_commit_selection(delta);
}
} else {
// Changes view or commit-detail: move file row selection.
if app.history_active() {
app.exit_history();
let root = app.repo_root.clone();
load_scope(&root, app);
}
app.move_selection(delta);
refresh_diff(repo, app);
}
}
Pane::Diff => app.move_diff_cursor(delta),
Pane::Comments => app.move_comment_selection(delta),
}
}
fn setup_terminal() -> Result<Terminal<CrosstermBackend<Stdout>>> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
hook(info);
}));
let terminal = Terminal::new(CrosstermBackend::new(stdout))?;
Ok(terminal)
}
fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}