crates/diff/src/viewer/tree.rs 23.0 KiB raw
1
//! File-tree model, rendering, and navigation for the diff viewer.
2
3
use std::collections::BTreeSet;
4
use std::path::PathBuf;
5
6
use rustik_tui as tui;
7
use tui::{
8
    Buffer, Cell, Color, Constraint, Label, Placement, Point, Rect, Size, Style, Tree, TreeHitZone,
9
    TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, Widget,
10
};
11
12
use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS, escape_path};
13
use crate::{DiffDecorator, DiffDocument, FileId, FileKind};
14
15
/// Blank rows above the file tree list.
16
const TOP_PADDING_ROWS: usize = 1;
17
/// Background color for the selected or active file row.
18
const SELECTED_FILE_BG: Color = Color::Fixed(235);
19
/// Background color for the selected or active folder row.
20
const SELECTED_FOLDER_BG: Color = Color::Fixed(234);
21
/// Foreground color for active file-tree row labels.
22
const SELECTED_FG: Color = Color::Fixed(252);
23
/// Foreground color for folder labels in the file tree.
24
const FOLDER_FG: Color = Color::Fixed(245);
25
/// Foreground color for collapsed folders containing the active file.
26
const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
27
/// Selected-row styling for the file tree.
28
const FILE_TREE_STYLE: TreeStyle =
29
    TreeStyle::new(Style::new(Color::Unset), Style::new(Color::Unset));
30
/// Style for the active file row.
31
const SELECTED_FILE_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_FILE_BG);
32
/// Style for a collapsed folder containing the active file.
33
const 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.
36
pub(super) const GAP_COLS: usize = 1;
37
/// Blank columns after file-tree row contents.
38
const RIGHT_PADDING_COLS: usize = 1;
39
/// Minimum main diff columns preserved when the file tree is visible.
40
pub(super) const MIN_DIFF_COLS: usize = 80;
41
42
/// Selectable target in the file tree.
43
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44
pub 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)]
55
pub(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)]
64
pub 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)]
74
struct 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)]
87
struct 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)]
100
pub 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
111
impl 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
        buf.fill(tree_area, Cell::blank());
193
194
        let tree = Tree::new(&styled, &self.state).style(FILE_TREE_STYLE);
195
        let rows = tree.visible_rows();
196
        let view = tree.selected_view(&rows, tree_area.rows, Placement::Minimal);
197
198
        view.render_rows(tree_area, buf, |row, cols| tree.render_row(rows[row], cols));
199
    }
200
201
    /// Enters the file tree when it is visible.
202
    pub(super) fn enter(&mut self, active_file: Option<FileId>) {
203
        let chosen = active_file
204
            .and_then(|file| self.visible_node_for_file(file))
205
            .or_else(|| self.first_visible_node());
206
        if let Some(id) = chosen {
207
            self.state.select(id);
208
        }
209
    }
210
211
    /// Moves the file-tree cursor by `delta` visible rows.
212
    pub fn select(&mut self, delta: isize) -> Option<FileId> {
213
        self.state.select_next(&self.model, delta);
214
        self.selected_file()
215
    }
216
217
    /// Selects the visible file-tree row for `file`.
218
    pub fn select_file(&mut self, file: FileId) -> bool {
219
        let Some(id) = self.visible_node_for_file(file) else {
220
            return false;
221
        };
222
        self.state.select(id)
223
    }
224
225
    /// Clears the file-tree cursor.
226
    pub(super) fn clear_selection(&mut self) -> bool {
227
        self.state.clear_selection()
228
    }
229
230
    /// Selects the file-tree row at `point` inside `area`.
231
    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> Option<FileTreeClick> {
232
        let tree_area = Self::area(area)?;
233
        let tree = Tree::new(&self.model, &self.state);
234
        let rows = tree.visible_rows();
235
        let view = tree.selected_view(&rows, tree_area.rows, Placement::Minimal);
236
        let hit = tree.hit_test(&rows, view, tree_area, point)?;
237
        let id = hit.row.id;
238
239
        if self.model.kind(id) == TreeNodeKind::Branch && hit.zone == TreeHitZone::Marker {
240
            self.state.toggle(&self.model, id);
241
            Some(FileTreeClick::Disclosure)
242
        } else {
243
            self.state.select(id);
244
            Some(FileTreeClick::Row)
245
        }
246
    }
247
248
    /// Activates the current file-tree cursor.
249
    pub fn activate_target(&mut self) -> Option<FileId> {
250
        let id = self.state.selected()?;
251
        if self.model.kind(id) == TreeNodeKind::Branch {
252
            self.state.toggle(&self.model, id);
253
        }
254
        self.selected_file()
255
    }
256
257
    /// Returns the file represented by the selected file-tree row.
258
    pub fn selected_file(&self) -> Option<FileId> {
259
        self.state
260
            .selected()
261
            .and_then(|id| self.model.first_file_for(id))
262
    }
263
264
    /// Collapses the focused file-tree folder.
265
    pub fn collapse_folder(&mut self) {
266
        let Some(id) = self.state.selected() else {
267
            return;
268
        };
269
        if self.model.kind(id) == TreeNodeKind::Branch {
270
            self.state.collapse(id);
271
        }
272
    }
273
274
    /// Expands the focused file-tree folder.
275
    pub fn expand_folder(&mut self) {
276
        let Some(id) = self.state.selected() else {
277
            return;
278
        };
279
        if self.model.kind(id) == TreeNodeKind::Branch {
280
            self.state.expand(id);
281
        }
282
    }
283
284
    /// Returns the visible tree row that best represents `file`.
285
    fn visible_node_for_file(&self, file: FileId) -> Option<usize> {
286
        let mut collapsed_branch = None;
287
288
        for row in Tree::new(&self.model, &self.state).visible_rows() {
289
            match self.model.target_for(row.id) {
290
                Some(FileTreeTarget::File(candidate)) if candidate == file => {
291
                    return Some(row.id);
292
                }
293
                Some(FileTreeTarget::Root | FileTreeTarget::Directory(_))
294
                    if !self.state.is_expanded(row.id)
295
                        && self.model.files_for(row.id).contains(&file) =>
296
                {
297
                    collapsed_branch = Some(row.id);
298
                }
299
                _ => {}
300
            }
301
        }
302
        collapsed_branch
303
    }
304
305
    /// Returns the first visible tree row.
306
    fn first_visible_node(&self) -> Option<usize> {
307
        Tree::new(&self.model, &self.state)
308
            .visible_rows()
309
            .into_iter()
310
            .next()
311
            .map(|row| row.id)
312
    }
313
314
    /// Returns the drawable row area for file-tree contents.
315
    fn area(area: Rect) -> Option<Rect> {
316
        let body: Rect = Rect::new(
317
            area.x,
318
            area.y.saturating_add(TOP_PADDING_ROWS),
319
            area.cols,
320
            area.rows.saturating_sub(TOP_PADDING_ROWS),
321
        );
322
        if body.is_empty() {
323
            return None;
324
        }
325
        Some(body)
326
    }
327
}
328
329
impl Widget for FileTree {
330
    fn size(&self, parent: Constraint) -> Size {
331
        let tree = Tree::new(&self.model, &self.state);
332
        let cols = tree.content_cols(0).saturating_add(RIGHT_PADDING_COLS);
333
        let rows = tree.visible_rows().len().saturating_add(TOP_PADDING_ROWS);
334
335
        Size::new(cols, rows).constrain(parent)
336
    }
337
338
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
339
        self.draw(self.active_file, self.palette, None, area, buf);
340
    }
341
}
342
343
/// Path tree built once from a diff document. Immutable after construction.
344
#[derive(Clone, Debug, Eq, PartialEq)]
345
pub(super) struct FileTreeModel {
346
    /// Root node ids.
347
    roots: Vec<usize>,
348
    /// Tree nodes indexed by id.
349
    nodes: Vec<FileTreeNode>,
350
}
351
352
impl FileTreeModel {
353
    /// Creates a path tree from the files in `document`.
354
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
355
        let mut model = Self {
356
            roots: Vec::new(),
357
            nodes: Vec::new(),
358
        };
359
        let root = model.push_node(None, root, None, FileTreeTarget::Root);
360
361
        for file in &document.files {
362
            model.insert_file(
363
                root,
364
                Self::path_parts(file.header.display_path()),
365
                file.id,
366
                file.header.kind,
367
            );
368
        }
369
        model
370
    }
371
372
    /// Returns a tree state with every branch expanded.
373
    pub(super) fn initial_state(&self) -> TreeState<usize> {
374
        let mut state = TreeState::new();
375
376
        for id in self.branch_ids() {
377
            state.expand(id);
378
        }
379
        state
380
    }
381
382
    /// Returns the tree target represented by `id`.
383
    fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
384
        self.nodes.get(id).map(|node| node.target.clone())
385
    }
386
387
    /// Returns the ids of every branch (non-leaf) node.
388
    fn branch_ids(&self) -> impl Iterator<Item = usize> + '_ {
389
        self.nodes
390
            .iter()
391
            .enumerate()
392
            .filter_map(|(id, node)| (!node.children.is_empty()).then_some(id))
393
    }
394
395
    /// Returns the files included below `id`.
396
    fn files_for(&self, id: usize) -> BTreeSet<FileId> {
397
        let mut files = BTreeSet::new();
398
399
        if let Some(file) = self.nodes[id].file {
400
            files.insert(file.id);
401
        }
402
        for child in &self.nodes[id].children {
403
            files.extend(self.files_for(*child));
404
        }
405
        files
406
    }
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
419
    /// Returns display path components for a file header path.
420
    fn path_parts(path: Option<&PathBuf>) -> Vec<String> {
421
        let Some(path) = path else {
422
            return vec!["<unknown>".to_owned()];
423
        };
424
        let parts: Vec<String> = path
425
            .iter()
426
            .map(|part| part.to_string_lossy().into_owned())
427
            .filter(|part| !part.is_empty())
428
            .collect();
429
430
        if parts.is_empty() {
431
            vec!["<unknown>".to_owned()]
432
        } else {
433
            parts
434
        }
435
    }
436
437
    /// Inserts one file path into the model.
438
    fn insert_file(&mut self, root: usize, parts: Vec<String>, file: FileId, kind: FileKind) {
439
        let mut parent = Some(root);
440
        let mut path = PathBuf::new();
441
        let end = parts.len().saturating_sub(1);
442
443
        for (index, name) in parts.into_iter().enumerate() {
444
            path.push(&name);
445
            let is_file = index == end;
446
            let target = if is_file {
447
                FileTreeTarget::File(file)
448
            } else {
449
                FileTreeTarget::Directory(path.clone())
450
            };
451
            let existing = self.child(parent, &target);
452
            let node = existing.unwrap_or_else(|| {
453
                let file = is_file.then_some(FileTreeFile { id: file, kind });
454
                self.push_node(parent, name, file, target)
455
            });
456
            parent = Some(node);
457
        }
458
    }
459
460
    /// Returns a matching child node below `parent`.
461
    fn child(&self, parent: Option<usize>, target: &FileTreeTarget) -> Option<usize> {
462
        let children = parent.map_or(self.roots.as_slice(), |id| {
463
            self.nodes[id].children.as_slice()
464
        });
465
466
        children
467
            .iter()
468
            .copied()
469
            .find(|&child| self.nodes[child].target == *target)
470
    }
471
472
    /// Appends a node below `parent`.
473
    fn push_node(
474
        &mut self,
475
        parent: Option<usize>,
476
        name: String,
477
        file: Option<FileTreeFile>,
478
        target: FileTreeTarget,
479
    ) -> usize {
480
        let id = self.nodes.len();
481
482
        self.nodes.push(FileTreeNode {
483
            name,
484
            children: Vec::new(),
485
            file,
486
            target,
487
        });
488
        if let Some(parent) = parent {
489
            self.nodes[parent].children.push(id);
490
        } else {
491
            self.roots.push(id);
492
        }
493
        id
494
    }
495
496
    /// Returns a folder row (used by both structural and styled tree views).
497
    fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow {
498
        let node = &self.nodes[id];
499
        let name = escape_path(&node.name);
500
        let label = if name == "/" {
501
            name.into_owned()
502
        } else {
503
            format!("{name}/")
504
        };
505
        TreeRow::new(Label::from(label).fg(fg))
506
            .marker_style(Style::new(fg))
507
            .style(style)
508
    }
509
}
510
511
impl TreeModel for FileTreeModel {
512
    type Id = usize;
513
514
    fn roots(&self) -> &[Self::Id] {
515
        &self.roots
516
    }
517
518
    fn children(&self, id: Self::Id) -> &[Self::Id] {
519
        &self.nodes[id].children
520
    }
521
522
    fn kind(&self, id: Self::Id) -> TreeNodeKind {
523
        if self.nodes[id].file.is_some() {
524
            TreeNodeKind::Leaf
525
        } else {
526
            TreeNodeKind::Branch
527
        }
528
    }
529
530
    fn row(&self, id: Self::Id) -> TreeRow {
531
        let node = &self.nodes[id];
532
        let Some(file) = node.file else {
533
            return self.folder_row(id, FOLDER_FG, Style::default());
534
        };
535
        TreeRow::new(Label::from(escape_path(&node.name).into_owned()).fg(Color::White))
536
            .marker(file.kind.marker())
537
            .marker_style(Style::new(Color::Unset))
538
    }
539
}
540
541
/// Render-time view over a [`FileTreeModel`] that applies active-file styling.
542
///
543
/// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows
544
/// without forcing render-time state into the structural model.
545
struct StyledFileTree<'a> {
546
    /// Underlying structural tree.
547
    model: &'a FileTreeModel,
548
    /// File-tree cursor row.
549
    selected: Option<usize>,
550
    /// File currently active in the diff view.
551
    active_file: Option<FileId>,
552
    /// Branch ids that are currently collapsed.
553
    collapsed: BTreeSet<usize>,
554
    /// Positive and negative colors used for file details.
555
    palette: DiffPalette,
556
    /// Optional host-supplied file decorations.
557
    decorator: Option<&'a dyn DiffDecorator>,
558
}
559
560
impl StyledFileTree<'_> {
561
    /// Returns whether `id` should render with active styling.
562
    ///
563
    /// The file-tree cursor takes precedence over the active diff file so only
564
    /// one visible row is highlighted.
565
    fn is_active(&self, id: usize) -> bool {
566
        if let Some(selected) = self.selected {
567
            return selected == id;
568
        }
569
        let Some(node) = self.model.nodes.get(id) else {
570
            return false;
571
        };
572
        let Some(active_file) = self.active_file else {
573
            return false;
574
        };
575
        match &node.target {
576
            FileTreeTarget::File(file) => *file == active_file,
577
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => {
578
                self.collapsed.contains(&id) && self.model.files_for(id).contains(&active_file)
579
            }
580
        }
581
    }
582
583
    /// Returns the full-row style for an active tree target.
584
    fn row_style(&self, id: usize) -> Style {
585
        if !self.is_active(id) {
586
            return Style::default();
587
        }
588
        match self.model.nodes[id].target {
589
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE,
590
            FileTreeTarget::File(_) => SELECTED_FILE_STYLE,
591
        }
592
    }
593
}
594
595
impl TreeModel for StyledFileTree<'_> {
596
    type Id = usize;
597
598
    fn roots(&self) -> &[Self::Id] {
599
        self.model.roots()
600
    }
601
602
    fn children(&self, id: Self::Id) -> &[Self::Id] {
603
        self.model.children(id)
604
    }
605
606
    fn kind(&self, id: Self::Id) -> TreeNodeKind {
607
        self.model.kind(id)
608
    }
609
610
    fn row(&self, id: Self::Id) -> TreeRow {
611
        let node = &self.model.nodes[id];
612
        let active = self.is_active(id);
613
        let Some(file) = node.file else {
614
            let fg = if active {
615
                SELECTED_FOLDER_FG
616
            } else {
617
                FOLDER_FG
618
            };
619
            return self.model.folder_row(id, fg, self.row_style(id));
620
        };
621
        let fg = if active { SELECTED_FG } else { Color::White };
622
        let kind_fg = match file.kind {
623
            FileKind::Added => self.palette.positive_fg,
624
            FileKind::Deleted => self.palette.negative_fg,
625
            FileKind::Renamed => FILE_KIND_BADGE_FG,
626
            FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
627
                Color::Yellow
628
            }
629
        };
630
        let status = self
631
            .decorator
632
            .and_then(|decorator| decorator.file(file.id).status);
633
        let marker = status.map_or_else(|| file.kind.marker(), |status| status.item);
634
        let marker_style = status.map_or_else(|| Style::new(kind_fg), |status| status.style);
635
636
        TreeRow::new(Label::from(escape_path(&node.name).into_owned()).fg(fg))
637
            .marker(marker)
638
            .marker_style(marker_style)
639
            .style(self.row_style(id))
640
    }
641
}
642
643
#[cfg(test)]
644
#[allow(clippy::unwrap_used)]
645
mod tests {
646
    use super::*;
647
648
    use rustik_tui::{Buffer, Color, Rect, Widget};
649
650
    use crate::{Decode, DiffDocument, DiffOptions, DiffViewer};
651
652
    fn two_file_viewer() -> DiffViewer {
653
        let document = DiffDocument::decode_str(
654
            "\
655
diff --git a/a.rs b/a.rs
656
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
657
--- a/a.rs
658
+++ b/a.rs
659
@@ -1,3 +1,4 @@ fn a
660
 context
661
-old
662
+new
663
+extra
664
 tail
665
diff --git a/b.rs b/b.rs
666
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
667
--- a/b.rs
668
+++ b/b.rs
669
@@ -1,2 +1,2 @@ fn b
670
 keep
671
-before
672
+after
673
",
674
        )
675
        .unwrap();
676
677
        DiffViewer::new(document, DiffOptions::default())
678
    }
679
680
    #[test]
681
    fn file_tree_keeps_all_files_in_main_diff_rows() {
682
        let viewer = two_file_viewer();
683
684
        assert_eq!(viewer.index.files.len(), 2);
685
        assert_eq!(viewer.index.rows, 16);
686
    }
687
    #[test]
688
    fn file_tree_clears_the_previous_selection() {
689
        let viewer = two_file_viewer();
690
        let document = viewer.document.clone();
691
        let first = document.files[0].id;
692
        let second = document.files[1].id;
693
        let mut tree = FileTree::new(&document, "root".to_owned());
694
        let mut buffer = Buffer::empty(Rect::new(0, 0, 20, 4));
695
696
        tree.select_file(first);
697
        tree.render(buffer.area(), &mut buffer);
698
        tree.select_file(second);
699
        tree.render(buffer.area(), &mut buffer);
700
701
        assert_eq!(
702
            buffer.get(19, 2).map(|cell| cell.style().bg_color()),
703
            Some(Color::Unset)
704
        );
705
        assert_eq!(
706
            buffer.get(19, 3).map(|cell| cell.style().bg_color()),
707
            Some(SELECTED_FILE_BG)
708
        );
709
    }
710
711
    #[test]
712
    fn file_tree_escapes_control_characters_in_paths() {
713
        let mut document = two_file_viewer().document;
714
        let path = PathBuf::from("tab\tname.txt");
715
        document.files[0].header.old_path = Some(path.clone());
716
        document.files[0].header.new_path = Some(path);
717
        let mut tree = FileTree::new(&document, "root".to_owned());
718
        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 4));
719
720
        tree.render(buffer.area(), &mut buffer);
721
722
        let text = (0..buffer.area().rows)
723
            .map(|row| buffer.line(row))
724
            .collect::<String>();
725
        assert!(text.contains("tab\\tname.txt"), "text: {text:?}");
726
    }
727
}