-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathevents.rs
More file actions
2357 lines (2142 loc) · 95.1 KB
/
Copy pathevents.rs
File metadata and controls
2357 lines (2142 loc) · 95.1 KB
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Event handling for the application
//!
//! This module contains all input handling logic including keyboard events,
//! command mode, filter mode, and confirmation dialogs.
use super::core::App;
use super::state::{HealthFilter, PendingOperation, View};
use crate::tui::commands;
use crate::watcher::ResourceKey;
use crossterm::event::KeyEvent;
/// A `:` command handler dispatched from [`App::execute_command`]. Receives the
/// app and the original (case-preserving) command string.
type CommandHandler = fn(&mut App, &str);
/// Data-driven dispatch for the uniform `(predicate over the lowercased command,
/// handler)` `:` commands. Checked in order; the first matching predicate wins.
/// Special commands (help/quit/readonly, the connection gate) and the
/// resource-type fallback are handled directly in [`App::execute_command`].
const COMMAND_TABLE: &[(fn(&str) -> bool, CommandHandler)] = &[
(commands::is_skin_command, App::cmd_set_skin),
(commands::is_trace_command, App::cmd_trace),
(commands::is_context_command, App::cmd_switch_context),
(commands::is_namespace_command, App::cmd_switch_namespace),
(commands::is_healthy_command, App::cmd_filter_healthy),
(commands::is_unhealthy_command, App::cmd_filter_unhealthy),
(commands::is_favorites_command, App::cmd_show_favorites),
(commands::is_events_command, App::cmd_show_events),
(commands::is_logs_command, App::cmd_show_logs),
(commands::is_all_command, App::cmd_show_all),
];
impl App {
/// Scroll the active view down by `amount` lines, or advance the list
/// selection when a list view is active. Shared by j/Down, PageDown and
/// Ctrl+F so all scroll keys behave identically in every view.
fn scroll_down(&mut self, amount: usize) {
let view = self.view_state.current_view;
// Manual scrolling in the log view pauses following (G resumes).
if view == View::Logs {
self.logs.follow = false;
}
// In the graph, j/Down/PageDown move keyboard focus between nodes instead
// of free-scrolling; the renderer scrolls to keep the focused node on screen.
if view == View::ResourceGraph {
self.move_graph_focus(true);
} else if let Some(offset) = view.scroll_offset_mut(&mut self.view_state) {
*offset += amount;
} else {
let max_index = if view == View::EventList {
self.filtered_kube_events().len().saturating_sub(1)
} else {
self.get_filtered_resources().len().saturating_sub(1)
};
self.view_state.selected_index =
(self.view_state.selected_index + amount).min(max_index);
}
}
/// Scroll the active view up by `amount` lines, or move the list selection
/// up when a list view is active (keeping the selection visible).
fn scroll_up(&mut self, amount: usize) {
let view = self.view_state.current_view;
// Manual scrolling in the log view pauses following (G resumes).
if view == View::Logs {
self.logs.follow = false;
}
if view == View::ResourceGraph {
self.move_graph_focus(false);
} else if let Some(offset) = view.scroll_offset_mut(&mut self.view_state) {
*offset = offset.saturating_sub(amount);
} else {
self.view_state.selected_index = self.view_state.selected_index.saturating_sub(amount);
if self.view_state.selected_index < self.view_state.scroll_offset {
self.view_state.scroll_offset = self.view_state.selected_index;
}
}
}
/// Main keyboard event handler
///
/// Returns Some(true) to quit, Some(false) to continue with special action,
/// None for normal continuation
pub fn handle_key(&mut self, key: KeyEvent) -> Option<bool> {
// Return Some(true) to quit, Some(false) to continue, None for no action
// If splash is showing, dismiss it immediately on any keypress
if self.ui_state.show_splash {
self.ui_state.show_splash = false;
self.ui_state.splash_start_time = None;
// Don't process the key further - just dismiss splash
return None;
}
// Handle confirmation dialog first
if self.async_state.confirmation_pending.is_some() {
return self.handle_confirmation_key(key);
}
// Handle quit confirmation dialog (shown when q/Esc is pressed at top level)
if self.ui_state.show_quit_confirm {
return self.handle_quit_confirm_key(key);
}
// Handle submenu navigation if a submenu is active
if self.view_state.submenu_state.is_some() {
return self.handle_submenu_key(key);
}
// Handle connection error state keys
if self.has_connection_error() {
// Check status message timeout
self.check_status_message_timeout();
// Clear status messages on Esc
if self.ui_state.status_message.is_some()
&& !self.ui_state.command_mode
&& key.code == crossterm::event::KeyCode::Esc
{
self.ui_state.status_message = None;
self.ui_state.status_message_time = None;
return None;
}
if self.ui_state.command_mode {
if let Some(should_quit) = self.handle_command_key(key) {
return Some(should_quit);
}
return None;
}
// Only allow quit/Esc, Ctrl+C, :, ? when in connection error state
match (key.modifiers, key.code) {
(crossterm::event::KeyModifiers::CONTROL, crossterm::event::KeyCode::Char('c')) => {
return Some(true);
}
(crossterm::event::KeyModifiers::NONE, crossterm::event::KeyCode::Char(':')) => {
self.ui_state.command_mode = true;
self.ui_state.command_buffer.clear();
return None;
}
(crossterm::event::KeyModifiers::NONE, crossterm::event::KeyCode::Char('?')) => {
self.ui_state.show_help = !self.ui_state.show_help;
return None;
}
(
crossterm::event::KeyModifiers::NONE,
crossterm::event::KeyCode::Char('q') | crossterm::event::KeyCode::Esc,
) => {
return self.navigate_back_or_confirm_quit();
}
_ => {
// Clear status messages on any key press (except in command mode/etc)
if self.ui_state.status_message.is_some() {
self.ui_state.status_message = None;
self.ui_state.status_message_time = None;
}
// Ignore all other keys
return None;
}
}
}
// Handle Esc to dismiss status messages
if self.ui_state.status_message.is_some()
&& !self.ui_state.command_mode
&& !self.view_state.filter_mode
&& key.code == crossterm::event::KeyCode::Esc
{
self.ui_state.status_message = None;
self.ui_state.status_message_time = None;
return None;
}
// Check status message timeout
self.check_status_message_timeout();
// Clear status messages on any key press (except in special modes and operation keys)
// Don't clear if this is an operation key - we'll set a new message
let is_operation_key = matches!(
(key.modifiers, key.code),
(
crossterm::event::KeyModifiers::NONE,
crossterm::event::KeyCode::Char('s')
| crossterm::event::KeyCode::Char('r')
| crossterm::event::KeyCode::Char('R')
| crossterm::event::KeyCode::Char('W')
) | (
crossterm::event::KeyModifiers::CONTROL,
crossterm::event::KeyCode::Char('d')
)
);
if self.ui_state.status_message.is_some()
&& !self.ui_state.command_mode
&& !self.view_state.filter_mode
&& !is_operation_key
&& key.code != crossterm::event::KeyCode::Esc
{
self.ui_state.status_message = None;
self.ui_state.status_message_time = None;
}
if self.ui_state.command_mode {
if let Some(should_quit) = self.handle_command_key(key) {
return Some(should_quit);
}
return None;
}
if self.view_state.filter_mode {
return self.handle_filter_key(key);
}
// Text-view search input (typing the query after pressing / in YAML/describe/trace)
if self.view_state.text_search.input_mode {
return self.handle_text_search_key(key);
}
// Handle namespace hotkeys (0-9)
if let crossterm::event::KeyCode::Char(c) = key.code {
if c.is_ascii_digit() {
let index = c as usize - '0' as usize;
if index < self.namespace_hotkeys.len() {
let ns_name = &self.namespace_hotkeys[index];
let new_namespace = if ns_name == "all" {
None
} else {
Some(ns_name.clone())
};
// Update namespace and restart watchers if changed
if self.namespace != new_namespace {
self.namespace = new_namespace.clone();
self.state.clear();
self.resource_objects.clear();
self.controller_pods.clear();
// Restarted watchers start clean; stale degraded state
// from the old set would otherwise never clear.
self.degraded_watchers.clear();
if let Some(ref mut watcher) = self.watcher {
if let Err(e) = watcher.set_namespace(new_namespace) {
self.set_status_message((
format!("Failed to switch namespace: {}", e),
true,
));
} else {
self.set_status_message((
format!("Switched to namespace: {}", ns_name),
false,
));
}
}
self.view_state.selected_index = 0;
self.view_state.scroll_offset = 0;
}
return None;
}
}
}
// Handle Ctrl+F (page down), Ctrl+B (page up), and Ctrl+C (quit) before main key dispatch.
// These must be checked here so they don't collide with the plain 'f' / 'b' handlers below.
//
// Note: in raw mode the OS no longer converts Ctrl+C into SIGINT — it arrives as a
// regular key event that the application must handle explicitly.
if key.modifiers == crossterm::event::KeyModifiers::CONTROL {
let page_size = self.view_state.page_size;
match key.code {
crossterm::event::KeyCode::Char('c') => {
return Some(true); // Unconditional quit, matching terminal convention
}
crossterm::event::KeyCode::Char('f') => {
self.scroll_down(page_size);
return None;
}
crossterm::event::KeyCode::Char('b') => {
self.scroll_up(page_size);
return None;
}
crossterm::event::KeyCode::Char('d') => {
self.handle_operation_key('d');
return None;
}
_ => {}
}
}
// Handle PageDown / PageUp keys (no modifiers required).
if key.modifiers == crossterm::event::KeyModifiers::NONE {
let page_size = self.view_state.page_size;
match key.code {
crossterm::event::KeyCode::PageDown => {
self.scroll_down(page_size);
return None;
}
crossterm::event::KeyCode::PageUp => {
self.scroll_up(page_size);
return None;
}
_ => {}
}
}
match key.code {
crossterm::event::KeyCode::Char('q') => {
// Navigate back a level, closer to k9s behaviour where q never
// exits directly. At the top-level view a confirmation dialog is shown
// instead. Use Q, :q, or Ctrl+C to exit without the dialog.
return self.navigate_back_or_confirm_quit();
}
crossterm::event::KeyCode::Char('Q') => {
// Immediate unconditional quit (uppercase, intentional).
// Provides a direct exit for users who do not want the confirmation
// dialog that q/Esc shows at the top-level view.
return Some(true);
}
crossterm::event::KeyCode::Esc => {
// In a text view with an active search, Esc clears the search first
if self.is_text_search_view() && self.view_state.text_search.is_active() {
self.view_state.text_search.clear();
return None;
}
// Navigate back a level, closer to k9s behaviour where Esc never
// exits directly. At the top-level view a confirmation dialog is shown.
return self.navigate_back_or_confirm_quit();
}
crossterm::event::KeyCode::Char('?') => {
self.ui_state.show_help = !self.ui_state.show_help;
}
crossterm::event::KeyCode::Char('s')
| crossterm::event::KeyCode::Char('r')
| crossterm::event::KeyCode::Char('R')
| crossterm::event::KeyCode::Char('W') => {
let op_key = match key.code {
crossterm::event::KeyCode::Char('s') => 's',
crossterm::event::KeyCode::Char('r') => 'r',
crossterm::event::KeyCode::Char('R') => 'R',
crossterm::event::KeyCode::Char('W') => 'W',
_ => return None,
};
self.handle_operation_key(op_key);
}
crossterm::event::KeyCode::Char('t') => {
// Trace command - works from list, favorites, and detail view
if let Some(resource) = self.get_current_resource() {
self.async_state.trace.request(ResourceKey::new(
resource.resource_type.clone(),
resource.namespace.clone(),
resource.name.clone(),
));
self.view_state.trace_scroll_offset = 0;
}
}
crossterm::event::KeyCode::Char(':') => {
self.ui_state.command_mode = true;
self.ui_state.command_buffer.clear();
}
// Jump to the newest log line and resume following.
crossterm::event::KeyCode::Char('G') if self.view_state.current_view == View::Logs => {
self.logs.follow = true;
}
crossterm::event::KeyCode::Up | crossterm::event::KeyCode::Char('k') => {
self.scroll_up(1);
}
crossterm::event::KeyCode::Down | crossterm::event::KeyCode::Char('j') => {
// Max scroll in scrollable views is clamped during render
self.scroll_down(1);
}
crossterm::event::KeyCode::Char('/') => {
if self.is_text_search_view() {
// Search within the current text view (YAML/describe/trace)
self.view_state.text_search.clear();
self.view_state.text_search.input_mode = true;
} else {
// Enter filter mode
self.view_state.filter_mode = true;
self.view_state.filter.clear();
self.invalidate_layout_cache(); // Filter state affects header height
}
}
// Cycle search matches in text views (vim-style n/N)
crossterm::event::KeyCode::Char('n')
if self.is_text_search_view() && self.view_state.text_search.is_active() =>
{
self.advance_text_search(1);
}
crossterm::event::KeyCode::Char('N')
if self.is_text_search_view() && self.view_state.text_search.is_active() =>
{
self.advance_text_search(-1);
}
// Column sorting in list views (k9s-style shift-key sort)
crossterm::event::KeyCode::Char(c @ ('N' | 'A' | 'T' | 'S'))
if matches!(
self.view_state.current_view,
View::ResourceList | View::ResourceFavorites
) =>
{
use crate::tui::app::state::SortField;
let field = match c {
'N' => SortField::Name,
'A' => SortField::Age,
'T' => SortField::Type,
_ => SortField::Status,
};
self.toggle_sort(field);
}
crossterm::event::KeyCode::Char('y') => {
// View YAML - trigger async fetch
if let Some(key) = self.prepare_selected_resource_key_for_nested_view() {
self.async_state.yaml.request(key);
self.view_state.yaml_scroll_offset = 0;
self.view_state.text_search.clear();
self.view_state.current_view = View::ResourceYAML;
}
}
crossterm::event::KeyCode::Char('d') => {
if let Some(key) = self.prepare_selected_resource_key_for_nested_view() {
self.async_state.describe.request(key);
self.view_state.describe_scroll_offset = 0;
self.view_state.text_search.clear();
self.view_state.current_view = View::ResourceDescribe;
}
}
crossterm::event::KeyCode::Enter
if self.view_state.current_view == View::ResourceGraph =>
{
// Drill into the focused graph node's resource.
self.navigate_to_focused_graph_node();
}
crossterm::event::KeyCode::Enter if self.view_state.current_view == View::EventList => {
// Jump to the event's involved resource when flux9s watches it.
self.navigate_to_selected_event_resource();
}
crossterm::event::KeyCode::Enter if self.view_state.current_view.is_list_view() => {
// Save current view as previous list view before navigating
self.view_state.previous_list_view = self.view_state.current_view;
let resources = self.get_filtered_resources();
if let Some(resource) = resources.get(self.view_state.selected_index) {
let key = crate::watcher::resource_key(
&resource.namespace,
&resource.name,
&resource.resource_type,
);
self.selection_state.selected_resource_key = Some(key);
// Opened from the list, so Back returns to the list.
self.view_state.detail_back_view = None;
self.view_state.current_view = View::ResourceDetail;
}
}
// Toggle favorite - works from list view
crossterm::event::KeyCode::Char('f') if self.view_state.current_view.is_list_view() => {
let resources = self.get_filtered_resources();
if let Some(resource) = resources.get(self.view_state.selected_index) {
let key = crate::watcher::resource_key(
&resource.namespace,
&resource.name,
&resource.resource_type,
);
self.toggle_favorite(&key);
self.set_status_message((
if self.is_favorite(&key) {
format!("Added {} to favorites", resource.name)
} else {
format!("Removed {} from favorites", resource.name)
},
false,
));
}
}
crossterm::event::KeyCode::Char('h') => {
// View reconciliation history - works from list, favorites, and detail view
if let Some(resource) = self.get_current_resource() {
use crate::models::FluxResourceKind;
let key = crate::watcher::resource_key(
&resource.namespace,
&resource.name,
&resource.resource_type,
);
// Check if resource object exists and has status.history
let obj = self.resource_objects.get(&key);
let has_history = obj
.and_then(|obj| obj.get("status"))
.and_then(|s| s.get("history"))
.and_then(|h| h.as_array())
.map(|arr| !arr.is_empty())
.unwrap_or(false);
let is_kustomization = matches!(
FluxResourceKind::parse_optional(&resource.resource_type),
Some(FluxResourceKind::Kustomization)
);
if has_history {
// Save current view as previous list view before navigating
self.view_state.previous_list_view = self.view_state.current_view;
self.selection_state.selected_resource_key = Some(key);
self.view_state.current_view = View::ResourceHistory;
self.view_state.history_scroll_offset = 0;
} else {
// Show error message immediately
let error_msg = if is_kustomization {
format!(
"Reconciliation history is not supported for Kustomization '{}' in this version of Flux. History requires Flux v2.3.0 or later.",
resource.name
)
} else {
let supported_types: Vec<String> =
FluxResourceKind::history_supported_types()
.iter()
.map(|k| k.as_str().to_string())
.collect();
format!(
"Resource '{}' does not have reconciliation history. History is only available for: {}",
resource.name,
supported_types.join(", ")
)
};
self.set_status_message((error_msg, true));
}
} else {
self.set_status_message(("No resource selected".to_string(), true));
}
}
crossterm::event::KeyCode::Char('g') => {
// View resource graph - works from list, favorites, and detail view
if let Some(resource) = self.get_current_resource() {
// Check if resource type supports graph view
if !crate::trace::is_resource_type_with_graph(&resource.resource_type) {
self.set_status_message((
format!(
"Graph view not supported for {} resources",
resource.resource_type
),
true,
));
return None;
}
// Save current view as previous list view before navigating
if self.view_state.current_view.is_list_view()
|| self.view_state.current_view == View::EventList
{
self.view_state.previous_list_view = self.view_state.current_view;
}
// Trigger graph building
let key = crate::watcher::resource_key(
&resource.namespace,
&resource.name,
&resource.resource_type,
);
self.selection_state.selected_resource_key = Some(key.clone());
self.async_state.graph.request(ResourceKey {
resource_type: resource.resource_type.clone(),
namespace: resource.namespace.clone(),
name: resource.name.clone(),
});
self.view_state.graph_scroll_offset = 0; // Reset scroll
self.view_state.graph_focus_index = None; // Reset focus (set when graph loads)
self.view_state.current_view = View::ResourceGraph;
} else {
self.set_status_message(("No resource selected".to_string(), true));
}
}
crossterm::event::KeyCode::Backspace => {
// Backspace goes back (same as Escape for detail view)
if self.view_state.current_view.is_nested_view() {
// Mirror Esc: return to the graph if we came from there,
// otherwise to the previous list view.
if let Some(back) = self.detail_graph_back() {
self.view_state.current_view = back;
} else {
self.view_state.current_view = self.view_state.previous_list_view;
self.selection_state.selected_resource_key = None;
self.view_state.text_search.clear();
}
} else if self.view_state.current_view == View::ResourceFavorites {
self.view_state.current_view = View::ResourceList;
self.selection_state.selected_resource_key = None;
} else if self.view_state.current_view == View::EventList {
self.stop_kube_events_watch();
self.view_state.current_view = View::ResourceList;
self.selection_state.selected_resource_key = None;
} else if self.view_state.current_view == View::Logs {
self.logs.stop();
self.view_state.text_search.clear();
self.view_state.current_view = self.view_state.previous_list_view;
}
}
_ => {}
}
None
}
fn handle_filter_key(&mut self, key: KeyEvent) -> Option<bool> {
match key.code {
crossterm::event::KeyCode::Esc => {
// Exit filter mode
self.view_state.filter_mode = false;
let was_filtering = !self.view_state.filter.is_empty();
self.view_state.filter.clear();
if was_filtering {
self.invalidate_layout_cache(); // Filter state affects header height
}
None
}
crossterm::event::KeyCode::Enter => {
// Apply filter and exit filter mode
self.view_state.filter_mode = false;
self.view_state.selected_index = 0;
self.view_state.scroll_offset = 0;
// Only invalidate if filter was applied (non-empty) - this is when header changes
if !self.view_state.filter.is_empty() {
self.invalidate_layout_cache();
}
None
}
crossterm::event::KeyCode::Backspace => {
let was_empty = self.view_state.filter.is_empty();
self.view_state.filter.pop();
// Invalidate when transitioning from non-empty to empty (header line change)
if !was_empty && self.view_state.filter.is_empty() {
self.invalidate_layout_cache();
}
None
}
crossterm::event::KeyCode::Char(c) => {
let was_empty = self.view_state.filter.is_empty();
self.view_state.filter.push(c);
self.view_state.selected_index = 0;
self.view_state.scroll_offset = 0;
// Invalidate when transitioning from empty to non-empty (header line change)
if was_empty {
self.invalidate_layout_cache();
}
None
}
_ => None,
}
}
/// Whether the current view supports text search (`/`)
fn is_text_search_view(&self) -> bool {
self.view_state.current_view.is_text_search_view()
}
/// Handle a key press while typing a text-view search query
fn handle_text_search_key(&mut self, key: KeyEvent) -> Option<bool> {
match key.code {
crossterm::event::KeyCode::Esc => {
self.view_state.text_search.clear();
}
crossterm::event::KeyCode::Enter => {
let search = &mut self.view_state.text_search;
search.input_mode = false;
if search.is_active() {
search.current_match = 0;
search.pending_jump = true;
} else {
search.clear();
}
}
crossterm::event::KeyCode::Backspace => {
self.view_state.text_search.query.pop();
}
crossterm::event::KeyCode::Char(c) => {
self.view_state.text_search.query.push(c);
}
_ => {}
}
None
}
/// Move to the next (+1) or previous (-1) search match, wrapping around
fn advance_text_search(&mut self, delta: isize) {
let search = &mut self.view_state.text_search;
if search.total_matches == 0 {
return;
}
let total = search.total_matches as isize;
search.current_match = (search.current_match as isize + delta).rem_euclid(total) as usize;
search.pending_jump = true;
}
fn handle_submenu_key(&mut self, key: KeyEvent) -> Option<bool> {
if let Some(ref mut submenu) = self.view_state.submenu_state {
match key.code {
crossterm::event::KeyCode::Char('j') | crossterm::event::KeyCode::Down => {
submenu.move_down();
// Update scroll if needed (assuming we have enough visible space)
let visible_height = 20; // Rough estimate for submenu height
submenu.update_scroll(visible_height);
// Preview theme if this is a skin submenu
self.preview_theme_in_submenu();
}
crossterm::event::KeyCode::Char('k') | crossterm::event::KeyCode::Up => {
submenu.move_up();
let visible_height = 20;
submenu.update_scroll(visible_height);
// Preview theme if this is a skin submenu
self.preview_theme_in_submenu();
}
// Save/persist current selection (for skin submenu)
crossterm::event::KeyCode::Char('s') | crossterm::event::KeyCode::Char('S')
if submenu.command == "skin" =>
{
if let Some(value) = submenu.selected_value() {
match self.persist_theme(&value) {
Ok(_) => {
// Close submenu and clear preview
self.view_state.submenu_state = None;
self.view_state.preview_original_theme = None;
let readonly_msg = if self.config.read_only {
" (readonly mode)"
} else {
""
};
let msg =
format!("Theme '{}' saved to config{}", value, readonly_msg);
self.set_status_message((msg, false));
}
Err(e) => {
let msg = format!("Failed to save theme: {}", e);
self.set_status_message((msg, true));
}
}
}
}
crossterm::event::KeyCode::Enter => {
// Select the current item and execute the command
if let Some(value) = submenu.selected_value() {
let command = submenu.command.clone();
// Close submenu and clear preview
self.view_state.submenu_state = None;
self.view_state.preview_original_theme = None;
// Execute the command with the selected value
// For context command, trigger context switch
if command == "ctx" {
self.pending_context_switch = Some(value.clone());
self.set_status_message((
format!("Switching to context '{}'...", value),
false,
));
} else if command == "logs" {
self.open_log_view(&value);
} else if command == "skin" {
// Change theme (already previewed, so just confirm)
match self.set_theme(&value) {
Ok(_) => {
let msg = format!("Theme changed to: {}", value);
self.set_status_message((msg, false));
}
Err(e) => {
let msg = format!("Failed to load theme '{}': {}", value, e);
self.set_status_message((msg, true));
}
}
}
}
}
crossterm::event::KeyCode::Esc => {
// Cancel submenu - restore original theme if previewing
if submenu.command == "skin" {
if let Some(original_theme) = self.view_state.preview_original_theme.clone()
{
let _ = self.set_theme(&original_theme);
}
}
self.view_state.submenu_state = None;
self.view_state.preview_original_theme = None;
}
_ => {}
}
}
None
}
/// Preview theme when navigating skin submenu
fn preview_theme_in_submenu(&mut self) {
if let Some(ref submenu) = self.view_state.submenu_state {
if submenu.command == "skin" {
if let Some(theme_name) = submenu.selected_value() {
// Preview the theme (don't show errors, just silently fail)
let _ = self.preview_theme(&theme_name);
}
}
}
}
/// Navigate back one level, or show the quit confirmation dialog at the top level.
///
/// Shared implementation for `q` and `Esc`, matching k9s behaviour where
/// neither key exits the application directly. The help overlay is treated as
/// a navigable layer and is dismissed first before any view transition occurs.
/// Move keyboard focus between graph nodes in visual (top-to-bottom) order.
/// Clamps at the ends rather than wrapping so the direction stays intuitive.
/// Auto-scrolling to keep the focused node visible is handled by the renderer.
fn move_graph_focus(&mut self, forward: bool) {
let Some(graph) = self.async_state.graph.result() else {
return;
};
let order = graph.focus_order();
if order.is_empty() {
return;
}
// Where the current focus sits within the visual order (start by default).
let current_pos = self
.view_state
.graph_focus_index
.and_then(|idx| order.iter().position(|&i| i == idx));
let next_pos = match current_pos {
Some(pos) if forward => (pos + 1).min(order.len() - 1),
Some(pos) => pos.saturating_sub(1),
None => 0,
};
self.view_state.graph_focus_index = Some(order[next_pos]);
}
/// Identity of the keyboard-focused graph node when it is an individual
/// resource. Aggregate nodes (workload/resource groups) and external
/// upstream URLs have no single resource to act on, so they resolve to
/// `None`.
pub(crate) fn focused_graph_node_target(&self) -> Option<ResourceKey> {
use crate::trace::NodeType;
let node = self.async_state.graph.result().and_then(|graph| {
self.view_state
.graph_focus_index
.and_then(|idx| graph.nodes.get(idx))
})?;
if matches!(
node.node_type,
NodeType::WorkloadGroup | NodeType::ResourceGroup | NodeType::Upstream
) {
return None;
}
Some(ResourceKey::new(
node.kind.clone(),
node.namespace.clone(),
node.name.clone(),
))
}
/// Open the detail view for the focused graph node when it maps to a watched
/// resource. Aggregate nodes (workload/resource groups) and external upstream
/// URLs are not directly navigable and just show a hint instead.
fn navigate_to_focused_graph_node(&mut self) {
let has_focused_node = self
.async_state
.graph
.result()
.and_then(|graph| {
self.view_state
.graph_focus_index
.and_then(|idx| graph.nodes.get(idx))
})
.is_some();
let Some(rk) = self.focused_graph_node_target() else {
if has_focused_node {
self.set_status_message((
"Aggregate node — select an individual Flux resource to open it".to_string(),
false,
));
}
return;
};
let key = rk.to_key_string();
if self.state.get(&key).is_some() {
self.selection_state.selected_resource_key = Some(key);
// Remember to return to the graph (not the list) when the user backs
// out of the detail view.
self.view_state.detail_back_view = Some(View::ResourceGraph);
self.view_state.current_view = View::ResourceDetail;
} else {
self.set_status_message((
format!(
"{} {} is not in the current view",
rk.resource_type, rk.name
),
false,
));
}
}
/// If the current nested view was entered by drilling into a graph node
/// (detail via Enter, or YAML/describe/etc. directly on the focused node),
/// consume and return the stored back target (the graph). Returns `None`
/// for any other entry path, leaving normal back-to-list behaviour in place.
fn detail_graph_back(&mut self) -> Option<View> {
if self.view_state.current_view.is_nested_view()
&& self.view_state.current_view != View::ResourceGraph
{
self.view_state.detail_back_view.take()
} else {
None
}
}
fn navigate_back_or_confirm_quit(&mut self) -> Option<bool> {
if self.ui_state.show_help {
self.ui_state.show_help = false;
return None;
}
match self.view_state.current_view {
View::ResourceList => {
// At the top-level view there is nowhere to go back to, so ask
// for confirmation rather than exiting immediately (k9s convention).
self.ui_state.show_quit_confirm = true;
None
}
View::ResourceDetail
| View::ResourceDescribe
| View::ResourceYAML
| View::ResourceTrace
| View::ResourceHistory
| View::ResourceGraph => {
// If we drilled into this detail view from the graph, return to
// the graph; otherwise go back to the previous list view
// (favourites if we came from there, else the main resource list).
if let Some(back) = self.detail_graph_back() {
self.view_state.current_view = back;
} else {
self.view_state.current_view = self.view_state.previous_list_view;
self.selection_state.selected_resource_key = None;
self.view_state.text_search.clear();
}
None
}
View::ResourceFavorites => {
self.view_state.current_view = View::ResourceList;
None
}
View::EventList => {
self.stop_kube_events_watch();
self.view_state.current_view = View::ResourceList;
None
}
View::Logs => {
// Stop the stream; return to wherever logs were opened from.
self.logs.stop();
self.view_state.text_search.clear();
self.view_state.current_view = self.view_state.previous_list_view;
None
}
View::Help => {
self.view_state.current_view = View::ResourceList;
None
}
}
}
/// Handle a key press while the quit confirmation dialog is visible.
///
/// `y`/`Y` confirms and exits. `n`/`N`/`q`/`Esc` all cancel — `q` is
/// included so the footer hint is consistent with what actually works.
/// All other keys are ignored while the dialog is open.
fn handle_quit_confirm_key(&mut self, key: KeyEvent) -> Option<bool> {
match key.code {
crossterm::event::KeyCode::Char('y') | crossterm::event::KeyCode::Char('Y') => {
Some(true) // Confirmed — exit the application
}
crossterm::event::KeyCode::Char('n')
| crossterm::event::KeyCode::Char('N')
| crossterm::event::KeyCode::Char('q')
| crossterm::event::KeyCode::Esc => {
self.ui_state.show_quit_confirm = false;
None // Cancelled — return to normal view
}
_ => None, // Ignore all other keys while the dialog is open
}
}
/// Open the detail view for the resource the selected event is about,
/// when it is a Flux resource flux9s is watching. Back returns to the
/// events feed (the events watcher keeps running meanwhile).
fn navigate_to_selected_event_resource(&mut self) {
let events = self.filtered_kube_events();
let Some(event) = events.get(self.view_state.selected_index) else {
return;
};
let key = crate::watcher::resource_key(
&event.involved_namespace,
&event.involved_name,
&event.involved_kind,
);
if self.state.get(&key).is_none() {
// Not in the watch state: outside the namespace scope, a non-Flux
// kind, or its watcher isn't running. Name the namespace so a
// scope mismatch is visible, and point at the keys that still work.
self.set_status_message((
format!(