tij 0.4.16

Text-mode interface for Jujutsu - a TUI for jj version control
Documentation
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
//! Diff View
//!
//! Displays the diff for a selected change from the log view.

mod input;
mod render;

use crate::model::{CompareInfo, DiffContent, DiffDisplayFormat};

/// Action returned by DiffView key handling
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffAction {
    /// No action needed
    None,
    /// Return to log view
    Back,
    /// Open blame/annotation for current file
    OpenBlame {
        /// File path to annotate
        file_path: String,
    },
    /// Show an info notification (e.g., feature unavailable in current mode)
    ShowNotification(String),
    /// Copy diff to clipboard (full = jj show, !full = jj diff)
    CopyToClipboard { full: bool },
    /// Export diff to .patch file
    ExportToFile,
    /// Cycle display format (color-words → stat → git → color-words)
    CycleFormat,
}

/// Diff view state
#[derive(Debug)]
pub struct DiffView {
    /// Change ID being displayed
    pub revision: String,
    /// Parsed diff content
    pub content: DiffContent,
    /// Scroll offset (line index)
    pub scroll_offset: usize,
    /// Positions of file headers in the lines array
    pub file_header_positions: Vec<usize>,
    /// File names (extracted from headers)
    pub file_names: Vec<String>,
    /// Current file index (for context bar)
    pub current_file_index: usize,
    /// Last known visible height (updated during render)
    visible_height: usize,
    /// Compare info (set when in compare mode, None for normal single-revision diff)
    pub compare_info: Option<CompareInfo>,
    /// Current display format
    pub display_format: DiffDisplayFormat,
}

impl Default for DiffView {
    fn default() -> Self {
        Self::empty()
    }
}

impl DiffView {
    /// Default visible height for scroll calculations when not specified
    const DEFAULT_VISIBLE_HEIGHT: usize = 20;

    /// Create a new empty DiffView
    pub fn empty() -> Self {
        Self {
            revision: String::new(),
            content: DiffContent::default(),
            scroll_offset: 0,
            file_header_positions: Vec::new(),
            file_names: Vec::new(),
            current_file_index: 0,
            visible_height: Self::DEFAULT_VISIBLE_HEIGHT,
            compare_info: None,
            display_format: DiffDisplayFormat::default(),
        }
    }

    /// Create a new DiffView with content
    pub fn new(revision: String, content: DiffContent) -> Self {
        let mut view = Self::empty();
        view.set_content(revision, content);
        view
    }

    /// Create a new DiffView in compare mode (two-revision diff)
    pub fn new_compare(content: DiffContent, compare_info: CompareInfo) -> Self {
        let mut view = Self::empty();
        // Use the "from" commit_id as the primary ID (divergent-safe)
        let revision = compare_info.from.commit_id.to_string();
        view.set_content(revision, content);
        view.compare_info = Some(compare_info);
        view
    }

    /// Set the content to display
    pub fn set_content(&mut self, revision: String, content: DiffContent) {
        use crate::model::DiffLineKind;

        // Extract file header positions and names
        let (positions, names): (Vec<_>, Vec<_>) = content
            .lines
            .iter()
            .enumerate()
            .filter(|(_, line)| line.kind == DiffLineKind::FileHeader)
            .map(|(i, line)| (i, line.content.clone()))
            .unzip();

        self.file_header_positions = positions;
        self.file_names = names;
        self.revision = revision;
        self.content = content;
        self.scroll_offset = 0;
        self.current_file_index = 0;
    }

    /// Clear the view (test-only helper)
    #[cfg(test)]
    pub fn clear(&mut self) {
        self.revision.clear();
        self.content = DiffContent::default();
        self.scroll_offset = 0;
        self.file_header_positions.clear();
        self.file_names.clear();
        self.current_file_index = 0;
        self.visible_height = Self::DEFAULT_VISIBLE_HEIGHT;
        self.display_format = DiffDisplayFormat::default();
    }

    /// Cycle to the next display format
    pub fn cycle_format(&mut self) -> DiffDisplayFormat {
        self.display_format = self.display_format.next();
        self.display_format
    }

    /// Get current file name for context bar
    pub fn current_file_name(&self) -> Option<&str> {
        self.file_names
            .get(self.current_file_index)
            .map(|s| s.as_str())
    }

    /// Get total file count
    pub fn file_count(&self) -> usize {
        self.file_names.len()
    }

    /// Count description lines for header height calculation
    pub fn description_line_count(&self) -> usize {
        if self.content.description.is_empty() {
            1 // "(no description)" placeholder
        } else {
            self.content.description.lines().count().max(1)
        }
    }

    /// Check if there are any changes to display
    pub fn has_changes(&self) -> bool {
        self.content.has_changes()
    }

    /// Total number of diff lines
    pub fn total_lines(&self) -> usize {
        self.content.lines.len()
    }

    /// Get current context string for status bar
    pub fn current_context(&self) -> String {
        if self.file_count() > 0 {
            let file_name = self.current_file_name().unwrap_or("(unknown)");
            format!(
                "{} [{}/{}]",
                file_name,
                self.current_file_index + 1,
                self.file_count()
            )
        } else {
            "(no files)".to_string()
        }
    }

    // =========================================================================
    // Navigation
    // =========================================================================

    /// Scroll up by one line
    pub fn scroll_up(&mut self) {
        self.scroll_offset = self.scroll_offset.saturating_sub(1);
        self.update_current_file_index();
    }

    /// Scroll down by one line
    pub fn scroll_down(&mut self) {
        let max_offset = self.max_scroll_offset();
        if self.scroll_offset < max_offset {
            self.scroll_offset += 1;
        }
        self.update_current_file_index();
    }

    /// Calculate maximum scroll offset based on visible height
    fn max_scroll_offset(&self) -> usize {
        // If visible_height is 0, don't allow scrolling
        if self.visible_height == 0 {
            return 0;
        }
        let total = self.total_lines();
        total.saturating_sub(self.visible_height)
    }

    /// Scroll up by half page
    pub fn scroll_half_page_up(&mut self, visible_height: usize) {
        self.visible_height = visible_height;
        let half = visible_height / 2;
        self.scroll_offset = self.scroll_offset.saturating_sub(half);
        self.update_current_file_index();
    }

    /// Scroll down by half page
    pub fn scroll_half_page_down(&mut self, visible_height: usize) {
        self.visible_height = visible_height;
        let half = visible_height / 2;
        let max_offset = self.max_scroll_offset();
        self.scroll_offset = (self.scroll_offset + half).min(max_offset);
        self.update_current_file_index();
    }

    /// Jump to the top
    pub fn jump_to_top(&mut self) {
        self.scroll_offset = 0;
        self.current_file_index = 0;
    }

    /// Jump to the bottom
    pub fn jump_to_bottom(&mut self, visible_height: usize) {
        self.visible_height = visible_height;
        self.scroll_offset = self.max_scroll_offset();
        self.update_current_file_index();
    }

    /// Jump to the next file
    pub fn next_file(&mut self) {
        if self.file_header_positions.is_empty() {
            return;
        }

        // Find the next file header position after current scroll
        for (i, &pos) in self.file_header_positions.iter().enumerate() {
            if pos > self.scroll_offset {
                self.scroll_offset = pos;
                self.current_file_index = i;
                return;
            }
        }

        // Wrap around to first file
        if let Some(&first_pos) = self.file_header_positions.first() {
            self.scroll_offset = first_pos;
            self.current_file_index = 0;
        }
    }

    /// Jump to the previous file
    pub fn prev_file(&mut self) {
        if self.file_header_positions.is_empty() {
            return;
        }

        // Find the previous file header position before current scroll
        for (i, &pos) in self.file_header_positions.iter().enumerate().rev() {
            if pos < self.scroll_offset {
                self.scroll_offset = pos;
                self.current_file_index = i;
                return;
            }
        }

        // Wrap around to last file
        if let Some(&last_pos) = self.file_header_positions.last() {
            self.scroll_offset = last_pos;
            self.current_file_index = self.file_header_positions.len() - 1;
        }
    }

    /// Update current_file_index based on scroll position
    fn update_current_file_index(&mut self) {
        self.current_file_index = self
            .file_header_positions
            .iter()
            .rposition(|&pos| pos <= self.scroll_offset)
            .unwrap_or(0);
    }

    /// Jump to a specific file by path
    ///
    /// If the file is found, scrolls to its header position.
    /// If not found, does nothing.
    ///
    /// This handles renamed files where jj show outputs `prefix{old => new}`
    /// but StatusView passes just the new path `prefix/new`.
    pub fn jump_to_file(&mut self, file_path: &str) {
        // First try exact match
        if let Some(idx) = self.file_names.iter().position(|name| name == file_path)
            && let Some(&pos) = self.file_header_positions.get(idx)
        {
            self.scroll_offset = pos;
            self.current_file_index = idx;
            return;
        }

        // Try matching renamed files: "prefix{old => new}" should match "prefix/new"
        for (idx, name) in self.file_names.iter().enumerate() {
            if let Some(new_path) = Self::extract_new_path_from_rename(name)
                && new_path == file_path
                && let Some(&pos) = self.file_header_positions.get(idx)
            {
                self.scroll_offset = pos;
                self.current_file_index = idx;
                return;
            }
        }
    }

    /// Extract the new path from a rename pattern like "prefix{old => new}"
    ///
    /// Returns the reconstructed new path: "prefix/new"
    fn extract_new_path_from_rename(name: &str) -> Option<String> {
        let brace_start = name.find('{')?;
        let brace_end = name.find('}')?;
        let prefix = &name[..brace_start];
        let inner = &name[brace_start + 1..brace_end];
        let (_, new_part) = inner.split_once(" => ")?;
        Some(format!("{}{}", prefix, new_part))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{CommitId, DiffContent, DiffLine};
    use crossterm::event::KeyEvent;

    fn create_test_content() -> DiffContent {
        let mut content = DiffContent {
            commit_id: CommitId::new("abc123def456".to_string()),
            author: "Test User <test@example.com>".to_string(),
            timestamp: "2024-01-30 12:00:00".to_string(),
            description: "Test commit".to_string(),
            lines: Vec::new(),
        };

        // Add some test diff lines
        content.lines.push(DiffLine::file_header("src/main.rs"));
        content
            .lines
            .push(DiffLine::context(Some(10), Some(10), "fn main() {"));
        content
            .lines
            .push(DiffLine::deleted(11, "    println!(\"old\");"));
        content
            .lines
            .push(DiffLine::added(11, "    println!(\"new\");"));
        content
            .lines
            .push(DiffLine::context(Some(12), Some(12), "}"));
        content.lines.push(DiffLine::separator());
        content.lines.push(DiffLine::file_header("src/lib.rs"));
        content.lines.push(DiffLine::added(1, "pub fn hello() {}"));

        content
    }

    #[test]
    fn test_diff_view_empty() {
        let view = DiffView::empty();
        assert!(view.revision.is_empty());
        assert!(!view.has_changes());
        assert_eq!(view.file_count(), 0);
    }

    #[test]
    fn test_diff_view_new() {
        let view = DiffView::new("testchange".to_string(), create_test_content());

        assert_eq!(view.revision, "testchange");
        assert!(view.has_changes());
        assert_eq!(view.file_count(), 2);
        assert_eq!(view.file_names, vec!["src/main.rs", "src/lib.rs"]);
        assert_eq!(view.file_header_positions, vec![0, 6]);
    }

    #[test]
    fn test_diff_view_scroll() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        // Set visible height smaller than total lines to allow scrolling
        view.visible_height = 5;

        assert_eq!(view.scroll_offset, 0);

        view.scroll_down();
        assert_eq!(view.scroll_offset, 1);

        view.scroll_down();
        view.scroll_down();
        assert_eq!(view.scroll_offset, 3);

        view.scroll_up();
        assert_eq!(view.scroll_offset, 2);

        view.jump_to_top();
        assert_eq!(view.scroll_offset, 0);
    }

    #[test]
    fn test_diff_view_scroll_bounds() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // Scroll up at top should stay at 0
        view.scroll_up();
        assert_eq!(view.scroll_offset, 0);

        // Set a visible height smaller than total lines
        view.visible_height = 5;

        // Scroll to bottom
        for _ in 0..20 {
            view.scroll_down();
        }

        // With 8 total lines and 5 visible, max offset should be 3
        // (so the last 5 lines are visible)
        let expected_max = view.total_lines().saturating_sub(view.visible_height);
        assert_eq!(view.scroll_offset, expected_max);
    }

    #[test]
    fn test_diff_view_file_jump() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);

        // Jump to next file (src/lib.rs at position 6)
        view.next_file();
        assert_eq!(view.current_file_index, 1);
        assert_eq!(view.scroll_offset, 6);

        // Jump to next file wraps to first
        view.next_file();
        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);

        // Jump to previous file
        view.prev_file();
        assert_eq!(view.current_file_index, 1);
        assert_eq!(view.scroll_offset, 6);
    }

    #[test]
    fn test_diff_view_current_file_name() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        assert_eq!(view.current_file_name(), Some("src/main.rs"));

        view.next_file();
        assert_eq!(view.current_file_name(), Some("src/lib.rs"));
    }

    #[test]
    fn test_diff_view_handle_key_scroll() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // Use handle_key_with_height to set visible height smaller than total lines
        let action =
            view.handle_key_with_height(KeyEvent::from(crossterm::event::KeyCode::Char('j')), 5);
        assert_eq!(action, DiffAction::None);
        assert_eq!(view.scroll_offset, 1);
    }

    #[test]
    fn test_diff_view_handle_key_back() {
        let mut view = DiffView::empty();

        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('q')));
        assert_eq!(action, DiffAction::Back);

        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Esc));
        assert_eq!(action, DiffAction::Back);
    }

    #[test]
    fn test_diff_view_half_page_scroll() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // With 8 total lines and visible_height 4, max offset is 4
        // Half page is 2, so first scroll goes to 2
        view.scroll_half_page_down(4);
        assert_eq!(view.scroll_offset, 2);

        view.scroll_half_page_up(4);
        assert_eq!(view.scroll_offset, 0);
    }

    #[test]
    fn test_diff_view_clear() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        // Set visible height smaller than total lines to allow scrolling
        view.visible_height = 5;
        view.scroll_down();

        assert!(view.has_changes());
        assert_eq!(view.scroll_offset, 1);

        view.clear();

        assert!(!view.has_changes());
        assert_eq!(view.scroll_offset, 0);
        assert!(view.revision.is_empty());
    }

    #[test]
    fn test_diff_view_update_current_file_index() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // At start, should be file 0
        assert_eq!(view.current_file_index, 0);

        // After scrolling past file header of second file
        view.scroll_offset = 7;
        view.update_current_file_index();
        assert_eq!(view.current_file_index, 1);

        // Back before second file
        view.scroll_offset = 3;
        view.update_current_file_index();
        assert_eq!(view.current_file_index, 0);
    }

    #[test]
    fn test_diff_view_current_context() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        assert_eq!(view.current_context(), "src/main.rs [1/2]");

        view.next_file();
        assert_eq!(view.current_context(), "src/lib.rs [2/2]");
    }

    #[test]
    fn test_diff_view_current_context_empty() {
        let view = DiffView::empty();
        assert_eq!(view.current_context(), "(no files)");
    }

    #[test]
    fn test_diff_view_scroll_with_zero_visible_height() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // When visible_height is 0, scrolling should not be allowed
        view.visible_height = 0;

        // Try to scroll down - should stay at 0
        view.scroll_down();
        assert_eq!(view.scroll_offset, 0);

        // Try half page down with 0 height
        view.scroll_half_page_down(0);
        assert_eq!(view.scroll_offset, 0);
    }

    #[test]
    fn test_diff_view_jump_to_file() {
        let mut view = DiffView::new("test".to_string(), create_test_content());

        // Start at first file
        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);

        // Jump to second file by path
        view.jump_to_file("src/lib.rs");
        assert_eq!(view.current_file_index, 1);
        assert_eq!(view.scroll_offset, 6); // Second file header is at position 6

        // Jump back to first file
        view.jump_to_file("src/main.rs");
        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);

        // Jump to non-existent file should do nothing
        view.jump_to_file("non_existent.rs");
        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);
    }

    #[test]
    fn test_extract_new_path_from_rename() {
        // Standard rename with prefix
        assert_eq!(
            DiffView::extract_new_path_from_rename("src/{old.rs => new.rs}"),
            Some("src/new.rs".to_string())
        );

        // Rename without prefix
        assert_eq!(
            DiffView::extract_new_path_from_rename("{old.rs => new.rs}"),
            Some("new.rs".to_string())
        );

        // Deep path rename
        assert_eq!(
            DiffView::extract_new_path_from_rename("src/components/{Button.tsx => button.tsx}"),
            Some("src/components/button.tsx".to_string())
        );

        // Not a rename pattern
        assert_eq!(DiffView::extract_new_path_from_rename("src/main.rs"), None);
    }

    #[test]
    fn test_compare_mode_blame_returns_notification() {
        use crate::model::{ChangeId, CommitId, CompareInfo, CompareRevisionInfo};

        let compare_info = CompareInfo {
            from: CompareRevisionInfo {
                change_id: ChangeId::new("aaaa1111".to_string()),
                commit_id: CommitId::new("ff001111".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-01".to_string(),
                description: "from revision".to_string(),
            },
            to: CompareRevisionInfo {
                change_id: ChangeId::new("bbbb2222".to_string()),
                commit_id: CommitId::new("ff002222".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-02".to_string(),
                description: "to revision".to_string(),
            },
        };
        let mut view = DiffView::new_compare(create_test_content(), compare_info);

        // Press 'a' (annotate/blame) in compare mode — should return notification
        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('a')));
        assert_eq!(
            action,
            DiffAction::ShowNotification("Blame is not available in compare mode".to_string())
        );
    }

    #[test]
    fn test_jump_to_file_with_rename() {
        // Create content with a renamed file
        let content = DiffContent {
            commit_id: CommitId::new("test123".to_string()),
            author: "Test".to_string(),
            timestamp: "2024-01-30".to_string(),
            description: "Test".to_string(),
            lines: vec![
                DiffLine::file_header("src/{old.rs => new.rs}"),
                DiffLine::added(1, "content"),
            ],
        };

        let mut view = DiffView::new("test".to_string(), content);
        assert_eq!(view.file_names, vec!["src/{old.rs => new.rs}"]);

        // Jump using the new path (as StatusView would provide)
        view.jump_to_file("src/new.rs");
        assert_eq!(view.current_file_index, 0);
        assert_eq!(view.scroll_offset, 0);
    }

    #[test]
    fn test_yank_key_returns_copy_full() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('y')));
        assert_eq!(action, DiffAction::CopyToClipboard { full: true });
    }

    #[test]
    fn test_yank_diff_key_returns_copy_diff_only() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('Y')));
        assert_eq!(action, DiffAction::CopyToClipboard { full: false });
    }

    #[test]
    fn test_write_key_returns_export() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('w')));
        assert_eq!(action, DiffAction::ExportToFile);
    }

    #[test]
    fn test_format_cycle_key_returns_cycle_format() {
        let mut view = DiffView::new("test".to_string(), create_test_content());
        let action = view.handle_key(KeyEvent::from(crossterm::event::KeyCode::Char('m')));
        assert_eq!(action, DiffAction::CycleFormat);
    }

    #[test]
    fn test_cycle_format_cycles_through_all() {
        use crate::model::DiffDisplayFormat;

        let mut view = DiffView::new("test".to_string(), create_test_content());
        assert_eq!(view.display_format, DiffDisplayFormat::ColorWords);

        let fmt = view.cycle_format();
        assert_eq!(fmt, DiffDisplayFormat::Stat);
        assert_eq!(view.display_format, DiffDisplayFormat::Stat);

        let fmt = view.cycle_format();
        assert_eq!(fmt, DiffDisplayFormat::Git);

        let fmt = view.cycle_format();
        assert_eq!(fmt, DiffDisplayFormat::ColorWords);
    }

    #[test]
    fn test_clear_resets_format() {
        use crate::model::DiffDisplayFormat;

        let mut view = DiffView::new("test".to_string(), create_test_content());
        view.cycle_format(); // Now Stat
        assert_eq!(view.display_format, DiffDisplayFormat::Stat);

        view.clear();
        assert_eq!(view.display_format, DiffDisplayFormat::ColorWords);
    }

    #[test]
    fn test_format_rollback_pattern() {
        // Verify the old_format / cycle_format / rollback pattern used in App
        use crate::model::DiffDisplayFormat;

        let mut view = DiffView::new("test".to_string(), create_test_content());

        // Simulate: save old, cycle, then rollback on error
        let old_format = view.display_format;
        assert_eq!(old_format, DiffDisplayFormat::ColorWords);

        let new_format = view.cycle_format();
        assert_eq!(new_format, DiffDisplayFormat::Stat);
        assert_eq!(view.display_format, DiffDisplayFormat::Stat);

        // Simulate error → rollback
        view.display_format = old_format;
        assert_eq!(view.display_format, DiffDisplayFormat::ColorWords);
    }
}