fresh-editor 0.3.4

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
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
use super::ignore::IgnorePatterns;
use super::node::NodeId;
use super::search::FileExplorerSearch;
use super::tree::FileTree;
use crate::input::fuzzy::FuzzyMatch;
use crate::model::filesystem::DirEntry;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

/// View state for file tree navigation and filtering
#[derive(Debug)]
pub struct FileTreeView {
    /// The underlying tree model
    tree: FileTree,
    /// Cursor / focus node (always a single item)
    selected_node: Option<NodeId>,
    /// Multi-selection set — empty means single-cursor mode
    multi_selection: HashSet<NodeId>,
    /// Anchor for Shift+range extension
    selection_anchor: Option<NodeId>,
    /// Scroll offset (index into visible nodes)
    scroll_offset: usize,
    /// Sort mode for entries
    sort_mode: SortMode,
    /// Ignore patterns for filtering
    ignore_patterns: IgnorePatterns,
    /// Last known viewport height (for scrolling calculations)
    pub(crate) viewport_height: usize,
    /// Search state for quick navigation
    search: FileExplorerSearch,
}

/// Sort mode for file tree entries
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortMode {
    /// Sort by name alphabetically
    Name,
    /// Sort by type (directories first, then files)
    Type,
    /// Sort by modification time (newest first)
    Modified,
}

impl FileTreeView {
    /// Create a new file tree view
    pub fn new(tree: FileTree) -> Self {
        let root_id = tree.root_id();
        Self {
            tree,
            selected_node: Some(root_id),
            multi_selection: HashSet::new(),
            selection_anchor: None,
            scroll_offset: 0,
            sort_mode: SortMode::Type,
            ignore_patterns: IgnorePatterns::new(),
            viewport_height: 10, // Default, will be updated during rendering
            search: FileExplorerSearch::new(),
        }
    }

    /// Get visible nodes filtered by ignore patterns (hidden files, gitignored, etc.)
    ///
    /// Walks the expanded tree and skips ignored nodes along with their entire
    /// subtree. The root node is never filtered out.
    fn filtered_visible_nodes(&self) -> Vec<NodeId> {
        let mut result = Vec::new();
        self.collect_filtered_visible(self.tree.root_id(), &mut result);
        result
    }

    /// Recursively collect visible nodes, skipping ignored subtrees.
    fn collect_filtered_visible(&self, id: NodeId, result: &mut Vec<NodeId>) {
        let is_root = id == self.tree.root_id();
        if !is_root && !self.is_node_visible(id) {
            return;
        }

        result.push(id);

        if let Some(node) = self.tree.get_node(id) {
            if node.is_expanded() {
                for &child_id in &node.children {
                    self.collect_filtered_visible(child_id, result);
                }
            }
        }
    }

    /// Set the viewport height (should be called during rendering)
    pub fn set_viewport_height(&mut self, height: usize) {
        self.viewport_height = height;
    }

    /// Get the underlying tree
    pub fn tree(&self) -> &FileTree {
        &self.tree
    }

    /// Get mutable reference to the underlying tree
    pub fn tree_mut(&mut self) -> &mut FileTree {
        &mut self.tree
    }

    /// Get currently visible nodes with their indent levels
    ///
    /// Returns a list of (NodeId, indent_level) tuples for rendering.
    pub fn get_display_nodes(&self) -> Vec<(NodeId, usize)> {
        let visible = self.filtered_visible_nodes();
        visible
            .into_iter()
            .map(|id| {
                let depth = self.tree.get_depth(id);
                (id, depth)
            })
            .collect()
    }

    /// Get the currently selected node ID
    pub fn get_selected(&self) -> Option<NodeId> {
        self.selected_node
    }

    /// Set the selected node
    pub fn set_selected(&mut self, node_id: Option<NodeId>) {
        self.selected_node = node_id;
    }

    /// Select the next visible node (clears multi-selection)
    pub fn select_next(&mut self) {
        self.clear_multi_selection();
        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = visible.iter().position(|&id| id == current) {
                if pos + 1 < visible.len() {
                    self.selected_node = Some(visible[pos + 1]);
                }
            }
        } else {
            self.selected_node = Some(visible[0]);
        }
    }

    /// Select the previous visible node (clears multi-selection)
    pub fn select_prev(&mut self) {
        self.clear_multi_selection();
        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = visible.iter().position(|&id| id == current) {
                if pos > 0 {
                    self.selected_node = Some(visible[pos - 1]);
                }
            }
        } else {
            self.selected_node = Some(visible[0]);
        }
    }

    /// Move selection up by a page (viewport height)
    pub fn select_page_up(&mut self) {
        if self.viewport_height == 0 {
            return;
        }

        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = visible.iter().position(|&id| id == current) {
                let new_pos = pos.saturating_sub(self.viewport_height);
                self.selected_node = Some(visible[new_pos]);
            }
        } else {
            self.selected_node = Some(visible[0]);
        }
    }

    /// Move selection down by a page (viewport height)
    pub fn select_page_down(&mut self) {
        if self.viewport_height == 0 {
            return;
        }

        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = visible.iter().position(|&id| id == current) {
                let new_pos = (pos + self.viewport_height).min(visible.len() - 1);
                self.selected_node = Some(visible[new_pos]);
            }
        } else {
            self.selected_node = Some(visible[0]);
        }
    }

    /// Update scroll offset to ensure symmetric scrolling behavior
    ///
    /// This should be called after navigation to implement symmetric scrolling:
    /// - When moving down, cursor moves to bottom of viewport before scrolling
    /// - When moving up, cursor moves to top of viewport before scrolling
    ///
    /// Uses the stored viewport_height which is updated during rendering.
    pub fn update_scroll_for_selection(&mut self) {
        if self.viewport_height == 0 {
            return;
        }
        let visible = self.filtered_visible_nodes();
        self.update_scroll_with_nodes(&visible);
    }

    fn update_scroll_with_nodes(&mut self, visible: &[NodeId]) {
        if self.viewport_height == 0 {
            return;
        }
        if let Some(selected) = self.selected_node {
            if let Some(pos) = visible.iter().position(|&id| id == selected) {
                if pos < self.scroll_offset {
                    self.scroll_offset = pos;
                } else if pos >= self.scroll_offset + self.viewport_height {
                    self.scroll_offset = pos - self.viewport_height + 1;
                }
            }
        }
    }

    /// Select the first visible node
    pub fn select_first(&mut self) {
        let visible = self.filtered_visible_nodes();
        if !visible.is_empty() {
            self.selected_node = Some(visible[0]);
        }
    }

    /// Select the last visible node
    pub fn select_last(&mut self) {
        let visible = self.filtered_visible_nodes();
        if !visible.is_empty() {
            self.selected_node = Some(*visible.last().unwrap());
        }
    }

    /// Toggle the cursor item in/out of the multi-selection and set the anchor.
    pub fn toggle_select(&mut self) {
        if let Some(cursor) = self.selected_node {
            if self.multi_selection.contains(&cursor) {
                self.multi_selection.remove(&cursor);
            } else {
                self.multi_selection.insert(cursor);
            }
            self.selection_anchor = Some(cursor);
        }
    }

    /// Extend the selection one step upward from the current cursor.
    pub fn extend_selection_up(&mut self) {
        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }
        let Some(current) = self.selected_node else {
            return;
        };
        let Some(pos) = visible.iter().position(|&id| id == current) else {
            return;
        };
        // Always seed the selection with the cursor row first — even at the
        // top boundary, so Escape / a subsequent Shift+Down sees a live
        // selection anchored on wherever the user started the range.
        if self.multi_selection.is_empty() {
            self.multi_selection.insert(current);
            self.selection_anchor = Some(current);
        }
        if pos == 0 {
            return;
        }
        let anchor = self.selection_anchor.unwrap_or(current);
        let new_pos = pos - 1;
        self.selected_node = Some(visible[new_pos]);
        let anchor_pos = visible
            .iter()
            .position(|&id| id == anchor)
            .unwrap_or(new_pos);
        let (lo, hi) = (new_pos.min(anchor_pos), new_pos.max(anchor_pos));
        self.multi_selection = visible[lo..=hi].iter().copied().collect();
        self.update_scroll_with_nodes(&visible);
    }

    /// Extend the selection one step downward from the current cursor.
    pub fn extend_selection_down(&mut self) {
        let visible = self.filtered_visible_nodes();
        if visible.is_empty() {
            return;
        }
        let Some(current) = self.selected_node else {
            return;
        };
        let Some(pos) = visible.iter().position(|&id| id == current) else {
            return;
        };
        // Always seed the selection with the cursor row first — even at the
        // bottom boundary, so Escape / a subsequent Shift+Up sees a live
        // selection anchored on wherever the user started the range.
        if self.multi_selection.is_empty() {
            self.multi_selection.insert(current);
            self.selection_anchor = Some(current);
        }
        if pos + 1 >= visible.len() {
            return;
        }
        let anchor = self.selection_anchor.unwrap_or(current);
        let new_pos = pos + 1;
        self.selected_node = Some(visible[new_pos]);
        let anchor_pos = visible
            .iter()
            .position(|&id| id == anchor)
            .unwrap_or(new_pos);
        let (lo, hi) = (new_pos.min(anchor_pos), new_pos.max(anchor_pos));
        self.multi_selection = visible[lo..=hi].iter().copied().collect();
        self.update_scroll_with_nodes(&visible);
    }

    /// Select all currently visible nodes.
    pub fn select_all(&mut self) {
        let visible = self.filtered_visible_nodes();
        self.multi_selection = visible.iter().copied().collect();
        self.selection_anchor = self.selected_node;
    }

    /// Clear multi-selection (return to single-cursor mode).
    pub fn clear_multi_selection(&mut self) {
        self.multi_selection.clear();
        self.selection_anchor = None;
    }

    /// True when the explorer is in multi-selection mode — i.e. at least
    /// one item has been explicitly added to the selection via Shift+arrow,
    /// Space, or Ctrl+A. Distinguishes "user picked a specific set" from
    /// plain cursor navigation, even when that set holds just one item.
    pub fn has_multi_selection(&self) -> bool {
        !self.multi_selection.is_empty()
    }

    /// Returns the set of multi-selected nodes (empty in single-cursor mode).
    pub fn multi_selection(&self) -> &HashSet<NodeId> {
        &self.multi_selection
    }

    /// The nodes that operations (copy/cut/delete) should act on.
    /// Returns the multi-selection when non-empty, otherwise `[cursor]`.
    ///
    /// Multi-selected items are returned in visible tree order rather than
    /// `HashSet` iteration order, so callers (e.g. multi-paste) see a
    /// deterministic sequence matching what the user sees on screen.
    pub fn effective_selection(&self) -> Vec<NodeId> {
        if self.multi_selection.is_empty() {
            return self.selected_node.into_iter().collect();
        }
        // Walk visible nodes in order and keep those in the selection set.
        // This also filters out any stale NodeIds that may have lingered
        // from a prior tree mutation.
        self.filtered_visible_nodes()
            .into_iter()
            .filter(|id| self.multi_selection.contains(id))
            .collect()
    }

    /// Select the parent of the currently selected node
    pub fn select_parent(&mut self) {
        if let Some(current) = self.selected_node {
            if let Some(node) = self.tree.get_node(current) {
                if let Some(parent_id) = node.parent {
                    self.selected_node = Some(parent_id);
                }
            }
        }
    }

    /// Get the scroll offset
    pub fn get_scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    /// Set the scroll offset
    pub fn set_scroll_offset(&mut self, offset: usize) {
        self.scroll_offset = offset;
    }

    /// Ensure the selected node is visible within the viewport
    ///
    /// Adjusts scroll offset if necessary to keep the selected node visible.
    ///
    /// # Arguments
    ///
    /// * `viewport_height` - Number of visible lines in the viewport
    pub fn ensure_visible(&mut self, viewport_height: usize) {
        if viewport_height == 0 {
            return;
        }

        if let Some(selected) = self.selected_node {
            let visible = self.filtered_visible_nodes();
            if let Some(pos) = visible.iter().position(|&id| id == selected) {
                // If selection is above viewport, scroll up
                if pos < self.scroll_offset {
                    self.scroll_offset = pos;
                }
                // If selection is below viewport, scroll down
                else if pos >= self.scroll_offset + viewport_height {
                    self.scroll_offset = pos - viewport_height + 1;
                }
            }
        }
    }

    /// Get the sort mode
    pub fn get_sort_mode(&self) -> SortMode {
        self.sort_mode
    }

    /// Set the sort mode
    pub fn set_sort_mode(&mut self, mode: SortMode) {
        self.sort_mode = mode;
        // TODO: Re-sort children when sort mode changes
    }

    /// Get selected node entry (convenience method)
    pub fn get_selected_entry(&self) -> Option<&DirEntry> {
        self.selected_node
            .and_then(|id| self.tree.get_node(id))
            .map(|node| &node.entry)
    }

    /// Navigate to a specific path if it exists in the tree
    pub fn navigate_to_path(&mut self, path: &std::path::Path) {
        if let Some(node) = self.tree.get_node_by_path(path) {
            self.selected_node = Some(node.id);
            self.update_scroll_for_selection();
        }
    }

    /// Get the index of the selected node in the visible list
    pub fn get_selected_index(&self) -> Option<usize> {
        if let Some(selected) = self.selected_node {
            let visible = self.filtered_visible_nodes();
            visible.iter().position(|&id| id == selected)
        } else {
            None
        }
    }

    /// Get visible node at index (accounting for scroll offset)
    pub fn get_node_at_index(&self, index: usize) -> Option<NodeId> {
        let visible = self.filtered_visible_nodes();
        visible.get(index).copied()
    }

    /// Get the number of visible nodes
    pub fn visible_count(&self) -> usize {
        self.filtered_visible_nodes().len()
    }

    /// Get reference to ignore patterns
    pub fn ignore_patterns(&self) -> &IgnorePatterns {
        &self.ignore_patterns
    }

    /// Get mutable reference to ignore patterns
    pub fn ignore_patterns_mut(&mut self) -> &mut IgnorePatterns {
        &mut self.ignore_patterns
    }

    /// Toggle showing hidden files
    pub fn toggle_show_hidden(&mut self) {
        self.ignore_patterns.toggle_show_hidden();
    }

    /// Toggle showing gitignored files
    pub fn toggle_show_gitignored(&mut self) {
        self.ignore_patterns.toggle_show_gitignored();
    }

    /// Check if a node should be visible (not filtered by ignore patterns)
    pub fn is_node_visible(&self, node_id: NodeId) -> bool {
        if let Some(node) = self.tree.get_node(node_id) {
            !self
                .ignore_patterns
                .is_ignored(&node.entry.path, node.is_dir())
        } else {
            false
        }
    }

    /// Install a gitignore for `dir_path` from already-read bytes. Caller
    /// performs the I/O via the editor's filesystem authority.
    pub fn load_gitignore_from_bytes(
        &mut self,
        dir_path: &std::path::Path,
        contents: &[u8],
        mtime: Option<std::time::SystemTime>,
    ) {
        self.ignore_patterns
            .load_gitignore_from_bytes(dir_path, contents, mtime);
    }

    /// Expand all parent directories and select the given file path
    ///
    /// This is useful for revealing a specific file in the tree when switching
    /// focus to the file explorer. All parent directories will be expanded as needed,
    /// and the file will be selected.
    ///
    /// # Arguments
    ///
    /// * `path` - The full path to the file to reveal and select
    ///
    /// # Returns
    ///
    /// Returns true if the file was successfully expanded and selected, false otherwise.
    /// This will return false if:
    /// - The path is not under the root directory
    /// - The path doesn't exist
    /// - There was an error expanding intermediate directories
    pub async fn expand_and_select_file(&mut self, path: &std::path::Path) -> bool {
        if let Some(node_id) = self.tree.expand_to_path(path).await {
            self.selected_node = Some(node_id);
            true
        } else {
            false
        }
    }

    /// Collect symlink mappings from expanded symlink directories.
    ///
    /// Returns a HashMap where keys are symlink paths and values are their canonical targets.
    /// This is used to create decoration aliases so files under symlinked directories
    /// can show their git status correctly.
    pub fn collect_symlink_mappings(&self) -> HashMap<PathBuf, PathBuf> {
        let mut mappings = HashMap::new();

        for node_id in self.filtered_visible_nodes() {
            if let Some(node) = self.tree.get_node(node_id) {
                // Only process expanded symlink directories
                if node.entry.is_symlink() && node.is_dir() && node.is_expanded() {
                    // Canonicalize the symlink to get the target
                    if let Ok(canonical) = node.entry.path.canonicalize() {
                        if canonical != node.entry.path {
                            mappings.insert(node.entry.path.clone(), canonical);
                        }
                    }
                }
            }
        }

        mappings
    }

    // ==================== Search Methods ====================

    /// Get the current search query
    pub fn search_query(&self) -> &str {
        self.search.query()
    }

    /// Check if search is active
    pub fn is_search_active(&self) -> bool {
        self.search.is_active()
    }

    /// Add a character to the search query and jump to first match
    pub fn search_push_char(&mut self, c: char) {
        self.search.push_char(c);
        self.jump_to_first_match();
    }

    /// Remove the last character from the search query
    pub fn search_pop_char(&mut self) {
        self.search.pop_char();
        if self.search.is_active() {
            self.jump_to_first_match();
        }
    }

    /// Clear the search query
    pub fn search_clear(&mut self) {
        self.search.clear();
    }

    /// Get nodes that match the current search query
    fn get_matching_nodes(&self) -> Vec<NodeId> {
        if !self.search.is_active() {
            return self.filtered_visible_nodes();
        }

        self.filtered_visible_nodes()
            .into_iter()
            .filter(|&id| {
                if let Some(node) = self.tree.get_node(id) {
                    self.search.matches(&node.entry.name)
                } else {
                    false
                }
            })
            .collect()
    }

    /// Jump to the first matching node
    fn jump_to_first_match(&mut self) {
        let matching = self.get_matching_nodes();
        if let Some(&first) = matching.first() {
            self.selected_node = Some(first);
            self.update_scroll_for_selection();
        }
    }

    /// Select the next matching node (when search is active)
    pub fn select_next_match(&mut self) {
        if !self.search.is_active() {
            self.select_next();
            return;
        }

        let matching = self.get_matching_nodes();
        if matching.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = matching.iter().position(|&id| id == current) {
                // Move to next match (wrap around)
                let next_pos = (pos + 1) % matching.len();
                self.selected_node = Some(matching[next_pos]);
            } else {
                // Current not in matches, select first match
                self.selected_node = Some(matching[0]);
            }
        } else {
            self.selected_node = Some(matching[0]);
        }
    }

    /// Select the previous matching node (when search is active)
    pub fn select_prev_match(&mut self) {
        if !self.search.is_active() {
            self.select_prev();
            return;
        }

        let matching = self.get_matching_nodes();
        if matching.is_empty() {
            return;
        }

        if let Some(current) = self.selected_node {
            if let Some(pos) = matching.iter().position(|&id| id == current) {
                // Move to previous match (wrap around)
                let prev_pos = if pos == 0 {
                    matching.len() - 1
                } else {
                    pos - 1
                };
                self.selected_node = Some(matching[prev_pos]);
            } else {
                // Current not in matches, select last match
                self.selected_node = Some(*matching.last().unwrap());
            }
        } else {
            self.selected_node = Some(*matching.last().unwrap());
        }
    }

    /// Get match result for a node's name (for highlighting)
    pub fn get_match_for_node(&self, node_id: NodeId) -> Option<FuzzyMatch> {
        if !self.search.is_active() {
            return None;
        }

        self.tree
            .get_node(node_id)
            .and_then(|node| self.search.match_name(&node.entry.name))
    }

    /// Check if a node matches the current search
    pub fn node_matches_search(&self, node_id: NodeId) -> bool {
        if !self.search.is_active() {
            return true;
        }

        self.tree
            .get_node(node_id)
            .map(|node| self.search.matches(&node.entry.name))
            .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::filesystem::StdFileSystem;
    use crate::services::fs::FsManager;
    use std::fs as std_fs;
    use std::sync::Arc;
    use tempfile::TempDir;

    async fn create_test_view() -> (TempDir, FileTreeView) {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create test structure
        std_fs::create_dir(temp_path.join("dir1")).unwrap();
        std_fs::write(temp_path.join("dir1/file1.txt"), "content1").unwrap();
        std_fs::write(temp_path.join("dir1/file2.txt"), "content2").unwrap();
        std_fs::create_dir(temp_path.join("dir2")).unwrap();
        std_fs::write(temp_path.join("file3.txt"), "content3").unwrap();

        let backend = Arc::new(StdFileSystem);
        let manager = Arc::new(FsManager::new(backend));
        let tree = FileTree::new(temp_path.to_path_buf(), manager)
            .await
            .unwrap();
        let view = FileTreeView::new(tree);

        (temp_dir, view)
    }

    #[tokio::test]
    async fn test_view_creation() {
        let (_temp_dir, view) = create_test_view().await;

        assert!(view.get_selected().is_some());
        assert_eq!(view.get_scroll_offset(), 0);
        assert_eq!(view.get_sort_mode(), SortMode::Type);
    }

    #[tokio::test]
    async fn test_get_display_nodes() {
        let (_temp_dir, mut view) = create_test_view().await;

        // Initially only root
        let display = view.get_display_nodes();
        assert_eq!(display.len(), 1);
        assert_eq!(display[0].1, 0); // Root has depth 0

        // Expand root
        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        let display = view.get_display_nodes();
        assert_eq!(display.len(), 4); // root + 3 children

        // Check depths
        assert_eq!(display[0].1, 0); // root
        assert_eq!(display[1].1, 1); // child
        assert_eq!(display[2].1, 1); // child
        assert_eq!(display[3].1, 1); // child
    }

    #[tokio::test]
    async fn test_navigation() {
        let (_temp_dir, mut view) = create_test_view().await;

        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        let root_id = view.tree().root_id();
        assert_eq!(view.get_selected(), Some(root_id));

        // Select next
        view.select_next();
        assert_ne!(view.get_selected(), Some(root_id));

        // Select prev
        view.select_prev();
        assert_eq!(view.get_selected(), Some(root_id));

        // Select last
        view.select_last();
        let visible = view.tree().get_visible_nodes();
        assert_eq!(view.get_selected(), Some(*visible.last().unwrap()));

        // Select first
        view.select_first();
        assert_eq!(view.get_selected(), Some(root_id));
    }

    #[tokio::test]
    async fn test_select_parent() {
        let (_temp_dir, mut view) = create_test_view().await;

        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        // Select first child
        view.select_next();
        let child_id = view.get_selected().unwrap();
        assert_ne!(child_id, root_id);

        // Select parent
        view.select_parent();
        assert_eq!(view.get_selected(), Some(root_id));
    }

    #[tokio::test]
    async fn test_ensure_visible() {
        let (_temp_dir, mut view) = create_test_view().await;

        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        let viewport_height = 2;

        // Select last item
        view.select_last();
        view.ensure_visible(viewport_height);

        // Scroll offset should be adjusted
        let selected_index = view.get_selected_index().unwrap();
        assert!(selected_index >= view.get_scroll_offset());
        assert!(selected_index < view.get_scroll_offset() + viewport_height);

        // Select first item
        view.select_first();
        view.ensure_visible(viewport_height);

        // Scroll offset should be 0
        assert_eq!(view.get_scroll_offset(), 0);
    }

    #[tokio::test]
    async fn test_get_selected_entry() {
        let (_temp_dir, view) = create_test_view().await;

        let entry = view.get_selected_entry();
        assert!(entry.is_some());
        assert!(entry.unwrap().is_dir());
    }

    #[tokio::test]
    async fn test_navigate_to_path() {
        let (_temp_dir, mut view) = create_test_view().await;

        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        let dir1_path = view.tree().root_path().join("dir1");
        view.navigate_to_path(&dir1_path);

        let selected_entry = view.get_selected_entry().unwrap();
        assert_eq!(selected_entry.name, "dir1");
    }

    #[tokio::test]
    async fn test_get_selected_index() {
        let (_temp_dir, mut view) = create_test_view().await;

        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();

        // Root is at index 0
        assert_eq!(view.get_selected_index(), Some(0));

        // Move to next
        view.select_next();
        assert_eq!(view.get_selected_index(), Some(1));

        // Move to last
        view.select_last();
        let visible_count = view.visible_count();
        assert_eq!(view.get_selected_index(), Some(visible_count - 1));
    }

    #[tokio::test]
    async fn test_visible_count() {
        let (_temp_dir, mut view) = create_test_view().await;

        // Initially only root
        assert_eq!(view.visible_count(), 1);

        // After expanding root
        let root_id = view.tree().root_id();
        view.tree_mut().expand_node(root_id).await.unwrap();
        assert_eq!(view.visible_count(), 4); // root + 3 children
    }

    #[tokio::test]
    async fn test_sort_mode() {
        let (_temp_dir, mut view) = create_test_view().await;

        assert_eq!(view.get_sort_mode(), SortMode::Type);

        view.set_sort_mode(SortMode::Name);
        assert_eq!(view.get_sort_mode(), SortMode::Name);

        view.set_sort_mode(SortMode::Modified);
        assert_eq!(view.get_sort_mode(), SortMode::Modified);
    }
}