Skip to main content

rustik_diff/viewer/
tree.rs

1//! File-tree model, rendering, and navigation for the diff viewer.
2
3use std::collections::BTreeSet;
4use std::path::PathBuf;
5
6use rustik_tui as tui;
7use tui::{
8    Buffer, Color, Label, Line, Placement, Point, Rect, Style, Table, TableOptions, Tree,
9    TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, View, Widget, colors,
10};
11
12use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
13use crate::{DiffDocument, FileId, FileKind, Stats};
14
15/// Minimum columns reserved for the file tree when it is visible.
16const DEFAULT_COLS: usize = 28;
17/// Blank rows above the file tree list.
18const TOP_PADDING_ROWS: usize = 1;
19/// Rows reserved for the summary box below the file tree.
20const INFO_BOX_ROWS: usize = 4;
21/// Blank rows between the file tree and the summary box.
22const INFO_BOX_GAP_ROWS: usize = 1;
23/// Minimum tree rows kept visible when the summary box is shown.
24const MIN_TREE_ROWS_WITH_INFO: usize = 3;
25/// Columns added by the tree widget for each nesting level.
26const TREE_INDENT_COLS: usize = 2;
27/// Background color for the selected or active file row.
28const SELECTED_FILE_BG: Color = Color::Fixed(235);
29/// Background color for the selected or active folder row.
30const SELECTED_FOLDER_BG: Color = Color::Fixed(234);
31/// Foreground color for active file-tree row labels.
32const SELECTED_FG: Color = Color::Fixed(252);
33/// Foreground color for folder labels in the file tree.
34const FOLDER_FG: Color = Color::Fixed(245);
35/// Foreground color for collapsed folders containing the active file.
36const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
37/// Selected-row styling for the file tree.
38const FILE_TREE_STYLE: TreeStyle =
39    TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset));
40/// Style for the active file row.
41const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG);
42/// Style for a collapsed folder containing the active file.
43const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_FOLDER_BG);
44
45/// Blank columns between the file tree and the diff body.
46pub(super) const GAP_COLS: usize = 1;
47/// Minimum viewport width that can show the file tree beside the diff.
48pub(super) const MIN_VIEW_COLS: usize = 80;
49
50/// Selectable target in the file tree.
51#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
52pub enum FileTreeTarget {
53    /// Root row for the current working directory.
54    Root,
55    /// Directory row containing changed files.
56    Directory(PathBuf),
57    /// File row from the diff document.
58    File(FileId),
59}
60
61/// Mouse target selected inside the file tree.
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63pub(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
70/// File-tree rendering policy.
71#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
72pub enum FileTreeMode {
73    /// Never render the file tree.
74    #[default]
75    Hidden,
76    /// Render the file tree when the viewport is wide enough.
77    Auto,
78}
79
80/// One node in the rendered file tree.
81#[derive(Clone, Debug, Eq, PartialEq)]
82struct FileTreeNode {
83    /// Display name for this path segment.
84    name: String,
85    /// Child node ids.
86    children: Vec<usize>,
87    /// Diff file data when this node is a file leaf.
88    file: Option<FileTreeFile>,
89    /// Stable tree target represented by this node.
90    target: FileTreeTarget,
91}
92
93/// Diff file metadata stored in a file-tree leaf node.
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95struct FileTreeFile {
96    /// Stable file identifier.
97    id: FileId,
98    /// Kind of file-level change.
99    kind: FileKind,
100}
101
102/// Stateful file tree owned by the diff viewer.
103#[derive(Clone, Debug, Eq, PartialEq)]
104pub(super) struct FileTreeViewer {
105    /// Path tree rendered in the file tree.
106    model: FileTreeModel,
107    /// Expansion and cursor state for the file tree.
108    state: TreeState<usize>,
109}
110
111impl FileTreeViewer {
112    /// Creates a file-tree viewer from `document`.
113    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
114        let model = FileTreeModel::new(document, root);
115        let state = model.initial_state();
116
117        Self { model, state }
118    }
119
120    /// Returns the file tree's expansion and cursor state.
121    ///
122    /// The `model` is immutable after construction, so this is the only part
123    /// that changes between actions.
124    pub(super) fn state(&self) -> &TreeState<usize> {
125        &self.state
126    }
127
128    /// Returns the file-tree target under the cursor.
129    #[cfg(test)]
130    pub(super) fn target(&self) -> Option<FileTreeTarget> {
131        self.state
132            .selected()
133            .and_then(|id| self.model.target_for(id))
134    }
135
136    /// Returns the file tree width for a viewport.
137    pub(super) fn cols(&self, view_cols: usize) -> usize {
138        let available = view_cols.saturating_sub(GAP_COLS + MIN_RENDER_COLS);
139
140        Tree::new(&self.model, &self.state)
141            .content_cols(DEFAULT_COLS)
142            .min(available)
143    }
144
145    /// Renders the file tree.
146    pub(super) fn render(
147        &mut self,
148        active_file: Option<FileId>,
149        palette: DiffPalette,
150        area: Rect,
151        buf: &mut Buffer,
152    ) {
153        let Some((tree_area, info_area)) = Self::areas(area) else {
154            return;
155        };
156        let collapsed = self
157            .model
158            .branch_ids()
159            .filter(|id| !self.state.is_expanded(*id))
160            .collect();
161        let styled = StyledFileTree {
162            model: &self.model,
163            selected: self.state.selected(),
164            active_file,
165            collapsed,
166            palette,
167        };
168        let tree = Tree::new(&styled, &self.state).style(FILE_TREE_STYLE);
169        let rows = tree.visible_rows();
170        let row = tree.selected_row(&rows).unwrap_or_default();
171        let view =
172            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
173
174        view.render_rows(tree_area, buf, |row, cols| tree.render_row(rows[row], cols));
175        if let Some(area) = info_area {
176            let mut table = Table::new(TableOptions {
177                border: Some(tui::Border::new(colors::FAINT)),
178                spacing: 2,
179                ..TableOptions::default()
180            });
181            let stats = self.model.stats;
182
183            table.push([
184                Line::new(Label::new("lines changed").fg(FOLDER_FG)),
185                Line::spaced([
186                    Label::from(format!("+{}", stats.insertions)).fg(palette.positive_fg),
187                    Label::from(format!("-{}", stats.deletions)).fg(palette.negative_fg),
188                ]),
189            ]);
190            table.push([
191                Line::new(Label::new("files changed").fg(FOLDER_FG)),
192                Line::new(Label::from(format!(" {}", stats.files_changed)).fg(Color::White)),
193            ]);
194            table.render(area, buf);
195        }
196    }
197
198    /// Enters the file tree when it is visible.
199    pub(super) fn enter(&mut self, active_file: Option<FileId>) {
200        let chosen = active_file
201            .and_then(|file| self.visible_node_for_file(file))
202            .or_else(|| self.first_visible_node());
203        if let Some(id) = chosen {
204            self.state.select(id);
205        }
206    }
207
208    /// Moves the file-tree cursor by `delta` visible rows.
209    pub(super) fn select(&mut self, delta: isize) -> Option<FileId> {
210        self.state.select_next(&self.model, delta);
211        self.selected_file()
212    }
213
214    /// Selects the visible file-tree row for `file`.
215    pub(super) fn select_file(&mut self, file: FileId) -> bool {
216        let Some(id) = self.visible_node_for_file(file) else {
217            return false;
218        };
219        self.state.select(id)
220    }
221
222    /// Selects the file-tree row at `point` inside `area`.
223    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> Option<FileTreeClick> {
224        let (tree_area, _) = Self::areas(area)?;
225        let tree = Tree::new(&self.model, &self.state);
226        let rows = tree.visible_rows();
227        let row = tree.selected_row(&rows).unwrap_or_default();
228        let view =
229            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
230        let row = view.row_at(tree_area, point)?;
231        let row = rows.get(row)?;
232        if self.model.kind(row.id) == TreeNodeKind::Branch
233            && point.x.saturating_sub(tree_area.x) == row.depth.saturating_mul(TREE_INDENT_COLS)
234        {
235            self.state.toggle(&self.model, row.id);
236            Some(FileTreeClick::Disclosure)
237        } else {
238            self.state.select(row.id);
239            Some(FileTreeClick::Row)
240        }
241    }
242
243    /// Activates the current file-tree cursor.
244    pub(super) fn activate_target(&mut self) -> Option<FileId> {
245        let id = self.state.selected()?;
246        if self.model.kind(id) == TreeNodeKind::Branch {
247            self.state.toggle(&self.model, id);
248        }
249        self.selected_file()
250    }
251
252    /// Returns the file represented by the selected file-tree row.
253    pub(super) fn selected_file(&self) -> Option<FileId> {
254        self.state
255            .selected()
256            .and_then(|id| self.model.first_file_for(id))
257    }
258
259    /// Collapses the focused file-tree folder.
260    pub(super) fn collapse_folder(&mut self) {
261        let Some(id) = self.state.selected() else {
262            return;
263        };
264        if self.model.kind(id) == TreeNodeKind::Branch {
265            self.state.collapse(id);
266        }
267    }
268
269    /// Expands the focused file-tree folder.
270    pub(super) fn expand_folder(&mut self) {
271        let Some(id) = self.state.selected() else {
272            return;
273        };
274        if self.model.kind(id) == TreeNodeKind::Branch {
275            self.state.expand(id);
276        }
277    }
278
279    /// Returns the visible tree row that best represents `file`.
280    fn visible_node_for_file(&self, file: FileId) -> Option<usize> {
281        let mut collapsed_branch = None;
282
283        for row in Tree::new(&self.model, &self.state).visible_rows() {
284            match self.model.target_for(row.id) {
285                Some(FileTreeTarget::File(candidate)) if candidate == file => {
286                    return Some(row.id);
287                }
288                Some(FileTreeTarget::Root | FileTreeTarget::Directory(_))
289                    if !self.state.is_expanded(row.id)
290                        && self.model.files_for(row.id).contains(&file) =>
291                {
292                    collapsed_branch = Some(row.id);
293                }
294                _ => {}
295            }
296        }
297        collapsed_branch
298    }
299
300    /// Returns the first visible tree row.
301    fn first_visible_node(&self) -> Option<usize> {
302        Tree::new(&self.model, &self.state)
303            .visible_rows()
304            .into_iter()
305            .next()
306            .map(|row| row.id)
307    }
308
309    /// Returns the drawable row area for file-tree contents.
310    fn areas(area: Rect) -> Option<(Rect, Option<Rect>)> {
311        let body: Rect = Rect::new(
312            area.x,
313            area.y.saturating_add(TOP_PADDING_ROWS),
314            area.cols,
315            area.rows.saturating_sub(TOP_PADDING_ROWS),
316        );
317        if body.is_empty() {
318            return None;
319        }
320        let info_rows = INFO_BOX_ROWS + INFO_BOX_GAP_ROWS + MIN_TREE_ROWS_WITH_INFO;
321        let info = (body.rows >= info_rows).then(|| {
322            Rect::new(
323                body.x,
324                body.bottom().saturating_sub(INFO_BOX_ROWS),
325                body.cols,
326                INFO_BOX_ROWS,
327            )
328        });
329        let tree_rows = if info.is_some() {
330            body.rows.saturating_sub(INFO_BOX_ROWS + INFO_BOX_GAP_ROWS)
331        } else {
332            body.rows
333        };
334
335        Some((Rect::new(body.x, body.y, body.cols, tree_rows), info))
336    }
337}
338
339/// Path tree built once from a diff document. Immutable after construction.
340#[derive(Clone, Debug, Eq, PartialEq)]
341pub(super) struct FileTreeModel {
342    /// Root node ids.
343    roots: Vec<usize>,
344    /// Tree nodes indexed by id.
345    nodes: Vec<FileTreeNode>,
346    /// Aggregate diff statistics for the summary box.
347    stats: Stats,
348}
349
350impl FileTreeModel {
351    /// Creates a path tree from the files in `document`.
352    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
353        let mut model = Self {
354            roots: Vec::new(),
355            nodes: Vec::new(),
356            stats: document.stats(),
357        };
358        let root = model.push_node(None, root, None, FileTreeTarget::Root);
359
360        for file in &document.files {
361            model.insert_file(
362                root,
363                Self::path_parts(file.header.display_path()),
364                file.id,
365                file.header.kind,
366            );
367        }
368        model
369    }
370
371    /// Returns a tree state with every branch expanded.
372    pub(super) fn initial_state(&self) -> TreeState<usize> {
373        let mut state = TreeState::new();
374
375        for id in self.branch_ids() {
376            state.expand(id);
377        }
378        state
379    }
380
381    /// Returns the tree target represented by `id`.
382    fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
383        self.nodes.get(id).map(|node| node.target.clone())
384    }
385
386    /// Returns the ids of every branch (non-leaf) node.
387    fn branch_ids(&self) -> impl Iterator<Item = usize> + '_ {
388        self.nodes
389            .iter()
390            .enumerate()
391            .filter_map(|(id, node)| (!node.children.is_empty()).then_some(id))
392    }
393
394    /// Returns the files included below `id`.
395    fn files_for(&self, id: usize) -> BTreeSet<FileId> {
396        let mut files = BTreeSet::new();
397
398        if let Some(file) = self.nodes[id].file {
399            files.insert(file.id);
400        }
401        for child in &self.nodes[id].children {
402            files.extend(self.files_for(*child));
403        }
404        files
405    }
406
407    /// Returns the first file contained by `id` in tree order.
408    fn first_file_for(&self, id: usize) -> Option<FileId> {
409        if let Some(file) = self.nodes[id].file {
410            return Some(file.id);
411        }
412        self.nodes[id]
413            .children
414            .iter()
415            .find_map(|child| self.first_file_for(*child))
416    }
417
418    /// Returns display path components for a file header path.
419    fn path_parts(path: Option<&PathBuf>) -> Vec<String> {
420        let Some(path) = path else {
421            return vec!["<unknown>".to_owned()];
422        };
423        let parts: Vec<String> = path
424            .iter()
425            .map(|part| part.to_string_lossy().into_owned())
426            .filter(|part| !part.is_empty())
427            .collect();
428
429        if parts.is_empty() {
430            vec!["<unknown>".to_owned()]
431        } else {
432            parts
433        }
434    }
435
436    /// Inserts one file path into the model.
437    fn insert_file(&mut self, root: usize, parts: Vec<String>, file: FileId, kind: FileKind) {
438        let mut parent = Some(root);
439        let mut path = PathBuf::new();
440        let end = parts.len().saturating_sub(1);
441
442        for (index, name) in parts.into_iter().enumerate() {
443            path.push(&name);
444            let is_file = index == end;
445            let target = if is_file {
446                FileTreeTarget::File(file)
447            } else {
448                FileTreeTarget::Directory(path.clone())
449            };
450            let existing = self.child(parent, &target);
451            let node = existing.unwrap_or_else(|| {
452                let file = is_file.then_some(FileTreeFile { id: file, kind });
453                self.push_node(parent, name, file, target)
454            });
455            parent = Some(node);
456        }
457    }
458
459    /// Returns a matching child node below `parent`.
460    fn child(&self, parent: Option<usize>, target: &FileTreeTarget) -> Option<usize> {
461        let children = parent.map_or(self.roots.as_slice(), |id| {
462            self.nodes[id].children.as_slice()
463        });
464
465        children
466            .iter()
467            .copied()
468            .find(|&child| self.nodes[child].target == *target)
469    }
470
471    /// Appends a node below `parent`.
472    fn push_node(
473        &mut self,
474        parent: Option<usize>,
475        name: String,
476        file: Option<FileTreeFile>,
477        target: FileTreeTarget,
478    ) -> usize {
479        let id = self.nodes.len();
480
481        self.nodes.push(FileTreeNode {
482            name,
483            children: Vec::new(),
484            file,
485            target,
486        });
487        if let Some(parent) = parent {
488            self.nodes[parent].children.push(id);
489        } else {
490            self.roots.push(id);
491        }
492        id
493    }
494
495    /// Returns a folder row (used by both structural and styled tree views).
496    fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow {
497        let node = &self.nodes[id];
498        let label = if node.name == "/" {
499            node.name.to_owned()
500        } else {
501            format!("{}/", node.name)
502        };
503        TreeRow::new(Label::from(label).fg(fg))
504            .marker_style(Style::new(fg))
505            .style(style)
506    }
507}
508
509impl TreeModel for FileTreeModel {
510    type Id = usize;
511
512    fn roots(&self) -> &[Self::Id] {
513        &self.roots
514    }
515
516    fn children(&self, id: Self::Id) -> &[Self::Id] {
517        &self.nodes[id].children
518    }
519
520    fn kind(&self, id: Self::Id) -> TreeNodeKind {
521        if self.nodes[id].file.is_some() {
522            TreeNodeKind::Leaf
523        } else {
524            TreeNodeKind::Branch
525        }
526    }
527
528    fn row(&self, id: Self::Id) -> TreeRow {
529        let node = &self.nodes[id];
530        let Some(file) = node.file else {
531            return self.folder_row(id, FOLDER_FG, Style::default());
532        };
533        TreeRow::new(Label::new(&node.name).fg(Color::White))
534            .marker(file.kind.marker())
535            .marker_style(Style::new(Color::Unset))
536    }
537}
538
539/// Render-time view over a [`FileTreeModel`] that applies active-file styling.
540///
541/// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows
542/// without forcing render-time state into the structural model.
543struct StyledFileTree<'a> {
544    /// Underlying structural tree.
545    model: &'a FileTreeModel,
546    /// File-tree cursor row.
547    selected: Option<usize>,
548    /// File currently active in the diff view.
549    active_file: Option<FileId>,
550    /// Branch ids that are currently collapsed.
551    collapsed: BTreeSet<usize>,
552    /// Positive and negative colors used for file details.
553    palette: DiffPalette,
554}
555
556impl StyledFileTree<'_> {
557    /// Returns whether `id` should render with active styling.
558    ///
559    /// True when the file-tree cursor is on `id` or when `id` represents the
560    /// active diff file directly (a file row) or indirectly (a collapsed folder
561    /// containing it).
562    fn is_active(&self, id: usize) -> bool {
563        if self.selected == Some(id) {
564            return true;
565        }
566        let Some(node) = self.model.nodes.get(id) else {
567            return false;
568        };
569        let Some(active_file) = self.active_file else {
570            return false;
571        };
572        match &node.target {
573            FileTreeTarget::File(file) => *file == active_file,
574            FileTreeTarget::Root | FileTreeTarget::Directory(_) => {
575                self.collapsed.contains(&id) && self.model.files_for(id).contains(&active_file)
576            }
577        }
578    }
579
580    /// Returns the full-row style for an active tree target.
581    fn row_style(&self, id: usize) -> Style {
582        if !self.is_active(id) {
583            return Style::default();
584        }
585        match self.model.nodes[id].target {
586            FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE,
587            FileTreeTarget::File(_) => SELECTED_FILE_STYLE,
588        }
589    }
590}
591
592impl TreeModel for StyledFileTree<'_> {
593    type Id = usize;
594
595    fn roots(&self) -> &[Self::Id] {
596        self.model.roots()
597    }
598
599    fn children(&self, id: Self::Id) -> &[Self::Id] {
600        self.model.children(id)
601    }
602
603    fn kind(&self, id: Self::Id) -> TreeNodeKind {
604        self.model.kind(id)
605    }
606
607    fn row(&self, id: Self::Id) -> TreeRow {
608        let node = &self.model.nodes[id];
609        let active = self.is_active(id);
610        let Some(file) = node.file else {
611            let fg = if active {
612                SELECTED_FOLDER_FG
613            } else {
614                FOLDER_FG
615            };
616            return self.model.folder_row(id, fg, self.row_style(id));
617        };
618        let fg = if active { SELECTED_FG } else { Color::White };
619        let kind_fg = match file.kind {
620            FileKind::Added => self.palette.positive_fg,
621            FileKind::Deleted => self.palette.negative_fg,
622            FileKind::Renamed => FILE_KIND_BADGE_FG,
623            FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
624                Color::Yellow
625            }
626        };
627
628        TreeRow::new(Label::new(&node.name).fg(fg))
629            .marker(file.kind.marker())
630            .marker_style(Style::new(kind_fg))
631            .style(self.row_style(id))
632    }
633}
634
635#[cfg(test)]
636#[allow(clippy::unwrap_used)]
637mod tests {
638    use crate::{Decode, DiffDocument, DiffOptions, DiffViewer};
639
640    fn two_file_viewer() -> DiffViewer {
641        let document = DiffDocument::decode_str(
642            "\
643diff --git a/a.rs b/a.rs
644index 1111111..2222222 100644
645--- a/a.rs
646+++ b/a.rs
647@@ -1,3 +1,4 @@ fn a
648 context
649-old
650+new
651+extra
652 tail
653diff --git a/b.rs b/b.rs
654index 3333333..4444444 100644
655--- a/b.rs
656+++ b/b.rs
657@@ -1,2 +1,2 @@ fn b
658 keep
659-before
660+after
661",
662        )
663        .unwrap();
664
665        DiffViewer::new(document, DiffOptions::default())
666    }
667
668    #[test]
669    fn file_tree_keeps_all_files_in_main_diff_rows() {
670        let viewer = two_file_viewer();
671
672        assert_eq!(viewer.index.files.len(), 2);
673        assert_eq!(viewer.index.rows, 16);
674    }
675}