diff: Simplify file tree navigation

0aa30cd4dc86331d614f6a4ab86ac2a9c58317e0
Assisted-by: Claude:claude-opus-4.7
Alexis Sellier committed ago 1 parent eb2ec2d2
crates/diff/src/context.rs +1 -1
41 41
pub enum ContextChange {
42 42
    /// Show one more unchanged line around each changed group.
43 43
    Increase,
44 44
    /// Show one fewer unchanged line around each changed group.
45 45
    Decrease,
46 -
    /// Toggle selected file(s) between bounded hunks and full source.
46 +
    /// Toggle the active file between bounded hunks and full source.
47 47
    ToggleFile,
48 48
}
49 49
50 50
impl ContextState {
51 51
    /// Creates a fresh tracker at Git's default context width.
a.txt +0 -0
a.txt +0 -0
crates/diff/src/lib.rs +2 -2
30 30
pub use highlight::{
31 31
    BuiltinHighlighter, DiffHighlighter, DiffSide, HighlightKey, HighlightKeyInput,
32 32
    HighlightRequest, HighlightResult, HighlightSource,
33 33
};
34 34
pub use viewer::{
35 -
    ContextRequest, ContextUpdate, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane,
36 -
    DiffState, DiffViewer, FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
35 +
    ContextRequest, ContextUpdate, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffState,
36 +
    DiffViewer, FileTreeMode, FileTreeTarget, ViewChange,
37 37
};
crates/diff/src/viewer.rs +171 -174
7 7
use std::convert::Infallible;
8 8
use std::path::{Path, PathBuf};
9 9
10 10
use rustik_highlight as syntax;
11 11
use rustik_tui as tui;
12 -
use tui::event::Modifiers;
13 12
use tui::{
14 13
    Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton,
15 14
    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
16 15
    VStack, View, Viewport, Widget, colors,
17 16
};
22 21
use crate::{
23 22
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
24 23
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
25 24
};
26 25
27 -
pub use tree::{FileSelection, FileTreeMode, FileTreeTarget};
26 +
pub use tree::{FileTreeMode, FileTreeTarget};
28 27
29 28
/// Minimum width before the viewer attempts table-style diff rows.
30 29
const MIN_RENDER_COLS: usize = 12;
31 30
/// Width of old and new line number cells.
32 31
const LINE_NUMBER_WIDTH: usize = 5;
84 83
    pub scroll: usize,
85 84
    /// Currently focused file or hunk.
86 85
    pub focus: Option<DiffFocus>,
87 86
    /// Collapsed file sections.
88 87
    pub collapsed_files: BTreeSet<FileId>,
89 -
    /// Active pane in the interactive viewer.
90 -
    pub pane: DiffPane,
91 -
    /// File selection shown in the main diff pane.
92 -
    pub file_selection: FileSelection,
93 88
}
94 89
95 90
impl DiffState {
96 91
    /// Returns whether replacing this state with `next` invalidates cached row positions.
97 92
    fn invalidates_index(&self, next: &Self) -> bool {
98 -
        self.collapsed_files != next.collapsed_files || self.file_selection != next.file_selection
93 +
        self.collapsed_files != next.collapsed_files
99 94
    }
100 95
}
101 96
102 97
/// Focus target inside a diff document.
103 98
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
106 101
    File(FileId),
107 102
    /// Focus a hunk header.
108 103
    Hunk(HunkId),
109 104
}
110 105
111 -
/// Active pane in the diff viewer.
112 -
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
113 -
pub enum DiffPane {
114 -
    /// The main diff pane owns input.
115 -
    #[default]
116 -
    Main,
117 -
    /// The file tree owns input.
118 -
    FileTree,
119 -
}
120 -
121 106
/// Viewer action accepted by [`DiffViewer::apply`].
122 107
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
123 108
pub enum DiffAction {
124 109
    /// Scroll the viewport.
125 110
    Scroll(Scroll),
135 120
    PreviousHunk,
136 121
    /// Toggle the focused file between collapsed and expanded states.
137 122
    ToggleFocusedFile,
138 123
    /// Collapse the focused file, or report no change if it is already collapsed.
139 124
    CollapseFocusedFile,
140 -
    /// Move focus from the main diff into the file tree.
141 -
    EnterFileTree,
142 -
    /// Move focus from the file tree back to the main diff without changing selection.
143 -
    LeaveFileTree,
144 125
    /// Toggle the file tree between automatic visibility and hidden.
145 126
    ToggleFileTree,
146 -
    /// Move the file-tree cursor by visible file rows.
127 +
    /// Move the file-tree cursor by visible rows, jumping to files as they are selected.
147 128
    MoveFileTree(isize),
148 -
    /// Extend the selected file range from the current anchor.
149 -
    ExtendFileTreeSelection(isize),
129 +
    /// Show the current file-tree target without changing folder expansion.
130 +
    ShowFileTreeTarget,
150 131
    /// Activate the current file-tree target.
151 132
    ActivateFileTreeTarget,
152 -
    /// Toggle the current file-tree target in the main diff pane.
153 -
    ToggleFileTreeTarget,
154 133
    /// Collapse the focused file-tree folder.
155 134
    CollapseFileTreeFolder,
156 135
    /// Expand the focused file-tree folder.
157 136
    ExpandFileTreeFolder,
158 137
}
243 222
    hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
244 223
    /// Cached intra-line word diffs, keyed by hunk.
245 224
    word_diffs: BTreeMap<HunkId, word::WordChanges>,
246 225
    /// Rendered commit-preamble rows for the most recent body width.
247 226
    preamble: Vec<Line>,
248 -
    /// File-tree pane state and model.
227 +
    /// File-tree state and model.
249 228
    file_tree: tree::FileTreeViewer,
250 229
    /// Interactive override for file-tree visibility.
251 230
    file_tree_visibility: FileTreeVisibility,
252 231
    /// Cached rendered row positions for visible files.
253 232
    index: RowIndex,
545 524
        self.apply(DiffAction::Resize, area) == ViewChange::Changed
546 525
    }
547 526
548 527
    /// Returns the active file targeted by context changes.
549 528
    fn active_context_file(&self) -> Option<FileId> {
550 -
        self.focused_file()
551 -
            .or_else(|| self.document.files.first().map(|file| file.id))
529 +
        self.focused_file().or_else(|| self.visible_file())
552 530
    }
553 531
554 532
    /// Returns the files targeted by a context change.
555 533
    fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
556 -
        match &self.state.file_selection {
557 -
            FileSelection::All => {
558 -
                let active =
559 -
                    active.filter(|id| self.document.files.iter().any(|file| file.id == *id));
560 -
561 -
                active
562 -
                    .or_else(|| self.document.files.first().map(|file| file.id))
563 -
                    .into_iter()
564 -
                    .collect()
565 -
            }
566 -
            FileSelection::Files(files) => self
567 -
                .document
568 -
                .files
569 -
                .iter()
570 -
                .filter(|file| files.contains(&file.id))
571 -
                .map(|file| file.id)
572 -
                .collect(),
573 -
        }
534 +
        active
535 +
            .filter(|id| self.document.files.iter().any(|file| file.id == *id))
536 +
            .or_else(|| self.document.files.first().map(|file| file.id))
537 +
            .into_iter()
538 +
            .collect()
574 539
    }
575 540
576 541
    /// Sets the first visible rendered row.
577 542
    pub fn set_scroll(&mut self, scroll: usize) {
578 543
        self.state.scroll = scroll;
600 565
                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
601 566
                .map(|file| file.id),
602 567
        }
603 568
    }
604 569
570 +
    /// Returns the file occupying the first visible diff row.
571 +
    fn visible_file(&self) -> Option<FileId> {
572 +
        self.file_row_location(self.state.scroll)
573 +
            .map(|location| location.file.id)
574 +
            .or_else(|| self.document.files.first().map(|file| file.id))
575 +
    }
576 +
577 +
    /// Returns rendered rows plus trailing space needed to top-anchor the final file.
578 +
    fn scroll_rows(&self, visible_rows: usize) -> usize {
579 +
        let last_file_start = self.index.files.last().map_or(0, |file| file.start);
580 +
581 +
        self.index
582 +
            .rows
583 +
            .max(last_file_start.saturating_add(visible_rows))
584 +
    }
585 +
586 +
    /// Returns rendered rows plus trailing space needed by `scroll`.
587 +
    fn render_rows_for(&self, scroll: usize, visible_rows: usize) -> usize {
588 +
        self.index.rows.max(scroll.saturating_add(visible_rows))
589 +
    }
590 +
591 +
    /// Shows `file` in the diff view without moving the file-tree cursor.
592 +
    fn show_file(&mut self, file: FileId, visible_rows: usize) {
593 +
        let Some(row) = self.index.files.iter().find_map(|indexed| {
594 +
            let candidate = self.document.files.get(indexed.file_index)?;
595 +
596 +
            (candidate.id == file).then_some(indexed.start)
597 +
        }) else {
598 +
            return;
599 +
        };
600 +
        self.state.focus = Some(DiffFocus::File(file));
601 +
        self.state.scroll = View::new(row, self.scroll_rows(visible_rows), visible_rows).offset;
602 +
    }
603 +
604 +
    /// Updates the file-tree cursor to the visible diff file.
605 +
    fn sync_file_tree(&mut self) {
606 +
        if let Some(file) = self.visible_file() {
607 +
            self.file_tree.select_file(file);
608 +
        }
609 +
    }
610 +
605 611
    /// Renders the current frame into `buf`.
606 612
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
607 613
        if area.is_empty() {
608 614
            return;
609 615
        }
637 643
            diff,
638 644
            tree: Some(tree),
639 645
        }
640 646
    }
641 647
642 -
    /// Renders the file tree pane.
648 +
    /// Renders the file tree.
643 649
    fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
644 -
        let active = self.state.pane == DiffPane::FileTree;
645 -
        self.file_tree.render(
646 -
            &self.state.file_selection,
647 -
            self.options.diff_palette,
648 -
            active,
649 -
            area,
650 -
            buf,
651 -
        );
650 +
        let active_file = self.visible_file();
651 +
        self.file_tree
652 +
            .render(active_file, self.options.diff_palette, area, buf);
652 653
    }
653 654
654 -
    /// Renders the main diff pane into `buf`.
655 +
    /// Renders the main diff view into `buf`.
655 656
    fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
656 657
        let body_cols = ScrollView::body_cols(area);
657 658
        // Rebuild preamble for the available body width so line wrapping matches
658 659
        // current viewport size.
659 660
        let preamble_rows = self.preamble.len();
665 666
        let scroll = self.state.scroll;
666 667
        let sticky = self.sticky_rows(scroll, area.rows, body_cols);
667 668
        // Body offset skips sticky rows so the main diff starts below the fixed
668 669
        // header strip.
669 670
        let body_offset = scroll.saturating_add(sticky.len().min(area.rows));
671 +
        let render_rows = self.render_rows_for(scroll, area.rows);
670 672
671 -
        ScrollView::virtualized(self.index.rows, body_offset, |row, cols| {
673 +
        ScrollView::virtualized(render_rows, body_offset, |row, cols| {
672 674
            self.render_row(row, cols)
673 675
                .map(|row| row.line)
674 676
                .unwrap_or_default()
675 677
        })
676 678
        .sticky(sticky)
677 -
        .scrollbar_view(View::new(scroll, self.index.rows, area.rows))
679 +
        .scrollbar_view(View::new(scroll, render_rows, area.rows))
678 680
        .scrollbar(Self::scrollbar_style())
679 681
        .render(area, buf);
680 682
    }
681 683
682 684
    /// Applies an action to the viewer state.
685 687
        let before_visibility = self.file_tree_visibility;
686 688
        let before_file_tree = self.file_tree.state().clone();
687 689
        let layout = self.layout(area);
688 690
        let diff = layout.diff;
689 691
692 +
        if layout.tree.is_none()
693 +
            && matches!(
694 +
                action,
695 +
                DiffAction::MoveFileTree(_)
696 +
                    | DiffAction::ShowFileTreeTarget
697 +
                    | DiffAction::ActivateFileTreeTarget
698 +
                    | DiffAction::CollapseFileTreeFolder
699 +
                    | DiffAction::ExpandFileTreeFolder,
700 +
            )
701 +
        {
702 +
            return ViewChange::Unchanged;
703 +
        }
704 +
690 705
        match action {
691 706
            DiffAction::Scroll(scroll) => {
692 707
                let mut viewport = Viewport::from_offset(self.state.scroll);
693 -
                viewport.scroll(scroll, self.index.rows, diff.rows);
708 +
                let previous = self.state.scroll;
709 +
                viewport.scroll(scroll, self.scroll_rows(diff.rows), diff.rows);
694 710
                self.state.scroll = viewport.offset;
711 +
                if self.state.scroll != previous
712 +
                    && layout.tree.is_some()
713 +
                    && let Some(file) = self.visible_file()
714 +
                {
715 +
                    self.state.focus = Some(DiffFocus::File(file));
716 +
                    self.file_tree.select_file(file);
717 +
                }
695 718
            }
696 719
            DiffAction::Resize => {
697 720
                let mut viewport = Viewport::from_offset(self.state.scroll);
698 -
                viewport.clamp(self.index.rows, diff.rows);
721 +
                viewport.clamp(self.scroll_rows(diff.rows), diff.rows);
699 722
                self.state.scroll = viewport.offset;
700 -
                if layout.tree.is_none() {
701 -
                    self.state.pane = DiffPane::Main;
723 +
                if layout.tree.is_some() {
724 +
                    self.sync_file_tree();
702 725
                }
703 726
            }
704 727
            DiffAction::FocusNext => {
705 728
                self.focus(diff.rows, 1, FocusFilter::File);
729 +
                self.sync_file_tree();
706 730
            }
707 731
            DiffAction::FocusPrevious => {
708 732
                self.focus(diff.rows, -1, FocusFilter::File);
733 +
                self.sync_file_tree();
709 734
            }
710 735
            DiffAction::NextHunk => {
711 736
                self.focus(diff.rows, 1, FocusFilter::Hunk);
737 +
                self.sync_file_tree();
712 738
            }
713 739
            DiffAction::PreviousHunk => {
714 740
                self.focus(diff.rows, -1, FocusFilter::Hunk);
741 +
                self.sync_file_tree();
715 742
            }
716 743
            DiffAction::ToggleFocusedFile => {
744 +
                let had_focus = self.focused_file().is_some();
717 745
                self.toggle_focused_file();
746 +
                if had_focus {
747 +
                    self.sync_file_tree();
748 +
                }
718 749
            }
719 750
            DiffAction::CollapseFocusedFile => {
751 +
                let had_focus = self.focused_file().is_some();
720 752
                self.collapse_focused_file();
721 -
            }
722 -
            DiffAction::EnterFileTree => {
723 -
                if layout.tree.is_some() {
724 -
                    let focused_file = self.focused_file();
725 -
                    self.state.pane = DiffPane::FileTree;
726 -
                    self.file_tree
727 -
                        .enter(&self.state.file_selection, focused_file);
753 +
                if had_focus {
754 +
                    self.sync_file_tree();
728 755
                }
729 756
            }
730 -
            DiffAction::LeaveFileTree => {
731 -
                self.state.pane = DiffPane::Main;
732 -
            }
733 -
            DiffAction::ToggleFileTree => {
734 -
                match self.file_tree_visibility {
735 -
                    FileTreeVisibility::Hidden => {
736 -
                        self.file_tree_visibility = FileTreeVisibility::Auto;
737 -
                    }
738 -
                    FileTreeVisibility::Auto if layout.tree.is_some() => {
739 -
                        self.file_tree_visibility = FileTreeVisibility::Hidden;
757 +
            DiffAction::ToggleFileTree => match self.file_tree_visibility {
758 +
                FileTreeVisibility::Hidden => {
759 +
                    self.file_tree_visibility = FileTreeVisibility::Auto;
760 +
                    if self.layout(area).tree.is_some() {
761 +
                        self.sync_file_tree();
740 762
                    }
741 -
                    FileTreeVisibility::Auto => {}
742 763
                }
743 -
                if self.file_tree_visibility == FileTreeVisibility::Hidden {
744 -
                    self.state.pane = DiffPane::Main;
764 +
                FileTreeVisibility::Auto if layout.tree.is_some() => {
765 +
                    self.file_tree_visibility = FileTreeVisibility::Hidden;
745 766
                }
746 -
            }
767 +
                FileTreeVisibility::Auto => {}
768 +
            },
747 769
            DiffAction::MoveFileTree(delta) => {
748 -
                self.file_tree.select(delta);
770 +
                if self.file_tree.state().selected().is_none() {
771 +
                    self.file_tree.enter(self.visible_file());
772 +
                }
773 +
                if let Some(file) = self.file_tree.select(delta) {
774 +
                    self.show_file(file, diff.rows);
775 +
                }
749 776
            }
750 -
            DiffAction::ExtendFileTreeSelection(delta) => {
751 -
                self.state.file_selection = self.file_tree.extend_selection(delta);
777 +
            DiffAction::ShowFileTreeTarget => {
778 +
                if let Some(file) = self.file_tree.selected_file() {
779 +
                    self.show_file(file, diff.rows);
780 +
                }
752 781
            }
753 782
            DiffAction::ActivateFileTreeTarget => {
754 -
                self.file_tree.activate_target(&mut self.state);
755 -
            }
756 -
            DiffAction::ToggleFileTreeTarget => {
757 -
                self.file_tree.toggle_target(&mut self.state);
783 +
                if let Some(file) = self.file_tree.activate_target() {
784 +
                    self.show_file(file, diff.rows);
785 +
                }
758 786
            }
759 787
            DiffAction::CollapseFileTreeFolder => {
760 788
                self.file_tree.collapse_folder();
761 789
            }
762 790
            DiffAction::ExpandFileTreeFolder => {
764 792
            }
765 793
        }
766 794
767 795
        if before.invalidates_index(&self.state) {
768 796
            self.rebuild_index();
769 -
            self.state.scroll = View::new(self.state.scroll, self.index.rows, diff.rows).offset;
797 +
            self.state.scroll =
798 +
                View::new(self.state.scroll, self.scroll_rows(diff.rows), diff.rows).offset;
770 799
        }
771 800
        if self.state == before
772 801
            && self.file_tree_visibility == before_visibility
773 802
            && *self.file_tree.state() == before_file_tree
774 803
        {
796 825
                ..
797 826
            }) => DiffAction::Scroll(Scroll::Lines(-WHEEL_SCROLL_ROWS)),
798 827
            Event::Mouse(Mouse::Press {
799 828
                button: MouseButton::Left,
800 829
                at,
801 -
                modifiers,
830 +
                ..
802 831
            }) => {
803 832
                let Some(tree) = self.layout(area).tree else {
804 833
                    return Control::Continue;
805 834
                };
806 -
                if !self.file_tree.select_at(tree, at) {
807 -
                    return Control::Continue;
808 -
                }
809 -
                self.state.pane = DiffPane::FileTree;
810 -
                if modifiers.contains(Modifiers::CONTROL) {
811 -
                    DiffAction::ToggleFileTreeTarget
812 -
                } else {
813 -
                    DiffAction::ActivateFileTreeTarget
814 -
                }
835 +
                let action = match self.file_tree.select_at(tree, at) {
836 +
                    Some(tree::FileTreeClick::Disclosure) => return Control::Redraw,
837 +
                    Some(tree::FileTreeClick::Row) => DiffAction::ShowFileTreeTarget,
838 +
                    None => return Control::Continue,
839 +
                };
840 +
                self.apply(action, area);
841 +
                return Control::Redraw;
815 842
            }
816 -
            event => match (self.state.pane, event) {
817 -
                (DiffPane::Main, Event::Key(Key::Char('h'))) => DiffAction::EnterFileTree,
818 -
                (DiffPane::Main, Event::Key(Key::Esc)) => {
819 -
                    if self.apply(DiffAction::EnterFileTree, area) == ViewChange::Changed {
820 -
                        return Control::Redraw;
821 -
                    }
822 -
                    if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
823 -
                        return Control::Redraw;
824 -
                    }
825 -
                    return Control::Quit;
826 -
                }
827 -
                (DiffPane::Main, Event::Key(Key::Char('j') | Key::Down)) => {
828 -
                    DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
829 -
                }
830 -
                (DiffPane::Main, Event::Key(Key::Char('k') | Key::Up)) => {
831 -
                    DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
832 -
                }
833 -
                (DiffPane::Main, Event::Key(Key::Char(' ') | Key::PageDown)) => {
834 -
                    DiffAction::Scroll(Scroll::Pages(1))
843 +
            Event::Key(Key::Esc) => {
844 +
                if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
845 +
                    return Control::Redraw;
835 846
                }
836 -
                (DiffPane::Main, Event::Key(Key::PageUp)) => DiffAction::Scroll(Scroll::Pages(-1)),
837 -
                (DiffPane::Main, Event::Key(Key::Ctrl('d'))) => {
838 -
                    DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
839 -
                }
840 -
                (DiffPane::Main, Event::Key(Key::Ctrl('u'))) => {
841 -
                    DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
842 -
                }
843 -
                (DiffPane::Main, Event::Key(Key::Char('g') | Key::Home)) => {
844 -
                    DiffAction::Scroll(Scroll::Top)
845 -
                }
846 -
                (DiffPane::Main, Event::Key(Key::Char('G') | Key::End)) => {
847 -
                    DiffAction::Scroll(Scroll::Bottom)
848 -
                }
849 -
                (DiffPane::Main, Event::Key(Key::Char('n'))) => DiffAction::FocusNext,
850 -
                (DiffPane::Main, Event::Key(Key::Char('p'))) => DiffAction::FocusPrevious,
851 -
                (DiffPane::Main, Event::Key(Key::Enter)) => DiffAction::ToggleFocusedFile,
852 -
                (DiffPane::FileTree, Event::Key(Key::Esc | Key::Char('l'))) => {
853 -
                    DiffAction::LeaveFileTree
854 -
                }
855 -
                (DiffPane::FileTree, Event::Key(Key::Enter)) => DiffAction::ActivateFileTreeTarget,
856 -
                (DiffPane::FileTree, Event::Key(Key::Char(' '))) => {
857 -
                    DiffAction::ToggleFileTreeTarget
858 -
                }
859 -
                (DiffPane::FileTree, Event::Key(Key::Char('j') | Key::Down)) => {
860 -
                    DiffAction::MoveFileTree(1)
861 -
                }
862 -
                (DiffPane::FileTree, Event::Key(Key::Char('k') | Key::Up)) => {
863 -
                    DiffAction::MoveFileTree(-1)
864 -
                }
865 -
                (DiffPane::FileTree, Event::Key(Key::Right)) => DiffAction::ExpandFileTreeFolder,
866 -
                (DiffPane::FileTree, Event::Key(Key::Left)) => DiffAction::CollapseFileTreeFolder,
867 -
                (DiffPane::FileTree, Event::Key(Key::Char('J'))) => {
868 -
                    DiffAction::ExtendFileTreeSelection(1)
869 -
                }
870 -
                (DiffPane::FileTree, Event::Key(Key::Char('K'))) => {
871 -
                    DiffAction::ExtendFileTreeSelection(-1)
872 -
                }
873 -
                _ => return Control::Continue,
874 -
            },
847 +
                return Control::Quit;
848 +
            }
849 +
            Event::Key(Key::Char('j') | Key::Down) => {
850 +
                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
851 +
            }
852 +
            Event::Key(Key::Char('k') | Key::Up) => {
853 +
                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
854 +
            }
855 +
            Event::Key(Key::Char('J')) => DiffAction::MoveFileTree(1),
856 +
            Event::Key(Key::Char('K')) => DiffAction::MoveFileTree(-1),
857 +
            Event::Key(Key::Char('H')) => DiffAction::ExpandFileTreeFolder,
858 +
            Event::Key(Key::Char('L')) => DiffAction::CollapseFileTreeFolder,
859 +
            Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
860 +
            Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
861 +
            Event::Key(Key::Ctrl('d')) => {
862 +
                DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
863 +
            }
864 +
            Event::Key(Key::Ctrl('u')) => {
865 +
                DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
866 +
            }
867 +
            Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
868 +
            Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
869 +
            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
870 +
            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
871 +
            Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
872 +
            _ => return Control::Continue,
875 873
        };
876 874
        match self.apply(action, area) {
877 875
            ViewChange::Changed => Control::Redraw,
878 876
            ViewChange::Unchanged => Control::Continue,
879 877
        }
881 879
882 880
    /// Returns highlight requests for visible source rows plus configured lookahead.
883 881
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
884 882
        let diff = self.layout(area).diff;
885 883
        let take = diff.rows.saturating_add(self.options.highlight_lookahead);
886 -
        let view = View::new(self.state.scroll, self.index.rows, diff.rows);
884 +
        let view = View::new(
885 +
            self.state.scroll,
886 +
            self.render_rows_for(self.state.scroll, diff.rows),
887 +
            diff.rows,
888 +
        );
887 889
        let start = view
888 890
            .offset
889 891
            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
890 892
        let mut requests = Vec::new();
891 893
1011 1013
            return false;
1012 1014
        }
1013 1015
        self.apply_highlights(highlighter.highlight_batch(requests))
1014 1016
    }
1015 1017
1016 -
    /// Returns whether `file` is shown in the main diff pane.
1017 -
    fn file_visible(&self, file: FileId) -> bool {
1018 -
        self.state.file_selection.contains(file)
1019 -
    }
1020 -
1021 1018
    /// Returns the row count for one file card.
1022 1019
    fn file_rows(&self, file: &FileDiff) -> usize {
1023 1020
        file.rendered_rows(self.state.collapsed_files.contains(&file.id))
1024 1021
    }
1025 1022
1158 1155
    fn rebuild_index(&mut self) {
1159 1156
        let mut rows = self.preamble.len();
1160 1157
        let mut files = Vec::new();
1161 1158
1162 1159
        for (file_index, file) in self.document.files.iter().enumerate() {
1163 -
            if !self.file_visible(file.id) {
1164 -
                continue;
1165 -
            }
1166 1160
            files.push(IndexedFileRows {
1167 1161
                file_index,
1168 1162
                start: rows,
1169 1163
            });
1170 1164
            rows += self.file_rows(file);
1298 1292
            .map(|sticky| sticky.start)
1299 1293
    }
1300 1294
1301 1295
    /// Returns the visible sticky header rows at the current offset.
1302 1296
    fn sticky_header_rows(&self, scroll: usize, visible_rows: usize) -> Option<StickyHeaderRows> {
1303 -
        let scroll = scroll.min(self.index.rows.saturating_sub(visible_rows));
1297 +
        let scroll = scroll.min(
1298 +
            self.render_rows_for(scroll, visible_rows)
1299 +
                .saturating_sub(visible_rows),
1300 +
        );
1304 1301
        if scroll == 0 {
1305 1302
            return None;
1306 1303
        }
1307 1304
        let location = self.file_row_location(scroll)?;
1308 1305
        if scroll <= location.start {
1342 1339
            return;
1343 1340
        };
1344 1341
1345 1342
        self.state.focus = Some(target.focus);
1346 1343
        if filter == FocusFilter::File {
1347 -
            self.state.scroll = View::new(target.row, self.index.rows, visible_rows).offset;
1344 +
            self.state.scroll =
1345 +
                View::new(target.row, self.scroll_rows(visible_rows), visible_rows).offset;
1348 1346
            return;
1349 1347
        }
1350 1348
1351 1349
        let mut viewport = Viewport::from_offset(self.state.scroll);
1352 1350
        let margin = visible_rows / 4;
1353 1351
        viewport.scroll_to_row(
1354 1352
            target.row,
1355 -
            self.index.rows,
1353 +
            self.scroll_rows(visible_rows),
1356 1354
            visible_rows,
1357 1355
            Placement::Margin {
1358 1356
                before: margin.max(self.sticky_row_count(self.state.scroll, visible_rows)),
1359 1357
                after: margin,
1360 1358
            },
1783 1781
}
1784 1782
1785 1783
#[cfg(test)]
1786 1784
#[allow(clippy::unwrap_used)]
1787 1785
mod tests {
1788 -
    use std::collections::BTreeSet;
1789 1786
    use std::path::PathBuf;
1790 1787
    use std::str::FromStr;
1791 1788
1792 1789
    use super::*;
1793 1790
1794 1791
    use crate::Decode;
1795 1792
    use crate::DiffDocument;
1796 1793
    use rustik_repo::{Repo, RepoError};
1797 -
    use rustik_tui::Point;
1794 +
    use rustik_tui::{Modifiers, Point};
1798 1795
1799 1796
    /// Returns a left-click event for tests.
1800 1797
    fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
1801 1798
        Event::Mouse(Mouse::Press {
1802 1799
            button: MouseButton::Left,
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/viewer/tree.rs +124 -184
7 7
use tui::{
8 8
    Buffer, Color, Label, Placement, Point, Rect, Style, Table, TableOptions, Tree, TreeModel,
9 9
    TreeNodeKind, TreeRow, TreeState, TreeStyle, View, Widget, colors,
10 10
};
11 11
12 -
use super::{DiffFocus, DiffPalette, DiffState, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
12 +
use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
13 13
use crate::{DiffDocument, FileId, FileKind, Stats};
14 14
15 15
/// Minimum columns reserved for the file tree when it is visible.
16 16
const DEFAULT_COLS: usize = 28;
17 17
/// Blank rows above the file tree list.
20 20
const INFO_BOX_ROWS: usize = 5;
21 21
/// Blank rows between the file tree and the summary box.
22 22
const INFO_BOX_GAP_ROWS: usize = 1;
23 23
/// Minimum tree rows kept visible when the summary box is shown.
24 24
const MIN_TREE_ROWS_WITH_INFO: usize = 3;
25 -
/// Background color for the current file-tree cursor row.
26 -
const CURSOR_BG: Color = Color::Fixed(235);
27 -
/// Background color for selected file-tree rows.
28 -
const SELECTED_BG: Color = Color::Fixed(234);
29 -
/// Foreground color for selected file-tree row labels.
25 +
/// Columns added by the tree widget for each nesting level.
26 +
const TREE_INDENT_COLS: usize = 2;
27 +
/// Background color for the selected or active file row.
28 +
const SELECTED_FILE_BG: Color = Color::Fixed(235);
29 +
/// Background color for the selected or active folder row.
30 +
const SELECTED_FOLDER_BG: Color = Color::Fixed(234);
31 +
/// Foreground color for active file-tree row labels.
30 32
const SELECTED_FG: Color = Color::Fixed(252);
31 33
/// Foreground color for folder labels in the file tree.
32 34
const FOLDER_FG: Color = Color::Fixed(245);
33 -
/// Foreground color for collapsed folders containing selected files.
35 +
/// Foreground color for collapsed folders containing the active file.
34 36
const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
35 37
/// Selected-row styling for the file tree.
36 -
const FILE_TREE_STYLE: TreeStyle = TreeStyle::new(
37 -
    Style::new(SELECTED_FG).bg(CURSOR_BG),
38 -
    Style::new(Color::Unset),
39 -
);
40 -
/// Style for file rows selected into the main diff pane.
41 -
const SELECTED_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_BG);
42 -
/// Style for folder rows selected into the main diff pane.
43 -
const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_BG);
38 +
const FILE_TREE_STYLE: TreeStyle =
39 +
    TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset));
40 +
/// Style for the active file row.
41 +
const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG);
42 +
/// Style for a collapsed folder containing the active file.
43 +
const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_FOLDER_BG);
44 44
45 45
/// Blank columns between the file tree and the diff body.
46 46
pub(super) const GAP_COLS: usize = 1;
47 47
/// Minimum viewport width that can show the file tree beside the diff.
48 48
pub(super) const MIN_VIEW_COLS: usize = 80;
49 49
50 -
/// File selection shown in the main diff pane.
51 -
#[derive(Clone, Debug, Default, Eq, PartialEq)]
52 -
pub enum FileSelection {
53 -
    /// Every file in the diff is visible.
54 -
    #[default]
55 -
    All,
56 -
    /// Only the listed files are visible.
57 -
    Files(BTreeSet<FileId>),
58 -
}
59 -
60 50
/// Selectable target in the file tree.
61 51
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
62 52
pub enum FileTreeTarget {
63 53
    /// Root row for the current working directory.
64 54
    Root,
66 56
    Directory(PathBuf),
67 57
    /// File row from the diff document.
68 58
    File(FileId),
69 59
}
70 60
61 +
/// Mouse target selected inside the file tree.
62 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63 +
pub(super) enum FileTreeClick {
64 +
    /// The disclosure marker for a folder row was clicked.
65 +
    Disclosure,
66 +
    /// The row body was clicked.
67 +
    Row,
68 +
}
69 +
71 70
/// File-tree rendering policy.
72 71
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
73 72
pub enum FileTreeMode {
74 73
    /// Never render the file tree.
75 74
    #[default]
98 97
    id: FileId,
99 98
    /// Kind of file-level change.
100 99
    kind: FileKind,
101 100
}
102 101
103 -
impl FileSelection {
104 -
    /// Returns whether `file` is included in this selection.
105 -
    pub fn contains(&self, file: FileId) -> bool {
106 -
        match self {
107 -
            Self::All => true,
108 -
            Self::Files(files) => files.contains(&file),
109 -
        }
110 -
    }
111 -
}
112 -
113 -
/// Stateful file-tree pane owned by the diff viewer.
102 +
/// Stateful file tree owned by the diff viewer.
114 103
#[derive(Clone, Debug, Eq, PartialEq)]
115 104
pub(super) struct FileTreeViewer {
116 -
    /// Path tree rendered in the file-tree pane.
105 +
    /// Path tree rendered in the file tree.
117 106
    model: FileTreeModel,
118 -
    /// Expansion, cursor, and anchor state for the file-tree pane.
107 +
    /// Expansion and cursor state for the file tree.
119 108
    state: TreeState<usize>,
120 109
}
121 110
122 111
impl FileTreeViewer {
123 112
    /// Creates a file-tree viewer from `document`.
126 115
        let state = model.initial_state();
127 116
128 117
        Self { model, state }
129 118
    }
130 119
131 -
    /// Returns the file-tree pane's expansion, cursor, and anchor state.
120 +
    /// Returns the file tree's expansion and cursor state.
132 121
    ///
133 122
    /// The `model` is immutable after construction, so this is the only part
134 123
    /// that changes between actions.
135 124
    pub(super) fn state(&self) -> &TreeState<usize> {
136 125
        &self.state
151 140
        Tree::new(&self.model, &self.state)
152 141
            .content_cols(DEFAULT_COLS)
153 142
            .min(available)
154 143
    }
155 144
156 -
    /// Renders the file tree pane.
145 +
    /// Renders the file tree.
157 146
    pub(super) fn render(
158 147
        &mut self,
159 -
        selection: &FileSelection,
148 +
        active_file: Option<FileId>,
160 149
        palette: DiffPalette,
161 -
        active: bool,
162 150
        area: Rect,
163 151
        buf: &mut Buffer,
164 152
    ) {
165 153
        let Some((tree_area, info_area)) = Self::areas(area) else {
166 154
            return;
170 158
            .branch_ids()
171 159
            .filter(|id| !self.state.is_expanded(*id))
172 160
            .collect();
173 161
        let styled = StyledFileTree {
174 162
            model: &self.model,
175 -
            selection,
163 +
            selected: self.state.selected(),
164 +
            active_file,
176 165
            collapsed,
177 166
            palette,
178 167
        };
179 -
        let tree = Tree::new(&styled, &self.state)
180 -
            .active(active)
181 -
            .style(FILE_TREE_STYLE);
168 +
        let tree = Tree::new(&styled, &self.state).style(FILE_TREE_STYLE);
182 169
        let rows = tree.visible_rows();
183 170
        let row = tree.selected_row(&rows).unwrap_or_default();
184 171
        let view =
185 172
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
186 173
208 195
            table.render(area, buf);
209 196
        }
210 197
    }
211 198
212 199
    /// Enters the file tree when it is visible.
213 -
    pub(super) fn enter(&mut self, selection: &FileSelection, focused_file: Option<FileId>) {
214 -
        if self.state.selected().is_none() {
215 -
            let chosen = focused_file
216 -
                .and_then(|file| self.model.id_for(&FileTreeTarget::File(file)))
217 -
                .or_else(|| self.first_selected_node(selection))
218 -
                .or_else(|| self.first_visible_node());
219 -
            if let Some(id) = chosen {
220 -
                self.state.select(id);
221 -
            }
200 +
    pub(super) fn enter(&mut self, active_file: Option<FileId>) {
201 +
        let chosen = active_file
202 +
            .and_then(|file| self.visible_node_for_file(file))
203 +
            .or_else(|| self.first_visible_node());
204 +
        if let Some(id) = chosen {
205 +
            self.state.select(id);
222 206
        }
223 207
    }
224 208
225 209
    /// Moves the file-tree cursor by `delta` visible rows.
226 -
    pub(super) fn select(&mut self, delta: isize) {
210 +
    pub(super) fn select(&mut self, delta: isize) -> Option<FileId> {
227 211
        self.state.select_next(&self.model, delta);
212 +
        self.selected_file()
228 213
    }
229 214
230 -
    /// Selects the file-tree row at `point` inside `area`.
231 -
    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> bool {
232 -
        let Some((tree_area, _)) = Self::areas(area) else {
215 +
    /// Selects the visible file-tree row for `file`.
216 +
    pub(super) fn select_file(&mut self, file: FileId) -> bool {
217 +
        let Some(id) = self.visible_node_for_file(file) else {
233 218
            return false;
234 219
        };
220 +
        self.state.select(id)
221 +
    }
222 +
223 +
    /// Selects the file-tree row at `point` inside `area`.
224 +
    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> Option<FileTreeClick> {
225 +
        let (tree_area, _) = Self::areas(area)?;
235 226
        let tree = Tree::new(&self.model, &self.state);
236 227
        let rows = tree.visible_rows();
237 228
        let row = tree.selected_row(&rows).unwrap_or_default();
238 229
        let view =
239 230
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
240 -
        let Some(row) = view.row_at(tree_area, point) else {
241 -
            return false;
242 -
        };
243 -
        let Some(row) = rows.get(row) else {
244 -
            return false;
245 -
        };
246 -
        self.state.select(row.id);
247 -
        true
248 -
    }
249 -
250 -
    /// Extends file selection from the current anchor by `delta` rows.
251 -
    pub(super) fn extend_selection(&mut self, delta: isize) -> FileSelection {
252 -
        let range = self.state.extend_selection(&self.model, delta);
253 -
        let mut files = BTreeSet::new();
254 -
255 -
        for id in range {
256 -
            files.extend(self.model.files_for(id));
257 -
        }
258 -
        if files.is_empty() {
259 -
            FileSelection::All
231 +
        let row = view.row_at(tree_area, point)?;
232 +
        let row = rows.get(row)?;
233 +
        if self.model.kind(row.id) == TreeNodeKind::Branch
234 +
            && point.x.saturating_sub(tree_area.x) == row.depth.saturating_mul(TREE_INDENT_COLS)
235 +
        {
236 +
            self.state.toggle(&self.model, row.id);
237 +
            Some(FileTreeClick::Disclosure)
260 238
        } else {
261 -
            FileSelection::Files(files)
239 +
            self.state.select(row.id);
240 +
            Some(FileTreeClick::Row)
262 241
        }
263 242
    }
264 243
265 244
    /// Activates the current file-tree cursor.
266 -
    pub(super) fn activate_target(&mut self, state: &mut DiffState) {
267 -
        let Some(id) = self.state.selected() else {
268 -
            return;
269 -
        };
270 -
        match self.model.kind(id) {
271 -
            TreeNodeKind::Branch => {
272 -
                self.state.toggle(&self.model, id);
273 -
            }
274 -
            TreeNodeKind::Leaf => {
275 -
                if let Some(FileTreeTarget::File(file)) = self.model.target_for(id) {
276 -
                    state.file_selection = FileSelection::Files(BTreeSet::from([file]));
277 -
                    state.focus = Some(DiffFocus::File(file));
278 -
                }
279 -
            }
245 +
    pub(super) fn activate_target(&mut self) -> Option<FileId> {
246 +
        let id = self.state.selected()?;
247 +
        if self.model.kind(id) == TreeNodeKind::Branch {
248 +
            self.state.toggle(&self.model, id);
280 249
        }
281 -
        self.state.set_anchor(Some(id));
250 +
        self.selected_file()
282 251
    }
283 252
284 -
    /// Toggles the current file-tree cursor files in the main diff pane.
285 -
    pub(super) fn toggle_target(&mut self, state: &mut DiffState) {
286 -
        let Some(id) = self.state.selected() else {
287 -
            return;
288 -
        };
289 -
        let target_files = self.model.files_for(id);
290 -
291 -
        if target_files.is_empty() {
292 -
            return;
293 -
        }
294 -
        let all_files = self.model.all_files();
295 -
        let target_selected = target_files
296 -
            .iter()
297 -
            .all(|file| state.file_selection.contains(*file));
298 -
        let mut files = match &state.file_selection {
299 -
            FileSelection::All => all_files.clone(),
300 -
            FileSelection::Files(files) => files.clone(),
301 -
        };
302 -
303 -
        if target_selected {
304 -
            for file in target_files {
305 -
                files.remove(&file);
306 -
            }
307 -
        } else {
308 -
            files.extend(target_files);
309 -
        }
310 -
        state.file_selection = if files.len() == all_files.len() {
311 -
            FileSelection::All
312 -
        } else {
313 -
            FileSelection::Files(files)
314 -
        };
315 -
        self.state.set_anchor(Some(id));
316 -
317 -
        state.focus = all_files
318 -
            .into_iter()
319 -
            .find(|file| state.file_selection.contains(*file))
320 -
            .map(DiffFocus::File);
253 +
    /// Returns the file represented by the selected file-tree row.
254 +
    pub(super) fn selected_file(&self) -> Option<FileId> {
255 +
        self.state
256 +
            .selected()
257 +
            .and_then(|id| self.model.first_file_for(id))
321 258
    }
322 259
323 260
    /// Collapses the focused file-tree folder.
324 261
    pub(super) fn collapse_folder(&mut self) {
325 262
        let Some(id) = self.state.selected() else {
338 275
        if self.model.kind(id) == TreeNodeKind::Branch {
339 276
            self.state.expand(id);
340 277
        }
341 278
    }
342 279
343 -
    /// Returns the first visible tree row that contains a currently selected file.
344 -
    fn first_selected_node(&self, selection: &FileSelection) -> Option<usize> {
345 -
        Tree::new(&self.model, &self.state)
346 -
            .visible_rows()
347 -
            .into_iter()
348 -
            .find(|row| match selection {
349 -
                FileSelection::All => true,
350 -
                FileSelection::Files(files) => self
351 -
                    .model
352 -
                    .files_for(row.id)
353 -
                    .iter()
354 -
                    .any(|file| files.contains(file)),
355 -
            })
356 -
            .map(|row| row.id)
280 +
    /// Returns the visible tree row that best represents `file`.
281 +
    fn visible_node_for_file(&self, file: FileId) -> Option<usize> {
282 +
        let mut collapsed_branch = None;
283 +
284 +
        for row in Tree::new(&self.model, &self.state).visible_rows() {
285 +
            match self.model.target_for(row.id) {
286 +
                Some(FileTreeTarget::File(candidate)) if candidate == file => {
287 +
                    return Some(row.id);
288 +
                }
289 +
                Some(FileTreeTarget::Root | FileTreeTarget::Directory(_))
290 +
                    if !self.state.is_expanded(row.id)
291 +
                        && self.model.files_for(row.id).contains(&file) =>
292 +
                {
293 +
                    collapsed_branch = Some(row.id);
294 +
                }
295 +
                _ => {}
296 +
            }
297 +
        }
298 +
        collapsed_branch
357 299
    }
358 300
359 301
    /// Returns the first visible tree row.
360 302
    fn first_visible_node(&self) -> Option<usize> {
361 303
        Tree::new(&self.model, &self.state)
425 367
            );
426 368
        }
427 369
        model
428 370
    }
429 371
430 -
    /// Returns every file id known to this tree, in document order.
431 -
    fn all_files(&self) -> BTreeSet<FileId> {
432 -
        self.nodes
433 -
            .iter()
434 -
            .filter_map(|node| node.file.map(|file| file.id))
435 -
            .collect()
436 -
    }
437 -
438 372
    /// Returns a tree state with every branch expanded.
439 373
    pub(super) fn initial_state(&self) -> TreeState<usize> {
440 374
        let mut state = TreeState::new();
441 375
442 376
        for id in self.branch_ids() {
448 382
    /// Returns the tree target represented by `id`.
449 383
    fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
450 384
        self.nodes.get(id).map(|node| node.target.clone())
451 385
    }
452 386
453 -
    /// Returns the node id for `target`.
454 -
    fn id_for(&self, target: &FileTreeTarget) -> Option<usize> {
455 -
        self.nodes.iter().position(|node| node.target == *target)
456 -
    }
457 -
458 387
    /// Returns the ids of every branch (non-leaf) node.
459 388
    fn branch_ids(&self) -> impl Iterator<Item = usize> + '_ {
460 389
        self.nodes
461 390
            .iter()
462 391
            .enumerate()
474 403
            files.extend(self.files_for(*child));
475 404
        }
476 405
        files
477 406
    }
478 407
408 +
    /// Returns the first file contained by `id` in tree order.
409 +
    fn first_file_for(&self, id: usize) -> Option<FileId> {
410 +
        if let Some(file) = self.nodes[id].file {
411 +
            return Some(file.id);
412 +
        }
413 +
        self.nodes[id]
414 +
            .children
415 +
            .iter()
416 +
            .find_map(|child| self.first_file_for(*child))
417 +
    }
418 +
479 419
    /// Returns display path components for a file header path.
480 420
    fn path_parts(path: Option<&PathBuf>) -> Vec<String> {
481 421
        let Some(path) = path else {
482 422
            return vec!["<unknown>".to_owned()];
483 423
        };
595 535
            .marker(file.kind.marker())
596 536
            .marker_style(Style::new(Color::Unset))
597 537
    }
598 538
}
599 539
600 -
/// Render-time view over a [`FileTreeModel`] that applies selection-aware styling.
540 +
/// Render-time view over a [`FileTreeModel`] that applies active-file styling.
601 541
///
602 542
/// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows
603 543
/// without forcing render-time state into the structural model.
604 544
struct StyledFileTree<'a> {
605 545
    /// Underlying structural tree.
606 546
    model: &'a FileTreeModel,
607 -
    /// File selection used to mark included rows.
608 -
    selection: &'a FileSelection,
547 +
    /// File-tree cursor row.
548 +
    selected: Option<usize>,
549 +
    /// File currently active in the diff view.
550 +
    active_file: Option<FileId>,
609 551
    /// Branch ids that are currently collapsed.
610 552
    collapsed: BTreeSet<usize>,
611 553
    /// Positive and negative colors used for file details.
612 554
    palette: DiffPalette,
613 555
}
614 556
615 557
impl StyledFileTree<'_> {
616 -
    /// Returns whether `id` should render as included in the diff pane.
617 -
    fn highlighted(&self, id: usize) -> bool {
558 +
    /// Returns whether `id` should render with active styling.
559 +
    ///
560 +
    /// True when the file-tree cursor is on `id` or when `id` represents the
561 +
    /// active diff file directly (a file row) or indirectly (a collapsed folder
562 +
    /// containing it).
563 +
    fn is_active(&self, id: usize) -> bool {
564 +
        if self.selected == Some(id) {
565 +
            return true;
566 +
        }
618 567
        let Some(node) = self.model.nodes.get(id) else {
619 568
            return false;
620 569
        };
570 +
        let Some(active_file) = self.active_file else {
571 +
            return false;
572 +
        };
621 573
        match &node.target {
622 -
            FileTreeTarget::File(file) => self.selection.contains(*file),
574 +
            FileTreeTarget::File(file) => *file == active_file,
623 575
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => {
624 -
                self.collapsed.contains(&id)
625 -
                    && self
626 -
                        .model
627 -
                        .files_for(id)
628 -
                        .iter()
629 -
                        .any(|file| self.selection.contains(*file))
576 +
                self.collapsed.contains(&id) && self.model.files_for(id).contains(&active_file)
630 577
            }
631 578
        }
632 579
    }
633 580
634 -
    /// Returns the full-row style for a highlighted tree target.
581 +
    /// Returns the full-row style for an active tree target.
635 582
    fn row_style(&self, id: usize) -> Style {
636 -
        if !self.highlighted(id) {
583 +
        if !self.is_active(id) {
637 584
            return Style::default();
638 585
        }
639 586
        match self.model.nodes[id].target {
640 587
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE,
641 -
            FileTreeTarget::File(_) => SELECTED_STYLE,
588 +
            FileTreeTarget::File(_) => SELECTED_FILE_STYLE,
642 589
        }
643 590
    }
644 591
}
645 592
646 593
impl TreeModel for StyledFileTree<'_> {
658 605
        self.model.kind(id)
659 606
    }
660 607
661 608
    fn row(&self, id: Self::Id) -> TreeRow {
662 609
        let node = &self.model.nodes[id];
610 +
        let active = self.is_active(id);
663 611
        let Some(file) = node.file else {
664 -
            let fg = if self.highlighted(id) {
612 +
            let fg = if active {
665 613
                SELECTED_FOLDER_FG
666 614
            } else {
667 615
                FOLDER_FG
668 616
            };
669 617
            return self.model.folder_row(id, fg, self.row_style(id));
670 618
        };
671 -
        let fg = if self.selection.contains(file.id) {
672 -
            SELECTED_FG
673 -
        } else {
674 -
            Color::White
675 -
        };
619 +
        let fg = if active { SELECTED_FG } else { Color::White };
676 620
        let kind_fg = match file.kind {
677 621
            FileKind::Added => self.palette.positive_fg,
678 622
            FileKind::Deleted => self.palette.negative_fg,
679 623
            FileKind::Renamed => FILE_KIND_BADGE_FG,
680 624
            FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
690 634
}
691 635
692 636
#[cfg(test)]
693 637
#[allow(clippy::unwrap_used)]
694 638
mod tests {
695 -
    use std::collections::BTreeSet;
696 -
697 639
    use crate::{Decode, DiffDocument, DiffOptions, DiffViewer};
698 640
699 -
    use super::*;
700 -
701 641
    fn two_file_viewer() -> DiffViewer {
702 642
        let document = DiffDocument::decode_str(
703 643
            "\
704 644
a.rs +0 -0
b.rs +0 -0