1use 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
15const TOP_PADDING_ROWS: usize = 1;
17const SELECTED_FILE_BG: Color = Color::Fixed(235);
19const SELECTED_FOLDER_BG: Color = Color::Fixed(234);
21const SELECTED_FG: Color = Color::Fixed(252);
23const FOLDER_FG: Color = Color::Fixed(245);
25const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
27const FILE_TREE_STYLE: TreeStyle =
29 TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset));
30const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG);
32const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_FOLDER_BG);
34
35pub(super) const GAP_COLS: usize = 1;
37const RIGHT_PADDING_COLS: usize = 1;
39pub(super) const MIN_DIFF_COLS: usize = 80;
41
42#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub enum FileTreeTarget {
45 Root,
47 Directory(PathBuf),
49 File(FileId),
51}
52
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55pub(super) enum FileTreeClick {
56 Disclosure,
58 Row,
60}
61
62#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
64pub enum FileTreeMode {
65 #[default]
67 Hidden,
68 Auto,
70}
71
72#[derive(Clone, Debug, Eq, PartialEq)]
74struct FileTreeNode {
75 name: String,
77 children: Vec<usize>,
79 file: Option<FileTreeFile>,
81 target: FileTreeTarget,
83}
84
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
87struct FileTreeFile {
88 id: FileId,
90 kind: FileKind,
92}
93
94#[derive(Clone, Debug, Eq, PartialEq)]
100pub struct FileTree {
101 model: FileTreeModel,
103 state: TreeState<usize>,
105 active_file: Option<FileId>,
107 palette: DiffPalette,
109}
110
111impl FileTree {
112 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 #[must_use]
127 pub fn active_file(mut self, file: Option<FileId>) -> Self {
128 self.active_file = file;
129 self
130 }
131
132 #[must_use]
134 pub fn palette(mut self, palette: DiffPalette) -> Self {
135 self.palette = palette;
136 self
137 }
138
139 pub fn state(&self) -> &TreeState<usize> {
144 &self.state
145 }
146
147 pub fn target(&self) -> Option<FileTreeTarget> {
149 self.state
150 .selected()
151 .and_then(|id| self.model.target_for(id))
152 }
153
154 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 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 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 pub fn select(&mut self, delta: isize) -> Option<FileId> {
211 self.state.select_next(&self.model, delta);
212 self.selected_file()
213 }
214
215 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 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 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 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 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 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 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 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 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#[derive(Clone, Debug, Eq, PartialEq)]
338pub(super) struct FileTreeModel {
339 roots: Vec<usize>,
341 nodes: Vec<FileTreeNode>,
343}
344
345impl FileTreeModel {
346 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 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 fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
377 self.nodes.get(id).map(|node| node.target.clone())
378 }
379
380 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 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 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 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 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 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 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 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
533struct StyledFileTree<'a> {
538 model: &'a FileTreeModel,
540 selected: Option<usize>,
542 active_file: Option<FileId>,
544 collapsed: BTreeSet<usize>,
546 palette: DiffPalette,
548 decorator: Option<&'a dyn DiffDecorator>,
550}
551
552impl StyledFileTree<'_> {
553 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 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}