tui-file-explorer 4.0.1

Embeddable keyboard-driven multi-pane file explorer for Ratatui
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
//! Public data types exposed by the `tui-file-explorer` crate.

use std::path::PathBuf;

// ── ExplorerCommand ───────────────────────────────────────────────────────────

command_enum! {
    /// Semantic command accepted by [`crate::FileExplorer::handle_command`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum ExplorerCommand {
        /// Move the cursor up one row.
        MoveUp => "move_up",
        /// Move the cursor down one row.
        MoveDown => "move_down",
        /// Move the cursor up one page.
        PageUp => "page_up",
        /// Move the cursor down one page.
        PageDown => "page_down",
        /// Jump to the first entry.
        Top => "top",
        /// Jump to the last entry.
        Bottom => "bottom",
        /// Go to the parent directory.
        Ascend => "ascend",
        /// Enter the directory under the cursor; on a file, move down instead.
        Navigate => "navigate",
        /// Select the entry under the cursor, or enter it when directories can't be selected.
        Confirm => "confirm",
        /// Show or hide dotfiles.
        ToggleHidden => "toggle_hidden",
        /// Show or hide file sizes.
        ToggleSizes => "toggle_sizes",
        /// Show or hide directory sizes.
        ToggleDirSizes => "toggle_dir_sizes",
        /// Start incremental search.
        Search => "search",
        /// Switch to the next sort order.
        CycleSort => "cycle_sort",
        /// Mark or unmark the entry under the cursor.
        ToggleMark => "toggle_mark",
        /// Create a directory in the current directory.
        NewDirectory => "new_directory",
        /// Create an empty file in the current directory.
        NewFile => "new_file",
        /// Rename the entry under the cursor.
        Rename => "rename",
        /// Close the explorer without selecting anything.
        Dismiss => "dismiss",
    }
}

// ── Prompt ────────────────────────────────────────────────────────────────────

/// Which single-line text prompt an explorer is showing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PromptKind {
    /// Rename the entry under the cursor.
    Rename,
    /// Create a new empty file.
    Touch,
    /// Create a new directory.
    Mkdir,
}

impl PromptKind {
    /// Footer label shown in front of the typed text.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Rename => " \u{270F}\u{FE0F}  Rename: ",
            Self::Touch => " \u{1F4C4} New file: ",
            Self::Mkdir => " \u{1F4C2} New folder: ",
        }
    }

    /// Short verb used in status messages (`"mkdir failed: …"`).
    #[must_use]
    pub fn verb(self) -> &'static str {
        match self {
            Self::Rename => "rename",
            Self::Touch => "touch",
            Self::Mkdir => "mkdir",
        }
    }
}

/// An open text prompt: what it is for and what has been typed so far.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prompt {
    /// What the prompt is for.
    pub kind: PromptKind,
    /// Text typed so far.
    pub text: String,
}

// ── SelectionMode ─────────────────────────────────────────────────────────────

/// Which entry kinds can be confirmed by `Enter`/`l`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SelectionMode {
    /// Files are selected; directories are entered.
    #[default]
    Files,
    /// Directories are selected; use Right Arrow to navigate into them.
    Directories,
    /// Files and directories are selected; use Right Arrow for navigation.
    Any,
}

// ── SortMode ──────────────────────────────────────────────────────────────────

/// Controls the order in which directory entries are listed.
///
/// The sort order can be changed at runtime with the `s` key (which cycles
/// through all variants) or programmatically via
/// [`crate::FileExplorer::set_sort_mode`].
///
/// Directories are always shown before files regardless of the active mode.
///
/// ```
/// use tui_file_explorer::SortMode;
///
/// let mode = SortMode::default(); // SortMode::Name
/// let next = mode.next();         // SortMode::SizeDesc
/// println!("{}", mode.label());   // "name"
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortMode {
    /// Alphabetical by file name, A → Z. This is the default.
    #[default]
    Name,
    /// By file size, largest first. Directories sort alphabetically among
    /// themselves (they have no meaningful size).
    SizeDesc,
    /// By file extension (A → Z), then by name within each extension group.
    Extension,
}

impl SortMode {
    /// Return the next mode in the cycle: `Name → SizeDesc → Extension → Name`.
    ///
    /// Intended for the `s` key binding that cycles sort modes at runtime.
    #[must_use]
    pub fn next(self) -> Self {
        match self {
            Self::Name => Self::SizeDesc,
            Self::SizeDesc => Self::Extension,
            Self::Extension => Self::Name,
        }
    }

    /// A short human-readable label for display in the footer status bar.
    ///
    /// ```
    /// use tui_file_explorer::SortMode;
    ///
    /// assert_eq!(SortMode::Name.label(),      "name");
    /// assert_eq!(SortMode::SizeDesc.label(),  "size ↓");
    /// assert_eq!(SortMode::Extension.label(), "ext");
    /// ```
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Name => "name",
            Self::SizeDesc => "size ↓",
            Self::Extension => "ext",
        }
    }
}

// ── FsEntry ───────────────────────────────────────────────────────────────────

/// A single entry shown in the file-explorer list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FsEntry {
    /// Display name (filename only, not full path).
    pub name: String,
    /// Absolute path to the entry.
    pub path: PathBuf,
    /// `true` if the entry is a directory.
    pub is_dir: bool,
    /// File size in bytes (`None` for directories or when unavailable).
    pub size: Option<u64>,
    /// Number of immediate entries inside the directory (`None` for files,
    /// or when the directory could not be read — e.g. permission denied).
    ///
    /// This is a shallow (non-recursive) count, kept cheap on purpose: a
    /// full recursive byte-size for every listed directory would require
    /// walking entire subtrees on every render, which can freeze the UI on
    /// large directories (`node_modules`, `.git`, `target`, ...).
    pub item_count: Option<usize>,
    /// File extension in lower-case (empty string for directories / no ext).
    pub extension: String,
}

// ── DiskUsage ─────────────────────────────────────────────────────────────────

/// Total and free space (in bytes) for the storage device backing a
/// directory, as reported by the OS (`statvfs` on Unix, `GetDiskFreeSpaceExW`
/// on Windows).
///
/// Obtained via [`crate::fs_util::disk_usage`] and refreshed on every
/// [`crate::FileExplorer::reload`], since navigating across a mount point
/// (e.g. into a different external drive) changes which device applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DiskUsage {
    /// Total capacity of the filesystem, in bytes.
    pub total_bytes: u64,
    /// Space available to the current user, in bytes.
    pub free_bytes: u64,
}

impl DiskUsage {
    /// Bytes currently in use (`total_bytes - free_bytes`, saturating).
    #[must_use]
    pub fn used_bytes(&self) -> u64 {
        self.total_bytes.saturating_sub(self.free_bytes)
    }

    /// Fraction of the filesystem currently in use, in the range `0.0..=1.0`.
    ///
    /// Returns `0.0` when `total_bytes` is zero to avoid dividing by zero.
    #[must_use]
    pub fn used_fraction(&self) -> f64 {
        if self.total_bytes == 0 {
            0.0
        } else {
            self.used_bytes() as f64 / self.total_bytes as f64
        }
    }
}

// ── ExplorerOutcome ───────────────────────────────────────────────────────────

/// Outcome returned by [`crate::FileExplorer::handle_key`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExplorerOutcome {
    /// The user confirmed a file selection — contains the chosen path.
    Selected(PathBuf),
    /// The user dismissed the explorer (`Esc` / `q`) without selecting anything.
    Dismissed,
    /// A key was consumed but produced no navigational outcome yet.
    Pending,
    /// The key was not recognised / consumed by the explorer.
    Unhandled,
    /// A new directory was successfully created at the given path.
    MkdirCreated(PathBuf),
    /// A new empty file was successfully created at the given path.
    TouchCreated(PathBuf),
    /// An entry was successfully renamed.
    RenameCompleted {
        /// The old path.
        from: PathBuf,
        /// The new path.
        to: PathBuf,
    },
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── SortMode ──────────────────────────────────────────────────────────────

    #[test]
    fn sort_mode_default_is_name() {
        assert_eq!(SortMode::default(), SortMode::Name);
    }

    #[test]
    fn sort_mode_next_name_gives_size_desc() {
        assert_eq!(SortMode::Name.next(), SortMode::SizeDesc);
    }

    #[test]
    fn sort_mode_next_size_desc_gives_extension() {
        assert_eq!(SortMode::SizeDesc.next(), SortMode::Extension);
    }

    #[test]
    fn sort_mode_next_extension_wraps_to_name() {
        assert_eq!(SortMode::Extension.next(), SortMode::Name);
    }

    #[test]
    fn sort_mode_full_cycle_returns_to_start() {
        let start = SortMode::Name;
        let cycled = start.next().next().next();
        assert_eq!(cycled, start);
    }

    #[test]
    fn sort_mode_label_name() {
        assert_eq!(SortMode::Name.label(), "name");
    }

    #[test]
    fn sort_mode_label_size_desc() {
        assert_eq!(SortMode::SizeDesc.label(), "size ↓");
    }

    #[test]
    fn sort_mode_label_extension() {
        assert_eq!(SortMode::Extension.label(), "ext");
    }

    #[test]
    fn sort_mode_is_copy() {
        let a = SortMode::Name;
        let b = a;
        assert_eq!(a, b);
    }

    // ── FsEntry ───────────────────────────────────────────────────────────────

    #[test]
    fn fs_entry_construction_file() {
        let entry = FsEntry {
            name: "main.rs".into(),
            path: PathBuf::from("/src/main.rs"),
            is_dir: false,
            size: Some(1024),
            item_count: None,
            extension: "rs".into(),
        };
        assert_eq!(entry.name, "main.rs");
        assert_eq!(entry.path, PathBuf::from("/src/main.rs"));
        assert!(!entry.is_dir);
        assert_eq!(entry.size, Some(1024));
        assert_eq!(entry.extension, "rs");
    }

    #[test]
    fn fs_entry_construction_directory() {
        let entry = FsEntry {
            name: "src".into(),
            path: PathBuf::from("/src"),
            is_dir: true,
            size: None,
            item_count: Some(3),
            extension: String::new(),
        };
        assert!(entry.is_dir);
        assert!(entry.size.is_none());
        assert_eq!(entry.item_count, Some(3));
        assert!(entry.extension.is_empty());
    }

    #[test]
    fn fs_entry_equality() {
        let a = FsEntry {
            name: "a.txt".into(),
            path: PathBuf::from("/a.txt"),
            is_dir: false,
            size: Some(42),
            item_count: None,
            extension: "txt".into(),
        };
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn fs_entry_no_extension_is_empty_string() {
        let entry = FsEntry {
            name: "Makefile".into(),
            path: PathBuf::from("/Makefile"),
            is_dir: false,
            size: Some(256),
            item_count: None,
            extension: String::new(),
        };
        assert!(entry.extension.is_empty());
    }

    // ── DiskUsage ─────────────────────────────────────────────────────────────

    #[test]
    fn disk_usage_used_bytes_computes_difference() {
        let du = DiskUsage {
            total_bytes: 1000,
            free_bytes: 400,
        };
        assert_eq!(du.used_bytes(), 600);
    }

    #[test]
    fn disk_usage_used_bytes_saturates_when_free_exceeds_total() {
        let du = DiskUsage {
            total_bytes: 100,
            free_bytes: 500,
        };
        assert_eq!(du.used_bytes(), 0);
    }

    #[test]
    fn disk_usage_used_fraction_half_full() {
        let du = DiskUsage {
            total_bytes: 1000,
            free_bytes: 500,
        };
        assert!((du.used_fraction() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn disk_usage_used_fraction_zero_total_does_not_panic() {
        let du = DiskUsage {
            total_bytes: 0,
            free_bytes: 0,
        };
        assert_eq!(du.used_fraction(), 0.0);
    }

    #[test]
    fn disk_usage_default_is_zeroed() {
        let du = DiskUsage::default();
        assert_eq!(du.total_bytes, 0);
        assert_eq!(du.free_bytes, 0);
    }

    // ── ExplorerOutcome ───────────────────────────────────────────────────────

    #[test]
    fn explorer_outcome_dismissed_equals_dismissed() {
        assert_eq!(ExplorerOutcome::Dismissed, ExplorerOutcome::Dismissed);
    }

    #[test]
    fn explorer_outcome_pending_equals_pending() {
        assert_eq!(ExplorerOutcome::Pending, ExplorerOutcome::Pending);
    }

    #[test]
    fn explorer_outcome_unhandled_equals_unhandled() {
        assert_eq!(ExplorerOutcome::Unhandled, ExplorerOutcome::Unhandled);
    }

    #[test]
    fn explorer_outcome_selected_carries_path() {
        let path = PathBuf::from("/tmp/file.txt");
        let outcome = ExplorerOutcome::Selected(path.clone());
        assert_eq!(outcome, ExplorerOutcome::Selected(path));
    }

    #[test]
    fn explorer_outcome_selected_neq_dismissed() {
        let outcome = ExplorerOutcome::Selected(PathBuf::from("/tmp/x"));
        assert_ne!(outcome, ExplorerOutcome::Dismissed);
    }

    #[test]
    fn explorer_outcome_is_clone() {
        let a = ExplorerOutcome::Pending;
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn explorer_outcome_rename_completed_carries_path() {
        let path = PathBuf::from("/tmp/renamed.txt");
        let from = PathBuf::from("/tmp/old.txt");
        let outcome = ExplorerOutcome::RenameCompleted {
            from: from.clone(),
            to: path.clone(),
        };
        assert_eq!(outcome, ExplorerOutcome::RenameCompleted { from, to: path });
    }

    #[test]
    fn explorer_outcome_rename_completed_neq_touch_created() {
        let path = PathBuf::from("/tmp/file.txt");
        assert_ne!(
            ExplorerOutcome::RenameCompleted {
                from: path.clone(),
                to: path.clone(),
            },
            ExplorerOutcome::TouchCreated(path),
        );
    }

    #[test]
    fn explorer_outcome_rename_completed_is_clone() {
        let a = ExplorerOutcome::RenameCompleted {
            from: PathBuf::from("/tmp/w.txt"),
            to: PathBuf::from("/tmp/x.txt"),
        };
        let b = a.clone();
        assert_eq!(a, b);
    }
}