fresh-editor 0.1.95

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
//! File open dialog state and logic
//!
//! This module provides a plugin-free file browser for the Open File command.
//! It renders a structured popup above the prompt with sortable columns,
//! navigation shortcuts, and filtering.

use crate::input::fuzzy::fuzzy_match;
use crate::model::filesystem::{DirEntry, EntryType};
use rust_i18n::t;
use std::cmp::Ordering;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// A file entry in the browser with filter match state
#[derive(Debug, Clone)]
pub struct FileOpenEntry {
    /// The filesystem entry
    pub fs_entry: DirEntry,
    /// Whether this entry matches the current filter
    pub matches_filter: bool,
    /// Fuzzy match score (higher is better match, used for sorting when filter is active)
    pub match_score: i32,
}

/// Sort mode for file list
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortMode {
    #[default]
    Name,
    Size,
    Modified,
    Type,
}

/// Which section of the file browser is active
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FileOpenSection {
    /// Navigation shortcuts (parent, root, home)
    Navigation,
    /// Main file list
    #[default]
    Files,
}

/// Navigation shortcut entry
#[derive(Debug, Clone)]
pub struct NavigationShortcut {
    /// Display label (e.g., "~", "..", "/")
    pub label: String,
    /// Full path to navigate to
    pub path: PathBuf,
    /// Description (e.g., "Home directory")
    pub description: String,
}

/// State for the file open dialog
#[derive(Debug, Clone)]
pub struct FileOpenState {
    /// Current directory being browsed
    pub current_dir: PathBuf,

    /// Directory entries with metadata
    pub entries: Vec<FileOpenEntry>,

    /// Whether directory is currently loading
    pub loading: bool,

    /// Error message if directory load failed
    pub error: Option<String>,

    /// Current sort mode
    pub sort_mode: SortMode,

    /// Sort direction (true = ascending)
    pub sort_ascending: bool,

    /// Selected index in the current section (None = no selection)
    pub selected_index: Option<usize>,

    /// Scroll offset for file list
    pub scroll_offset: usize,

    /// Which section is currently active
    pub active_section: FileOpenSection,

    /// Filter text (from prompt input)
    pub filter: String,

    /// Navigation shortcuts
    pub shortcuts: Vec<NavigationShortcut>,

    /// Selected shortcut index (when in Navigation section)
    pub selected_shortcut: usize,

    /// Whether to show hidden files
    pub show_hidden: bool,
}

impl FileOpenState {
    /// Create a new file open state for the given directory
    pub fn new(dir: PathBuf, show_hidden: bool) -> Self {
        let shortcuts = Self::build_shortcuts(&dir);
        Self {
            current_dir: dir,
            entries: Vec::new(),
            loading: true,
            error: None,
            sort_mode: SortMode::Name,
            sort_ascending: true,
            selected_index: None,
            scroll_offset: 0,
            active_section: FileOpenSection::Files,
            filter: String::new(),
            shortcuts,
            selected_shortcut: 0,
            show_hidden,
        }
    }

    /// Build navigation shortcuts for the given directory
    fn build_shortcuts(current_dir: &Path) -> Vec<NavigationShortcut> {
        let mut shortcuts = Vec::new();

        // Parent directory
        if let Some(parent) = current_dir.parent() {
            shortcuts.push(NavigationShortcut {
                label: "..".to_string(),
                path: parent.to_path_buf(),
                description: t!("file_browser.parent_dir").to_string(),
            });
        }

        // Root directory
        #[cfg(unix)]
        {
            shortcuts.push(NavigationShortcut {
                label: "/".to_string(),
                path: PathBuf::from("/"),
                description: t!("file_browser.root_dir").to_string(),
            });
        }

        // Home directory
        if let Some(home) = dirs::home_dir() {
            shortcuts.push(NavigationShortcut {
                label: "~".to_string(),
                path: home,
                description: t!("file_browser.home_dir").to_string(),
            });
        }

        // Documents directory
        if let Some(docs) = dirs::document_dir() {
            shortcuts.push(NavigationShortcut {
                label: t!("file_browser.documents").to_string(),
                path: docs,
                description: t!("file_browser.documents_folder").to_string(),
            });
        }

        // Downloads directory
        if let Some(downloads) = dirs::download_dir() {
            shortcuts.push(NavigationShortcut {
                label: t!("file_browser.downloads").to_string(),
                path: downloads,
                description: t!("file_browser.downloads_folder").to_string(),
            });
        }

        // Windows: Add drive letters
        #[cfg(windows)]
        {
            for letter in b'A'..=b'Z' {
                let path = PathBuf::from(format!("{}:\\", letter as char));
                if path.exists() {
                    shortcuts.push(NavigationShortcut {
                        label: format!("{}:", letter as char),
                        path,
                        description: t!("file_browser.drive").to_string(),
                    });
                }
            }
        }

        shortcuts
    }

    /// Update shortcuts when directory changes
    pub fn update_shortcuts(&mut self) {
        self.shortcuts = Self::build_shortcuts(&self.current_dir);
        self.selected_shortcut = 0;
    }

    /// Set entries from filesystem and apply initial sort
    pub fn set_entries(&mut self, entries: Vec<DirEntry>) {
        let mut result: Vec<FileOpenEntry> = Vec::new();

        // Add ".." entry for parent directory navigation (unless at root)
        if let Some(parent) = self.current_dir.parent() {
            let parent_entry =
                DirEntry::new(parent.to_path_buf(), "..".to_string(), EntryType::Directory);
            result.push(FileOpenEntry {
                fs_entry: parent_entry,
                matches_filter: true,
                match_score: 0,
            });
        }

        // Add filtered entries
        result.extend(
            entries
                .into_iter()
                .filter(|e| self.show_hidden || !Self::is_hidden(&e.name))
                .map(|fs_entry| FileOpenEntry {
                    fs_entry,
                    matches_filter: true,
                    match_score: 0,
                }),
        );

        self.entries = result;
        self.loading = false;
        self.error = None;
        self.apply_filter_internal();
        self.sort_entries();
        // No selection by default - user must type or navigate to select
        self.selected_index = None;
        self.scroll_offset = 0;
    }

    /// Set error state
    pub fn set_error(&mut self, error: String) {
        self.loading = false;
        self.error = Some(error);
        self.entries.clear();
    }

    /// Check if a filename is hidden (starts with .)
    fn is_hidden(name: &str) -> bool {
        name.starts_with('.')
    }

    /// Apply filter text to entries
    /// When filter is active, entries are sorted by fuzzy match score (best matches first).
    /// Non-matching entries are de-emphasized visually but stay at the bottom.
    pub fn apply_filter(&mut self, filter: &str) {
        self.filter = filter.to_string();
        self.apply_filter_internal();

        // When filter is non-empty, sort by match score (best matches first)
        if !filter.is_empty() {
            self.entries.sort_by(|a, b| {
                // ".." always stays at top
                let a_is_parent = a.fs_entry.name == "..";
                let b_is_parent = b.fs_entry.name == "..";

                if a_is_parent && !b_is_parent {
                    return Ordering::Less;
                }
                if !a_is_parent && b_is_parent {
                    return Ordering::Greater;
                }

                // Matching entries before non-matching
                match (a.matches_filter, b.matches_filter) {
                    (true, false) => Ordering::Less,
                    (false, true) => Ordering::Greater,
                    (true, true) => {
                        // Both match: sort by score descending (higher score = better match)
                        b.match_score.cmp(&a.match_score)
                    }
                    (false, false) => {
                        // Neither match: keep alphabetical order
                        a.fs_entry
                            .name
                            .to_lowercase()
                            .cmp(&b.fs_entry.name.to_lowercase())
                    }
                }
            });

            // Select first matching entry (skip "..")
            let first_match = self
                .entries
                .iter()
                .position(|e| e.matches_filter && e.fs_entry.name != "..");
            if let Some(idx) = first_match {
                self.selected_index = Some(idx);
                self.ensure_selected_visible();
            } else {
                self.selected_index = None;
            }
        } else {
            // No filter: restore normal sort order and clear selection
            self.sort_entries();
            self.selected_index = None;
        }
    }

    fn apply_filter_internal(&mut self) {
        for entry in &mut self.entries {
            if self.filter.is_empty() {
                entry.matches_filter = true;
                entry.match_score = 0;
            } else {
                let result = fuzzy_match(&self.filter, &entry.fs_entry.name);
                entry.matches_filter = result.matched;
                entry.match_score = result.score;
            }
        }
    }

    /// Sort entries according to current sort mode
    pub fn sort_entries(&mut self) {
        let sort_mode = self.sort_mode;
        let ascending = self.sort_ascending;

        self.entries.sort_by(|a, b| {
            // ".." always stays at top
            let a_is_parent = a.fs_entry.name == "..";
            let b_is_parent = b.fs_entry.name == "..";
            match (a_is_parent, b_is_parent) {
                (true, false) => return Ordering::Less,
                (false, true) => return Ordering::Greater,
                (true, true) => return Ordering::Equal,
                _ => {}
            }

            // Don't reorder based on filter match - just de-emphasize non-matching
            // entries visually. Keep original sort order.

            // Directories before files
            match (a.fs_entry.is_dir(), b.fs_entry.is_dir()) {
                (true, false) => return Ordering::Less,
                (false, true) => return Ordering::Greater,
                _ => {}
            }

            // Apply sort mode
            let ord = match sort_mode {
                SortMode::Name => a
                    .fs_entry
                    .name
                    .to_lowercase()
                    .cmp(&b.fs_entry.name.to_lowercase()),
                SortMode::Size => {
                    let a_size = a.fs_entry.metadata.as_ref().map(|m| m.size).unwrap_or(0);
                    let b_size = b.fs_entry.metadata.as_ref().map(|m| m.size).unwrap_or(0);
                    a_size.cmp(&b_size)
                }
                SortMode::Modified => {
                    let a_mod = a.fs_entry.metadata.as_ref().and_then(|m| m.modified);
                    let b_mod = b.fs_entry.metadata.as_ref().and_then(|m| m.modified);
                    match (a_mod, b_mod) {
                        (Some(a), Some(b)) => a.cmp(&b),
                        (Some(_), None) => Ordering::Less,
                        (None, Some(_)) => Ordering::Greater,
                        (None, None) => Ordering::Equal,
                    }
                }
                SortMode::Type => {
                    let a_ext = std::path::Path::new(&a.fs_entry.name)
                        .extension()
                        .and_then(|e| e.to_str())
                        .unwrap_or("");
                    let b_ext = std::path::Path::new(&b.fs_entry.name)
                        .extension()
                        .and_then(|e| e.to_str())
                        .unwrap_or("");
                    a_ext.to_lowercase().cmp(&b_ext.to_lowercase())
                }
            };

            if ascending {
                ord
            } else {
                ord.reverse()
            }
        });
    }

    /// Set sort mode and re-sort
    pub fn set_sort_mode(&mut self, mode: SortMode) {
        if self.sort_mode == mode {
            // Toggle direction if same mode
            self.sort_ascending = !self.sort_ascending;
        } else {
            self.sort_mode = mode;
            self.sort_ascending = true;
        }
        self.sort_entries();
    }

    /// Toggle hidden files visibility
    pub fn toggle_hidden(&mut self) {
        self.show_hidden = !self.show_hidden;
        // Need to reload directory to apply this change
    }

    /// Move selection up
    pub fn select_prev(&mut self) {
        match self.active_section {
            FileOpenSection::Navigation => {
                if self.selected_shortcut > 0 {
                    self.selected_shortcut -= 1;
                }
            }
            FileOpenSection::Files => {
                if let Some(idx) = self.selected_index {
                    if idx > 0 {
                        self.selected_index = Some(idx - 1);
                        self.ensure_selected_visible();
                    }
                } else if !self.entries.is_empty() {
                    // No selection, select last entry
                    self.selected_index = Some(self.entries.len() - 1);
                    self.ensure_selected_visible();
                }
            }
        }
    }

    /// Move selection down
    pub fn select_next(&mut self) {
        match self.active_section {
            FileOpenSection::Navigation => {
                if self.selected_shortcut + 1 < self.shortcuts.len() {
                    self.selected_shortcut += 1;
                }
            }
            FileOpenSection::Files => {
                if let Some(idx) = self.selected_index {
                    if idx + 1 < self.entries.len() {
                        self.selected_index = Some(idx + 1);
                        self.ensure_selected_visible();
                    }
                } else if !self.entries.is_empty() {
                    // No selection, select first entry
                    self.selected_index = Some(0);
                    self.ensure_selected_visible();
                }
            }
        }
    }

    /// Page up
    pub fn page_up(&mut self, page_size: usize) {
        if self.active_section == FileOpenSection::Files {
            if let Some(idx) = self.selected_index {
                self.selected_index = Some(idx.saturating_sub(page_size));
                self.ensure_selected_visible();
            } else if !self.entries.is_empty() {
                self.selected_index = Some(0);
            }
        }
    }

    /// Page down
    pub fn page_down(&mut self, page_size: usize) {
        if self.active_section == FileOpenSection::Files {
            if let Some(idx) = self.selected_index {
                self.selected_index =
                    Some((idx + page_size).min(self.entries.len().saturating_sub(1)));
                self.ensure_selected_visible();
            } else if !self.entries.is_empty() {
                self.selected_index = Some(self.entries.len().saturating_sub(1));
            }
        }
    }

    /// Jump to first entry
    pub fn select_first(&mut self) {
        match self.active_section {
            FileOpenSection::Navigation => self.selected_shortcut = 0,
            FileOpenSection::Files => {
                if !self.entries.is_empty() {
                    self.selected_index = Some(0);
                    self.scroll_offset = 0;
                }
            }
        }
    }

    /// Jump to last entry
    pub fn select_last(&mut self) {
        match self.active_section {
            FileOpenSection::Navigation => {
                self.selected_shortcut = self.shortcuts.len().saturating_sub(1);
            }
            FileOpenSection::Files => {
                if !self.entries.is_empty() {
                    self.selected_index = Some(self.entries.len() - 1);
                    self.ensure_selected_visible();
                }
            }
        }
    }

    /// Ensure selected item is visible in viewport
    fn ensure_selected_visible(&mut self) {
        let Some(idx) = self.selected_index else {
            return;
        };
        // This will be called with actual visible_rows from renderer
        // For now, use a reasonable default
        let visible_rows = 15;
        if idx < self.scroll_offset {
            self.scroll_offset = idx;
        } else if idx >= self.scroll_offset + visible_rows {
            self.scroll_offset = idx.saturating_sub(visible_rows - 1);
        }
    }

    /// Update scroll offset based on visible rows
    pub fn update_scroll_for_visible_rows(&mut self, visible_rows: usize) {
        let Some(idx) = self.selected_index else {
            return;
        };
        if idx < self.scroll_offset {
            self.scroll_offset = idx;
        } else if idx >= self.scroll_offset + visible_rows {
            self.scroll_offset = idx.saturating_sub(visible_rows - 1);
        }
    }

    /// Switch between navigation and files sections
    pub fn switch_section(&mut self) {
        self.active_section = match self.active_section {
            FileOpenSection::Navigation => FileOpenSection::Files,
            FileOpenSection::Files => FileOpenSection::Navigation,
        };
    }

    /// Get the currently selected entry (file or directory)
    pub fn selected_entry(&self) -> Option<&FileOpenEntry> {
        if self.active_section == FileOpenSection::Files {
            self.selected_index.and_then(|idx| self.entries.get(idx))
        } else {
            None
        }
    }

    /// Get the currently selected shortcut
    pub fn selected_shortcut_entry(&self) -> Option<&NavigationShortcut> {
        if self.active_section == FileOpenSection::Navigation {
            self.shortcuts.get(self.selected_shortcut)
        } else {
            None
        }
    }

    /// Get the path to open/navigate to based on current selection
    pub fn get_selected_path(&self) -> Option<PathBuf> {
        match self.active_section {
            FileOpenSection::Navigation => self
                .shortcuts
                .get(self.selected_shortcut)
                .map(|s| s.path.clone()),
            FileOpenSection::Files => self
                .selected_index
                .and_then(|idx| self.entries.get(idx))
                .map(|e| e.fs_entry.path.clone()),
        }
    }

    /// Check if selected item is a directory
    pub fn selected_is_dir(&self) -> bool {
        match self.active_section {
            FileOpenSection::Navigation => true, // Shortcuts are always directories
            FileOpenSection::Files => self
                .selected_index
                .and_then(|idx| self.entries.get(idx))
                .map(|e| e.fs_entry.is_dir())
                .unwrap_or(false),
        }
    }

    /// Count matching entries
    pub fn matching_count(&self) -> usize {
        self.entries.iter().filter(|e| e.matches_filter).count()
    }

    /// Get visible entries (for rendering)
    pub fn visible_entries(&self, max_rows: usize) -> &[FileOpenEntry] {
        let start = self.scroll_offset;
        let end = (start + max_rows).min(self.entries.len());
        &self.entries[start..end]
    }
}

/// Format file size in human-readable form
pub fn format_size(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if size >= GB {
        format!("{:.1} GB", size as f64 / GB as f64)
    } else if size >= MB {
        format!("{:.1} MB", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.1} KB", size as f64 / KB as f64)
    } else {
        format!("{} B", size)
    }
}

/// Format timestamp in relative or absolute form
pub fn format_modified(time: SystemTime) -> String {
    let now = SystemTime::now();
    match now.duration_since(time) {
        Ok(duration) => {
            let secs = duration.as_secs();
            if secs < 60 {
                "just now".to_string()
            } else if secs < 3600 {
                format!("{} min ago", secs / 60)
            } else if secs < 86400 {
                format!("{} hr ago", secs / 3600)
            } else if secs < 86400 * 7 {
                format!("{} days ago", secs / 86400)
            } else {
                // Format as date
                let datetime: chrono::DateTime<chrono::Local> = time.into();
                datetime.format("%Y-%m-%d").to_string()
            }
        }
        Err(_) => {
            // Time is in the future
            let datetime: chrono::DateTime<chrono::Local> = time.into();
            datetime.format("%Y-%m-%d").to_string()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn make_entry(name: &str, is_dir: bool) -> DirEntry {
        DirEntry::new(
            PathBuf::from(format!("/test/{}", name)),
            name.to_string(),
            if is_dir {
                EntryType::Directory
            } else {
                EntryType::File
            },
        )
    }

    fn make_entry_with_size(name: &str, size: u64) -> DirEntry {
        make_entry(name, false).with_metadata(crate::model::filesystem::FileMetadata::new(size))
    }

    #[test]
    fn test_sort_by_name() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("zebra.txt", false),
            make_entry("alpha.txt", false),
            make_entry("beta", true),
        ]);

        assert_eq!(state.entries[0].fs_entry.name, "beta"); // Dir first
        assert_eq!(state.entries[1].fs_entry.name, "alpha.txt");
        assert_eq!(state.entries[2].fs_entry.name, "zebra.txt");
    }

    #[test]
    fn test_sort_by_size() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.sort_mode = SortMode::Size;
        state.set_entries(vec![
            make_entry_with_size("big.txt", 1000),
            make_entry_with_size("small.txt", 100),
            make_entry_with_size("medium.txt", 500),
        ]);

        assert_eq!(state.entries[0].fs_entry.name, "small.txt");
        assert_eq!(state.entries[1].fs_entry.name, "medium.txt");
        assert_eq!(state.entries[2].fs_entry.name, "big.txt");
    }

    #[test]
    fn test_filter() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("foo.txt", false),
            make_entry("bar.txt", false),
            make_entry("foobar.txt", false),
        ]);

        state.apply_filter("foo");

        // With fuzzy matching, matching entries are sorted by score and appear first
        // foo.txt has a better score (starts with "foo") than foobar.txt
        // Non-matching bar.txt appears last
        assert_eq!(state.entries[0].fs_entry.name, "foo.txt");
        assert!(state.entries[0].matches_filter);

        assert_eq!(state.entries[1].fs_entry.name, "foobar.txt");
        assert!(state.entries[1].matches_filter);

        assert_eq!(state.entries[2].fs_entry.name, "bar.txt");
        assert!(!state.entries[2].matches_filter);

        assert_eq!(state.matching_count(), 2);
    }

    #[test]
    fn test_filter_case_insensitive() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("README.md", false),
            make_entry("readme.txt", false),
            make_entry("other.txt", false),
        ]);

        state.apply_filter("readme");

        // Matching entries first (sorted by score), non-matching last
        // Both README.md and readme.txt match with similar scores
        assert!(state.entries[0].matches_filter);
        assert!(state.entries[1].matches_filter);

        assert_eq!(state.entries[2].fs_entry.name, "other.txt");
        assert!(!state.entries[2].matches_filter);
    }

    #[test]
    fn test_hidden_files() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.show_hidden = false;
        state.set_entries(vec![
            make_entry(".hidden", false),
            make_entry("visible.txt", false),
        ]);

        // Hidden file should be filtered out
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.entries[0].fs_entry.name, "visible.txt");
    }

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(500), "500 B");
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
        assert_eq!(format_size(1048576), "1.0 MB");
        assert_eq!(format_size(1073741824), "1.0 GB");
    }

    #[test]
    fn test_navigation() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("a.txt", false),
            make_entry("b.txt", false),
            make_entry("c.txt", false),
        ]);

        // Initially no selection
        assert_eq!(state.selected_index, None);

        // First down selects first entry
        state.select_next();
        assert_eq!(state.selected_index, Some(0));

        state.select_next();
        assert_eq!(state.selected_index, Some(1));

        state.select_next();
        assert_eq!(state.selected_index, Some(2));

        state.select_next(); // Should stay at last
        assert_eq!(state.selected_index, Some(2));

        state.select_prev();
        assert_eq!(state.selected_index, Some(1));

        state.select_first();
        assert_eq!(state.selected_index, Some(0));

        state.select_last();
        assert_eq!(state.selected_index, Some(2));
    }

    #[test]
    fn test_fuzzy_filter() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("command_registry.rs", false),
            make_entry("commands.rs", false),
            make_entry("keybindings.rs", false),
            make_entry("mod.rs", false),
        ]);

        // Fuzzy match "cmdreg" should match "command_registry.rs"
        state.apply_filter("cmdreg");

        // command_registry.rs should match and be first
        assert!(state.entries[0].matches_filter);
        assert_eq!(state.entries[0].fs_entry.name, "command_registry.rs");

        // commands.rs might also match "cmd" part
        // Other files shouldn't match
        assert_eq!(state.matching_count(), 1);
    }

    #[test]
    fn test_fuzzy_filter_sparse_match() {
        // Use root path so no ".." entry is added
        let mut state = FileOpenState::new(PathBuf::from("/"), false);
        state.set_entries(vec![
            make_entry("Save File", false),
            make_entry("Select All", false),
            make_entry("something_else.txt", false),
        ]);

        // "sf" should match "Save File" (S and F)
        state.apply_filter("sf");

        assert_eq!(state.matching_count(), 1);
        assert!(state.entries[0].matches_filter);
        assert_eq!(state.entries[0].fs_entry.name, "Save File");
    }
}