ratada 0.4.0

A ratatui widget toolkit: driver, modals, forms, pickers, theming
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
//! User-remappable key bindings: parse chords from config, resolve them
//! against an app's actions, and render them back for the hints footer.
//!
//! An app supplies its own action type (what the keys *do*) by implementing
//! [`Action`]; this module owns everything else - the chord grammar, the
//! defaults-vs-overrides merge, conflict detection, and the display form. That
//! split is the point: the action table is the app's identity, while
//! [`KeyChord::matches`] is the function in which "the modifier comparison gets
//! forgotten", so it should exist exactly once.
//!
//! # Modifier semantics
//!
//! `ctrl` and `alt` are matched **exactly**, never with `contains`. That is
//! what keeps `AltGr` - reported as `Control + Alt`, and a real character on
//! e.g. a German layout - from triggering a `ctrl+…` binding.
//!
//! `shift` depends on the key: for a character it is carried by the character's
//! *case* (`G` is the chord, not `shift+g`) and not compared, because terminals
//! report the shifted character itself. For every other key it is significant,
//! so `left` and `shift+left` are distinct chords and an app can bind both.
//!
//! # Examples
//!
//! ```
//! use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
//! use ratada::keymap::KeyChord;
//!
//! let chord = KeyChord::parse("ctrl+s").expect("a valid chord");
//! assert!(chord.matches(&KeyEvent::new(
//!     KeyCode::Char('s'),
//!     KeyModifiers::CONTROL,
//! )));
//!
//! // `AltGr` is Control+Alt and types a character; it is not a Ctrl chord.
//! assert!(!chord.matches(&KeyEvent::new(
//!     KeyCode::Char('s'),
//!     KeyModifiers::CONTROL | KeyModifiers::ALT,
//! )));
//!
//! // The display form parses back into the same chord.
//! assert_eq!(chord.display(), "ctrl+s");
//! ```

use std::collections::BTreeMap;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{Deserialize, Serialize};

/// The highest function key the chord grammar accepts (`f1`..`f12`).
const MAX_FUNCTION_KEY: u8 = 12;

/// A parsed key chord: a key plus its `ctrl`/`alt`/`shift` modifiers.
///
/// See the [module docs](self#modifier-semantics) for how each modifier is
/// compared - in particular why `shift` is only significant for non-character
/// keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyChord {
    code: KeyCode,
    ctrl: bool,
    alt: bool,
    shift: bool,
}

impl KeyChord {
    /// Parses a chord like `"a"`, `"G"`, `"ctrl+q"`, `"shift+left"`, `"f2"`,
    /// `"pgup"` or `"enter"`, or `None` for an unrecognised string.
    ///
    /// The last `+`-separated token is the key; the ones before it are
    /// modifiers (`ctrl`/`control`, `alt`/`option`, `shift`). A key token is
    /// case-preserving, so `"G"` is the shifted `g`.
    #[must_use]
    pub fn parse(text: &str) -> Option<KeyChord> {
        let parts: Vec<&str> = text
            .split('+')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .collect();
        let (code_token, modifiers) = parts.split_last()?;
        let mut chord = KeyChord {
            code: code_from_token(code_token)?,
            ctrl: false,
            alt: false,
            shift: false,
        };
        for modifier in modifiers {
            match modifier.to_ascii_lowercase().as_str() {
                "ctrl" | "control" => chord.ctrl = true,
                "alt" | "option" => chord.alt = true,
                "shift" => chord.shift = true,
                _ => return None,
            }
        }
        Some(chord)
    }

    /// The chord a pressed key *is*, for rendering a live key as a label.
    ///
    /// The inverse of [`KeyChord::matches`] in the sense that the result always
    /// matches `key`: a character keeps its case and drops `shift` (the case
    /// carries it), any other key keeps `shift` as pressed.
    #[must_use]
    pub fn from_key(key: KeyEvent) -> Self {
        KeyChord {
            code: key.code,
            ctrl: key.modifiers.contains(KeyModifiers::CONTROL),
            alt: key.modifiers.contains(KeyModifiers::ALT),
            shift: !matches!(key.code, KeyCode::Char(_))
                && key.modifiers.contains(KeyModifiers::SHIFT),
        }
    }

    /// Whether `key` triggers this chord.
    ///
    /// `ctrl`/`alt` must match exactly, so `AltGr` (`Control + Alt`) never
    /// stands in for `Control`. `shift` is compared only for a non-character
    /// key; for a character the case already carries it.
    #[must_use]
    pub fn matches(&self, key: &KeyEvent) -> bool {
        if self.code != key.code
            || self.ctrl != key.modifiers.contains(KeyModifiers::CONTROL)
            || self.alt != key.modifiers.contains(KeyModifiers::ALT)
        {
            return false;
        }
        if matches!(self.code, KeyCode::Char(_)) {
            return true;
        }
        self.shift == key.modifiers.contains(KeyModifiers::SHIFT)
    }

    /// The chord's display string, e.g. `ctrl+q`, `shift+left`, `f2`, `G`.
    ///
    /// This is the single rendering of a chord: the hints footer and a config
    /// file show the same text, and it round-trips - [`KeyChord::parse`] of the
    /// result yields the same chord. That contract is why the case is preserved
    /// (`G` must not become `g`, or it collides with the `g` binding) and why
    /// the tokens are the terse ones (`del`, `pgup`) the grammar accepts.
    #[must_use]
    pub fn display(&self) -> String {
        let mut text = String::new();
        if self.ctrl {
            text.push_str("ctrl+");
        }
        if self.alt {
            text.push_str("alt+");
        }
        // A character's shift lives in its case, so spelling it out here would
        // render "shift+G" and no longer parse back to this chord.
        if self.shift && !matches!(self.code, KeyCode::Char(_)) {
            text.push_str("shift+");
        }
        text.push_str(&token_for_code(self.code));
        text
    }

    /// The chord's key, without its modifiers.
    #[must_use]
    pub fn code(&self) -> KeyCode {
        self.code
    }

    /// A key press that triggers this chord: the inverse of
    /// [`KeyChord::from_key`], and always accepted by [`KeyChord::matches`].
    ///
    /// For synthesizing a press - replaying a chord picked from a command
    /// palette, or asserting in a test that a binding resolves back to its
    /// action - without rebuilding the modifiers by hand.
    #[must_use]
    pub fn to_key(&self) -> KeyEvent {
        let mut modifiers = KeyModifiers::NONE;
        if self.ctrl {
            modifiers |= KeyModifiers::CONTROL;
        }
        if self.alt {
            modifiers |= KeyModifiers::ALT;
        }
        if self.shift {
            modifiers |= KeyModifiers::SHIFT;
        }
        KeyEvent::new(self.code, modifiers)
    }
}

/// An app's action type: what its keys do, and how they are named in config.
///
/// The app owns the variants and their defaults; this module owns the chords.
/// Implement it on a small `Copy` enum. `'static` because the descriptions and
/// default keys are `&'static str`, which a fieldless enum satisfies for free.
pub trait Action: Copy + Eq + 'static {
    /// Every action, in the order they claim keys: on a conflict the earlier
    /// one keeps the chord.
    ///
    /// An iterator rather than a slice: an app's actions are typically one
    /// column of a catalog table (`ACTIONS.iter().map(|spec| spec.action)`),
    /// and demanding a `&'static [Self]` would force a second, redundant list
    /// that could drift from the table.
    fn all() -> impl Iterator<Item = Self> + Clone;

    /// The action's key in the config's `[keys]` table.
    fn config_name(&self) -> &'static str;

    /// A one-line description for the help screen.
    fn description(&self) -> &'static str;

    /// The chords bound to it when config says nothing.
    fn default_keys(&self) -> &'static [&'static str];

    /// Whether two actions compete for one chord.
    ///
    /// The default is "always", i.e. one flat map in which a chord belongs to a
    /// single action. An app whose actions are scoped (per view, per focus)
    /// overrides this so two actions in disjoint scopes may share a chord.
    fn overlaps(&self, other: &Self) -> bool {
        let _ = other;
        true
    }

    /// The action a config name refers to, if any.
    fn from_config_name(name: &str) -> Option<Self> {
        Self::all().find(|action| action.config_name() == name)
    }
}

/// A key binding as written in config: one key, or a list of them.
///
/// `#[serde(untagged)]`, so `key = "ctrl+s"` and `key = ["ctrl+s", "f2"]` both
/// deserialize.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum KeyBinding {
    /// A single chord.
    One(String),
    /// Several chords, all triggering the action.
    Many(Vec<String>),
}

impl KeyBinding {
    /// The chords as a list, whichever form was written.
    #[must_use]
    pub fn into_keys(self) -> Vec<String> {
        match self {
            KeyBinding::One(key) => vec![key],
            KeyBinding::Many(keys) => keys,
        }
    }
}

/// A configured key dropped because an earlier action already claimed it.
///
/// Surfaced rather than swallowed, so a silently shadowed binding is visible.
#[derive(Debug, Clone)]
pub struct Conflict<A> {
    /// The contested key, in [`KeyChord::display`] form.
    pub key: String,
    /// The action whose binding was dropped.
    pub action: A,
    /// The action that already owns the key.
    pub claimed_by: A,
}

/// The resolved bindings for an action type.
#[derive(Debug, Clone)]
pub struct Keymap<A> {
    entries: Vec<(KeyChord, A)>,
    conflicts: Vec<Conflict<A>>,
}

impl<A: Action> Default for Keymap<A> {
    /// The compiled-in defaults, i.e. the map an empty config yields.
    fn default() -> Self {
        Self::from_overrides(&BTreeMap::new())
    }
}

impl<A: Action> Keymap<A> {
    /// Builds the map for every action, applying `overrides`.
    ///
    /// An action named in `overrides` uses those keys instead of its defaults.
    /// An unparseable key is logged and skipped; a chord an earlier action
    /// already owns (per [`Action::all`] order, narrowed by
    /// [`Action::overlaps`]) keeps that binding, and the later one is recorded
    /// in [`Keymap::conflicts`].
    #[must_use]
    pub fn from_overrides(overrides: &BTreeMap<String, Vec<String>>) -> Self {
        Self::for_actions(A::all(), overrides)
    }

    /// Like [`Keymap::from_overrides`], but only for `actions`.
    ///
    /// For an app that resolves keys per view or per focus and wants one map
    /// per subset rather than one map plus a scope check. Takes anything
    /// iterable, so a catalog iterator, a `Vec` of a view's actions and a bare
    /// array all fit.
    #[must_use]
    pub fn for_actions(
        actions: impl IntoIterator<Item = A>,
        overrides: &BTreeMap<String, Vec<String>>,
    ) -> Self {
        let mut map = Keymap {
            entries: Vec::new(),
            conflicts: Vec::new(),
        };
        for action in actions {
            for key in override_keys(overrides, action) {
                map.bind(action, &key);
            }
        }
        map
    }

    /// The action bound to `key`, if any.
    #[must_use]
    pub fn action_for(&self, key: &KeyEvent) -> Option<A> {
        self.action_for_where(key, |_| true)
    }

    /// The first action bound to `key` that `allow` accepts.
    ///
    /// For an app whose actions are only live in some contexts (a view, a
    /// focused pane): one map holds every binding, and the caller decides which
    /// are reachable right now. Pair it with an [`Action::overlaps`] that draws
    /// the same line, or two actions sharing a chord across contexts would be
    /// reported as a conflict.
    #[must_use]
    pub fn action_for_where(
        &self,
        key: &KeyEvent,
        allow: impl Fn(&A) -> bool,
    ) -> Option<A> {
        self.entries
            .iter()
            .find(|(chord, action)| allow(action) && chord.matches(key))
            .map(|(_, action)| *action)
    }

    /// The display strings of the keys bound to `action`, in binding order.
    #[must_use]
    pub fn keys_for(&self, action: A) -> Vec<String> {
        self.entries
            .iter()
            .filter(|(_, bound)| *bound == action)
            .map(|(chord, _)| chord.display())
            .collect()
    }

    /// The bindings dropped because an earlier action owned the key.
    #[must_use]
    pub fn conflicts(&self) -> &[Conflict<A>] {
        &self.conflicts
    }

    /// `(keys, description)` hint pairs for `actions`, in the given order,
    /// skipping any action with no bound key.
    ///
    /// The one source for a footer and a help screen: several keys for one
    /// action join with `/` (`"up/k"`), and the keys read exactly as they do in
    /// config, since both come from [`KeyChord::display`]. Feed the result to
    /// `shortcut_hints`.
    #[must_use]
    pub fn hints(&self, actions: &[A]) -> Vec<(String, String)> {
        actions
            .iter()
            .filter_map(|&action| {
                let keys = self.keys_for(action).join("/");
                if keys.is_empty() {
                    return None;
                }
                Some((keys, action.description().to_string()))
            })
            .collect()
    }

    /// Binds `key` to `action`, or records why it was dropped.
    fn bind(&mut self, action: A, key: &str) {
        let Some(chord) = KeyChord::parse(key) else {
            log::warn!("invalid key '{key}' for '{}'", action.config_name());
            return;
        };
        let owner = self.entries.iter().find(|(existing, owner)| {
            *existing == chord && owner.overlaps(&action)
        });
        if let Some((_, owner)) = owner {
            log::warn!(
                "key '{}' for '{}' is already bound to '{}', ignoring",
                chord.display(),
                action.config_name(),
                owner.config_name(),
            );
            self.conflicts.push(Conflict {
                key: chord.display(),
                action,
                claimed_by: *owner,
            });
            return;
        }
        self.entries.push((chord, action));
    }
}

/// Logs every `[keys]` entry that names no action, so a typo in config is not
/// silently ignored.
pub fn warn_unknown<A: Action>(overrides: &BTreeMap<String, Vec<String>>) {
    for name in overrides.keys() {
        if A::from_config_name(name).is_none() {
            log::warn!("unknown key action '{name}' in config, ignoring");
        }
    }
}

/// The keys to use for `action`: the override if config names it, else its
/// defaults.
fn override_keys<A: Action>(
    overrides: &BTreeMap<String, Vec<String>>,
    action: A,
) -> Vec<String> {
    overrides
        .get(action.config_name())
        .cloned()
        .unwrap_or_else(|| {
            action
                .default_keys()
                .iter()
                .map(|key| (*key).to_string())
                .collect()
        })
}

/// Parses a single key token (no modifiers) into a [`KeyCode`].
fn code_from_token(token: &str) -> Option<KeyCode> {
    let lower = token.to_ascii_lowercase();
    let code = match lower.as_str() {
        "enter" | "return" => KeyCode::Enter,
        "esc" | "escape" => KeyCode::Esc,
        "tab" => KeyCode::Tab,
        "backtab" => KeyCode::BackTab,
        "space" => KeyCode::Char(' '),
        "backspace" => KeyCode::Backspace,
        "insert" | "ins" => KeyCode::Insert,
        "up" => KeyCode::Up,
        "down" => KeyCode::Down,
        "left" => KeyCode::Left,
        "right" => KeyCode::Right,
        "pgup" | "pageup" => KeyCode::PageUp,
        "pgdn" | "pgdown" | "pagedown" => KeyCode::PageDown,
        "home" => KeyCode::Home,
        "end" => KeyCode::End,
        "del" | "delete" => KeyCode::Delete,
        _ => return function_or_char(token, &lower),
    };
    Some(code)
}

/// Resolves an `fN` function key or a single character (preserving case).
fn function_or_char(token: &str, lower: &str) -> Option<KeyCode> {
    if let Some(digits) = lower.strip_prefix('f')
        && let Ok(number) = digits.parse::<u8>()
        && (1..=MAX_FUNCTION_KEY).contains(&number)
    {
        return Some(KeyCode::F(number));
    }
    let mut chars = token.chars();
    let first = chars.next()?;
    // More than one remaining char is a word, not a key.
    if chars.next().is_some() {
        return None;
    }
    Some(KeyCode::Char(first))
}

/// The display token for a key code, the inverse of [`code_from_token`].
fn token_for_code(code: KeyCode) -> String {
    match code {
        KeyCode::Char(' ') => "space".to_string(),
        KeyCode::Char(ch) => ch.to_string(),
        KeyCode::Enter => "enter".to_string(),
        KeyCode::Esc => "esc".to_string(),
        KeyCode::Tab => "tab".to_string(),
        KeyCode::BackTab => "backtab".to_string(),
        KeyCode::Backspace => "backspace".to_string(),
        KeyCode::Insert => "insert".to_string(),
        KeyCode::Up => "up".to_string(),
        KeyCode::Down => "down".to_string(),
        KeyCode::Left => "left".to_string(),
        KeyCode::Right => "right".to_string(),
        KeyCode::PageUp => "pgup".to_string(),
        KeyCode::PageDown => "pgdn".to_string(),
        KeyCode::Home => "home".to_string(),
        KeyCode::End => "end".to_string(),
        KeyCode::Delete => "del".to_string(),
        KeyCode::F(number) => format!("f{number}"),
        _ => "?".to_string(),
    }
}

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

    /// A miniature app action set, standing in for a real one.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Act {
        Up,
        Down,
        Quit,
        Extend,
    }

    impl Action for Act {
        fn all() -> impl Iterator<Item = Self> + Clone {
            [Act::Up, Act::Down, Act::Quit, Act::Extend].into_iter()
        }

        fn config_name(&self) -> &'static str {
            match self {
                Act::Up => "up",
                Act::Down => "down",
                Act::Quit => "quit",
                Act::Extend => "extend",
            }
        }

        fn description(&self) -> &'static str {
            "test action"
        }

        fn default_keys(&self) -> &'static [&'static str] {
            match self {
                Act::Up => &["up", "k"],
                Act::Down => &["down", "j"],
                Act::Quit => &["ctrl+q", "q"],
                Act::Extend => &["shift+up"],
            }
        }
    }

    fn event(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, mods)
    }

    fn chord(text: &str) -> KeyChord {
        KeyChord::parse(text).expect("a valid literal chord")
    }

    #[test]
    fn parses_modifiers_keys_and_function_keys() {
        assert_eq!(chord("a").display(), "a");
        assert_eq!(chord("G").display(), "G");
        assert_eq!(chord("ctrl+q").display(), "ctrl+q");
        assert_eq!(chord("control+q").display(), "ctrl+q");
        assert_eq!(chord("alt+up").display(), "alt+up");
        assert_eq!(chord("option+up").display(), "alt+up");
        assert_eq!(chord("shift+left").display(), "shift+left");
        assert_eq!(chord("f2").display(), "f2");
        assert_eq!(chord("pgup").display(), "pgup");
        assert_eq!(chord("pageup").display(), "pgup");
        assert_eq!(chord("space").display(), "space");
        assert_eq!(chord("ctrl+alt+del").display(), "ctrl+alt+del");
    }

    #[test]
    fn rejects_an_unknown_modifier_or_a_word_key() {
        assert!(KeyChord::parse("hyper+a").is_none());
        assert!(KeyChord::parse("cmd+a").is_none());
        assert!(KeyChord::parse("arrows").is_none());
        assert!(KeyChord::parse("f13").is_none());
        assert!(KeyChord::parse("").is_none());
    }

    /// The contract the hints footer and the config file share: whatever is
    /// rendered can be typed back into config and means the same chord.
    #[test]
    fn chords_round_trip_through_parse_and_display() {
        for text in [
            "a",
            "G",
            "ctrl+q",
            "alt+up",
            "shift+left",
            "f2",
            "pgup",
            "pgdn",
            "space",
            "enter",
            "esc",
            "tab",
            "del",
            "home",
            "end",
            "backspace",
            "ctrl+alt+left",
        ] {
            let parsed = chord(text);
            assert_eq!(parsed.display(), text, "{text} must round-trip");
            assert_eq!(chord(&parsed.display()), parsed);
        }
    }

    /// The reason `matches` compares ctrl/alt exactly: `AltGr` is reported as
    /// Control+Alt and produces a real character, so it must never stand in for
    /// a Ctrl chord.
    #[test]
    fn altgr_does_not_trigger_a_ctrl_chord() {
        let ctrl_q = chord("ctrl+q");
        assert!(
            ctrl_q.matches(&event(KeyCode::Char('q'), KeyModifiers::CONTROL))
        );
        assert!(!ctrl_q.matches(&event(
            KeyCode::Char('q'),
            KeyModifiers::CONTROL | KeyModifiers::ALT,
        )));
    }

    #[test]
    fn a_plain_chord_does_not_match_a_modified_key() {
        let plain = chord("q");
        assert!(plain.matches(&event(KeyCode::Char('q'), KeyModifiers::NONE)));
        assert!(
            !plain.matches(&event(KeyCode::Char('q'), KeyModifiers::CONTROL))
        );
        assert!(!plain.matches(&event(KeyCode::Char('q'), KeyModifiers::ALT)));
    }

    /// Shift is significant for a non-character key, so an app can bind `left`
    /// and `shift+left` to different actions.
    #[test]
    fn shift_distinguishes_non_character_chords() {
        let plain = chord("left");
        let shifted = chord("shift+left");
        assert!(plain.matches(&event(KeyCode::Left, KeyModifiers::NONE)));
        assert!(!plain.matches(&event(KeyCode::Left, KeyModifiers::SHIFT)));
        assert!(shifted.matches(&event(KeyCode::Left, KeyModifiers::SHIFT)));
        assert!(!shifted.matches(&event(KeyCode::Left, KeyModifiers::NONE)));
    }

    /// For a character, shift lives in the case: the terminal reports `G`, not
    /// `shift+g`, so the modifier must not be compared or `G` would never fire.
    #[test]
    fn shift_is_ignored_for_a_character_chord() {
        let upper = chord("G");
        assert!(upper.matches(&event(KeyCode::Char('G'), KeyModifiers::SHIFT)));
        assert!(upper.matches(&event(KeyCode::Char('G'), KeyModifiers::NONE)));
        // A different case is a different chord.
        assert!(!upper.matches(&event(KeyCode::Char('g'), KeyModifiers::NONE)));
    }

    #[test]
    fn defaults_resolve_every_action() {
        let map: Keymap<Act> = Keymap::from_overrides(&BTreeMap::new());
        assert!(map.conflicts().is_empty());
        assert_eq!(
            map.action_for(&event(KeyCode::Char('k'), KeyModifiers::NONE)),
            Some(Act::Up)
        );
        assert_eq!(
            map.action_for(&event(KeyCode::Char('q'), KeyModifiers::CONTROL)),
            Some(Act::Quit)
        );
        assert_eq!(map.keys_for(Act::Up), vec!["up", "k"]);
        assert_eq!(
            map.action_for(&event(KeyCode::Char('z'), KeyModifiers::NONE)),
            None
        );
    }

    /// The shift semantics reaching all the way through the map: `up` and
    /// `shift+up` resolve to different actions.
    #[test]
    fn a_shifted_arrow_resolves_to_its_own_action() {
        let map: Keymap<Act> = Keymap::from_overrides(&BTreeMap::new());
        assert_eq!(
            map.action_for(&event(KeyCode::Up, KeyModifiers::NONE)),
            Some(Act::Up)
        );
        assert_eq!(
            map.action_for(&event(KeyCode::Up, KeyModifiers::SHIFT)),
            Some(Act::Extend)
        );
    }

    #[test]
    fn an_override_replaces_the_defaults() {
        let mut overrides = BTreeMap::new();
        overrides.insert("up".to_string(), vec!["ctrl+p".to_string()]);
        let map: Keymap<Act> = Keymap::from_overrides(&overrides);
        assert_eq!(
            map.action_for(&event(KeyCode::Char('p'), KeyModifiers::CONTROL)),
            Some(Act::Up)
        );
        // The default is gone, not merged.
        assert_eq!(
            map.action_for(&event(KeyCode::Char('k'), KeyModifiers::NONE)),
            None
        );
    }

    #[test]
    fn a_contested_key_keeps_the_earlier_action_and_is_reported() {
        let mut overrides = BTreeMap::new();
        overrides.insert("down".to_string(), vec!["k".to_string()]);
        let map: Keymap<Act> = Keymap::from_overrides(&overrides);
        // `Up` claims `k` first (it comes first in `all`).
        assert_eq!(
            map.action_for(&event(KeyCode::Char('k'), KeyModifiers::NONE)),
            Some(Act::Up)
        );
        let conflicts = map.conflicts();
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].key, "k");
        assert_eq!(conflicts[0].action, Act::Down);
        assert_eq!(conflicts[0].claimed_by, Act::Up);
    }

    #[test]
    fn an_unparseable_override_is_skipped_not_fatal() {
        let mut overrides = BTreeMap::new();
        overrides.insert(
            "quit".to_string(),
            vec!["nonsense+x".to_string(), "f4".to_string()],
        );
        let map: Keymap<Act> = Keymap::from_overrides(&overrides);
        // The bad key is dropped; the good one still binds.
        assert_eq!(
            map.action_for(&event(KeyCode::F(4), KeyModifiers::NONE)),
            Some(Act::Quit)
        );
    }

    /// A scoped app keeps every binding in one map and narrows the lookup, so
    /// the same chord can mean two things in two contexts.
    #[test]
    fn action_for_where_narrows_the_lookup() {
        let mut overrides = BTreeMap::new();
        // Both want `x`; `Up` claims it, `Down`'s is a conflict under the
        // default `overlaps`, so only `Up` is reachable.
        overrides.insert("up".to_string(), vec!["x".to_string()]);
        let map: Keymap<Act> = Keymap::from_overrides(&overrides);
        let key = event(KeyCode::Char('x'), KeyModifiers::NONE);
        assert_eq!(map.action_for(&key), Some(Act::Up));
        // Excluding the owner leaves nothing rather than falling through.
        assert_eq!(map.action_for_where(&key, |a| *a != Act::Up), None);
    }

    #[test]
    fn for_actions_restricts_the_map_to_a_subset() {
        let map: Keymap<Act> =
            Keymap::for_actions([Act::Quit], &BTreeMap::new());
        assert_eq!(
            map.action_for(&event(KeyCode::Char('q'), KeyModifiers::NONE)),
            Some(Act::Quit)
        );
        assert_eq!(
            map.action_for(&event(KeyCode::Char('k'), KeyModifiers::NONE)),
            None
        );
    }

    /// `to_key` and `from_key` are inverses, and what `to_key` builds is always
    /// a press the chord accepts - that is what makes it safe to replay.
    #[test]
    fn to_key_round_trips_and_always_matches() {
        for text in ["a", "G", "ctrl+q", "alt+up", "shift+left", "f2", "space"]
        {
            let parsed = chord(text);
            let key = parsed.to_key();
            assert!(parsed.matches(&key), "{text} must match its own key");
            assert_eq!(KeyChord::from_key(key), parsed, "{text} round-trips");
        }
    }

    #[test]
    fn hints_join_several_keys_and_skip_unbound_actions() {
        let mut overrides = BTreeMap::new();
        // Binding an action to nothing leaves it out of the hints.
        overrides.insert("quit".to_string(), Vec::new());
        let map: Keymap<Act> = Keymap::from_overrides(&overrides);
        assert_eq!(
            map.hints(&[Act::Up, Act::Quit]),
            vec![("up/k".to_string(), "test action".to_string())]
        );
    }

    #[test]
    fn from_config_name_resolves_every_action() {
        for action in Act::all() {
            assert_eq!(
                Act::from_config_name(action.config_name()),
                Some(action)
            );
        }
        assert_eq!(Act::from_config_name("nope"), None);
    }

    #[test]
    fn a_key_binding_reads_both_the_scalar_and_the_list_form() {
        assert_eq!(
            KeyBinding::One("ctrl+s".to_string()).into_keys(),
            vec!["ctrl+s".to_string()]
        );
        assert_eq!(
            KeyBinding::Many(vec!["a".to_string(), "b".to_string()])
                .into_keys(),
            vec!["a".to_string(), "b".to_string()]
        );
    }
}