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