complior-cli 0.9.9

AI Act Compliance Scanner & Fixer — CLI
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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};

use crate::app::App;
use crate::types::{ClickTarget, InputMode, Overlay, Panel, ViewState};

/// User actions produced by keyboard/mouse input mapping.
///
/// Each variant represents a semantic action that the app can handle.
/// Key bindings are defined in `handle_key_event()` below.
pub enum Action {
    /// Quit the application (Ctrl+C).
    Quit,
    /// Cycle to the next panel (Tab in Insert mode).
    #[allow(dead_code)] // Handled in app but not yet bound to a key
    NextPanel,
    /// Toggle the terminal panel (Ctrl+T).
    ToggleTerminal,
    /// Toggle the sidebar panel (Ctrl+B).
    ToggleSidebar,
    /// Toggle the files panel (Ctrl+F).
    ToggleFilesPanel,
    /// Close the currently open file viewer.
    CloseFile,
    /// Submit the current input (Enter in Insert mode).
    SubmitInput,
    /// Insert a character into the input buffer.
    InsertChar(char),
    /// Delete the character before the cursor (Backspace).
    DeleteChar,
    /// Move cursor left in input buffer.
    MoveCursorLeft,
    /// Move cursor right in input buffer.
    MoveCursorRight,
    /// Navigate input history up (Arrow Up).
    HistoryUp,
    /// Navigate input history down (Arrow Down).
    HistoryDown,
    /// Trigger tab completion for commands, @OBL- references, etc.
    TabComplete,
    /// Scroll content up by one line (k / Arrow Up in Normal mode).
    ScrollUp,
    /// Scroll content down by one line (j / Arrow Down in Normal mode).
    ScrollDown,
    /// Scroll half a page up (Ctrl+U).
    ScrollHalfPageUp,
    /// Scroll half a page down (Ctrl+D).
    ScrollHalfPageDown,
    /// Scroll to top of content (g in Normal mode).
    ScrollToTop,
    /// Scroll to bottom of content (G in Normal mode).
    ScrollToBottom,
    /// Enter Insert mode (i in Normal mode).
    EnterInsertMode,
    /// Enter Normal mode (Esc).
    EnterNormalMode,
    /// Enter Visual select mode (V in Normal mode).
    EnterVisualMode,
    /// Enter command mode (/ prefix).
    EnterCommandMode,
    /// Enter colon-command mode (: in Normal mode).
    EnterColonMode,
    /// Extend visual selection up.
    SelectionUp,
    /// Extend visual selection down.
    SelectionDown,
    /// Send visual selection to AI chat (Ctrl+K in Visual mode).
    SendSelectionToAi,
    /// Accept a proposed diff.
    AcceptDiff,
    /// Reject a proposed diff.
    RejectDiff,
    /// Toggle expand/collapse of a tree node.
    ToggleExpand,
    /// Open the selected file in the viewer.
    OpenFile,
    /// Open the command palette overlay (Ctrl+P).
    ShowCommandPalette,
    /// Open the file picker overlay.
    ShowFilePicker,
    /// Open the help overlay (? in Normal mode).
    ShowHelp,
    /// Focus a specific panel (Alt+1..5).
    FocusPanel(Panel),
    /// Jump to a specific line number.
    #[allow(dead_code)] // Handled in app but not yet bound to a key
    GotoLine,
    /// Switch to a numbered view (1-6 in Normal mode).
    SwitchView(ViewState),
    /// Toggle mode (Scan/Fix/Watch via Tab in Normal mode).
    ToggleMode,
    /// Trigger a compliance scan (Ctrl+S).
    StartScan,
    /// Toggle file watcher mode.
    WatchToggle,
    /// Open the theme picker overlay.
    #[allow(dead_code)] // Handled in app but not yet bound to a key
    ShowThemePicker,
    /// Start inline code search (/ in Normal mode on code viewer).
    CodeSearch,
    /// Jump to next code search match (n).
    CodeSearchNext,
    /// Jump to previous code search match (N).
    CodeSearchPrev,
    /// Undo the last action (Ctrl+Z).
    Undo,
    /// Show the undo history overlay (U in Normal mode).
    ShowUndoHistory,
    /// Mouse click at a specific UI target.
    ClickAt(ClickTarget),
    /// Mouse scroll by N lines (positive = down, negative = up).
    ScrollLines(i32),
    /// View-specific single-char key press (delegated to active view).
    ViewKey(char),
    /// View-specific Enter key press.
    ViewEnter,
    /// View-specific Escape key press.
    ViewEscape,
    /// No action (unhandled key).
    None,
}

pub fn handle_key_event(key: KeyEvent, app: &App) -> Action {
    // Global shortcuts (always active)
    if key.modifiers.contains(KeyModifiers::CONTROL) {
        match key.code {
            KeyCode::Char('c') => return Action::Quit,
            KeyCode::Char('t') => return Action::ToggleTerminal,
            KeyCode::Char('b') => return Action::ToggleSidebar,
            KeyCode::Char('f') => return Action::ToggleFilesPanel,
            KeyCode::Char('p') => return Action::ShowCommandPalette,
            // Note: Ctrl+M is indistinguishable from Enter in terminals (both send CR).
            // Model selector is mapped to 'M' (Shift+M) in Normal mode instead.
            KeyCode::Char('s') => return Action::StartScan,
            KeyCode::Char('k') if app.input_mode == InputMode::Visual => {
                return Action::SendSelectionToAi;
            }
            KeyCode::Char('z') => return Action::Undo,
            KeyCode::Char('d') => return Action::ScrollHalfPageDown,
            KeyCode::Char('u') => return Action::ScrollHalfPageUp,
            _ => {}
        }
    }

    // Alt+N panel shortcuts
    if key.modifiers.contains(KeyModifiers::ALT) {
        match key.code {
            KeyCode::Char('1') => return Action::FocusPanel(Panel::Chat),
            KeyCode::Char('2') => return Action::FocusPanel(Panel::Score),
            KeyCode::Char('3') => return Action::FocusPanel(Panel::FileBrowser),
            KeyCode::Char('4') => return Action::FocusPanel(Panel::CodeViewer),
            KeyCode::Char('5') => return Action::FocusPanel(Panel::Terminal),
            _ => {}
        }
    }

    // If an overlay is active, route input there
    if app.overlay != Overlay::None {
        return handle_overlay_keys(key, app);
    }

    match app.input_mode {
        InputMode::Insert => handle_insert_mode(key),
        InputMode::Normal => handle_normal_mode(key, app),
        InputMode::Command => handle_command_mode(key),
        InputMode::Visual => handle_visual_mode(key),
    }
}

pub fn handle_mouse_event(event: MouseEvent, app: &App) -> Action {
    match event.kind {
        MouseEventKind::ScrollUp => {
            let lines = scroll_line_count(app);
            Action::ScrollLines(-lines)
        }
        MouseEventKind::ScrollDown => {
            let lines = scroll_line_count(app);
            Action::ScrollLines(lines)
        }
        MouseEventKind::Down(MouseButton::Left) => {
            let col = event.column;
            let row = event.row;
            // Hit-test against registered click areas
            for (rect, target) in &app.click_areas {
                if col >= rect.x
                    && col < rect.x + rect.width
                    && row >= rect.y
                    && row < rect.y + rect.height
                {
                    return Action::ClickAt(target.clone());
                }
            }
            Action::None
        }
        _ => Action::None,
    }
}

/// Compute scroll lines based on recent scroll event frequency (acceleration).
fn scroll_line_count(app: &App) -> i32 {
    let now = std::time::Instant::now();
    let recent = app
        .scroll_events
        .iter()
        .filter(|&&t| now.duration_since(t).as_millis() < 300)
        .count();
    if recent >= 3 {
        let accel = app.config.scroll_acceleration;
        (accel * 3.0) as i32
    } else {
        1
    }
}

#[cfg(test)]
pub fn scroll_line_count_for_test(app: &App) -> i32 {
    scroll_line_count(app)
}

fn handle_overlay_keys(key: KeyEvent, app: &App) -> Action {
    let overlay = &app.overlay;

    // When onboarding is in text-input substep (key entry), treat all chars as text input
    let onboarding_text_mode = app
        .onboarding
        .as_ref()
        .is_some_and(|wiz| wiz.provider_substep == 1);

    // Navigable overlays: ThemePicker, Onboarding — support j/k/arrows for scrolling
    // Exception: onboarding text-input mode sends j/k as InsertChar
    let navigable = !onboarding_text_mode
        && matches!(
            overlay,
            Overlay::ThemePicker
                | Overlay::Onboarding
                | Overlay::DismissModal
                | Overlay::ConfirmDialog
                | Overlay::UndoHistory
                | Overlay::CommandPalette
                | Overlay::LlmSettings
        );
    match key.code {
        KeyCode::Esc => Action::EnterNormalMode,
        KeyCode::Enter => Action::SubmitInput,
        KeyCode::Char('j') | KeyCode::Down if navigable => Action::ScrollDown,
        KeyCode::Char('k') | KeyCode::Up if navigable => Action::ScrollUp,
        KeyCode::Char(c) => Action::InsertChar(c),
        KeyCode::Backspace => Action::DeleteChar,
        _ => Action::None,
    }
}

const fn handle_insert_mode(key: KeyEvent) -> Action {
    match key.code {
        // Shift+Enter = newline (requires modifyOtherKeys protocol, works in tmux 3.2+)
        KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => Action::InsertChar('\n'),
        // Ctrl+J = newline fallback (works in all terminals)
        KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            Action::InsertChar('\n')
        }
        KeyCode::Enter => Action::SubmitInput,
        KeyCode::Char(c) => Action::InsertChar(c),
        KeyCode::Backspace => Action::DeleteChar,
        KeyCode::Left => Action::MoveCursorLeft,
        KeyCode::Right => Action::MoveCursorRight,
        KeyCode::Up => Action::HistoryUp,
        KeyCode::Down => Action::HistoryDown,
        KeyCode::Esc => Action::EnterNormalMode,
        KeyCode::Tab => Action::TabComplete,
        _ => Action::None,
    }
}

fn handle_normal_mode(key: KeyEvent, app: &App) -> Action {
    match key.code {
        KeyCode::Char('q') => Action::Quit,
        KeyCode::Tab => Action::ToggleMode,
        KeyCode::Char('i') => Action::EnterInsertMode,
        // '/' opens code search when in CodeViewer, command mode otherwise
        KeyCode::Char('/') if app.active_panel == Panel::CodeViewer => Action::CodeSearch,
        KeyCode::Char('/') => Action::EnterCommandMode,
        KeyCode::Char('n')
            if app.active_panel == Panel::CodeViewer && app.code_search_query.is_some() =>
        {
            Action::CodeSearchNext
        }
        KeyCode::Char('N')
            if app.active_panel == Panel::CodeViewer && app.code_search_query.is_some() =>
        {
            Action::CodeSearchPrev
        }
        KeyCode::Char('j') | KeyCode::Down => Action::ScrollDown,
        KeyCode::Char('k') | KeyCode::Up => Action::ScrollUp,
        KeyCode::Char('g') if app.view_state != ViewState::Passport => Action::ScrollToTop,
        KeyCode::Char('G') => Action::ScrollToBottom,
        KeyCode::Char('v' | 'V') => Action::EnterVisualMode,
        KeyCode::Char(':') => Action::EnterColonMode,
        KeyCode::Char('U') => Action::ShowUndoHistory,
        KeyCode::Char('w') => Action::WatchToggle,
        KeyCode::Char('?') => Action::ShowHelp,
        KeyCode::Char('@') => Action::ShowFilePicker,
        // Uppercase letter-key view switching (avoids conflict with lowercase ViewKey chars)
        KeyCode::Char(c @ ('C' | 'D' | 'F' | 'L' | 'O' | 'P' | 'R' | 'S' | 'T')) => {
            if let Some(view) = ViewState::from_letter(c) {
                Action::SwitchView(view)
            } else {
                Action::None
            }
        }
        KeyCode::Enter => match app.active_panel {
            Panel::FileBrowser => Action::OpenFile,
            _ if matches!(
                app.view_state,
                ViewState::Scan
                    | ViewState::Fix
                    | ViewState::Passport
                    | ViewState::Obligations
                    | ViewState::Report
            ) =>
            {
                Action::ViewEnter
            }
            _ => Action::SubmitInput,
        },
        KeyCode::Char(' ') if app.view_state == ViewState::Fix => Action::ViewKey(' '),
        KeyCode::Char(' ') if app.active_panel == Panel::FileBrowser => Action::ToggleExpand,
        KeyCode::Char('y') if app.active_panel == Panel::DiffPreview => Action::AcceptDiff,
        KeyCode::Char('n') if app.active_panel == Panel::DiffPreview => Action::RejectDiff,
        KeyCode::Backspace if app.active_panel == Panel::CodeViewer => Action::CloseFile,
        // View-specific Esc
        KeyCode::Esc
            if matches!(
                app.view_state,
                ViewState::Scan
                    | ViewState::Fix
                    | ViewState::Dashboard
                    | ViewState::Passport
                    | ViewState::Obligations
                    | ViewState::Report
                    | ViewState::Timeline
                    | ViewState::Log
                    | ViewState::Chat
            ) =>
        {
            Action::ViewEscape
        }
        KeyCode::Esc if app.active_panel == Panel::CodeViewer => Action::CloseFile,
        // View-specific char keys — all interactive views
        KeyCode::Char(
            c @ ('a' | 'c' | 'h' | 'm' | 'l' | 'f' | 'd' | 'e' | 'g' | 'n' | 'p' | 'x' | 'o' | '<'
            | '>'),
        ) if matches!(
            app.view_state,
            ViewState::Scan
                | ViewState::Fix
                | ViewState::Report
                | ViewState::Dashboard
                | ViewState::Passport
                | ViewState::Obligations
                | ViewState::Timeline
                | ViewState::Log
                | ViewState::Chat
        ) =>
        {
            Action::ViewKey(c)
        }
        // Number keys for Report view generator selection
        KeyCode::Char(c @ ('1'..='9')) if app.view_state == ViewState::Report => Action::ViewKey(c),
        _ => Action::None,
    }
}

const fn handle_command_mode(key: KeyEvent) -> Action {
    match key.code {
        KeyCode::Enter => Action::SubmitInput,
        KeyCode::Char(c) => Action::InsertChar(c),
        KeyCode::Backspace => Action::DeleteChar,
        KeyCode::Esc => Action::EnterNormalMode,
        KeyCode::Tab => Action::TabComplete,
        _ => Action::None,
    }
}

const fn handle_visual_mode(key: KeyEvent) -> Action {
    match key.code {
        KeyCode::Esc => Action::EnterNormalMode,
        KeyCode::Char('j') | KeyCode::Down => Action::SelectionDown,
        KeyCode::Char('k') | KeyCode::Up => Action::SelectionUp,
        KeyCode::Char('y') => Action::AcceptDiff,
        KeyCode::Char('n') => Action::RejectDiff,
        _ => Action::None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn test_watch_key_w_action() {
        let app = App::new(crate::config::TuiConfig::default());
        let mut test_app = app;
        test_app.input_mode = InputMode::Normal;

        let action = handle_key_event(key(KeyCode::Char('w')), &test_app);
        assert!(matches!(action, Action::WatchToggle));
    }

    #[test]
    fn test_theme_picker_overlay_jk_navigation() {
        let mut app = App::new(crate::config::TuiConfig::default());
        app.overlay = Overlay::ThemePicker;

        let action_j = handle_key_event(key(KeyCode::Char('j')), &app);
        assert!(matches!(action_j, Action::ScrollDown));

        let action_k = handle_key_event(key(KeyCode::Char('k')), &app);
        assert!(matches!(action_k, Action::ScrollUp));

        let action_down = handle_key_event(key(KeyCode::Down), &app);
        assert!(matches!(action_down, Action::ScrollDown));

        let action_up = handle_key_event(key(KeyCode::Up), &app);
        assert!(matches!(action_up, Action::ScrollUp));
    }

    #[test]
    fn test_onboarding_overlay_jk_navigation() {
        let mut app = App::new(crate::config::TuiConfig::default());
        app.overlay = Overlay::Onboarding;

        let action_j = handle_key_event(key(KeyCode::Char('j')), &app);
        assert!(matches!(action_j, Action::ScrollDown));

        let action_k = handle_key_event(key(KeyCode::Char('k')), &app);
        assert!(matches!(action_k, Action::ScrollUp));
    }

    #[test]
    fn test_non_navigable_overlay_jk_inserts() {
        let mut app = App::new(crate::config::TuiConfig::default());
        app.overlay = Overlay::FilePicker;

        // In non-navigable overlays, j/k should produce InsertChar
        let action_j = handle_key_event(key(KeyCode::Char('j')), &app);
        assert!(matches!(action_j, Action::InsertChar('j')));
    }

    #[test]
    fn test_command_palette_jk_navigates() {
        let mut app = App::new(crate::config::TuiConfig::default());
        app.overlay = Overlay::CommandPalette;

        // CommandPalette is navigable — j/k should scroll
        let action_j = handle_key_event(key(KeyCode::Char('j')), &app);
        assert!(matches!(action_j, Action::ScrollDown));
        let action_k = handle_key_event(key(KeyCode::Char('k')), &app);
        assert!(matches!(action_k, Action::ScrollUp));
    }

    #[test]
    fn test_shift_m_no_op_in_normal_mode() {
        let mut app = App::new(crate::config::TuiConfig::default());
        app.input_mode = InputMode::Normal;

        // M is no longer bound (model selector removed in wrapper mode)
        let action = handle_key_event(key(KeyCode::Char('M')), &app);
        assert!(matches!(action, Action::None));
    }
}