//! File-tree model, rendering, and navigation for the diff viewer. use std::collections::BTreeSet; use std::path::PathBuf; use rustik_tui as tui; use tui::{ Buffer, Cell, Color, Constraint, Label, Placement, Point, Rect, Size, Style, Tree, TreeHitZone, TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, Widget, }; use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS}; use crate::{DiffDecorator, DiffDocument, FileId, FileKind}; /// Blank rows above the file tree list. const TOP_PADDING_ROWS: usize = 1; /// Background color for the selected or active file row. const SELECTED_FILE_BG: Color = Color::Fixed(235); /// Background color for the selected or active folder row. const SELECTED_FOLDER_BG: Color = Color::Fixed(234); /// Foreground color for active file-tree row labels. const SELECTED_FG: Color = Color::Fixed(252); /// Foreground color for folder labels in the file tree. const FOLDER_FG: Color = Color::Fixed(245); /// Foreground color for collapsed folders containing the active file. const SELECTED_FOLDER_FG: Color = Color::Fixed(246); /// Selected-row styling for the file tree. const FILE_TREE_STYLE: TreeStyle = TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset)); /// Style for the active file row. const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG); /// Style for a collapsed folder containing the active file. const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_FOLDER_BG); /// Blank columns between the file tree and the diff body. pub(super) const GAP_COLS: usize = 1; /// Blank columns after file-tree row contents. const RIGHT_PADDING_COLS: usize = 1; /// Minimum main diff columns preserved when the file tree is visible. pub(super) const MIN_DIFF_COLS: usize = 80; /// Selectable target in the file tree. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum FileTreeTarget { /// Root row for the current working directory. Root, /// Directory row containing changed files. Directory(PathBuf), /// File row from the diff document. File(FileId), } /// Mouse target selected inside the file tree. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum FileTreeClick { /// The disclosure marker for a folder row was clicked. Disclosure, /// The row body was clicked. Row, } /// File-tree rendering policy. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum FileTreeMode { /// Never render the file tree. #[default] Hidden, /// Render the file tree when the viewport is wide enough. Auto, } /// One node in the rendered file tree. #[derive(Clone, Debug, Eq, PartialEq)] struct FileTreeNode { /// Display name for this path segment. name: String, /// Child node ids. children: Vec, /// Diff file data when this node is a file leaf. file: Option, /// Stable tree target represented by this node. target: FileTreeTarget, } /// Diff file metadata stored in a file-tree leaf node. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct FileTreeFile { /// Stable file identifier. id: FileId, /// Kind of file-level change. kind: FileKind, } /// Stateful file tree over a diff document, usable as a standalone [`Widget`]. /// /// A host builds it from a [`DiffDocument`], drives selection through the /// navigation methods, and renders it anywhere via its [`Widget`] /// implementation. The diff viewer embeds one and renders it directly. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FileTree { /// Path tree rendered in the file tree. model: FileTreeModel, /// Expansion and cursor state for the file tree. state: TreeState, /// File highlighted as active when rendered through [`Widget`]. active_file: Option, /// Palette used for badges and stats when rendered through [`Widget`]. palette: DiffPalette, } impl FileTree { /// Creates a file tree from `document`, rooted at the folder named `root`. pub fn new(document: &DiffDocument, root: String) -> Self { let model = FileTreeModel::new(document, root); let state = model.initial_state(); Self { model, state, active_file: None, palette: DiffPalette::default(), } } /// Sets the file highlighted as active when rendered through [`Widget`]. #[must_use] pub fn active_file(mut self, file: Option) -> Self { self.active_file = file; self } /// Sets the palette used for badges and stats when rendered through [`Widget`]. #[must_use] pub fn palette(mut self, palette: DiffPalette) -> Self { self.palette = palette; self } /// Returns the file tree's expansion and cursor state. /// /// The `model` is immutable after construction, so this is the only part /// that changes between actions. pub fn state(&self) -> &TreeState { &self.state } /// Returns the file-tree target under the cursor. pub fn target(&self) -> Option { self.state .selected() .and_then(|id| self.model.target_for(id)) } /// Returns the file tree width for a viewport. pub fn cols(&self, view_cols: usize) -> usize { let available = view_cols.saturating_sub(GAP_COLS + MIN_RENDER_COLS); Tree::new(&self.model, &self.state) .content_cols(0) .saturating_add(RIGHT_PADDING_COLS) .min(available) } /// Renders the file tree into `area` with an explicit active file and palette. /// /// This is the workhorse the diff viewer calls directly; the [`Widget`] /// implementation delegates here using the configured fields. pub(super) fn draw( &mut self, active_file: Option, palette: DiffPalette, decorator: Option<&dyn DiffDecorator>, area: Rect, buf: &mut Buffer, ) { let Some(tree_area) = Self::area(area) else { return; }; let collapsed = self .model .branch_ids() .filter(|id| !self.state.is_expanded(*id)) .collect(); let styled = StyledFileTree { model: &self.model, selected: self.state.selected(), active_file, collapsed, palette, decorator, }; buf.fill(tree_area, Cell::blank()); let tree = Tree::new(&styled, &self.state).style(FILE_TREE_STYLE); let rows = tree.visible_rows(); let view = tree.selected_view(&rows, tree_area.rows, Placement::Minimal); view.render_rows(tree_area, buf, |row, cols| tree.render_row(rows[row], cols)); } /// Enters the file tree when it is visible. pub(super) fn enter(&mut self, active_file: Option) { let chosen = active_file .and_then(|file| self.visible_node_for_file(file)) .or_else(|| self.first_visible_node()); if let Some(id) = chosen { self.state.select(id); } } /// Moves the file-tree cursor by `delta` visible rows. pub fn select(&mut self, delta: isize) -> Option { self.state.select_next(&self.model, delta); self.selected_file() } /// Selects the visible file-tree row for `file`. pub fn select_file(&mut self, file: FileId) -> bool { let Some(id) = self.visible_node_for_file(file) else { return false; }; self.state.select(id) } /// Clears the file-tree cursor. pub(super) fn clear_selection(&mut self) -> bool { self.state.clear_selection() } /// Selects the file-tree row at `point` inside `area`. pub(super) fn select_at(&mut self, area: Rect, point: Point) -> Option { let tree_area = Self::area(area)?; let tree = Tree::new(&self.model, &self.state); let rows = tree.visible_rows(); let view = tree.selected_view(&rows, tree_area.rows, Placement::Minimal); let hit = tree.hit_test(&rows, view, tree_area, point)?; let id = hit.row.id; if self.model.kind(id) == TreeNodeKind::Branch && hit.zone == TreeHitZone::Marker { self.state.toggle(&self.model, id); Some(FileTreeClick::Disclosure) } else { self.state.select(id); Some(FileTreeClick::Row) } } /// Activates the current file-tree cursor. pub fn activate_target(&mut self) -> Option { let id = self.state.selected()?; if self.model.kind(id) == TreeNodeKind::Branch { self.state.toggle(&self.model, id); } self.selected_file() } /// Returns the file represented by the selected file-tree row. pub fn selected_file(&self) -> Option { self.state .selected() .and_then(|id| self.model.first_file_for(id)) } /// Collapses the focused file-tree folder. pub fn collapse_folder(&mut self) { let Some(id) = self.state.selected() else { return; }; if self.model.kind(id) == TreeNodeKind::Branch { self.state.collapse(id); } } /// Expands the focused file-tree folder. pub fn expand_folder(&mut self) { let Some(id) = self.state.selected() else { return; }; if self.model.kind(id) == TreeNodeKind::Branch { self.state.expand(id); } } /// Returns the visible tree row that best represents `file`. fn visible_node_for_file(&self, file: FileId) -> Option { let mut collapsed_branch = None; for row in Tree::new(&self.model, &self.state).visible_rows() { match self.model.target_for(row.id) { Some(FileTreeTarget::File(candidate)) if candidate == file => { return Some(row.id); } Some(FileTreeTarget::Root | FileTreeTarget::Directory(_)) if !self.state.is_expanded(row.id) && self.model.files_for(row.id).contains(&file) => { collapsed_branch = Some(row.id); } _ => {} } } collapsed_branch } /// Returns the first visible tree row. fn first_visible_node(&self) -> Option { Tree::new(&self.model, &self.state) .visible_rows() .into_iter() .next() .map(|row| row.id) } /// Returns the drawable row area for file-tree contents. fn area(area: Rect) -> Option { let body: Rect = Rect::new( area.x, area.y.saturating_add(TOP_PADDING_ROWS), area.cols, area.rows.saturating_sub(TOP_PADDING_ROWS), ); if body.is_empty() { return None; } Some(body) } } impl Widget for FileTree { fn size(&self, parent: Constraint) -> Size { let tree = Tree::new(&self.model, &self.state); let cols = tree.content_cols(0).saturating_add(RIGHT_PADDING_COLS); let rows = tree.visible_rows().len().saturating_add(TOP_PADDING_ROWS); Size::new(cols, rows).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { self.draw(self.active_file, self.palette, None, area, buf); } } /// Path tree built once from a diff document. Immutable after construction. #[derive(Clone, Debug, Eq, PartialEq)] pub(super) struct FileTreeModel { /// Root node ids. roots: Vec, /// Tree nodes indexed by id. nodes: Vec, } impl FileTreeModel { /// Creates a path tree from the files in `document`. pub(super) fn new(document: &DiffDocument, root: String) -> Self { let mut model = Self { roots: Vec::new(), nodes: Vec::new(), }; let root = model.push_node(None, root, None, FileTreeTarget::Root); for file in &document.files { model.insert_file( root, Self::path_parts(file.header.display_path()), file.id, file.header.kind, ); } model } /// Returns a tree state with every branch expanded. pub(super) fn initial_state(&self) -> TreeState { let mut state = TreeState::new(); for id in self.branch_ids() { state.expand(id); } state } /// Returns the tree target represented by `id`. fn target_for(&self, id: usize) -> Option { self.nodes.get(id).map(|node| node.target.clone()) } /// Returns the ids of every branch (non-leaf) node. fn branch_ids(&self) -> impl Iterator + '_ { self.nodes .iter() .enumerate() .filter_map(|(id, node)| (!node.children.is_empty()).then_some(id)) } /// Returns the files included below `id`. fn files_for(&self, id: usize) -> BTreeSet { let mut files = BTreeSet::new(); if let Some(file) = self.nodes[id].file { files.insert(file.id); } for child in &self.nodes[id].children { files.extend(self.files_for(*child)); } files } /// Returns the first file contained by `id` in tree order. fn first_file_for(&self, id: usize) -> Option { if let Some(file) = self.nodes[id].file { return Some(file.id); } self.nodes[id] .children .iter() .find_map(|child| self.first_file_for(*child)) } /// Returns display path components for a file header path. fn path_parts(path: Option<&PathBuf>) -> Vec { let Some(path) = path else { return vec!["".to_owned()]; }; let parts: Vec = path .iter() .map(|part| part.to_string_lossy().into_owned()) .filter(|part| !part.is_empty()) .collect(); if parts.is_empty() { vec!["".to_owned()] } else { parts } } /// Inserts one file path into the model. fn insert_file(&mut self, root: usize, parts: Vec, file: FileId, kind: FileKind) { let mut parent = Some(root); let mut path = PathBuf::new(); let end = parts.len().saturating_sub(1); for (index, name) in parts.into_iter().enumerate() { path.push(&name); let is_file = index == end; let target = if is_file { FileTreeTarget::File(file) } else { FileTreeTarget::Directory(path.clone()) }; let existing = self.child(parent, &target); let node = existing.unwrap_or_else(|| { let file = is_file.then_some(FileTreeFile { id: file, kind }); self.push_node(parent, name, file, target) }); parent = Some(node); } } /// Returns a matching child node below `parent`. fn child(&self, parent: Option, target: &FileTreeTarget) -> Option { let children = parent.map_or(self.roots.as_slice(), |id| { self.nodes[id].children.as_slice() }); children .iter() .copied() .find(|&child| self.nodes[child].target == *target) } /// Appends a node below `parent`. fn push_node( &mut self, parent: Option, name: String, file: Option, target: FileTreeTarget, ) -> usize { let id = self.nodes.len(); self.nodes.push(FileTreeNode { name, children: Vec::new(), file, target, }); if let Some(parent) = parent { self.nodes[parent].children.push(id); } else { self.roots.push(id); } id } /// Returns a folder row (used by both structural and styled tree views). fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow { let node = &self.nodes[id]; let label = if node.name == "/" { node.name.to_owned() } else { format!("{}/", node.name) }; TreeRow::new(Label::from(label).fg(fg)) .marker_style(Style::new(fg)) .style(style) } } impl TreeModel for FileTreeModel { type Id = usize; fn roots(&self) -> &[Self::Id] { &self.roots } fn children(&self, id: Self::Id) -> &[Self::Id] { &self.nodes[id].children } fn kind(&self, id: Self::Id) -> TreeNodeKind { if self.nodes[id].file.is_some() { TreeNodeKind::Leaf } else { TreeNodeKind::Branch } } fn row(&self, id: Self::Id) -> TreeRow { let node = &self.nodes[id]; let Some(file) = node.file else { return self.folder_row(id, FOLDER_FG, Style::default()); }; TreeRow::new(Label::new(&node.name).fg(Color::White)) .marker(file.kind.marker()) .marker_style(Style::new(Color::Unset)) } } /// Render-time view over a [`FileTreeModel`] that applies active-file styling. /// /// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows /// without forcing render-time state into the structural model. struct StyledFileTree<'a> { /// Underlying structural tree. model: &'a FileTreeModel, /// File-tree cursor row. selected: Option, /// File currently active in the diff view. active_file: Option, /// Branch ids that are currently collapsed. collapsed: BTreeSet, /// Positive and negative colors used for file details. palette: DiffPalette, /// Optional host-supplied file decorations. decorator: Option<&'a dyn DiffDecorator>, } impl StyledFileTree<'_> { /// Returns whether `id` should render with active styling. /// /// The file-tree cursor takes precedence over the active diff file so only /// one visible row is highlighted. fn is_active(&self, id: usize) -> bool { if let Some(selected) = self.selected { return selected == id; } let Some(node) = self.model.nodes.get(id) else { return false; }; let Some(active_file) = self.active_file else { return false; }; match &node.target { FileTreeTarget::File(file) => *file == active_file, FileTreeTarget::Root | FileTreeTarget::Directory(_) => { self.collapsed.contains(&id) && self.model.files_for(id).contains(&active_file) } } } /// Returns the full-row style for an active tree target. fn row_style(&self, id: usize) -> Style { if !self.is_active(id) { return Style::default(); } match self.model.nodes[id].target { FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE, FileTreeTarget::File(_) => SELECTED_FILE_STYLE, } } } impl TreeModel for StyledFileTree<'_> { type Id = usize; fn roots(&self) -> &[Self::Id] { self.model.roots() } fn children(&self, id: Self::Id) -> &[Self::Id] { self.model.children(id) } fn kind(&self, id: Self::Id) -> TreeNodeKind { self.model.kind(id) } fn row(&self, id: Self::Id) -> TreeRow { let node = &self.model.nodes[id]; let active = self.is_active(id); let Some(file) = node.file else { let fg = if active { SELECTED_FOLDER_FG } else { FOLDER_FG }; return self.model.folder_row(id, fg, self.row_style(id)); }; let fg = if active { SELECTED_FG } else { Color::White }; let kind_fg = match file.kind { FileKind::Added => self.palette.positive_fg, FileKind::Deleted => self.palette.negative_fg, FileKind::Renamed => FILE_KIND_BADGE_FG, FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => { Color::Yellow } }; let status = self .decorator .and_then(|decorator| decorator.file(file.id).status); let marker = status.map_or_else(|| file.kind.marker(), |status| status.item); let marker_style = status.map_or_else(|| Style::new(kind_fg), |status| status.style); TreeRow::new(Label::new(&node.name).fg(fg)) .marker(marker) .marker_style(marker_style) .style(self.row_style(id)) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; use rustik_tui::{Buffer, Color, Rect, Widget}; use crate::{Decode, DiffDocument, DiffOptions, DiffViewer}; fn two_file_viewer() -> DiffViewer { let document = DiffDocument::decode_str( "\ diff --git a/a.rs b/a.rs index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.rs +++ b/a.rs @@ -1,3 +1,4 @@ fn a context -old +new +extra tail diff --git a/b.rs b/b.rs index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644 --- a/b.rs +++ b/b.rs @@ -1,2 +1,2 @@ fn b keep -before +after ", ) .unwrap(); DiffViewer::new(document, DiffOptions::default()) } #[test] fn file_tree_keeps_all_files_in_main_diff_rows() { let viewer = two_file_viewer(); assert_eq!(viewer.index.files.len(), 2); assert_eq!(viewer.index.rows, 16); } #[test] fn file_tree_clears_the_previous_selection() { let viewer = two_file_viewer(); let document = viewer.document.clone(); let first = document.files[0].id; let second = document.files[1].id; let mut tree = FileTree::new(&document, "root".to_owned()); let mut buffer = Buffer::empty(Rect::new(0, 0, 20, 4)); tree.select_file(first); tree.render(buffer.area(), &mut buffer); tree.select_file(second); tree.render(buffer.area(), &mut buffer); assert_eq!( buffer.get(19, 2).map(|cell| cell.style().bg_color()), Some(Color::Unset) ); assert_eq!( buffer.get(19, 3).map(|cell| cell.style().bg_color()), Some(SELECTED_FILE_BG) ); } }