jiq 3.21.0

Interactive JSON query tool with real-time output
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
use ratatui::crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent,
};
use std::io;
use std::time::Duration;

use super::app_state::{App, Focus};
use crate::clipboard;
use crate::editor;
use crate::editor::EditorMode;
use crate::help::HelpTab;
use crate::history;
use crate::results;
use crate::snippets;

mod global;

/// Determine the default help tab based on current app context
///
/// Context-aware auto-selection:
/// - Input box focus -> Input tab
/// - Results box focus -> Result tab
/// - Search box focus -> Search tab
/// - Snippet manager focus -> Snippet tab
/// - Otherwise -> Global tab
///
/// Note: History and AI tabs never auto-focus - users navigate to them manually.
fn get_default_help_tab(app: &App) -> HelpTab {
    // Priority order: more specific contexts first

    // Snippet manager visible
    if app.snippets.is_visible() {
        return HelpTab::Snippet;
    }

    // Search mode active
    if app.search.is_visible() {
        return HelpTab::Search;
    }

    // Results pane focused
    if app.focus == Focus::ResultsPane {
        return HelpTab::Result;
    }

    // Input field focused (covers Insert and Normal modes)
    if app.focus == Focus::InputField {
        return HelpTab::Input;
    }

    // Fallback - Global tab
    // Note: History and AI tabs never auto-focus
    HelpTab::Global
}

fn handle_truly_global_keys(app: &mut App, key: KeyEvent) -> bool {
    match key.code {
        KeyCode::F(1) => {
            if app.help.visible {
                app.help.reset();
            } else {
                // Auto-select tab based on current context
                app.help.active_tab = get_default_help_tab(app);
                app.help.visible = true;
            }
            true
        }
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.should_quit = true;
            true
        }
        _ => false,
    }
}

fn handle_help_keys(app: &mut App, key: KeyEvent) -> bool {
    match key.code {
        // Close help
        KeyCode::Esc | KeyCode::F(1) => {
            app.help.reset();
            true
        }
        KeyCode::Char('q') if !key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.help.reset();
            true
        }
        KeyCode::Char('?') => {
            app.help.reset();
            true
        }

        // Tab navigation with Tab key
        KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
            app.help.active_tab = app.help.active_tab.prev();
            true
        }
        KeyCode::Tab => {
            app.help.active_tab = app.help.active_tab.next();
            true
        }
        KeyCode::BackTab => {
            app.help.active_tab = app.help.active_tab.prev();
            true
        }

        // Tab navigation with h/l keys
        KeyCode::Char('h') | KeyCode::Left => {
            app.help.active_tab = app.help.active_tab.prev();
            true
        }
        KeyCode::Char('l') | KeyCode::Right => {
            app.help.active_tab = app.help.active_tab.next();
            true
        }

        // Jump to tab by number (1-7)
        KeyCode::Char(c) if ('1'..='7').contains(&c) => {
            let index = (c as usize) - ('1' as usize);
            app.help.active_tab = HelpTab::from_index(index);
            true
        }

        // Scrolling (per-tab scroll state)
        KeyCode::Char('j') | KeyCode::Down => {
            app.help.current_scroll_mut().scroll_down(1);
            true
        }
        KeyCode::Char('J') => {
            app.help.current_scroll_mut().scroll_down(10);
            true
        }
        KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.help.current_scroll_mut().scroll_down(10);
            true
        }
        KeyCode::PageDown => {
            app.help.current_scroll_mut().scroll_down(10);
            true
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.help.current_scroll_mut().scroll_up(1);
            true
        }
        KeyCode::Char('K') => {
            app.help.current_scroll_mut().scroll_up(10);
            true
        }
        KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            app.help.current_scroll_mut().scroll_up(10);
            true
        }
        KeyCode::PageUp => {
            app.help.current_scroll_mut().scroll_up(10);
            true
        }
        KeyCode::Char('g') | KeyCode::Home => {
            app.help.current_scroll_mut().jump_to_top();
            true
        }
        KeyCode::Char('G') | KeyCode::End => {
            app.help.current_scroll_mut().jump_to_bottom();
            true
        }

        _ => {
            // Consume all other keys when help is visible
            true
        }
    }
}

/// Handle keys that should pass through even when snippets/history popups are visible
fn handle_popup_passthrough_keys(app: &mut App, key: KeyEvent) -> bool {
    // ? toggles help when snippets is visible (and not editing) or in normal mode/results pane
    if key.code == KeyCode::Char('?') {
        let snippets_allows = app.snippets.is_visible() && !app.snippets.is_editing();
        if snippets_allows
            || app.input.editor_mode == EditorMode::Normal
            || app.focus == Focus::ResultsPane
        {
            if app.help.visible {
                app.help.reset();
            } else {
                // Auto-select tab based on current context
                app.help.active_tab = get_default_help_tab(app);
                app.help.visible = true;
            }
            return true;
        }
    }

    // BackTab closes history and switches focus
    if key.code == KeyCode::BackTab && app.history.is_visible() {
        app.history.close();
        app.focus = match app.focus {
            Focus::InputField => Focus::ResultsPane,
            Focus::ResultsPane => Focus::InputField,
        };
        return true;
    }

    // Ctrl+S opens snippets (closes history)
    if key.code == KeyCode::Char('s')
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && app.history.is_visible()
    {
        app.snippets.open();
        app.autocomplete.hide();
        app.history.close();
        return true;
    }

    false
}

const EVENT_POLL_TIMEOUT: Duration = Duration::from_millis(100);

impl App {
    pub fn handle_events(&mut self) -> io::Result<()> {
        if self.debouncer.should_execute() {
            editor::editor_events::execute_query_with_auto_show(self);
            self.debouncer.mark_executed();
            self.mark_dirty();
        }

        // Poll for query responses
        if self.poll_query_response() {
            self.mark_dirty();
        }

        if crate::ai::ai_events::poll_response_channel(&mut self.ai) {
            self.mark_dirty();
        }

        // Check notification expiry
        if self.notification.clear_if_expired() {
            self.mark_dirty();
        }

        if event::poll(EVENT_POLL_TIMEOUT)? {
            match event::read()? {
                Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
                    self.handle_key_event(key_event);
                    self.mark_dirty();
                }
                Event::Paste(text) => {
                    self.handle_paste_event(text);
                    self.mark_dirty();
                }
                Event::Resize(_, _) => {
                    self.mark_dirty();
                }
                Event::Mouse(mouse_event) => {
                    self.handle_mouse_event(mouse_event);
                    self.mark_dirty();
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn handle_paste_event(&mut self, text: String) {
        self.input.textarea.insert_str(&text);

        self.input
            .brace_tracker
            .rebuild(self.input.textarea.lines()[0].as_ref());

        // Execute immediately for instant feedback (like old behavior)
        // Uses async execution to prevent race conditions
        editor::editor_events::execute_query(self);

        self.update_autocomplete();

        self.update_tooltip();
    }

    fn handle_mouse_event(&mut self, mouse: MouseEvent) {
        super::mouse_events::handle_mouse_event(self, mouse);
    }

    pub fn handle_key_event(&mut self, key: KeyEvent) {
        // STEP 1: Truly global keys - ALWAYS work regardless of any popup
        if handle_truly_global_keys(self, key) {
            return;
        }

        // STEP 2: Popup stack (topmost first) - each handles its own Esc
        if self.help.visible && handle_help_keys(self, key) {
            return;
        }

        if self.search.is_visible() && crate::search::search_events::handle_search_key(self, key) {
            return;
        }

        // STEP 3: Keys that should pass through even when snippets/history are visible
        if (self.snippets.is_visible() || self.history.is_visible())
            && handle_popup_passthrough_keys(self, key)
        {
            return;
        }

        if self.snippets.is_visible() {
            snippets::snippet_events::handle_snippet_popup_key(self, key);
            return;
        }

        if self.history.is_visible() {
            history::history_events::handle_history_popup_key(self, key);
            return;
        }

        // STEP 3: Other global keys (when no popup is active)
        if global::handle_global_keys(self, key) {
            return;
        }

        // STEP 4: Clipboard
        if clipboard::clipboard_events::handle_clipboard_key(self, key, self.clipboard_backend) {
            return;
        }

        // STEP 5: Focus-based routing
        match self.focus {
            Focus::InputField => self.handle_input_field_key(key),
            Focus::ResultsPane => results::results_events::handle_results_pane_key(self, key),
        }
    }

    fn handle_input_field_key(&mut self, key: KeyEvent) {
        if key.code == KeyCode::Esc {
            if self.autocomplete.is_visible() {
                self.autocomplete.hide();
            }
            self.input.editor_mode = EditorMode::Normal;
            return;
        }

        if key.code == KeyCode::Char('d') && key.modifiers.contains(KeyModifiers::CONTROL) {
            self.results_scroll.page_down();
            return;
        }

        if key.code == KeyCode::Char('u') && key.modifiers.contains(KeyModifiers::CONTROL) {
            self.results_scroll.page_up();
            return;
        }

        if self.input.editor_mode == EditorMode::Insert && self.autocomplete.is_visible() {
            match key.code {
                KeyCode::Down => {
                    self.autocomplete.select_next();
                    return;
                }
                KeyCode::Up => {
                    self.autocomplete.select_previous();
                    return;
                }
                _ => {}
            }
        }

        if self.input.editor_mode == EditorMode::Insert {
            if key.code == KeyCode::Char('p') && key.modifiers.contains(KeyModifiers::CONTROL) {
                if let Some(entry) = self.history.cycle_previous() {
                    self.replace_query_with(&entry);
                }
                return;
            }

            if key.code == KeyCode::Char('n') && key.modifiers.contains(KeyModifiers::CONTROL) {
                if let Some(entry) = self.history.cycle_next() {
                    self.replace_query_with(&entry);
                } else {
                    self.input.textarea.delete_line_by_head();
                    self.input.textarea.delete_line_by_end();
                    editor::editor_events::execute_query(self);
                }
                return;
            }

            if key.code == KeyCode::Char('r') && key.modifiers.contains(KeyModifiers::CONTROL) {
                self.open_history_popup();
                return;
            }

            if key.code == KeyCode::Up {
                self.open_history_popup();
                return;
            }
        }

        match self.input.editor_mode {
            EditorMode::Insert => editor::editor_events::handle_insert_mode_key(self, key),
            EditorMode::Normal => editor::editor_events::handle_normal_mode_key(self, key),
            EditorMode::Operator(_) => editor::editor_events::handle_operator_mode_key(self, key),
            EditorMode::CharSearch(_, _) => {
                editor::editor_events::handle_char_search_mode_key(self, key)
            }
            EditorMode::OperatorCharSearch(_, _, _, _) => {
                editor::editor_events::handle_operator_char_search_mode_key(self, key)
            }
            EditorMode::TextObject(_, _) => {
                editor::editor_events::handle_text_object_mode_key(self, key)
            }
        }
    }

    fn replace_query_with(&mut self, text: &str) {
        self.input.textarea.delete_line_by_head();
        self.input.textarea.delete_line_by_end();
        self.input.textarea.insert_str(text);
        editor::editor_events::execute_query(self);
    }

    fn open_history_popup(&mut self) {
        if self.history.total_count() == 0 {
            return;
        }

        let query = self.query().to_string();
        let initial_query = if query.is_empty() {
            None
        } else {
            Some(query.as_str())
        };
        self.history.open(initial_query);
        self.autocomplete.hide();
    }

    /// Poll for query responses and update state
    ///
    /// Checks for completed async queries and triggers AI updates when needed.
    /// Uses the query returned from poll_response() to ensure AI gets correct context.
    /// Returns true if state changed (query completed).
    fn poll_query_response(&mut self) -> bool {
        let completed_query = if let Some(query_state) = &mut self.query {
            query_state.poll_response()
        } else {
            None
        };

        if let Some(completed_query) = completed_query {
            // Result changed - update stats once (not on every frame)
            self.update_stats();

            // State changed - trigger AI update if visible and query is not empty
            if self.ai.visible && !completed_query.is_empty() {
                let query_state = self.query.as_ref().unwrap();
                let cursor_pos = self.input.textarea.cursor().1;

                let ai_result: Result<String, String> = match &query_state.result {
                    Ok(_) => query_state
                        .last_successful_result_unformatted
                        .as_ref()
                        .map(|s| Ok(s.as_ref().clone()))
                        .unwrap_or_else(|| Ok(String::new())),
                    Err(e) => Err(e.clone()),
                };

                crate::ai::ai_events::handle_query_result(
                    &mut self.ai,
                    &ai_result,
                    &completed_query, // Use query from response, not current input!
                    cursor_pos,
                    crate::ai::context::ContextParams {
                        input_schema: self.input_json_schema.as_deref(),
                        base_query: query_state.base_query_for_suggestions.as_deref(),
                        base_query_result: query_state
                            .last_successful_result_for_context
                            .as_deref()
                            .map(|s| s.as_ref()),
                        is_empty_result: query_state.is_empty_result,
                    },
                );
            }
            return true;
        }
        false
    }
}

#[cfg(test)]
#[path = "app_events_tests.rs"]
mod app_events_tests;