ite-cli 0.1.0

Interactive terminal tree explorer for filesystems and JSON
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
//! Application state: focus/expansion driven by app commands and keybindings.

use std::collections::HashMap;
use std::ffi::OsString;

use tui_treelistview::{TreeListViewState, TreeQuery};

use crate::cli::ExpandSpec;
use crate::config::{AppCommand, Binding, BindingAction, Config};
use crate::jump::{Jump, JumpOutcome};
use crate::keys::Key;
use crate::tree::{NodeId, Tree};

/// What the event loop must do after a key is handled.
#[derive(Clone, PartialEq, Debug)]
pub enum Effect {
    None,
    /// Exit without output.
    Quit,
    /// The default action: print the node's source-specific value and exit.
    PrintAndExit(OsString),
    /// Run a configured shell command on the focused node.
    RunShell {
        cmd: String,
        path: OsString,
        relpath: OsString,
        bg: bool,
        exit: bool,
    },
}

/// The app's input mode. `Normal` drives the tree via the keymap; other modes
/// take over key handling and rendering until they close. Adding a mode is a
/// new variant plus one dispatch arm in `handle_key` and one in `ui::draw`.
pub enum Mode {
    Normal,
    Jump(Jump),
}

pub struct App {
    pub tree: Tree,
    pub state: TreeListViewState<NodeId>,
    pub query: TreeQuery,
    /// The current input mode; see [`Mode`].
    pub mode: Mode,
    keymap: HashMap<Key, Binding>,
    /// True after a bare `g`, waiting for the second `g` of the chord.
    pending_g: bool,
    /// Rows per screen; the UI updates this every frame.
    pub page_height: usize,
    /// Terminal default colors, when the terminal answered the startup query.
    pub palette: Option<crate::ui::Palette>,
}

impl App {
    pub fn new(tree: Tree, config: &Config, expand: Option<ExpandSpec>) -> Self {
        let mut keymap = Self::default_keymap();
        keymap.extend(config.bindings.clone());
        let mut app = Self {
            tree,
            state: TreeListViewState::with_capacity(0),
            query: TreeQuery::new(),
            mode: Mode::Normal,
            keymap,
            pending_g: false,
            page_height: 20,
            palette: None,
        };
        match expand {
            None => {}
            Some(ExpandSpec::All) => {
                let branches: Vec<_> = app.tree.branches().collect();
                for (id, parent) in branches {
                    app.state.set_expanded(id, parent, true);
                }
            }
            Some(ExpandSpec::Depth(n)) => {
                let branches: Vec<_> = app.tree.branches().collect();
                for (id, parent) in branches {
                    if app.tree.node(id).depth < n {
                        app.state.set_expanded(id, parent, true);
                    }
                }
            }
        }
        app.state.ensure_projection(&app.tree, &app.query);
        app.state.select_first();
        app
    }

    /// The default keybindings, before user config is merged.
    pub fn default_keymap() -> HashMap<Key, Binding> {
        let cmd = |action: AppCommand| Binding {
            action: BindingAction::Cmd(action),
            exit: false,
            bg: false,
        };
        let mut map = HashMap::new();
        for (keys, action) in [
            (&["j", "down"][..], AppCommand::Down),
            (&["k", "up"], AppCommand::Up),
            (&["l", "right"], AppCommand::Expand),
            (&["h", "left"], AppCommand::Collapse),
            (&["L", "shift+right"], AppCommand::ExpandRecursively),
            (&["H", "shift+left"], AppCommand::CollapseRecursively),
            (&["enter"], AppCommand::Select),
            (&["ctrl+enter"], AppCommand::Accept),
            (&["alt+enter"], AppCommand::AcceptAlternate),
            (&["tab"], AppCommand::Descend),
            (&["J"], AppCommand::NextSibling),
            (&["K"], AppCommand::PrevSibling),
            (&["ctrl+f"], AppCommand::PageDown),
            (&["ctrl+b"], AppCommand::PageUp),
            (&["ctrl+d"], AppCommand::HalfPageDown),
            (&["ctrl+u"], AppCommand::HalfPageUp),
            (&["G"], AppCommand::Last),
            (&["/"], AppCommand::Jump),
            (&["q", "esc", "ctrl+c"], AppCommand::Quit),
        ] {
            for key in keys {
                map.insert(Key::parse(key).expect("valid default key"), cmd(action));
            }
        }
        map
    }

    pub fn focused_id(&mut self) -> Option<NodeId> {
        self.state.ensure_projection(&self.tree, &self.query);
        self.state.selected_id()
    }

    /// Names of currently visible rows, in on-screen order.
    pub fn visible_names(&mut self) -> Vec<String> {
        self.state.ensure_projection(&self.tree, &self.query);
        self.state
            .visible_ids()
            .map(|id| self.tree.node(id).name.clone())
            .collect()
    }

    /// Handle a normalized key, resolving chords and the keymap.
    pub fn handle_key(&mut self, key: Key) -> Effect {
        let _span = crate::profile::span("app::handle_key");
        // A modal picker takes over key handling until it closes. Accepting
        // moves focus (expanding ancestors); cancelling leaves focus untouched,
        // so the user returns to exactly where they opened it.
        if let Mode::Jump(jump) = &mut self.mode {
            return match jump.handle_key(key) {
                JumpOutcome::Stay => Effect::None,
                JumpOutcome::Cancel => {
                    self.mode = Mode::Normal;
                    Effect::None
                }
                JumpOutcome::Accept(id) => {
                    self.mode = Mode::Normal;
                    self.state.select_by_id(&self.tree, &self.query, id);
                    Effect::None
                }
            };
        }
        let g = Key::parse("g").unwrap();
        if self.pending_g {
            self.pending_g = false;
            if key == g {
                return self.run_command(AppCommand::First);
            }
            // fall through: the second key is handled normally
        } else if key == g && !self.keymap.contains_key(&g) {
            self.pending_g = true;
            return Effect::None;
        }
        match self.keymap.get(&key).cloned() {
            None => Effect::None,
            Some(binding) => match binding.action {
                BindingAction::Cmd(cmd) => self.run_command(cmd),
                BindingAction::Sh(cmd) => match self.focused_id() {
                    None => Effect::None,
                    Some(id) => Effect::RunShell {
                        cmd,
                        path: self.tree.node(id).action.path.clone(),
                        relpath: self.tree.node(id).action.relpath.clone(),
                        bg: binding.bg,
                        exit: binding.exit,
                    },
                },
            },
        }
    }

    /// Execute an app command.
    pub fn run_command(&mut self, cmd: AppCommand) -> Effect {
        self.state.ensure_projection(&self.tree, &self.query);
        match cmd {
            AppCommand::Down => {
                self.state.select_next();
            }
            AppCommand::Up => {
                self.state.select_prev();
            }
            AppCommand::Expand => {
                if let Some(id) = self.focused_branch() {
                    let parent = self.tree.node(id).parent;
                    if self.state.node_is_expanded(id, parent) {
                        self.state.select_id(Some(self.tree.node(id).children[0]));
                    } else {
                        self.state.set_expanded(id, parent, true);
                    }
                }
            }
            AppCommand::Collapse => {
                if let Some(id) = self.focused_id() {
                    let parent = self.tree.node(id).parent;
                    if !self.tree.is_leaf(id) && self.state.node_is_expanded(id, parent) {
                        self.state.set_expanded(id, parent, false);
                    } else if let Some(parent) = parent {
                        self.state.select_id(Some(parent));
                    }
                }
            }
            AppCommand::ExpandRecursively => self.set_expanded_recursively(true),
            AppCommand::CollapseRecursively => self.set_expanded_recursively(false),
            AppCommand::Select => {
                if let Some(id) = self.focused_id() {
                    if self.tree.is_leaf(id) {
                        return Effect::PrintAndExit(self.tree.node(id).action.output.clone());
                    }
                    self.state.set_expanded(id, self.tree.node(id).parent, true);
                }
            }
            AppCommand::Accept => {
                if let Some(id) = self.focused_id() {
                    return Effect::PrintAndExit(self.tree.node(id).action.output.clone());
                }
            }
            AppCommand::AcceptAlternate => {
                if let Some(id) = self.focused_id() {
                    return Effect::PrintAndExit(
                        self.tree.node(id).action.alternate_output.clone(),
                    );
                }
            }
            AppCommand::Descend => {
                if let Some(id) = self.focused_branch() {
                    self.state.set_expanded(id, self.tree.node(id).parent, true);
                    self.state.ensure_projection(&self.tree, &self.query);
                    let first_child = self.tree.node(id).children[0];
                    self.state.select_id(Some(first_child));
                }
            }
            AppCommand::NextSibling => self.move_sibling(1),
            AppCommand::PrevSibling => self.move_sibling(-1),
            AppCommand::PageDown => self.move_focus_by(self.page_height as isize),
            AppCommand::PageUp => self.move_focus_by(-(self.page_height as isize)),
            AppCommand::HalfPageDown => self.move_focus_by((self.page_height / 2) as isize),
            AppCommand::HalfPageUp => self.move_focus_by(-((self.page_height / 2) as isize)),
            AppCommand::First => {
                self.state.select_first();
            }
            AppCommand::Last => {
                self.state.select_last();
            }
            AppCommand::Jump => {
                self.mode = Mode::Jump(Jump::open(&self.tree));
            }
            AppCommand::Quit => return Effect::Quit,
        }
        Effect::None
    }

    /// The focused node if it is expandable.
    fn focused_branch(&mut self) -> Option<NodeId> {
        self.focused_id().filter(|&id| !self.tree.is_leaf(id))
    }

    fn set_expanded_recursively(&mut self, expanded: bool) {
        let Some(root) = self.focused_id() else {
            return;
        };
        let mut stack = vec![root];
        while let Some(id) = stack.pop() {
            if !self.tree.is_leaf(id) {
                self.state
                    .set_expanded(id, self.tree.node(id).parent, expanded);
                stack.extend_from_slice(&self.tree.node(id).children);
            }
        }
    }

    fn move_sibling(&mut self, delta: isize) {
        let Some(id) = self.focused_id() else { return };
        let siblings = match self.tree.node(id).parent {
            Some(parent) => self.tree.node(parent).children.as_slice(),
            None => self.tree.root_ids(),
        };
        let pos = siblings.iter().position(|&s| s == id).unwrap_or(0) as isize;
        let target = pos + delta;
        if (0..siblings.len() as isize).contains(&target) {
            let target = siblings[target as usize];
            self.state.select_id(Some(target));
        }
    }

    fn move_focus_by(&mut self, delta: isize) {
        let len = self.state.visible_len();
        if len == 0 {
            return;
        }
        let current = self.state.selected_index().unwrap_or(0) as isize;
        let target = (current + delta).clamp(0, len as isize - 1);
        self.state.select_index(Some(target as usize));
    }
}

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

    /// Builds:
    ///   root/
    ///     a/
    ///       aa/
    ///         aaa.txt
    ///       ab.txt
    ///     b/
    ///       ba.txt
    ///     c.txt
    fn fixture() -> (tempfile::TempDir, Tree) {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path();
        std::fs::create_dir_all(p.join("a/aa")).unwrap();
        std::fs::write(p.join("a/aa/aaa.txt"), "").unwrap();
        std::fs::write(p.join("a/ab.txt"), "").unwrap();
        std::fs::create_dir(p.join("b")).unwrap();
        std::fs::write(p.join("b/ba.txt"), "").unwrap();
        std::fs::write(p.join("c.txt"), "").unwrap();
        let tree = fstree::scan(p, false).unwrap();
        (dir, tree)
    }

    fn app() -> (tempfile::TempDir, App) {
        let (dir, tree) = fixture();
        (dir, App::new(tree, &Config::default(), None))
    }

    fn focused_name(app: &mut App) -> String {
        let id = app.focused_id().expect("something focused");
        app.tree.node(id).name.clone()
    }

    #[test]
    fn starts_focused_on_first_row_all_collapsed() {
        let (_d, mut app) = app();
        assert_eq!(app.visible_names(), ["a", "b", "c.txt"]);
        assert_eq!(focused_name(&mut app), "a");
    }

    #[test]
    fn down_and_up_move_focus_clamped() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Down);
        assert_eq!(focused_name(&mut app), "b");
        app.run_command(AppCommand::Down);
        assert_eq!(focused_name(&mut app), "c.txt");
        app.run_command(AppCommand::Down);
        assert_eq!(focused_name(&mut app), "c.txt");
        app.run_command(AppCommand::Up);
        assert_eq!(focused_name(&mut app), "b");
    }

    #[test]
    fn expand_reveals_children_and_down_enters_them() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Expand);
        assert_eq!(app.visible_names(), ["a", "aa", "ab.txt", "b", "c.txt"]);
        app.run_command(AppCommand::Down);
        assert_eq!(focused_name(&mut app), "aa");
    }

    #[test]
    fn l_on_expanded_branch_descends_to_first_child() {
        let (_d, mut app) = app();
        app.handle_key(Key::parse("l").unwrap());

        app.handle_key(Key::parse("l").unwrap());

        assert_eq!(focused_name(&mut app), "aa");
    }

    #[test]
    fn expand_is_noop_on_leaf() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Last);
        assert_eq!(focused_name(&mut app), "c.txt");
        assert_eq!(app.run_command(AppCommand::Expand), Effect::None);
        assert_eq!(app.visible_names(), ["a", "b", "c.txt"]);
    }

    #[test]
    fn collapse_hides_children() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Expand);
        app.run_command(AppCommand::Collapse);
        assert_eq!(app.visible_names(), ["a", "b", "c.txt"]);
    }

    #[test]
    fn h_on_leaf_focuses_parent_without_collapsing_it() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Expand);
        app.run_command(AppCommand::Down); // focus collapsed "aa"
        app.run_command(AppCommand::Expand);
        app.run_command(AppCommand::Down); // focus "aaa.txt"

        app.handle_key(Key::parse("h").unwrap());

        assert_eq!(focused_name(&mut app), "aa");
        assert_eq!(
            app.visible_names(),
            ["a", "aa", "aaa.txt", "ab.txt", "b", "c.txt"]
        );
    }

    #[test]
    fn h_on_collapsed_branch_focuses_parent_without_collapsing_it() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Expand);
        app.run_command(AppCommand::Down); // focus collapsed "aa"

        app.handle_key(Key::parse("h").unwrap());

        assert_eq!(focused_name(&mut app), "a");
        assert_eq!(app.visible_names(), ["a", "aa", "ab.txt", "b", "c.txt"]);
    }

    #[test]
    fn expand_recursively_expands_whole_subtree() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::ExpandRecursively);
        assert_eq!(
            app.visible_names(),
            ["a", "aa", "aaa.txt", "ab.txt", "b", "c.txt"]
        );
    }

    #[test]
    fn collapse_recursively_collapses_whole_subtree() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::ExpandRecursively);
        app.run_command(AppCommand::CollapseRecursively);
        assert_eq!(app.visible_names(), ["a", "b", "c.txt"]);
        // Descendant expansion was cleared, not just hidden.
        app.run_command(AppCommand::Expand);
        assert_eq!(app.visible_names(), ["a", "aa", "ab.txt", "b", "c.txt"]);
    }

    #[test]
    fn select_expands_collapsed_dir_and_prints_leaf() {
        let (_d, mut app) = app();
        assert_eq!(app.run_command(AppCommand::Select), Effect::None);
        assert_eq!(app.visible_names(), ["a", "aa", "ab.txt", "b", "c.txt"]);
        app.run_command(AppCommand::Last);
        let effect = app.run_command(AppCommand::Select);
        let Effect::PrintAndExit(path) = effect else {
            panic!("expected PrintAndExit, got {effect:?}");
        };
        assert!(std::path::Path::new(&path).is_absolute());
        assert!(std::path::Path::new(&path).ends_with("c.txt"));
    }

    #[test]
    fn select_does_not_descend_into_an_expanded_branch() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Select);

        app.run_command(AppCommand::Select);

        assert_eq!(focused_name(&mut app), "a");
    }

    #[test]
    fn accept_prints_even_on_dir() {
        let (_d, mut app) = app();
        let effect = app.run_command(AppCommand::Accept);
        let Effect::PrintAndExit(path) = effect else {
            panic!("expected PrintAndExit, got {effect:?}");
        };
        assert!(std::path::Path::new(&path).ends_with("a"));
    }

    #[test]
    fn alt_enter_prints_the_filesystem_basename() {
        let (_d, mut app) = app();

        assert_eq!(
            app.handle_key(Key::parse("alt+enter").unwrap()),
            Effect::PrintAndExit(OsString::from("a"))
        );
    }

    #[test]
    fn descend_expands_and_focuses_first_child() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Descend);
        assert_eq!(focused_name(&mut app), "aa");
    }

    #[test]
    fn sibling_navigation_skips_expanded_children() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Expand); // "a" expanded, children visible
        app.run_command(AppCommand::NextSibling);
        assert_eq!(focused_name(&mut app), "b");
        app.run_command(AppCommand::PrevSibling);
        assert_eq!(focused_name(&mut app), "a");
        // No previous sibling: no-op.
        app.run_command(AppCommand::PrevSibling);
        assert_eq!(focused_name(&mut app), "a");
    }

    #[test]
    fn first_and_last() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Last);
        assert_eq!(focused_name(&mut app), "c.txt");
        app.run_command(AppCommand::First);
        assert_eq!(focused_name(&mut app), "a");
    }

    #[test]
    fn paging_moves_focus_by_page_amounts() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::ExpandRecursively); // 6 visible rows
        app.page_height = 4;
        app.run_command(AppCommand::HalfPageDown);
        assert_eq!(focused_name(&mut app), "aaa.txt"); // moved 2
        app.run_command(AppCommand::PageDown);
        assert_eq!(focused_name(&mut app), "c.txt"); // clamped at end
        app.run_command(AppCommand::HalfPageUp);
        assert_eq!(focused_name(&mut app), "ab.txt");
        app.run_command(AppCommand::PageUp);
        assert_eq!(focused_name(&mut app), "a");
    }

    #[test]
    fn default_keys_drive_commands() {
        let (_d, mut app) = app();
        app.handle_key(Key::parse("j").unwrap());
        assert_eq!(focused_name(&mut app), "b");
        app.handle_key(Key::parse("k").unwrap());
        assert_eq!(focused_name(&mut app), "a");
        app.handle_key(Key::parse("l").unwrap());
        assert_eq!(app.visible_names().len(), 5);
        app.handle_key(Key::parse("h").unwrap());
        assert_eq!(app.visible_names().len(), 3);
        assert_eq!(app.handle_key(Key::parse("q").unwrap()), Effect::Quit);
        assert_eq!(app.handle_key(Key::parse("esc").unwrap()), Effect::Quit);
        assert_eq!(app.handle_key(Key::parse("ctrl+c").unwrap()), Effect::Quit);
    }

    #[test]
    fn gg_chord_goes_to_first_line() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Last);
        assert_eq!(app.handle_key(Key::parse("g").unwrap()), Effect::None);
        app.handle_key(Key::parse("g").unwrap());
        assert_eq!(focused_name(&mut app), "a");
        // A non-g key cancels the pending chord.
        app.run_command(AppCommand::Last);
        app.handle_key(Key::parse("g").unwrap());
        app.handle_key(Key::parse("j").unwrap());
        assert_eq!(focused_name(&mut app), "c.txt");
    }

    #[test]
    fn shift_g_goes_to_last_visible_line() {
        let (_d, mut app) = app();
        app.handle_key(Key::parse("G").unwrap());
        assert_eq!(focused_name(&mut app), "c.txt");
    }

    #[test]
    fn user_binding_produces_shell_effect_with_paths() {
        let (_d, tree) = fixture();
        let config = Config::parse("[ctrl+e]\nsh = \"vim $path\"\nexit = true\n").unwrap();
        let mut app = App::new(tree, &config, None);
        app.run_command(AppCommand::Down); // focus "b"
        let effect = app.handle_key(Key::parse("ctrl+e").unwrap());
        let Effect::RunShell {
            cmd,
            path,
            relpath,
            bg,
            exit,
        } = effect
        else {
            panic!("expected RunShell, got {effect:?}");
        };
        assert_eq!(cmd, "vim $path");
        assert!(std::path::Path::new(&path).is_absolute());
        assert!(std::path::Path::new(&path).ends_with("b"));
        assert_eq!(relpath, OsString::from("b"));
        assert!(!bg);
        assert!(exit);
    }

    #[test]
    fn user_binding_overrides_default() {
        let (_d, tree) = fixture();
        let config = Config::parse("[j]\ncmd = \"quit\"\n").unwrap();
        let mut app = App::new(tree, &config, None);
        assert_eq!(app.handle_key(Key::parse("j").unwrap()), Effect::Quit);
    }

    #[test]
    fn unbound_key_is_noop() {
        let (_d, mut app) = app();
        assert_eq!(app.handle_key(Key::parse("x").unwrap()), Effect::None);
    }

    #[test]
    fn initial_expand_depth_one_expands_top_level_only() {
        let (_d, tree) = fixture();
        let mut app = App::new(tree, &Config::default(), Some(ExpandSpec::Depth(1)));
        assert_eq!(
            app.visible_names(),
            ["a", "aa", "ab.txt", "b", "ba.txt", "c.txt"]
        );
    }

    #[test]
    fn initial_expand_all_expands_everything() {
        let (_d, tree) = fixture();
        let mut app = App::new(tree, &Config::default(), Some(ExpandSpec::All));
        assert_eq!(
            app.visible_names(),
            ["a", "aa", "aaa.txt", "ab.txt", "b", "ba.txt", "c.txt"]
        );
    }

    fn in_jump(app: &App) -> bool {
        matches!(app.mode, Mode::Jump(_))
    }

    #[test]
    fn slash_opens_the_jump_picker() {
        let (_d, mut app) = app();
        assert!(!in_jump(&app));
        app.handle_key(Key::parse("/").unwrap());
        assert!(in_jump(&app));
    }

    #[test]
    fn cancelling_the_picker_leaves_focus_untouched() {
        let (_d, mut app) = app();
        app.run_command(AppCommand::Down); // focus "b"
        assert_eq!(focused_name(&mut app), "b");
        app.handle_key(Key::parse("/").unwrap());
        app.handle_key(Key::parse("a").unwrap()); // type into the query
        app.handle_key(Key::parse("esc").unwrap());
        assert!(!in_jump(&app));
        assert_eq!(focused_name(&mut app), "b");
    }

    #[test]
    fn accepting_jumps_focus_and_expands_ancestors() {
        let (_d, mut app) = app();
        // Everything starts collapsed: only the top level is visible.
        assert_eq!(app.visible_names(), ["a", "b", "c.txt"]);
        app.handle_key(Key::parse("/").unwrap());
        for k in ["a", "a", "a"] {
            app.handle_key(Key::parse(k).unwrap()); // query "aaa" -> a/aa/aaa.txt
        }
        app.handle_key(Key::parse("enter").unwrap());
        assert!(!in_jump(&app));
        assert_eq!(focused_name(&mut app), "aaa.txt");
        // The path to it was expanded so the focused node is visible.
        assert!(app.visible_names().contains(&"aaa.txt".to_string()));
    }

    #[test]
    fn a_user_can_rebind_jump_off_slash() {
        let (_d, tree) = fixture();
        let config = Config::parse("[ctrl+p]\ncmd = \"jump\"\n").unwrap();
        let mut app = App::new(tree, &config, None);
        app.handle_key(Key::parse("ctrl+p").unwrap());
        assert!(in_jump(&app));
    }
}