aboutsummaryrefslogtreecommitdiffstats
path: root/crates/turtle/src/command/client/search/keybindings/keymap.rs
blob: 067d940382b7a4cbb73005f86573620066d0b6f7 (plain) (blame)
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
use std::collections::HashMap;

use super::actions::Action;
use super::conditions::{ConditionExpr, EvalContext};
use super::key::{KeyInput, SingleKey};

/// A single rule within a keybinding: an optional condition and an action.
/// If the condition is `None`, the rule always matches.
#[derive(Debug, Clone)]
pub(crate) struct KeyRule {
    pub(crate) condition: Option<ConditionExpr>,
    pub(crate) action: Action,
}

/// A keybinding is an ordered list of rules. The first rule whose condition
/// matches (or has no condition) wins.
#[derive(Debug, Clone)]
pub(crate) struct KeyBinding {
    pub(crate) rules: Vec<KeyRule>,
}

/// A keymap is a collection of keybindings indexed by key input.
#[derive(Debug, Clone)]
pub(crate) struct Keymap {
    pub(crate) bindings: HashMap<KeyInput, KeyBinding>,
}

impl KeyRule {
    /// Create an unconditional rule.
    pub(crate) fn always(action: Action) -> Self {
        Self {
            condition: None,
            action,
        }
    }

    /// Create a conditional rule. Accepts any type convertible to `ConditionExpr`,
    /// including bare `ConditionAtom` values.
    pub(crate) fn when(condition: impl Into<ConditionExpr>, action: Action) -> Self {
        Self {
            condition: Some(condition.into()),
            action,
        }
    }
}

impl KeyBinding {
    /// Create a simple (unconditional) binding.
    pub(crate) fn simple(action: Action) -> Self {
        Self {
            rules: vec![KeyRule::always(action)],
        }
    }

    /// Create a conditional binding from a list of rules.
    pub(crate) fn conditional(rules: Vec<KeyRule>) -> Self {
        Self { rules }
    }
}

impl Keymap {
    /// Create an empty keymap.
    pub(crate) fn new() -> Self {
        Self {
            bindings: HashMap::new(),
        }
    }

    /// Bind a key input to a simple (unconditional) action.
    pub(crate) fn bind(&mut self, key: KeyInput, action: Action) {
        self.bindings.insert(key, KeyBinding::simple(action));
    }

    /// Bind a key input to a conditional set of rules.
    pub(crate) fn bind_conditional(&mut self, key: KeyInput, rules: Vec<KeyRule>) {
        self.bindings.insert(key, KeyBinding::conditional(rules));
    }

    /// Resolve a key input to an action given the current evaluation context.
    /// Returns `None` if the key has no binding or no rule's condition matches.
    pub(crate) fn resolve(&self, key: &KeyInput, ctx: &EvalContext) -> Option<Action> {
        let binding = self.bindings.get(key)?;
        for rule in &binding.rules {
            match &rule.condition {
                None => return Some(rule.action.clone()),
                Some(cond) if cond.evaluate(ctx) => return Some(rule.action.clone()),
                Some(_) => {}
            }
        }
        None
    }

    /// Check if any binding starts with the given single key as the first key
    /// of a multi-key sequence. Used to detect pending multi-key sequences.
    pub(crate) fn has_sequence_starting_with(&self, prefix: &SingleKey) -> bool {
        self.bindings.keys().any(|ki| match ki {
            KeyInput::Sequence(keys) => keys.first() == Some(prefix),
            KeyInput::Single(_) => false,
        })
    }

    /// Merge another keymap into this one. Keys from `other` override keys in `self`.
    #[expect(dead_code)]
    pub(crate) fn merge(&mut self, other: &Self) {
        for (key, binding) in &other.bindings {
            self.bindings.insert(key.clone(), binding.clone());
        }
    }
}

impl Default for Keymap {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::super::conditions::ConditionAtom;
    use super::{Action, EvalContext, KeyInput, KeyRule, Keymap, SingleKey};

    fn make_ctx(cursor: usize, width: usize, selected: usize, len: usize) -> EvalContext {
        EvalContext {
            cursor_position: cursor,
            input_width: width,
            input_byte_len: width,
            selected_index: selected,
            results_len: len,
            original_input_empty: false,
            has_context: false,
        }
    }

    #[test]
    fn simple_binding_resolves() {
        let mut keymap = Keymap::new();
        let key = KeyInput::parse("ctrl-c").unwrap();
        keymap.bind(key.clone(), Action::ReturnOriginal);

        let ctx = make_ctx(0, 0, 0, 10);
        assert_eq!(keymap.resolve(&key, &ctx), Some(Action::ReturnOriginal));
    }

    #[test]
    fn conditional_first_match_wins() {
        let mut keymap = Keymap::new();
        let key = KeyInput::parse("left").unwrap();
        keymap.bind_conditional(
            key.clone(),
            vec![
                KeyRule::when(ConditionAtom::CursorAtStart, Action::Exit),
                KeyRule::always(Action::CursorLeft),
            ],
        );

        // Cursor at start → Exit
        let ctx = make_ctx(0, 5, 0, 10);
        assert_eq!(keymap.resolve(&key, &ctx), Some(Action::Exit));

        // Cursor not at start → CursorLeft
        let ctx = make_ctx(3, 5, 0, 10);
        assert_eq!(keymap.resolve(&key, &ctx), Some(Action::CursorLeft));
    }

    #[test]
    fn no_match_returns_none() {
        let keymap = Keymap::new();
        let key = KeyInput::parse("ctrl-c").unwrap();
        let ctx = make_ctx(0, 0, 0, 0);
        assert_eq!(keymap.resolve(&key, &ctx), None);
    }

    #[test]
    fn conditional_no_condition_matches_returns_none() {
        let mut keymap = Keymap::new();
        let key = KeyInput::parse("left").unwrap();
        // Only one rule with a condition that won't match
        keymap.bind_conditional(
            key.clone(),
            vec![KeyRule::when(ConditionAtom::CursorAtStart, Action::Exit)],
        );

        // Cursor not at start → no match
        let ctx = make_ctx(3, 5, 0, 10);
        assert_eq!(keymap.resolve(&key, &ctx), None);
    }

    #[test]
    fn has_sequence_starting_with() {
        let mut keymap = Keymap::new();
        let seq = KeyInput::parse("g g").unwrap();
        keymap.bind(seq, Action::ScrollToTop);

        let g = SingleKey::parse("g").unwrap();
        assert!(keymap.has_sequence_starting_with(&g));

        let h = SingleKey::parse("h").unwrap();
        assert!(!keymap.has_sequence_starting_with(&h));
    }

    #[test]
    fn merge_overrides() {
        let mut base = Keymap::new();
        let key = KeyInput::parse("ctrl-c").unwrap();
        base.bind(key.clone(), Action::ReturnOriginal);

        let mut overlay = Keymap::new();
        overlay.bind(key.clone(), Action::Exit);

        base.merge(&overlay);

        let ctx = make_ctx(0, 0, 0, 0);
        assert_eq!(base.resolve(&key, &ctx), Some(Action::Exit));
    }

    #[test]
    fn merge_preserves_unoverridden() {
        let mut base = Keymap::new();
        let key1 = KeyInput::parse("ctrl-c").unwrap();
        let key2 = KeyInput::parse("ctrl-d").unwrap();
        base.bind(key1.clone(), Action::ReturnOriginal);
        base.bind(key2.clone(), Action::DeleteCharAfter);

        let mut overlay = Keymap::new();
        overlay.bind(key1.clone(), Action::Exit);

        base.merge(&overlay);

        let ctx = make_ctx(0, 0, 0, 0);
        assert_eq!(base.resolve(&key1, &ctx), Some(Action::Exit));
        assert_eq!(base.resolve(&key2, &ctx), Some(Action::DeleteCharAfter));
    }
}