fast-fs 0.2.1

High-speed async file system traversal library with batteries-included file browser component
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
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
// <FILE>crates/fast-fs/src/nav/cls_browser.rs</FILE> - <DESC>Core browser state container</DESC>
// <VERS>VERSION: 0.9.0</VERS>
// <WCTX>Adding flat-mode, custom filter, and multi-root support</WCTX>
// <CLOG>Add flat recursive mode, consumer-supplied filter predicate, multi-root virtual listing</CLOG>

//! Browser - Core state container for file navigation
//!
//! Browser is the central component of the nav module. It maintains:
//! - Current directory and file list
//! - Cursor position and scroll offset
//! - Selection state
//! - Navigation history
//! - Filter state
//! - Pending operations
//!
//! # Async Design
//!
//! All methods that perform I/O are async, leveraging tokio for non-blocking
//! directory reads. This keeps the UI responsive even when navigating large
//! directories.

use super::action::Action;
use super::action_result::{ActionResult, InputRequest, PendingOp};
use super::browser_config::BrowserConfig;
use super::cls_history::History;
use super::cls_key_map::KeyMap;
use super::cls_selection::Selection;
use super::fnc_browser_actions as actions;
use super::fnc_browser_flat::load_flat_entries;
use super::fnc_browser_nav as nav;
use super::fnc_browser_virtual_root::{
    build_virtual_root_entries, is_virtual_root_path, virtual_root_path,
};
use super::fnc_file_ops;
use super::fnc_glob_match::glob_match;
use super::fnc_validate::validate_name;
use super::key_input::KeyInput;
use super::nav_error::NavError;
use crate::{read_dir, FileEntry, FileList, GitignoreMatcher, SortBy};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Consumer-provided filter predicate applied on top of the built-in filter.
///
/// Wrapped in `Arc` so it can be shared cheaply and so `Browser` remains
/// `Send + Sync` where the predicate itself is `Send + Sync`.
pub type CustomFilter = Arc<dyn Fn(&FileEntry) -> bool + Send + Sync>;

/// Pending state for operations requiring confirmation or input
#[derive(Debug, Clone)]
enum PendingState {
    Confirmation(PendingOp),
    Input(InputRequest),
}

/// Filter state
#[derive(Debug, Clone)]
struct FilterState {
    pattern: String,
    is_glob: bool,
}

/// Core browser state container
///
/// Browser is `Send` but not `Sync`. For shared access, wrap in `Arc<Mutex<Browser>>`.
///
/// # Thread Safety
///
/// - `Send`: Can be moved to another thread
/// - `!Sync`: Cannot be shared between threads without synchronization
///
/// # Async Design
///
/// Methods that perform I/O (navigation, refresh) are async and should be awaited.
/// State accessors (cursor, files, selection) are synchronous for UI rendering.
pub struct Browser {
    files: FileList,
    all_entries: Vec<FileEntry>,
    cursor: usize,
    scroll_offset: usize,
    /// Current viewport height (set by UI layer, used for scroll calculations)
    viewport_height: usize,
    current_path: PathBuf,
    selection: Selection,
    history: History,
    keymap: KeyMap,
    filter: Option<FilterState>,
    pending: Option<PendingState>,
    config: BrowserConfig,
    #[allow(dead_code)] // Future: will be used for filtering
    gitignore: Option<GitignoreMatcher>,
    /// When `Some`, the browser is in flat (recursive) mode.
    ///
    /// Inner `Option<usize>` bounds depth: `None` = unlimited, `Some(n)` = at
    /// most n levels below `current_path`.
    flat_mode: Option<Option<usize>>,
    /// Consumer-supplied predicate applied on top of the built-in filter.
    ///
    /// Stored as `Arc<dyn Fn ... Send + Sync>` so `Browser` remains `Send`.
    custom_filter: Option<CustomFilter>,
    /// Configured roots for multi-root mode. Empty when the browser was
    /// constructed with a single root via `new` / `at_path`.
    roots: Vec<PathBuf>,
    /// When true, the browser is currently showing the synthetic virtual root
    /// that lists the configured `roots`. Ignored when `roots.is_empty()`.
    virtual_root: bool,
}

impl Browser {
    /// Create a new browser at the current directory
    pub async fn new(config: BrowserConfig) -> Result<Self, NavError> {
        let path = config
            .initial_path
            .clone()
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")));
        Self::at_path(path, config).await
    }

    /// Create a new browser at the specified path
    pub async fn at_path(path: impl AsRef<Path>, config: BrowserConfig) -> Result<Self, NavError> {
        let path = path.as_ref().to_path_buf();
        if !path.exists() {
            return Err(NavError::NotFound(path));
        }
        if !path.is_dir() {
            return Err(NavError::NotADirectory(path));
        }

        let gitignore = if config.respect_ignore_files {
            GitignoreMatcher::from_path(&path).ok()
        } else {
            None
        };

        let mut browser = Self {
            files: FileList::new(),
            all_entries: Vec::new(),
            cursor: 0,
            scroll_offset: 0,
            viewport_height: 20, // Sensible default, caller should set via set_viewport_height()
            current_path: path,
            selection: Selection::new(),
            history: History::new(config.history_limit),
            keymap: config.keymap.clone(),
            filter: None,
            pending: None,
            config,
            gitignore,
            flat_mode: None,
            custom_filter: None,
            roots: Vec::new(),
            virtual_root: false,
        };
        browser.load_directory().await?;
        Ok(browser)
    }

    /// Construct a browser that mounts multiple roots at the top level.
    ///
    /// The browser starts at a synthetic "virtual root" that lists each
    /// configured root as a directory entry. Entering a root (via `Enter`
    /// or `navigate_to`) behaves identically to a standard browser rooted at
    /// that path. `GoParent` at a top-level root returns to the virtual root.
    ///
    /// The `initial_path` on `config` is ignored when this constructor is used.
    /// Returns `NavError::NotFound` if `roots` is empty or if any root fails
    /// to resolve to an existing directory.
    pub async fn with_roots(
        config: BrowserConfig,
        roots: Vec<PathBuf>,
    ) -> Result<Self, NavError> {
        if roots.is_empty() {
            return Err(NavError::NotFound(PathBuf::from(
                "with_roots requires at least one root",
            )));
        }
        for root in &roots {
            if !root.exists() {
                return Err(NavError::NotFound(root.clone()));
            }
            if !root.is_dir() {
                return Err(NavError::NotADirectory(root.clone()));
            }
        }

        let mut browser = Self {
            files: FileList::new(),
            all_entries: Vec::new(),
            cursor: 0,
            scroll_offset: 0,
            viewport_height: 20,
            current_path: virtual_root_path(),
            selection: Selection::new(),
            history: History::new(config.history_limit),
            keymap: config.keymap.clone(),
            filter: None,
            pending: None,
            config,
            gitignore: None,
            flat_mode: None,
            custom_filter: None,
            roots,
            virtual_root: true,
        };
        browser.load_directory().await?;
        Ok(browser)
    }

    /// Returns the configured roots for a multi-root browser.
    ///
    /// Empty iff the browser was constructed via `new` / `at_path`.
    pub fn roots_list(&self) -> &[PathBuf] {
        &self.roots
    }

    /// Returns true when the browser is currently displaying its virtual root
    /// (the synthetic list of mounted roots). Always false for single-root
    /// browsers.
    pub fn is_virtual_root(&self) -> bool {
        self.virtual_root
    }

    // --- State Access (Sync) ---

    /// Get the current file list
    pub fn files(&self) -> &FileList {
        &self.files
    }

    /// Get the current cursor position
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Get the current entry at cursor, if any
    pub fn current_entry(&self) -> Option<&FileEntry> {
        self.files.get(self.cursor)
    }

    /// Get the current directory path
    pub fn current_path(&self) -> &Path {
        &self.current_path
    }

    /// Get the selection state
    pub fn selection(&self) -> &Selection {
        &self.selection
    }

    /// Check if browser is in readonly mode
    pub fn is_readonly(&self) -> bool {
        self.config.readonly
    }

    /// Get browser configuration
    pub fn config(&self) -> &BrowserConfig {
        &self.config
    }

    /// Set viewport height (call from UI layer when terminal resizes)
    ///
    /// This is used for scroll calculations to ensure cursor stays visible.
    pub fn set_viewport_height(&mut self, height: usize) {
        self.viewport_height = height.max(1);
        // Re-validate scroll offset with new viewport
        self.update_scroll();
    }

    /// Get current viewport height
    pub fn viewport_height(&self) -> usize {
        self.viewport_height
    }

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

    /// Set cursor position directly (for mouse clicks)
    pub fn set_cursor(&mut self, index: usize) {
        let len = self.files.len();
        if len == 0 {
            self.cursor = 0;
            return;
        }
        self.cursor = index.min(len - 1);
        self.update_scroll();
    }

    /// Move cursor up by one
    pub fn move_up(&mut self) {
        self.selection.clear_anchor();
        self.move_cursor(-1);
    }

    /// Move cursor down by one
    pub fn move_down(&mut self) {
        self.selection.clear_anchor();
        self.move_cursor(1);
    }

    /// Calculate visible range for viewport
    pub fn visible_range(&self, viewport_height: usize) -> Range<usize> {
        let start = self.scroll_offset;
        let end = (start + viewport_height).min(self.files.len());
        start..end
    }

    /// Iterator over selected paths
    pub fn selected_paths(&self) -> impl Iterator<Item = &Path> {
        self.selection.iter()
    }

    /// Get paths to operate on: selected if any, otherwise current
    pub fn selected_or_current(&self) -> Vec<&Path> {
        if self.selection.is_empty() {
            self.current_entry()
                .map(|e| e.path.as_path())
                .into_iter()
                .collect()
        } else {
            self.selection.paths()
        }
    }

    // --- Filter (Sync) ---

    /// Set filter pattern (glob if contains * or ?, else substring)
    pub fn set_filter(&mut self, pattern: &str) {
        let is_glob = pattern.contains('*') || pattern.contains('?');
        self.filter = Some(FilterState {
            pattern: pattern.to_string(),
            is_glob,
        });
        self.apply_filter();
    }

    /// Clear active filter
    pub fn clear_filter(&mut self) {
        self.filter = None;
        self.apply_filter();
    }

    /// Get current filter pattern
    pub fn filter(&self) -> Option<&str> {
        self.filter.as_ref().map(|f| f.pattern.as_str())
    }

    /// Total entries before filtering
    pub fn total_count(&self) -> usize {
        self.all_entries.len()
    }

    /// Entries after filtering
    pub fn filtered_count(&self) -> usize {
        self.files.len()
    }

    // --- Flat mode (Sync toggles; effect on next load) ---

    /// Enable flat mode on the browser.
    ///
    /// In flat mode the browser shows all descendants of `current_path` as a
    /// single flat list instead of just the current directory. `depth` bounds
    /// traversal: `None` = unlimited, `Some(n)` = at most `n` levels below
    /// `current_path`.
    ///
    /// The caller must invoke `refresh()` (or any other directory-reload
    /// operation) to rebuild the listing — this method only updates the
    /// intent so that the next load applies it. The built-in filter,
    /// hidden-file toggle, and `respect_ignore_files` are honoured as in
    /// single-directory mode.
    ///
    /// Flat mode disables directory descent: `Enter` on a subdirectory in the
    /// flat listing becomes a no-op (behaves as `FileSelected` if invoked on
    /// a file, otherwise `Done`).
    pub fn set_flat_mode(&mut self, depth: Option<usize>) {
        self.flat_mode = Some(depth);
    }

    /// Turn flat mode off, restoring standard single-directory behaviour.
    ///
    /// Like `set_flat_mode`, this only updates intent; call `refresh()` to
    /// rebuild the listing.
    pub fn set_flat_mode_off(&mut self) {
        self.flat_mode = None;
    }

    /// Returns true if the browser is currently configured to use flat mode.
    pub fn is_flat_mode(&self) -> bool {
        self.flat_mode.is_some()
    }

    /// Returns the configured flat-mode depth, if flat mode is enabled.
    ///
    /// The outer `Option` reflects whether flat mode is on; the inner reflects
    /// the depth bound (`None` = unlimited).
    pub fn flat_mode_depth(&self) -> Option<Option<usize>> {
        self.flat_mode
    }

    // --- Custom filter (Sync) ---

    /// Layer a consumer-defined predicate on top of the built-in filter.
    ///
    /// The predicate receives each `FileEntry` after the built-in filter
    /// (set via `set_filter`) has accepted it. Both filters must return true
    /// for the entry to appear in the listing. Useful for content-aware
    /// filtering where the consumer needs to parse file contents or metadata.
    ///
    /// The predicate is stored as `Arc<dyn Fn + Send + Sync>` so `Browser`
    /// remains `Send`. Installing a new predicate replaces any previously
    /// installed one and applies immediately to the current listing.
    pub fn set_custom_filter<F>(&mut self, predicate: F)
    where
        F: Fn(&FileEntry) -> bool + Send + Sync + 'static,
    {
        self.custom_filter = Some(Arc::new(predicate));
        self.apply_filter();
    }

    /// Remove any previously installed custom filter.
    pub fn clear_custom_filter(&mut self) {
        let was_set = self.custom_filter.is_some();
        self.custom_filter = None;
        if was_set {
            self.apply_filter();
        }
    }

    /// Returns true if a custom filter is currently installed.
    pub fn has_custom_filter(&self) -> bool {
        self.custom_filter.is_some()
    }

    // --- Navigation (Async) ---

    /// Get breadcrumb components
    pub fn breadcrumbs(&self) -> Vec<(String, PathBuf)> {
        actions::build_breadcrumbs(&self.current_path)
    }

    /// Navigate to a breadcrumb by index
    pub async fn go_to_breadcrumb(&mut self, index: usize) -> Result<ActionResult, NavError> {
        let crumbs = self.breadcrumbs();
        if index >= crumbs.len() {
            return Ok(ActionResult::Done);
        }
        self.navigate_to(&crumbs[index].1).await
    }

    /// Navigate to a path (relative paths resolved against current)
    pub async fn navigate_to(&mut self, path: impl AsRef<Path>) -> Result<ActionResult, NavError> {
        let path = if path.as_ref().is_relative() {
            self.current_path.join(path)
        } else {
            path.as_ref().to_path_buf()
        };
        self.navigate_internal(path).await
    }

    /// Check if parent navigation is available
    pub fn has_parent_entry(&self) -> bool {
        if self.virtual_root {
            return false;
        }
        self.config.show_parent_entry && self.current_path.parent().is_some()
    }

    /// Get filesystem roots
    pub fn roots() -> Vec<PathBuf> {
        #[cfg(unix)]
        {
            vec![PathBuf::from("/")]
        }
        #[cfg(windows)]
        {
            let mut roots = Vec::new();
            for letter in b'A'..=b'Z' {
                let path = PathBuf::from(format!("{}:\\", letter as char));
                if path.exists() {
                    roots.push(path);
                }
            }
            roots
        }
        #[cfg(not(any(unix, windows)))]
        {
            vec![PathBuf::from("/")]
        }
    }

    // --- Key Handling (Async) ---

    /// Handle key input, return result
    pub async fn handle_key(&mut self, key: KeyInput) -> ActionResult {
        if let Some(action) = self.keymap.get(&key) {
            self.execute(action).await
        } else {
            ActionResult::Unhandled
        }
    }

    /// Execute an action directly
    pub async fn execute(&mut self, action: Action) -> ActionResult {
        // Block mutations in readonly mode
        if self.config.readonly && action.is_mutation() {
            return ActionResult::Done;
        }
        match action {
            Action::MoveUp => {
                self.selection.clear_anchor(); // End range selection
                self.move_cursor(-1);
                ActionResult::Done
            }
            Action::MoveDown => {
                self.selection.clear_anchor(); // End range selection
                self.move_cursor(1);
                ActionResult::Done
            }
            Action::MoveToTop => {
                self.selection.clear_anchor(); // End range selection
                self.cursor = 0;
                self.update_scroll();
                ActionResult::Done
            }
            Action::MoveToBottom => {
                self.selection.clear_anchor(); // End range selection
                self.cursor = self.files.len().saturating_sub(1);
                self.update_scroll();
                ActionResult::Done
            }
            Action::PageUp | Action::PageDown => ActionResult::Done, // Requires viewport
            Action::Enter => self.action_enter().await,
            Action::GoParent => self.action_go_parent().await,
            Action::GoBack => self.action_go_back().await,
            Action::GoForward => self.action_go_forward().await,
            Action::ToggleSelect => {
                self.toggle_current_selection();
                ActionResult::Done
            }
            Action::SelectAll => {
                self.select_all_visible();
                ActionResult::Done
            }
            Action::ClearSelection => {
                self.selection.clear();
                self.selection.clear_anchor();
                ActionResult::Done
            }
            Action::MoveUpExtend => {
                self.move_cursor_extend(-1);
                ActionResult::Done
            }
            Action::MoveDownExtend => {
                self.move_cursor_extend(1);
                ActionResult::Done
            }
            Action::Cut => self.action_cut(),
            Action::Copy => self.action_copy(),
            Action::Delete => self.action_delete().await,
            Action::Rename => self.action_rename(),
            Action::CreateDir => self.action_create_dir(),
            Action::CreateFile => self.action_create_file(),
            Action::ToggleHidden => {
                self.toggle_hidden();
                ActionResult::Done
            }
            Action::CycleSort => {
                self.cycle_sort();
                ActionResult::Done
            }
            Action::Refresh => {
                let _ = self.refresh().await;
                ActionResult::Done
            }
            Action::StartFilter => self.action_start_filter(),
            Action::ClearFilter => {
                self.clear_filter();
                ActionResult::Done
            }
            Action::StartPathInput => self.action_start_path_input(),
        }
    }

    /// Jump to next item starting with char (cycles through matches)
    pub fn jump_to_char(&mut self, c: char) -> bool {
        if let Some(idx) = nav::find_char_match(&self.files, self.cursor, c) {
            self.cursor = idx;
            self.update_scroll();
            true
        } else {
            false
        }
    }

    /// Jump to next item containing substring (cycles through matches)
    ///
    /// Unlike `set_filter`, this doesn't hide non-matches — it's typeahead search.
    pub fn jump_to_substring(&mut self, query: &str) -> bool {
        if let Some(idx) = nav::find_substring_match(&self.files, self.cursor, query) {
            self.cursor = idx;
            self.update_scroll();
            true
        } else {
            false
        }
    }

    /// Move cursor up by viewport height (page up)
    ///
    /// Keeps one line of overlap for context.
    pub fn page_up(&mut self, viewport_height: usize) {
        if self.files.is_empty() {
            return;
        }
        self.cursor = nav::page_up_cursor(self.cursor, viewport_height);
        self.update_scroll();
    }

    /// Move cursor down by viewport height (page down)
    ///
    /// Keeps one line of overlap for context.
    pub fn page_down(&mut self, viewport_height: usize) {
        if self.files.is_empty() {
            return;
        }
        self.cursor = nav::page_down_cursor(self.cursor, viewport_height, self.files.len());
        self.update_scroll();
    }

    /// Refresh current directory
    pub async fn refresh(&mut self) -> Result<(), NavError> {
        let cursor_name = self.current_entry().map(|e| e.name.clone());
        self.load_directory().await?;
        // Restore cursor if possible
        if let Some(name) = cursor_name {
            if let Some(idx) = self.files.iter().position(|e| e.name == name) {
                self.cursor = idx;
            }
        }
        self.update_scroll();
        Ok(())
    }

    // --- Confirmation/Input (Async) ---

    /// Resolve pending confirmation
    pub async fn resolve_confirmation(
        &mut self,
        confirmed: bool,
    ) -> Result<ActionResult, NavError> {
        let pending = self.pending.take().ok_or(NavError::NoPendingOperation)?;
        if let PendingState::Confirmation(op) = pending {
            if confirmed {
                self.execute_pending_op(&op)?;
                self.refresh().await?;
            }
            Ok(ActionResult::Done)
        } else {
            self.pending = Some(pending);
            Err(NavError::NoPendingOperation)
        }
    }

    /// Complete pending input
    pub async fn complete_input(&mut self, value: &str) -> Result<ActionResult, NavError> {
        let pending = self.pending.take().ok_or(NavError::NoPendingOperation)?;
        if let PendingState::Input(req) = pending {
            match req {
                InputRequest::Filter { .. } => {
                    self.set_filter(value);
                    Ok(ActionResult::Done)
                }
                InputRequest::Path { .. } => self.navigate_to(value).await,
                InputRequest::Rename { .. } => self.complete_rename(value).await,
                InputRequest::NewDirectory => self.complete_create_dir(value).await,
                InputRequest::NewFile => self.complete_create_file(value).await,
            }
        } else {
            self.pending = Some(pending);
            Err(NavError::NoPendingOperation)
        }
    }

    /// Cancel pending input
    pub fn cancel_input(&mut self) {
        self.pending = None;
    }

    /// Get pending operation if any
    pub fn pending_operation(&self) -> Option<&PendingOp> {
        match &self.pending {
            Some(PendingState::Confirmation(op)) => Some(op),
            _ => None,
        }
    }

    // --- Internal Helpers ---

    async fn load_directory(&mut self) -> Result<(), NavError> {
        // Virtual root: synthesize from configured roots, no filesystem walk.
        if self.virtual_root {
            self.all_entries = build_virtual_root_entries(&self.roots);
        } else if let Some(depth) = self.flat_mode {
            // Flat mode: recursive walk from current_path bounded by depth.
            self.all_entries = load_flat_entries(
                &self.current_path,
                depth,
                self.config.show_hidden,
                self.config.respect_ignore_files,
            )
            .await?;
        } else {
            // Path-aware error wrapping so callers see which directory failed
            // (preserved from the parallel nav-error refactor).
            self.all_entries = read_dir(&self.current_path)
                .await
                .map_err(|e| NavError::from_error_with_path(e, &self.current_path))?;
        }
        self.files.set_show_hidden(self.config.show_hidden);
        self.files.set_sort(self.config.sort_by);
        self.apply_filter();
        self.cursor = self.cursor.min(self.files.len().saturating_sub(1));
        self.update_scroll();
        Ok(())
    }

    fn apply_filter(&mut self) {
        // Built-in pattern filter (unchanged semantics).
        let built_in_pass = |e: &FileEntry| -> bool {
            if let Some(filter) = &self.filter {
                if filter.is_glob {
                    glob_match(&filter.pattern, &e.name)
                } else {
                    e.name
                        .to_lowercase()
                        .contains(&filter.pattern.to_lowercase())
                }
            } else {
                true
            }
        };

        let mut entries: Vec<_> = self
            .all_entries
            .iter()
            .filter(|e| {
                if !built_in_pass(e) {
                    return false;
                }
                // Custom filter is applied *after* the built-in filter so the
                // consumer sees only already-accepted entries. Both must pass.
                if let Some(predicate) = &self.custom_filter {
                    if !predicate(e) {
                        return false;
                    }
                }
                true
            })
            .cloned()
            .collect();

        // Prepend parent entry if enabled, not at root, not at virtual root,
        // and not in flat mode (a flat listing has no meaningful parent).
        if self.config.show_parent_entry && !self.virtual_root && self.flat_mode.is_none() {
            if let Some(parent) = self.current_path.parent() {
                // Don't offer a parent when current_path itself is the virtual
                // root sentinel (defensive — virtual_root flag normally covers
                // this case).
                if !is_virtual_root_path(&self.current_path) {
                    entries.insert(0, FileEntry::parent_entry(parent.to_path_buf()));
                }
            }
        }

        self.files.update_full(entries);
        self.files.catchup();
    }

    async fn navigate_internal(&mut self, path: PathBuf) -> Result<ActionResult, NavError> {
        // Handle navigation to the virtual-root sentinel (multi-root mode).
        if is_virtual_root_path(&path) {
            if self.roots.is_empty() {
                return Err(NavError::NotFound(path));
            }
            self.history.push(&self.current_path, self.cursor);
            self.current_path = virtual_root_path();
            self.virtual_root = true;
            self.filter = None;
            if self.config.clear_selection_on_navigate {
                self.selection.clear();
            }
            self.load_directory().await?;
            return Ok(ActionResult::DirectoryChanged);
        }

        if !path.exists() {
            return Err(NavError::NotFound(path));
        }
        if !path.is_dir() {
            return Err(NavError::NotADirectory(path));
        }
        self.history.push(&self.current_path, self.cursor);
        self.current_path = path;
        // Leaving the virtual root: from here on we behave like a standard
        // single-root browser until the user navigates back to the sentinel.
        self.virtual_root = false;
        self.filter = None;
        if self.config.clear_selection_on_navigate {
            self.selection.clear();
        }
        self.load_directory().await?;
        Ok(ActionResult::DirectoryChanged)
    }

    fn move_cursor(&mut self, delta: isize) {
        self.cursor = nav::move_cursor(self.cursor, delta, self.files.len());
        self.update_scroll();
    }

    /// Move cursor and extend selection (for Shift+Arrow)
    fn move_cursor_extend(&mut self, delta: isize) {
        let len = self.files.len();
        if len == 0 {
            return;
        }
        let old_cursor = self.cursor;
        let new_cursor = nav::move_cursor(self.cursor, delta, len);
        let files = &self.files;
        self.selection.extend_to(
            old_cursor,
            new_cursor,
            |i| files.get(i).map(|e| e.path.clone()),
            len,
        );
        self.cursor = new_cursor;
        self.update_scroll();
    }

    fn update_scroll(&mut self) {
        self.scroll_offset = nav::update_scroll_offset(
            self.cursor,
            self.scroll_offset,
            self.config.scroll_padding,
            self.viewport_height,
            self.files.len(),
        );
    }

    fn toggle_current_selection(&mut self) {
        if let Some(path) = self.current_entry().map(|e| e.path.clone()) {
            self.selection.toggle(&path);
        }
    }

    fn select_all_visible(&mut self) {
        for entry in self.files.iter() {
            self.selection.select(&entry.path);
        }
    }

    /// Toggle hidden files visibility
    pub fn toggle_hidden(&mut self) {
        self.config.show_hidden = !self.config.show_hidden;
        self.files.set_show_hidden(self.config.show_hidden);
        self.files.catchup();
        // Clamp cursor after filter changes list size
        let len = self.files.len();
        if len > 0 && self.cursor >= len {
            self.cursor = len - 1;
        }
        self.update_scroll();
    }

    fn cycle_sort(&mut self) {
        use SortBy::*;
        self.config.sort_by = match self.config.sort_by {
            Name => NameDesc,
            NameDesc => Extension,
            Extension => Size,
            Size => SizeDesc,
            SizeDesc => Modified,
            Modified => ModifiedDesc,
            ModifiedDesc => Name,
            DirsFirst => Name,
        };
        self.files.set_sort(self.config.sort_by);
        self.files.catchup();
    }

    // Action implementations
    async fn action_enter(&mut self) -> ActionResult {
        if let Some(entry) = self.current_entry().cloned() {
            if entry.is_dir {
                // Flat mode disables directory descent: files are addressed by
                // their relative path and the consumer is expected to act on
                // `FileSelected`. Entering a directory entry in flat mode is a
                // no-op (Done) rather than navigating — that would break the
                // "flat list" contract.
                if self.flat_mode.is_some() {
                    return ActionResult::Done;
                }
                match self.navigate_internal(entry.path).await {
                    Ok(r) => r,
                    Err(_) => ActionResult::Done,
                }
            } else {
                ActionResult::FileSelected(entry.path)
            }
        } else {
            ActionResult::Done
        }
    }

    async fn action_go_parent(&mut self) -> ActionResult {
        // Already at the virtual root — no parent above it.
        if self.virtual_root {
            return ActionResult::Done;
        }

        // Multi-root mode: ascending from a configured root returns to the
        // synthetic virtual-root listing rather than the OS-level parent.
        if !self.roots.is_empty() && self.roots.iter().any(|r| r == &self.current_path) {
            let came_from = self.current_path.clone();
            match self.navigate_internal(virtual_root_path()).await {
                Ok(r) => {
                    // Position cursor on the root we came from.
                    if let Some(idx) = self.files.iter().position(|e| e.path == came_from) {
                        self.cursor = idx;
                        self.update_scroll();
                    }
                    r
                }
                Err(_) => ActionResult::Done,
            }
        } else if let Some(parent) = self.current_path.parent().map(|p| p.to_path_buf()) {
            let current_name = self
                .current_path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned());
            match self.navigate_internal(parent).await {
                Ok(r) => {
                    // Position cursor on the directory we came from
                    if let Some(name) = current_name {
                        if let Some(idx) = self.files.iter().position(|e| e.name == name) {
                            self.cursor = idx;
                            self.update_scroll();
                        }
                    }
                    r
                }
                Err(_) => ActionResult::Done,
            }
        } else {
            ActionResult::Done
        }
    }

    async fn action_go_back(&mut self) -> ActionResult {
        if let Some(entry) = self.history.go_back(&self.current_path, self.cursor) {
            self.virtual_root = is_virtual_root_path(&entry.path);
            self.current_path = entry.path;
            self.filter = None;
            if self.config.clear_selection_on_navigate {
                self.selection.clear();
            }
            let _ = self.load_directory().await;
            self.cursor = entry.cursor.min(self.files.len().saturating_sub(1));
            self.update_scroll();
            ActionResult::DirectoryChanged
        } else {
            ActionResult::Done
        }
    }

    async fn action_go_forward(&mut self) -> ActionResult {
        if let Some(entry) = self.history.go_forward(&self.current_path, self.cursor) {
            self.virtual_root = is_virtual_root_path(&entry.path);
            self.current_path = entry.path;
            self.filter = None;
            if self.config.clear_selection_on_navigate {
                self.selection.clear();
            }
            let _ = self.load_directory().await;
            self.cursor = entry.cursor.min(self.files.len().saturating_sub(1));
            self.update_scroll();
            ActionResult::DirectoryChanged
        } else {
            ActionResult::Done
        }
    }

    fn action_cut(&mut self) -> ActionResult {
        let paths = actions::collect_target_paths(
            self.selection.iter(),
            self.current_entry().map(|e| e.path.as_path()),
            self.selection.is_empty(),
        );
        actions::build_cut_clipboard(paths, &self.current_path)
    }

    fn action_copy(&mut self) -> ActionResult {
        let paths = actions::collect_target_paths(
            self.selection.iter(),
            self.current_entry().map(|e| e.path.as_path()),
            self.selection.is_empty(),
        );
        actions::build_copy_clipboard(paths, &self.current_path)
    }

    async fn action_delete(&mut self) -> ActionResult {
        let paths: Vec<PathBuf> = self
            .selected_or_current()
            .iter()
            .map(|p| p.to_path_buf())
            .collect();
        if paths.is_empty() {
            return ActionResult::Done;
        }
        if self.config.confirm_delete {
            self.pending = Some(PendingState::Confirmation(PendingOp::Delete { paths }));
            ActionResult::NeedsConfirmation(PendingOp::Delete {
                paths: self
                    .selected_or_current()
                    .iter()
                    .map(|p| p.to_path_buf())
                    .collect(),
            })
        } else {
            for path in &paths {
                let _ = fnc_file_ops::delete_path(path);
            }
            let _ = self.refresh().await;
            ActionResult::Done
        }
    }

    fn action_rename(&mut self) -> ActionResult {
        if let Some(name) = self.current_entry().map(|e| e.name.clone()) {
            self.pending = Some(PendingState::Input(InputRequest::Rename {
                current_name: name.clone(),
            }));
            ActionResult::NeedsInput(InputRequest::Rename { current_name: name })
        } else {
            ActionResult::Done
        }
    }

    fn action_create_dir(&mut self) -> ActionResult {
        self.pending = Some(PendingState::Input(InputRequest::NewDirectory));
        ActionResult::NeedsInput(InputRequest::NewDirectory)
    }

    fn action_create_file(&mut self) -> ActionResult {
        self.pending = Some(PendingState::Input(InputRequest::NewFile));
        ActionResult::NeedsInput(InputRequest::NewFile)
    }

    fn action_start_filter(&mut self) -> ActionResult {
        let current = self.filter.as_ref().map(|f| f.pattern.clone());
        self.pending = Some(PendingState::Input(InputRequest::Filter {
            current: current.clone(),
        }));
        ActionResult::NeedsInput(InputRequest::Filter { current })
    }

    fn action_start_path_input(&mut self) -> ActionResult {
        self.pending = Some(PendingState::Input(InputRequest::Path {
            current: self.current_path.clone(),
        }));
        ActionResult::NeedsInput(InputRequest::Path {
            current: self.current_path.clone(),
        })
    }

    fn execute_pending_op(&mut self, op: &PendingOp) -> Result<(), NavError> {
        match op {
            PendingOp::Delete { paths } => {
                for path in paths {
                    fnc_file_ops::delete_path(path)?;
                }
            }
            PendingOp::Rename { from, to } => {
                fnc_file_ops::rename_path(from, to)?;
            }
            PendingOp::Overwrite { path } => {
                fnc_file_ops::delete_path(path)?;
            }
        }
        Ok(())
    }

    async fn complete_rename(&mut self, new_name: &str) -> Result<ActionResult, NavError> {
        validate_name(new_name)?;
        if let Some(entry) = self.current_entry() {
            let new_path = entry.path.parent().unwrap_or(Path::new("")).join(new_name);
            if new_path.exists() && self.config.confirm_overwrite {
                self.pending = Some(PendingState::Confirmation(PendingOp::Rename {
                    from: entry.path.clone(),
                    to: new_path.clone(),
                }));
                return Ok(ActionResult::NeedsConfirmation(PendingOp::Overwrite {
                    path: new_path,
                }));
            }
            fnc_file_ops::rename_path(&entry.path, &new_path)?;
            self.refresh().await?;
        }
        Ok(ActionResult::Done)
    }

    async fn complete_create_dir(&mut self, name: &str) -> Result<ActionResult, NavError> {
        validate_name(name)?;
        let path = self.current_path.join(name);
        fnc_file_ops::create_directory(&path)?;
        self.refresh().await?;
        Ok(ActionResult::Done)
    }

    async fn complete_create_file(&mut self, name: &str) -> Result<ActionResult, NavError> {
        validate_name(name)?;
        let path = self.current_path.join(name);
        fnc_file_ops::create_file(&path)?;
        self.refresh().await?;
        Ok(ActionResult::Done)
    }
}

// <FILE>crates/fast-fs/src/nav/cls_browser.rs</FILE>
// <VERS>END OF VERSION: 0.9.0</VERS>