Skip to main content

tea_cli/tui/
keymap.rs

1use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
2use tea_coding::config::TuiSettings;
3
4/// Semantic action selected by one configured key chord.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum BindingAction {
7    /// Submit a prompt while idle.
8    Submit,
9    /// Insert a newline without submitting.
10    Newline,
11    /// Abort the active operation.
12    Abort,
13    /// Clear the editor.
14    Clear,
15    /// Exit the interactive application.
16    Exit,
17    /// Open the model selector.
18    SelectModel,
19    /// Toggle reasoning visibility.
20    ToggleThinking,
21    /// Toggle tool detail visibility.
22    ToggleTools,
23    /// Copy the last assistant response.
24    Copy,
25    /// Submit steering while a run is active.
26    Steer,
27    /// Queue a follow-up while a run is active.
28    FollowUp,
29    /// Restore queued messages to the editor.
30    RetrieveQueued,
31}
32
33/// Built-in text editor action shared across terminal platforms.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum EditorAction {
36    InsertNewline,
37    MoveLeft,
38    MoveRight,
39    MoveUp,
40    MoveDown,
41    MoveWordLeft,
42    MoveWordRight,
43    MoveLineStart { cross_line: bool },
44    MoveLineEnd { cross_line: bool },
45    DeleteBackward,
46    DeleteForward,
47    DeleteWordBackward,
48    DeleteWordForward,
49    KillLineStart,
50    KillLineEnd,
51    Yank,
52    Undo,
53}
54
55/// Resolves Codex-style built-in composer editing shortcuts.
56pub(crate) fn resolve_editor_action(event: KeyEvent) -> Option<EditorAction> {
57    let code = event.code;
58    let modifiers = event.modifiers;
59    let none = KeyModifiers::NONE;
60    let shift = KeyModifiers::SHIFT;
61    let control = KeyModifiers::CONTROL;
62    let alt = KeyModifiers::ALT;
63    let control_shift = control | shift;
64    let control_alt = control | alt;
65
66    let action = match code {
67        KeyCode::Enter if matches!(modifiers, value if value == none || value == shift || value == alt) => {
68            EditorAction::InsertNewline
69        }
70        KeyCode::Char('j' | 'm') if modifiers == control => EditorAction::InsertNewline,
71        KeyCode::Left if modifiers == none => EditorAction::MoveLeft,
72        KeyCode::Char('b') if modifiers == control => EditorAction::MoveLeft,
73        KeyCode::Right if modifiers == none => EditorAction::MoveRight,
74        KeyCode::Char('f') if modifiers == control => EditorAction::MoveRight,
75        KeyCode::Up if modifiers == none => EditorAction::MoveUp,
76        KeyCode::Char('p') if modifiers == control => EditorAction::MoveUp,
77        KeyCode::Down if modifiers == none => EditorAction::MoveDown,
78        KeyCode::Char('n') if modifiers == control => EditorAction::MoveDown,
79        KeyCode::Left if modifiers == alt || modifiers == control => EditorAction::MoveWordLeft,
80        KeyCode::Char('b') if modifiers == alt => EditorAction::MoveWordLeft,
81        KeyCode::Right if modifiers == alt || modifiers == control => EditorAction::MoveWordRight,
82        KeyCode::Char('f') if modifiers == alt => EditorAction::MoveWordRight,
83        KeyCode::Home if modifiers == none => EditorAction::MoveLineStart { cross_line: false },
84        KeyCode::Char('a') if modifiers == control => {
85            EditorAction::MoveLineStart { cross_line: true }
86        }
87        KeyCode::End if modifiers == none => EditorAction::MoveLineEnd { cross_line: false },
88        KeyCode::Char('e') if modifiers == control => {
89            EditorAction::MoveLineEnd { cross_line: true }
90        }
91        KeyCode::Backspace
92            if modifiers == alt || modifiers == control || modifiers == control_shift =>
93        {
94            EditorAction::DeleteWordBackward
95        }
96        KeyCode::Char('w') if modifiers == control => EditorAction::DeleteWordBackward,
97        KeyCode::Char('h') if modifiers == control_alt => EditorAction::DeleteWordBackward,
98        KeyCode::Backspace if modifiers == none || modifiers == shift => {
99            EditorAction::DeleteBackward
100        }
101        KeyCode::Delete
102            if modifiers == alt || modifiers == control || modifiers == control_shift =>
103        {
104            EditorAction::DeleteWordForward
105        }
106        KeyCode::Char('d') if modifiers == alt => EditorAction::DeleteWordForward,
107        KeyCode::Delete if modifiers == none || modifiers == shift => EditorAction::DeleteForward,
108        KeyCode::Char('h') if modifiers == control => EditorAction::DeleteBackward,
109        KeyCode::Char('d') if modifiers == control => EditorAction::DeleteForward,
110        KeyCode::Char('u') if modifiers == control => EditorAction::KillLineStart,
111        KeyCode::Char('k') if modifiers == control => EditorAction::KillLineEnd,
112        KeyCode::Char('y') if modifiers == control => EditorAction::Yank,
113        KeyCode::Char('z') if modifiers == control => EditorAction::Undo,
114        _ => return None,
115    };
116    Some(action)
117}
118
119/// Invalid or ambiguous key binding configuration.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
121pub enum KeyMapError {
122    /// A key chord has invalid syntax.
123    #[error("key binding syntax is invalid")]
124    Invalid,
125    /// Two actions active in the same context use the same key chord.
126    #[error("key binding configuration is ambiguous")]
127    Ambiguous,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131struct KeyChord {
132    code: KeyCode,
133    modifiers: KeyModifiers,
134}
135
136impl KeyChord {
137    fn matches(self, event: KeyEvent) -> bool {
138        self.code == event.code && self.modifiers == event.modifiers
139    }
140}
141
142/// Validated context-aware interactive key map.
143#[derive(Debug, Clone)]
144pub struct KeyMap {
145    submit: KeyChord,
146    newline: KeyChord,
147    abort: KeyChord,
148    clear: KeyChord,
149    exit: KeyChord,
150    select_model: KeyChord,
151    toggle_thinking: KeyChord,
152    toggle_tools: KeyChord,
153    copy: KeyChord,
154    steer: KeyChord,
155    follow_up: KeyChord,
156    retrieve_queued: KeyChord,
157}
158
159impl KeyMap {
160    /// Parses and validates resolved TUI settings.
161    ///
162    /// # Errors
163    ///
164    /// Rejects invalid chords and same-context ambiguity.
165    pub fn from_settings(settings: &TuiSettings) -> Result<Self, KeyMapError> {
166        let map = Self {
167            submit: parse_chord(&settings.submit_key)?,
168            newline: parse_chord(&settings.newline_key)?,
169            abort: parse_chord(&settings.abort_key)?,
170            clear: parse_chord(&settings.clear_key)?,
171            exit: parse_chord(&settings.exit_key)?,
172            select_model: parse_chord(&settings.model_key)?,
173            toggle_thinking: parse_chord(&settings.toggle_thinking_key)?,
174            toggle_tools: parse_chord(&settings.toggle_tools_key)?,
175            copy: parse_chord(&settings.copy_key)?,
176            steer: parse_chord(&settings.steering_key)?,
177            follow_up: parse_chord(&settings.follow_up_key)?,
178            retrieve_queued: parse_chord(&settings.retrieve_queued_key)?,
179        };
180        map.validate_ambiguity()?;
181        Ok(map)
182    }
183
184    /// Resolves a key according to idle/running context.
185    #[must_use]
186    pub fn resolve(&self, event: KeyEvent, running: bool) -> Option<BindingAction> {
187        let contextual = if running {
188            [
189                (self.abort, BindingAction::Abort),
190                (self.follow_up, BindingAction::FollowUp),
191                (self.steer, BindingAction::Steer),
192            ]
193        } else {
194            [
195                (self.submit, BindingAction::Submit),
196                (self.newline, BindingAction::Newline),
197                (self.abort, BindingAction::Abort),
198            ]
199        };
200        contextual
201            .into_iter()
202            .chain([
203                (self.clear, BindingAction::Clear),
204                (self.exit, BindingAction::Exit),
205                (self.select_model, BindingAction::SelectModel),
206                (self.toggle_thinking, BindingAction::ToggleThinking),
207                (self.toggle_tools, BindingAction::ToggleTools),
208                (self.copy, BindingAction::Copy),
209                (self.retrieve_queued, BindingAction::RetrieveQueued),
210            ])
211            .find_map(|(chord, action)| chord.matches(event).then_some(action))
212    }
213
214    fn validate_ambiguity(&self) -> Result<(), KeyMapError> {
215        let globals = [
216            self.newline,
217            self.clear,
218            self.exit,
219            self.select_model,
220            self.toggle_thinking,
221            self.toggle_tools,
222            self.copy,
223            self.retrieve_queued,
224        ];
225        if has_duplicate(&globals)
226            || globals.contains(&self.submit)
227            || globals.contains(&self.steer)
228            || globals.contains(&self.follow_up)
229            || globals.contains(&self.abort)
230            || self.submit == self.abort
231            || self.steer == self.follow_up
232            || self.abort == self.steer
233            || self.abort == self.follow_up
234        {
235            return Err(KeyMapError::Ambiguous);
236        }
237        Ok(())
238    }
239}
240
241fn has_duplicate(values: &[KeyChord]) -> bool {
242    values
243        .iter()
244        .enumerate()
245        .any(|(index, value)| values[index + 1..].contains(value))
246}
247
248fn parse_chord(value: &str) -> Result<KeyChord, KeyMapError> {
249    let mut modifiers = KeyModifiers::NONE;
250    let mut code = None;
251    for token in value.split('+') {
252        let token = token.trim().to_ascii_lowercase();
253        match token.as_str() {
254            "ctrl" | "control" => modifiers.insert(KeyModifiers::CONTROL),
255            "alt" | "option" => modifiers.insert(KeyModifiers::ALT),
256            "shift" => modifiers.insert(KeyModifiers::SHIFT),
257            "super" | "cmd" | "command" => modifiers.insert(KeyModifiers::SUPER),
258            _ if code.is_none() => code = parse_code(&token),
259            _ => return Err(KeyMapError::Invalid),
260        }
261    }
262    Ok(KeyChord {
263        code: code.ok_or(KeyMapError::Invalid)?,
264        modifiers,
265    })
266}
267
268fn parse_code(value: &str) -> Option<KeyCode> {
269    match value {
270        "enter" | "return" => Some(KeyCode::Enter),
271        "esc" | "escape" => Some(KeyCode::Esc),
272        "backspace" => Some(KeyCode::Backspace),
273        "delete" => Some(KeyCode::Delete),
274        "tab" => Some(KeyCode::Tab),
275        "left" => Some(KeyCode::Left),
276        "right" => Some(KeyCode::Right),
277        "up" => Some(KeyCode::Up),
278        "down" => Some(KeyCode::Down),
279        "home" => Some(KeyCode::Home),
280        "end" => Some(KeyCode::End),
281        "space" => Some(KeyCode::Char(' ')),
282        value => {
283            let mut characters = value.chars();
284            let character = characters.next()?;
285            characters
286                .next()
287                .is_none()
288                .then_some(KeyCode::Char(character))
289        }
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::{EditorAction, resolve_editor_action};
296    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
297
298    #[test]
299    fn codex_editor_shortcut_matrix_resolves_to_text_actions() {
300        let ctrl = KeyModifiers::CONTROL;
301        let alt = KeyModifiers::ALT;
302        let shift = KeyModifiers::SHIFT;
303        let ctrl_shift = ctrl | shift;
304        let cases = [
305            (
306                KeyCode::Char('a'),
307                ctrl,
308                EditorAction::MoveLineStart { cross_line: true },
309            ),
310            (
311                KeyCode::Char('e'),
312                ctrl,
313                EditorAction::MoveLineEnd { cross_line: true },
314            ),
315            (KeyCode::Char('b'), ctrl, EditorAction::MoveLeft),
316            (KeyCode::Char('f'), ctrl, EditorAction::MoveRight),
317            (KeyCode::Char('p'), ctrl, EditorAction::MoveUp),
318            (KeyCode::Char('n'), ctrl, EditorAction::MoveDown),
319            (KeyCode::Char('b'), alt, EditorAction::MoveWordLeft),
320            (KeyCode::Char('f'), alt, EditorAction::MoveWordRight),
321            (KeyCode::Left, ctrl, EditorAction::MoveWordLeft),
322            (KeyCode::Right, alt, EditorAction::MoveWordRight),
323            (KeyCode::Char('h'), ctrl, EditorAction::DeleteBackward),
324            (KeyCode::Char('d'), ctrl, EditorAction::DeleteForward),
325            (KeyCode::Char('w'), ctrl, EditorAction::DeleteWordBackward),
326            (
327                KeyCode::Backspace,
328                ctrl_shift,
329                EditorAction::DeleteWordBackward,
330            ),
331            (KeyCode::Char('d'), alt, EditorAction::DeleteWordForward),
332            (KeyCode::Delete, ctrl_shift, EditorAction::DeleteWordForward),
333            (KeyCode::Char('u'), ctrl, EditorAction::KillLineStart),
334            (KeyCode::Char('k'), ctrl, EditorAction::KillLineEnd),
335            (KeyCode::Char('y'), ctrl, EditorAction::Yank),
336            (KeyCode::Char('j'), ctrl, EditorAction::InsertNewline),
337            (KeyCode::Char('m'), ctrl, EditorAction::InsertNewline),
338            (KeyCode::Enter, alt, EditorAction::InsertNewline),
339        ];
340
341        for (code, modifiers, expected) in cases {
342            assert_eq!(
343                resolve_editor_action(KeyEvent::new(code, modifiers)),
344                Some(expected)
345            );
346        }
347    }
348}