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
use super::*;
impl App {
/// Open the namespace switcher immediately with a loading placeholder, then
/// fetch the list off-thread (it arrives as `Msg::Namespaces`).
pub(super) fn open_namespaces(&mut self) {
// Show whatever is cached immediately (instant reopen); a fresh fetch
// refreshes it. Only fall back to the bare `<all>` placeholder when the
// cache is empty.
if self.ns_list.is_empty() {
self.ns_list = vec!["<all>".into()];
}
self.ns_state.select(Some(0));
self.ns_filter.clear();
self.mode = Mode::Namespaces;
self.spawn_namespace_fetch();
}
/// Fetch the namespace list off-thread; it arrives as `Msg::Namespaces` and
/// refreshes `ns_list`, which backs both the switcher popup and `:<kind>
/// <ns>` palette completion.
pub(super) fn spawn_namespace_fetch(&self) {
let client = self.cluster.client.clone();
let kind = self.cluster.resolve("namespaces").map(|k| k.ar);
let tx = self.tx.clone();
let genr = self.generation;
tokio::spawn(async move {
let Some(ar) = kind else { return };
let api: Api<DynamicObject> = Api::all_with(client, &ar);
if let Ok(list) = api.list(&ListParams::default()).await {
let mut names: Vec<String> = list
.items
.into_iter()
.filter_map(|o| o.metadata.name)
.collect();
names.sort();
names.insert(0, "<all>".into());
let _ = tx
.send(Msg::Namespaces {
generation: genr,
list: names,
})
.await;
}
});
}
/// Warm the namespace cache when the command palette opens, so `:<kind>
/// <ns>` can offer completions without waiting for the switcher popup. A
/// no-op once real namespaces are cached (the `<all>` sentinel doesn't
/// count).
pub(super) fn ensure_namespace_cache(&mut self) {
if !self.ns_list.iter().any(|n| n != "<all>") {
self.spawn_namespace_fetch();
}
}
/// Namespaces for the switcher: `<all>` is always pinned first, the rest
/// fuzzy-matched against the type-to-filter buffer.
pub fn filtered_namespaces(&self) -> Vec<String> {
let mut out = vec!["<all>".to_string()];
let rest = self.ns_list.iter().filter(|n| n.as_str() != "<all>");
if self.ns_filter.is_empty() {
out.extend(rest.cloned());
} else {
let mut scored: Vec<(i64, &String)> = rest
.filter_map(|n| self.matcher.fuzzy_match(n, &self.ns_filter).map(|s| (s, n)))
.collect();
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
out.extend(scored.into_iter().map(|(_, n)| n.clone()));
}
out
}
pub(super) fn key_namespaces(&mut self, key: KeyEvent) {
let len = self.filtered_namespaces().len();
match key.code {
KeyCode::Esc => {
// First esc clears the filter and jumps back to the top
// (`<all>`); a second esc closes the switcher.
if self.ns_filter.is_empty() {
self.mode = Mode::Table;
} else {
self.ns_filter.clear();
self.ns_state.select(Some(0));
}
}
KeyCode::Down => list_step(&mut self.ns_state, len, true),
KeyCode::Up => list_step(&mut self.ns_state, len, false),
KeyCode::Enter => {
let filtered = self.filtered_namespaces();
let has_real_match = filtered.iter().any(|n| n != "<all>");
let chosen = if !self.ns_filter.trim().is_empty() && !has_real_match {
// Typed text matches no listed namespace → take it verbatim
// so you can still switch when listing is restricted.
Some(self.ns_filter.trim().to_string())
} else {
self.ns_state
.selected()
.and_then(|i| filtered.get(i).cloned())
};
if let Some(ns) = chosen {
self.set_namespace(ns);
}
}
KeyCode::Backspace => {
self.ns_filter.pop();
self.select_best_namespace_match();
}
KeyCode::Char(c) => {
self.ns_filter.push(c);
self.select_best_namespace_match();
}
_ => {}
}
}
/// Jump the namespace-switcher cursor to the best fuzzy match after the
/// filter buffer changes. `<all>` stays pinned at index 0 of the list (so
/// it's always reachable), but it should only be *selected* by default
/// when browsing with no filter — once you've typed something with a
/// real match, that match belongs under the cursor, not `<all>`.
pub(super) fn select_best_namespace_match(&mut self) {
let idx = if !self.ns_filter.is_empty() && self.filtered_namespaces().len() > 1 {
1 // right after the pinned <all> — the top-scored real match
} else {
0
};
self.ns_state.select(Some(idx));
}
pub(super) fn set_namespace(&mut self, sel: String) {
self.namespace = normalize_ns(&sel);
self.flash = format!("namespace: {}", self.namespace_label());
self.flash_err = false;
self.ns_filter.clear();
self.mode = Mode::Table;
self.table_state.select(Some(0));
self.record_history();
self.start_watch();
}
pub(super) fn open_contexts(&mut self) {
self.ctx_filter.clear();
self.ctx_list.clear();
self.ctx_state.select(None);
self.mode = Mode::Contexts;
let tx = self.tx.clone();
let genr = self.generation;
tokio::spawn(async move {
let mut list = Cluster::list_contexts();
list.sort();
let _ = tx
.send(Msg::Contexts {
generation: genr,
list,
})
.await;
});
}
/// Contexts for the switcher, fuzzy-matched against the type-to-filter
/// buffer (see `filtered_namespaces` for the same pattern).
pub fn filtered_contexts(&self) -> Vec<String> {
if self.ctx_filter.is_empty() {
return self.ctx_list.clone();
}
let mut scored: Vec<(i64, &String)> = self
.ctx_list
.iter()
.filter_map(|c| {
self.matcher
.fuzzy_match(c, &self.ctx_filter)
.map(|s| (s, c))
})
.collect();
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
scored.into_iter().map(|(_, c)| c.clone()).collect()
}
pub(super) fn key_contexts(&mut self, key: KeyEvent) {
let len = self.filtered_contexts().len();
match key.code {
KeyCode::Esc => {
// First esc clears the filter, second closes the switcher.
if self.ctx_filter.is_empty() {
self.mode = Mode::Table;
} else {
self.ctx_filter.clear();
self.ctx_state.select(Some(0));
}
}
KeyCode::Down => list_step(&mut self.ctx_state, len, true),
KeyCode::Up => list_step(&mut self.ctx_state, len, false),
KeyCode::Enter => {
if let Some(name) = self
.ctx_state
.selected()
.and_then(|i| self.filtered_contexts().get(i).cloned())
{
self.mode = Mode::Table;
self.switch_context(name);
}
}
KeyCode::Backspace => {
self.ctx_filter.pop();
self.ctx_state.select(Some(0));
}
KeyCode::Char(c) => {
self.ctx_filter.push(c);
self.ctx_state.select(Some(0));
}
_ => {}
}
}
/// Rebuild the cluster connection against a different kubeconfig context.
/// Reconnecting re-runs API discovery, which can take seconds, so it runs
/// off-thread; the new cluster (or error) arrives as `Msg::ContextSwitched`.
pub(super) fn switch_context(&mut self, name: String) {
if name == self.cluster.context {
return;
}
self.flash = format!("switching to {name}…");
self.flash_err = false;
// Stop the current context's watches and clear stale rows while we
// reconnect; the new watch starts when the connection lands.
self.bump_generation();
self.store.clear();
self.invalidate_rows();
let tx = self.tx.clone();
let genr = self.generation;
tokio::spawn(async move {
let result = Cluster::connect_context(&name)
.await
.map(Box::new)
.map_err(|e| e.to_string());
let _ = tx
.send(Msg::ContextSwitched {
generation: genr,
name,
result,
})
.await;
});
}
/// Install a freshly-connected cluster from a context switch. Config is
/// re-resolved so per-cluster/per-context overrides (aliases, plugins,
/// skin, defaults) follow the new context.
pub(super) fn apply_context_switch(&mut self, name: String, mut cluster: Box<Cluster>) {
let resolved = self.config.resolve(&name, &cluster.cluster_name);
self.user_aliases = resolved.config.aliases;
self.plugins = resolved.config.plugins;
self.skin_colors = resolved.config.skin.colors;
self.readonly = self.readonly_override.unwrap_or(resolved.config.readonly);
cluster.add_aliases(&self.user_aliases);
self.bump_generation();
self.namespace = resolved
.config
.default_namespace
.unwrap_or_else(|| cluster.default_namespace.clone());
self.cluster = *cluster;
self.stack.clear();
// View history references the old cluster's kinds and namespaces.
self.history.clear();
self.history_pos = 0;
self.kind = None;
self.kind_plural.clear();
self.labels = None;
self.fields = None;
self.scope_label = None;
self.filter.clear();
// The old cluster's namespaces don't apply here — drop them so palette
// completion re-fetches against the new cluster on the next `:`.
self.ns_list.clear();
// Permissions differ per cluster — drop the old allow-list.
self.rbac_allowed = None;
self.last_rbac_ns = None;
crate::theme::set_background(resolved.config.skin.background);
self.apply_context_skin(resolved.skin_override);
self.flash = format!("context: {name}");
self.flash_err = false;
if let Some(w) = resolved.warnings.first() {
self.flash_warn(w);
}
let kind = resolved
.config
.default_resource
.unwrap_or_else(|| "pods".into());
self.switch_kind(&kind);
}
}