bettertree 1.0.0

An interactive terminal file tree driven like Helix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
pub mod scan;
pub mod watch;

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use scan::Entry;

pub const ROOT: NodeId = NodeId(0);

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId(usize);

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    File,
    Dir,
}

impl Kind {
    pub fn is_dir(self) -> bool {
        self == Kind::Dir
    }
}

/// Which entries the tree shows. Filters affect display only: nothing is unloaded or skipped.
#[derive(Clone, Copy, Default)]
pub struct Filter {
    pub show_hidden: bool,
    pub show_gitignored: bool,
    pub changed_only: bool,
}

pub struct Node {
    pub name: String,
    pub path: PathBuf,
    pub parent: Option<NodeId>,
    pub kind: Kind,
    pub symlink: bool,
    pub expanded: bool,
    pub children: Option<Vec<NodeId>>,
    pub ignored: Option<bool>,
    /// For a file, it has a git status; for a directory, something below it does.
    pub changed: bool,
    /// Cleared when the watcher sees the path disappear. Nodes are tombstoned rather than
    /// removed so that `NodeId`s, and the expansion state they carry, stay stable.
    pub alive: bool,
}

impl Node {
    pub fn is_loaded(&self) -> bool {
        self.children.is_some()
    }
}

pub struct Row {
    pub id: NodeId,
    pub depth: usize,
}

/// A running search, as the tree sees it: the entries that matched, the folders above them, and
/// which of the results the query fits best.
struct SearchFilter {
    matched: HashSet<NodeId>,
    path: HashSet<NodeId>,
    best: Option<NodeId>,
}

/// Nodes are added but never removed, so a collapsed folder keeps the expansion state of
/// everything inside it and re-expanding restores the exact previous shape.
pub struct Tree {
    nodes: Vec<Node>,
    index: HashMap<PathBuf, NodeId>,
    rows: Vec<Row>,
    rows_dirty: bool,
    filter: Filter,
    search: Option<SearchFilter>,
    /// Nodes below these marks have already been classified; everything above is new.
    ignore_mark: usize,
    changed_mark: usize,
    load_mark: usize,
    selected: NodeId,
    selected_row: usize,
}

impl Tree {
    pub fn new(root: PathBuf) -> Self {
        let name = root
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_else(|| root.to_string_lossy().into_owned());

        let root = Node {
            name,
            path: root,
            parent: None,
            kind: Kind::Dir,
            symlink: false,
            expanded: true,
            children: None,
            ignored: Some(false),
            changed: false,
            alive: true,
        };

        Self {
            index: HashMap::from([(root.path.clone(), ROOT)]),
            nodes: vec![root],
            rows: Vec::new(),
            rows_dirty: true,
            filter: Filter::default(),
            search: None,
            ignore_mark: 1,
            changed_mark: 0,
            load_mark: 0,
            selected: ROOT,
            selected_row: 0,
        }
    }

    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id.0]
    }

    pub fn find(&self, path: &Path) -> Option<NodeId> {
        self.index.get(path).copied()
    }

    pub fn selected(&self) -> NodeId {
        self.selected
    }

    pub fn selected_row(&self) -> usize {
        self.selected_row
    }

    pub fn rows(&self) -> &[Row] {
        &self.rows
    }

    pub fn graft(&mut self, id: NodeId, entries: Vec<Entry>) {
        let children = entries
            .into_iter()
            .map(|entry| self.push(id, entry))
            .collect();

        self.nodes[id.0].children = Some(children);
        self.rows_dirty = true;
    }

    fn push(&mut self, parent: NodeId, entry: Entry) -> NodeId {
        let id = NodeId(self.nodes.len());

        self.index.insert(entry.path.clone(), id);
        self.nodes.push(Node {
            name: entry.name,
            path: entry.path,
            parent: Some(parent),
            kind: entry.kind,
            symlink: entry.symlink,
            expanded: false,
            children: None,
            ignored: None,
            changed: false,
            alive: true,
        });

        id
    }

    /// Applies a fresh directory listing to an already-loaded folder. Entries that survive keep
    /// their node, and therefore their expansion and loaded children; the rest are tombstoned.
    /// Returns the paths that disappeared.
    pub fn reconcile(&mut self, id: NodeId, entries: Vec<Entry>) -> Vec<PathBuf> {
        let previous = self.nodes[id.0].children.clone().unwrap_or_default();
        let mut children = Vec::with_capacity(entries.len());

        for entry in entries {
            let survivor = previous.iter().copied().find(|child| {
                let node = &self.nodes[child.0];
                node.name == entry.name && node.kind == entry.kind && node.alive
            });

            match survivor {
                Some(child) => children.push(child),
                None => {
                    let child = self.push(id, entry);
                    children.push(child);
                }
            }
        }

        let mut removed = Vec::new();
        for child in previous {
            if !children.contains(&child) {
                self.kill(child, &mut removed);
            }
        }

        self.nodes[id.0].children = Some(children);
        self.rows_dirty = true;

        removed
    }

    fn kill(&mut self, id: NodeId, removed: &mut Vec<PathBuf>) {
        let node = &mut self.nodes[id.0];
        node.alive = false;

        let path = node.path.clone();
        let children = node.children.clone().unwrap_or_default();

        // A path recreated since then already points at its new node, so only stale entries go.
        if self.index.get(&path) == Some(&id) {
            self.index.remove(&path);
        }
        removed.push(path);

        for child in children {
            self.kill(child, removed);
        }
    }

    /// True when nodes have appeared that have no gitignore verdict yet. Checking this before
    /// classifying matters: building the exclude stack reads files.
    pub fn needs_ignore_classification(&self) -> bool {
        self.ignore_mark < self.nodes.len()
    }

    /// Fills in the gitignore state of newly loaded nodes. Children always sit after their parent
    /// in the arena, so a single forward pass can inherit exclusion from an ignored directory.
    pub fn classify_ignored(&mut self, is_ignored: &mut dyn FnMut(&Path, bool) -> bool) {
        for index in self.ignore_mark..self.nodes.len() {
            let inherited = self.nodes[index]
                .parent
                .is_some_and(|parent| self.nodes[parent.0].ignored == Some(true));

            let node = &self.nodes[index];
            let ignored = inherited || is_ignored(&node.path, node.kind.is_dir());

            self.nodes[index].ignored = Some(ignored);
        }

        self.ignore_mark = self.nodes.len();
        self.rows_dirty = true;
    }

    pub fn set_expanded(&mut self, id: NodeId, expanded: bool) {
        let node = &mut self.nodes[id.0];
        if !node.kind.is_dir() || node.expanded == expanded {
            return;
        }

        node.expanded = expanded;
        self.rows_dirty = true;
    }

    pub fn set_filter(&mut self, filter: Filter) {
        self.filter = filter;
        self.rows_dirty = true;
    }

    /// Narrows the tree to a set of results, best first, and the folders leading to them, or
    /// clears the search when given `None`.
    pub fn set_search(&mut self, ranked: Option<Vec<NodeId>>) {
        self.search = ranked.map(|ranked| SearchFilter {
            path: self.ancestors_of(&ranked),
            best: ranked.first().copied(),
            matched: ranked.into_iter().collect(),
        });

        self.rows_dirty = true;
    }

    /// The folders above the results. They are what the search opens, and walking up stops at
    /// the first one already recorded, so the whole set costs one pass over the results.
    fn ancestors_of(&self, matched: &[NodeId]) -> HashSet<NodeId> {
        let mut path = HashSet::new();

        for id in matched {
            let mut current = self.nodes[id.0].parent;

            while let Some(parent) = current {
                if !path.insert(parent) {
                    break;
                }
                current = self.nodes[parent.0].parent;
            }
        }

        path
    }

    pub fn is_searching(&self) -> bool {
        self.search.is_some()
    }

    pub fn match_count(&self) -> usize {
        self.search
            .as_ref()
            .map_or(0, |search| search.matched.len())
    }

    /// Steps between search results, passing over the folders that only lead to one. Walking on
    /// from the cursor and wrapping round is the same as visiting every row once, starting at
    /// the neighbour, so the ends need no special case.
    pub fn move_to_match(&mut self, delta: isize) {
        let count = self.rows.len();
        if count == 0 {
            return;
        }

        let target = (1..=count)
            .map(|step| match delta >= 0 {
                true => (self.selected_row + step) % count,
                false => (self.selected_row + count - step) % count,
            })
            .find(|row| self.is_match(*row));

        if let Some(row) = target {
            self.select_row(row);
        }
    }

    /// Puts the cursor on the result the query fits best, which the tree may well draw below a
    /// weaker one: the rows are in the tree's order, not the ranking's.
    pub fn select_best_match(&mut self) {
        if let Some(best) = self.search.as_ref().and_then(|search| search.best) {
            self.select(best);
        }
    }

    fn is_match(&self, row: usize) -> bool {
        let Some(search) = &self.search else {
            return false;
        };

        self.rows
            .get(row)
            .is_some_and(|row| search.matched.contains(&row.id))
    }

    /// Every entry the tree would show if all its folders were open: what a search looks through.
    pub fn reachable(&self) -> impl Iterator<Item = (NodeId, &Node)> {
        self.iter()
            .filter(|(id, _)| *id != ROOT && self.is_reachable(*id))
    }

    /// Filters hide a folder without hiding what is inside it, so a search has to walk up. The
    /// running search is left out on purpose: every query is matched against the whole tree.
    fn is_reachable(&self, id: NodeId) -> bool {
        let mut current = id;

        while current != ROOT {
            let node = &self.nodes[current.0];
            if !node.alive || !self.passes_filters(node) {
                return false;
            }

            let Some(parent) = node.parent else {
                return false;
            };
            current = parent;
        }

        true
    }

    /// The directories that appeared since the last call and still have not been read. Search
    /// walks the whole project this way, a batch per event, rather than re-scanning the arena.
    pub fn unloaded_directories(&mut self) -> Vec<NodeId> {
        let found = (self.load_mark..self.nodes.len())
            .map(NodeId)
            .filter(|id| {
                let node = &self.nodes[id.0];
                node.kind.is_dir() && !node.is_loaded() && self.is_reachable(*id)
            })
            .collect();

        self.load_mark = self.nodes.len();

        found
    }

    /// Starts the walk over, so entries a filter change has just revealed are read too.
    pub fn rewind_unloaded(&mut self) {
        self.load_mark = 0;
    }

    pub fn iter(&self) -> impl Iterator<Item = (NodeId, &Node)> {
        self.nodes
            .iter()
            .enumerate()
            .filter(|(_, node)| node.alive)
            .map(|(index, node)| (NodeId(index), node))
    }

    /// Records which nodes carry a git change. Directories are marked when anything below them
    /// changed, which is what lets `changed_only` reveal them.
    pub fn mark_all_changed(&mut self, has_changes: &mut dyn FnMut(&Path) -> bool) {
        self.changed_mark = 0;
        self.mark_changed(has_changes);
    }

    /// Marks only the nodes that appeared since the last pass, which keeps loading a large tree
    /// linear rather than quadratic.
    pub fn mark_changed(&mut self, has_changes: &mut dyn FnMut(&Path) -> bool) {
        for index in self.changed_mark..self.nodes.len() {
            let node = &mut self.nodes[index];
            node.changed = has_changes(&node.path);
        }

        self.changed_mark = self.nodes.len();
        self.rows_dirty = true;
    }

    /// Counts tombstones too, which is fine for the coarse limits it guards.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Collapses a folder and everything inside it, discarding the inner expansion on purpose.
    pub fn collapse_subtree(&mut self, id: NodeId) {
        let mut stack = vec![id];

        while let Some(current) = stack.pop() {
            if let Some(children) = &self.nodes[current.0].children {
                stack.extend(children.iter().copied());
            }

            self.set_expanded(current, false);
        }
    }

    pub fn refresh_rows(&mut self) {
        if !self.rows_dirty {
            return;
        }

        self.rows.clear();
        self.push_rows(ROOT, 0);
        self.rows_dirty = false;

        self.reconcile_selection();
    }

    fn push_rows(&mut self, id: NodeId, depth: usize) {
        let Some(children) = self.nodes[id.0].children.clone() else {
            return;
        };

        for child in children {
            if !self.is_visible(child) {
                continue;
            }

            let descend = self.is_open(child);
            self.rows.push(Row { id: child, depth });

            if descend {
                self.push_rows(child, depth + 1);
            }
        }
    }

    /// A running search narrows the tree further: only the results and the folders above them.
    fn is_visible(&self, id: NodeId) -> bool {
        let node = &self.nodes[id.0];
        if !node.alive || !self.passes_filters(node) {
            return false;
        }

        match &self.search {
            Some(search) => search.matched.contains(&id) || search.path.contains(&id),
            None => true,
        }
    }

    fn passes_filters(&self, node: &Node) -> bool {
        if !self.filter.show_hidden && node.name.starts_with('.') {
            return false;
        }
        if !self.filter.show_gitignored && node.ignored == Some(true) {
            return false;
        }
        if self.filter.changed_only && !node.changed {
            return false;
        }

        true
    }

    /// `changed_only` and a search both open folders without touching their saved expansion, so
    /// turning either off restores the tree exactly as it was.
    pub fn is_open(&self, id: NodeId) -> bool {
        let node = &self.nodes[id.0];
        if !node.kind.is_dir() {
            return false;
        }

        // A search shows the results and the folders leading to them, and nothing else: a
        // folder that only holds non-matching entries would otherwise open on an empty subtree.
        if let Some(search) = &self.search {
            return search.path.contains(&id);
        }

        node.expanded || (self.filter.changed_only && node.changed)
    }

    /// Keeps the cursor on the selected node, falling back to its nearest visible ancestor.
    fn reconcile_selection(&mut self) {
        let mut candidate = Some(self.selected);

        while let Some(id) = candidate {
            if let Some(row) = self.rows.iter().position(|row| row.id == id) {
                self.selected = id;
                self.selected_row = row;
                return;
            }
            candidate = self.nodes[id.0].parent;
        }

        self.selected = self.rows.first().map_or(ROOT, |row| row.id);
        self.selected_row = 0;
    }

    pub fn select_row(&mut self, row: usize) {
        if let Some(row_entry) = self.rows.get(row) {
            self.selected = row_entry.id;
            self.selected_row = row;
        }
    }

    pub fn select(&mut self, id: NodeId) {
        self.selected = id;
        self.reconcile_selection();
    }

    pub fn move_by(&mut self, delta: isize) {
        let target = self.selected_row.saturating_add_signed(delta);
        self.select_row(target.min(self.rows.len().saturating_sub(1)));
    }

    pub fn move_last(&mut self) {
        self.select_row(self.rows.len().saturating_sub(1));
    }

    /// Moves to the next entry at the current depth or shallower, skipping expanded subtrees.
    pub fn move_next_sibling(&mut self) {
        let Some(depth) = self.selected_depth() else {
            return;
        };

        let target = self.rows[self.selected_row + 1..]
            .iter()
            .position(|row| row.depth <= depth)
            .map(|offset| self.selected_row + 1 + offset);

        if let Some(target) = target {
            self.select_row(target);
        }
    }

    /// Moves to the previous entry at the current depth or shallower, skipping expanded subtrees.
    pub fn move_prev_sibling(&mut self) {
        let Some(depth) = self.selected_depth() else {
            return;
        };

        let target = self.rows[..self.selected_row]
            .iter()
            .rposition(|row| row.depth <= depth);

        if let Some(target) = target {
            self.select_row(target);
        }
    }

    pub fn move_parent(&mut self) {
        if let Some(parent) = self.nodes[self.selected.0].parent
            && parent != ROOT
        {
            self.select(parent);
        }
    }

    fn selected_depth(&self) -> Option<usize> {
        self.rows.get(self.selected_row).map(|row| row.depth)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(name: &str, kind: Kind) -> Entry {
        Entry {
            name: name.to_owned(),
            path: PathBuf::from(name),
            kind,
            symlink: false,
        }
    }

    fn find(tree: &Tree, name: &str) -> NodeId {
        tree.iter()
            .find(|(_, node)| node.name == name)
            .map(|(id, _)| id)
            .expect("live node exists")
    }

    /// root { a { b { deep.rs }, a.rs }, z.rs }
    fn sample() -> Tree {
        let mut tree = Tree::new(PathBuf::from("/root"));

        tree.graft(ROOT, vec![entry("a", Kind::Dir), entry("z.rs", Kind::File)]);
        let a = find(&tree, "a");

        tree.graft(a, vec![entry("b", Kind::Dir), entry("a.rs", Kind::File)]);
        let b = find(&tree, "b");

        tree.graft(b, vec![entry("deep.rs", Kind::File)]);

        tree
    }

    fn visible(tree: &mut Tree) -> Vec<&str> {
        tree.refresh_rows();
        tree.rows()
            .iter()
            .map(|row| tree.node(row.id).name.as_str())
            .collect()
    }

    #[test]
    fn collapsing_preserves_descendant_expansion() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");

        tree.set_expanded(a, true);
        tree.set_expanded(b, true);
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs", "a.rs", "z.rs"]);

        tree.set_expanded(a, false);
        assert_eq!(visible(&mut tree), ["a", "z.rs"]);

        tree.set_expanded(a, true);
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs", "a.rs", "z.rs"]);
    }

    #[test]
    fn next_sibling_skips_expanded_subtrees() {
        let mut tree = sample();
        let a = find(&tree, "a");
        tree.set_expanded(a, true);
        visible(&mut tree);

        tree.select(a);
        tree.move_next_sibling();

        assert_eq!(tree.node(tree.selected()).name, "z.rs");
    }

    #[test]
    fn next_sibling_leaves_a_subtree_at_its_last_entry() {
        let mut tree = sample();
        let a = find(&tree, "a");
        tree.set_expanded(a, true);
        visible(&mut tree);

        tree.select(find(&tree, "a.rs"));
        tree.move_next_sibling();

        assert_eq!(tree.node(tree.selected()).name, "z.rs");
    }

    #[test]
    fn prev_sibling_steps_back_over_an_expanded_subtree() {
        let mut tree = sample();
        let a = find(&tree, "a");
        tree.set_expanded(a, true);
        visible(&mut tree);

        tree.select(find(&tree, "z.rs"));
        tree.move_prev_sibling();

        assert_eq!(tree.node(tree.selected()).name, "a");
    }

    #[test]
    fn selection_falls_back_to_the_nearest_visible_ancestor() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        tree.set_expanded(a, true);
        tree.set_expanded(b, true);
        visible(&mut tree);

        tree.select(find(&tree, "deep.rs"));
        tree.set_expanded(a, false);
        visible(&mut tree);

        assert_eq!(tree.node(tree.selected()).name, "a");
    }

    #[test]
    fn hidden_entries_are_filtered_until_asked_for() {
        let mut tree = Tree::new(PathBuf::from("/root"));
        tree.graft(
            ROOT,
            vec![entry(".hidden", Kind::File), entry("shown", Kind::File)],
        );

        assert_eq!(visible(&mut tree), ["shown"]);

        tree.set_filter(Filter {
            show_hidden: true,
            ..Filter::default()
        });
        assert_eq!(visible(&mut tree), [".hidden", "shown"]);
    }

    #[test]
    fn gitignored_entries_are_filtered_until_asked_for() {
        let mut tree = sample();
        let ignored = find(&tree, "z.rs");
        tree.classify_ignored(&mut |path, _| path.ends_with("z.rs"));

        assert_eq!(visible(&mut tree), ["a"]);
        assert_eq!(tree.node(ignored).ignored, Some(true));

        tree.set_filter(Filter {
            show_gitignored: true,
            ..Filter::default()
        });
        assert_eq!(visible(&mut tree), ["a", "z.rs"]);
    }

    #[test]
    fn ignored_directories_pass_exclusion_to_their_children() {
        let mut tree = sample();
        tree.classify_ignored(&mut |path, _| path.ends_with("a"));

        assert_eq!(tree.node(find(&tree, "deep.rs")).ignored, Some(true));
        assert_eq!(tree.node(find(&tree, "z.rs")).ignored, Some(false));
    }

    #[test]
    fn changed_only_reveals_changes_without_altering_expansion() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        tree.set_expanded(b, true);
        tree.mark_changed(&mut |path| {
            let path = path.to_string_lossy().into_owned();
            ["a", "b", "deep.rs"]
                .iter()
                .any(|name| path.ends_with(name))
        });

        tree.set_filter(Filter {
            changed_only: true,
            ..Filter::default()
        });
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs"]);
        assert!(tree.is_open(a));
        assert!(
            !tree.node(a).expanded,
            "the filter must not persist expansion"
        );

        tree.set_filter(Filter::default());
        assert_eq!(visible(&mut tree), ["a", "z.rs"]);

        tree.set_expanded(a, true);
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs", "a.rs", "z.rs"]);
    }

    #[test]
    fn a_search_opens_the_way_to_its_results_without_altering_expansion() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        let deep = find(&tree, "deep.rs");
        assert_eq!(visible(&mut tree), ["a", "z.rs"]);

        tree.set_search(Some(vec![deep]));
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs"]);
        assert!(tree.is_open(a) && tree.is_open(b));
        assert!(
            !tree.node(a).expanded,
            "the search must not persist expansion"
        );

        tree.set_search(None);
        assert_eq!(visible(&mut tree), ["a", "z.rs"]);
    }

    #[test]
    fn stepping_through_results_skips_the_folders_and_wraps() {
        let mut tree = sample();
        let deep = find(&tree, "deep.rs");
        let z = find(&tree, "z.rs");

        tree.set_search(Some(vec![deep, z]));
        assert_eq!(visible(&mut tree), ["a", "b", "deep.rs", "z.rs"]);
        tree.select_best_match();
        assert_eq!(tree.selected(), deep);

        tree.move_to_match(1);
        assert_eq!(tree.selected(), z, "the folders in between are passed over");

        tree.move_to_match(1);
        assert_eq!(tree.selected(), deep, "the last result wraps to the first");

        tree.move_to_match(-1);
        assert_eq!(tree.selected(), z, "and the first back to the last");
    }

    #[test]
    fn a_folder_that_is_itself_a_result_stays_shut() {
        let mut tree = sample();
        let b = find(&tree, "b");

        tree.set_search(Some(vec![b]));

        assert_eq!(visible(&mut tree), ["a", "b"]);
        assert!(!tree.is_open(b), "nothing inside it matched");
    }

    #[test]
    fn a_search_looks_through_what_the_filters_leave() {
        let mut tree = Tree::new(PathBuf::from("/root"));
        tree.graft(
            ROOT,
            vec![entry(".git", Kind::Dir), entry("a.rs", Kind::File)],
        );
        tree.graft(find(&tree, ".git"), vec![entry("config", Kind::File)]);

        let names = |tree: &Tree| -> Vec<String> {
            tree.reachable()
                .map(|(_, node)| node.name.clone())
                .collect()
        };

        assert_eq!(names(&tree), ["a.rs"], "a hidden folder hides its contents");

        tree.set_filter(Filter {
            show_hidden: true,
            ..Filter::default()
        });
        assert_eq!(names(&tree), [".git", "a.rs", "config"]);
    }

    #[test]
    fn unloaded_directories_are_reported_once_each() {
        let mut tree = sample();
        tree.graft(find(&tree, "a"), vec![entry("fresh", Kind::Dir)]);

        let first: Vec<String> = tree
            .unloaded_directories()
            .into_iter()
            .map(|id| tree.node(id).name.clone())
            .collect();

        assert_eq!(first, ["fresh"], "the loaded folders are already read");
        assert!(tree.unloaded_directories().is_empty());

        tree.rewind_unloaded();
        assert_eq!(tree.unloaded_directories().len(), 1);
    }

    #[test]
    fn reconciling_keeps_surviving_nodes_and_their_expansion() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        tree.set_expanded(a, true);
        tree.set_expanded(b, true);
        visible(&mut tree);

        let removed = tree.reconcile(
            a,
            vec![
                entry("b", Kind::Dir),
                entry("a.rs", Kind::File),
                entry("new.rs", Kind::File),
            ],
        );

        assert!(removed.is_empty());
        assert_eq!(find(&tree, "b"), b, "the surviving node must be reused");
        assert!(tree.node(b).expanded, "expansion must survive a rescan");
        assert_eq!(
            visible(&mut tree),
            ["a", "b", "deep.rs", "a.rs", "new.rs", "z.rs"]
        );
    }

    #[test]
    fn reconciling_tombstones_entries_that_disappeared() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        let deep = find(&tree, "deep.rs");
        tree.set_expanded(a, true);

        let removed = tree.reconcile(a, vec![entry("a.rs", Kind::File)]);

        assert_eq!(removed.len(), 2, "the subtree goes with it: {removed:?}");
        assert!(!tree.node(b).alive);
        assert!(!tree.node(deep).alive);
        assert_eq!(tree.find(&PathBuf::from("b")), None);
        assert_eq!(visible(&mut tree), ["a", "a.rs", "z.rs"]);
    }

    #[test]
    fn reconciling_replaces_a_path_whose_kind_changed() {
        let mut tree = sample();
        let a = find(&tree, "a");
        let b = find(&tree, "b");
        tree.set_expanded(a, true);

        tree.reconcile(a, vec![entry("b", Kind::File), entry("a.rs", Kind::File)]);

        let replacement = find(&tree, "b");
        assert_ne!(replacement, b);
        assert!(!tree.node(b).alive);
        assert_eq!(tree.node(replacement).kind, Kind::File);
    }

    #[test]
    fn reconciling_the_same_listing_changes_nothing() {
        let mut tree = sample();
        let a = find(&tree, "a");
        tree.set_expanded(a, true);
        let before = visible(&mut tree).join(",");

        let removed = tree.reconcile(a, vec![entry("b", Kind::Dir), entry("a.rs", Kind::File)]);

        assert!(removed.is_empty());
        assert_eq!(visible(&mut tree).join(","), before);
    }

    #[test]
    fn a_tombstoned_node_is_skipped_when_iterating() {
        let mut tree = sample();
        let a = find(&tree, "a");
        tree.reconcile(a, Vec::new());

        let names: Vec<&str> = tree.iter().map(|(_, node)| node.name.as_str()).collect();

        assert!(!names.contains(&"deep.rs"), "{names:?}");
        assert!(names.contains(&"a"), "{names:?}");
    }
}