• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kdash-rs / kdash / 24322931837

13 Apr 2026 02:30AM UTC coverage: 71.561% (-0.2%) from 71.732%
24322931837

Pull #515

github

web-flow
Merge e1c42e98e into 5eb37a632
Pull Request #515: feat(ui): more efficient redraw

25 of 79 new or added lines in 3 files covered. (31.65%)

5 existing lines in 3 files now uncovered.

9977 of 13942 relevant lines covered (71.56%)

144.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.85
/src/ui/utils.rs
1
use std::{borrow::Cow, collections::BTreeMap, io::Cursor, rc::Rc, sync::OnceLock};
2

3
use glob_match::glob_match;
4
use ratatui::{
5
  layout::{Constraint, Direction, Layout, Position, Rect},
6
  style::{Color, Modifier, Style},
7
  symbols,
8
  text::{Line, Span, Text},
9
  widgets::{Block, Borders, Paragraph, Row, Table, Wrap},
10
  Frame,
11
};
12
use serde::Serialize;
13

14
use super::HIGHLIGHT;
15
use crate::app::{
16
  key_binding::DEFAULT_KEYBINDING,
17
  models::{KubeResource, StatefulTable},
18
  ActiveBlock, App,
19
};
20
use crate::event::Key;
21
use crate::ui::theme::override_color;
22
// Utils
23

24
#[derive(Clone, Debug, PartialEq, Eq)]
25
pub enum LinePart<'a> {
26
  Default(Cow<'a, str>),
27
  Help(Cow<'a, str>),
28
}
29

30
// Catppuccin Macchiato (dark)
31
pub const MACCHIATO_BASE: Color = Color::Rgb(36, 39, 58);
32
pub const MACCHIATO_BLUE: Color = Color::Rgb(138, 173, 244);
33
pub const MACCHIATO_GREEN: Color = Color::Rgb(166, 218, 149);
34
pub const MACCHIATO_RED: Color = Color::Rgb(237, 135, 150);
35
pub const MACCHIATO_YELLOW: Color = Color::Rgb(238, 212, 159);
36
pub const MACCHIATO_PEACH: Color = Color::Rgb(245, 169, 127);
37
pub const MACCHIATO_TEXT: Color = Color::Rgb(202, 211, 245);
38
pub const MACCHIATO_MAUVE: Color = Color::Rgb(198, 160, 246);
39
// Catppuccin Latte (light)
40
pub const LATTE_MAUVE: Color = Color::Rgb(136, 57, 239);
41
pub const LATTE_TEXT: Color = Color::Rgb(76, 79, 105);
42
pub const LATTE_BLUE: Color = Color::Rgb(30, 102, 245);
43
pub const LATTE_MAROON: Color = Color::Rgb(230, 69, 83);
44
pub const LATTE_GREEN: Color = Color::Rgb(64, 160, 43);
45
pub const LATTE_RED: Color = Color::Rgb(210, 15, 57);
46
pub const LATTE_PEACH: Color = Color::Rgb(254, 100, 11);
47
pub const LATTE_BASE: Color = Color::Rgb(239, 241, 245);
48
const CATPPUCCIN_MACCHIATO_THEME: &[u8] =
49
  include_bytes!("../../assets/themes/CatppuccinMacchiato.tmTheme");
50
const CATPPUCCIN_LATTE_THEME: &[u8] = include_bytes!("../../assets/themes/CatppuccinLatte.tmTheme");
51

52
/// Convert a syntect highlight segment into an owned ratatui Span.
53
fn syntect_to_ratatui_span_owned(
×
54
  (style, content): (syntect::highlighting::Style, &str),
×
55
) -> Option<Span<'static>> {
×
56
  use syntect::highlighting::FontStyle;
57
  let fg = if style.foreground.a > 0 {
×
58
    Some(Color::Rgb(
×
59
      style.foreground.r,
×
60
      style.foreground.g,
×
61
      style.foreground.b,
×
62
    ))
×
63
  } else {
64
    None
×
65
  };
66
  let bg = if style.background.a > 0 {
×
67
    Some(Color::Rgb(
×
68
      style.background.r,
×
69
      style.background.g,
×
70
      style.background.b,
×
71
    ))
×
72
  } else {
73
    None
×
74
  };
75
  let modifier = {
×
76
    let fs = style.font_style;
×
77
    let mut m = Modifier::empty();
×
78
    if fs.contains(FontStyle::BOLD) {
×
79
      m |= Modifier::BOLD;
×
80
    }
×
81
    if fs.contains(FontStyle::ITALIC) {
×
82
      m |= Modifier::ITALIC;
×
83
    }
×
84
    if fs.contains(FontStyle::UNDERLINE) {
×
85
      m |= Modifier::UNDERLINED;
×
86
    }
×
87
    m
×
88
  };
89
  let ratatui_style = Style::default()
×
90
    .fg(fg.unwrap_or_default())
×
91
    .bg(bg.unwrap_or_default())
×
92
    .add_modifier(modifier);
×
93
  Some(Span::styled(content.to_owned(), ratatui_style))
×
94
}
×
95

96
fn get_syntax_set() -> &'static syntect::parsing::SyntaxSet {
×
97
  static SYNTAX_SET: OnceLock<syntect::parsing::SyntaxSet> = OnceLock::new();
98
  SYNTAX_SET.get_or_init(syntect::parsing::SyntaxSet::load_defaults_newlines)
×
99
}
×
100

101
fn get_yaml_syntax_reference() -> &'static syntect::parsing::SyntaxReference {
×
102
  static YAML_SYNTAX_REFERENCE: OnceLock<syntect::parsing::SyntaxReference> = OnceLock::new();
103
  YAML_SYNTAX_REFERENCE.get_or_init(|| {
×
104
    get_syntax_set()
×
105
      .find_syntax_by_extension("yaml")
×
106
      .unwrap()
×
107
      .clone()
×
108
  })
×
109
}
×
110

111
struct YamlThemes {
112
  dark: syntect::highlighting::Theme,
113
  light: syntect::highlighting::Theme,
114
}
115

116
fn get_yaml_themes() -> &'static YamlThemes {
×
117
  static YAML_THEMES: OnceLock<YamlThemes> = OnceLock::new();
118
  YAML_THEMES.get_or_init(|| {
×
119
    let dark = load_embedded_theme(CATPPUCCIN_MACCHIATO_THEME);
×
120
    let light = load_embedded_theme(CATPPUCCIN_LATTE_THEME);
×
121
    YamlThemes { dark, light }
×
122
  })
×
123
}
×
124

125
fn load_embedded_theme(theme_bytes: &[u8]) -> syntect::highlighting::Theme {
×
126
  syntect::highlighting::ThemeSet::load_from_reader(&mut Cursor::new(theme_bytes))
×
127
    .expect("embedded theme should load")
×
128
}
×
129

130
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
131
pub enum Styles {
132
  Text,
133
  Failure,
134
  Warning,
135
  Success,
136
  Primary,
137
  Secondary,
138
  Help,
139
  Background,
140
}
141

142
pub fn theme_styles(light: bool) -> BTreeMap<Styles, Style> {
404✔
143
  let mut styles = if light {
404✔
144
    BTreeMap::from([
×
145
      (Styles::Text, Style::default().fg(LATTE_TEXT)),
×
146
      (Styles::Failure, Style::default().fg(LATTE_RED)),
×
147
      (Styles::Warning, Style::default().fg(LATTE_PEACH)),
×
148
      (Styles::Success, Style::default().fg(LATTE_GREEN)),
×
149
      (Styles::Primary, Style::default().fg(LATTE_MAUVE)),
×
150
      (Styles::Secondary, Style::default().fg(LATTE_MAROON)),
×
151
      (Styles::Help, Style::default().fg(LATTE_BLUE)),
×
152
      (
×
153
        Styles::Background,
×
154
        Style::default().bg(LATTE_BASE).fg(LATTE_TEXT),
×
155
      ),
×
156
    ])
×
157
  } else {
158
    BTreeMap::from([
404✔
159
      (Styles::Text, Style::default().fg(MACCHIATO_TEXT)),
404✔
160
      (Styles::Failure, Style::default().fg(MACCHIATO_RED)),
404✔
161
      (Styles::Warning, Style::default().fg(MACCHIATO_PEACH)),
404✔
162
      (Styles::Success, Style::default().fg(MACCHIATO_GREEN)),
404✔
163
      (Styles::Primary, Style::default().fg(MACCHIATO_MAUVE)),
404✔
164
      (Styles::Secondary, Style::default().fg(MACCHIATO_YELLOW)),
404✔
165
      (Styles::Help, Style::default().fg(MACCHIATO_BLUE)),
404✔
166
      (
404✔
167
        Styles::Background,
404✔
168
        Style::default().bg(MACCHIATO_BASE).fg(MACCHIATO_TEXT),
404✔
169
      ),
404✔
170
    ])
404✔
171
  };
172

173
  apply_theme_override(&mut styles, Styles::Text, "text", false, light);
404✔
174
  apply_theme_override(&mut styles, Styles::Failure, "failure", false, light);
404✔
175
  apply_theme_override(&mut styles, Styles::Warning, "warning", false, light);
404✔
176
  apply_theme_override(&mut styles, Styles::Success, "success", false, light);
404✔
177
  apply_theme_override(&mut styles, Styles::Primary, "primary", false, light);
404✔
178
  apply_theme_override(&mut styles, Styles::Secondary, "secondary", false, light);
404✔
179
  apply_theme_override(&mut styles, Styles::Help, "help", false, light);
404✔
180
  apply_theme_override(&mut styles, Styles::Background, "background", true, light);
404✔
181

182
  styles
404✔
183
}
404✔
184

185
pub fn title_style(txt: &str) -> Span<'_> {
8✔
186
  Span::styled(txt, style_bold())
8✔
187
}
8✔
188

189
pub fn default_part<'a, S: Into<Cow<'a, str>>>(text: S) -> LinePart<'a> {
99✔
190
  LinePart::Default(text.into())
99✔
191
}
99✔
192

193
pub fn help_part<'a, S: Into<Cow<'a, str>>>(text: S) -> LinePart<'a> {
143✔
194
  LinePart::Help(text.into())
143✔
195
}
143✔
196

197
pub fn style_header(light: bool) -> Style {
12✔
198
  style_primary(light).add_modifier(Modifier::REVERSED)
12✔
199
}
12✔
200

201
pub fn style_bold() -> Style {
8✔
202
  Style::default().add_modifier(Modifier::BOLD)
8✔
203
}
8✔
204

205
pub fn style_text(light: bool) -> Style {
107✔
206
  *theme_styles(light).get(&Styles::Text).unwrap()
107✔
207
}
107✔
208
pub fn style_logo(light: bool) -> Style {
3✔
209
  style_primary(light)
3✔
210
}
3✔
211
pub fn style_failure(light: bool) -> Style {
10✔
212
  *theme_styles(light).get(&Styles::Failure).unwrap()
10✔
213
}
10✔
214
pub fn style_warning(light: bool) -> Style {
2✔
215
  *theme_styles(light).get(&Styles::Warning).unwrap()
2✔
216
}
2✔
217
pub fn style_caution(light: bool) -> Style {
2✔
218
  style_warning(light)
2✔
219
}
2✔
220
pub fn style_success(light: bool) -> Style {
4✔
221
  *theme_styles(light).get(&Styles::Success).unwrap()
4✔
222
}
4✔
223
pub fn style_primary(light: bool) -> Style {
101✔
224
  *theme_styles(light).get(&Styles::Primary).unwrap()
101✔
225
}
101✔
226
pub fn style_help(light: bool) -> Style {
134✔
227
  *theme_styles(light).get(&Styles::Help).unwrap()
134✔
228
}
134✔
229

230
pub fn style_secondary(light: bool) -> Style {
40✔
231
  *theme_styles(light).get(&Styles::Secondary).unwrap()
40✔
232
}
40✔
233

234
pub fn style_main_background(light: bool) -> Style {
6✔
235
  *theme_styles(light).get(&Styles::Background).unwrap()
6✔
236
}
6✔
237

238
pub fn style_highlight() -> Style {
15✔
239
  Style::default().add_modifier(Modifier::REVERSED)
15✔
240
}
15✔
241

242
fn line_part_style(part: &LinePart<'_>, light: bool, bold: bool) -> Style {
229✔
243
  let style = match part {
229✔
244
    LinePart::Default(_) => style_text(light),
95✔
245
    LinePart::Help(_) => style_help(light),
134✔
246
  };
247
  if bold {
229✔
248
    style.add_modifier(Modifier::BOLD)
87✔
249
  } else {
250
    style
142✔
251
  }
252
}
229✔
253

254
fn apply_theme_override(
3,232✔
255
  styles: &mut BTreeMap<Styles, Style>,
3,232✔
256
  slot: Styles,
3,232✔
257
  config_key: &str,
3,232✔
258
  background: bool,
3,232✔
259
  light: bool,
3,232✔
260
) {
3,232✔
261
  if let Some(color) = override_color(config_key, light) {
3,232✔
262
    let style = styles.entry(slot).or_default();
×
263
    *style = if background {
×
264
      style.bg(color)
×
265
    } else {
266
      style.fg(color)
×
267
    };
268
  }
3,232✔
269
}
3,232✔
270

271
pub fn mixed_line<'a, I>(parts: I, light: bool) -> Line<'a>
74✔
272
where
74✔
273
  I: IntoIterator<Item = LinePart<'a>>,
74✔
274
{
275
  styled_line(parts, light, false)
74✔
276
}
74✔
277

278
pub fn mixed_bold_line<'a, I>(parts: I, light: bool) -> Line<'a>
39✔
279
where
39✔
280
  I: IntoIterator<Item = LinePart<'a>>,
39✔
281
{
282
  styled_line(parts, light, true)
39✔
283
}
39✔
284

285
pub fn help_bold_line<'a, S: Into<Cow<'a, str>>>(text: S, light: bool) -> Line<'a> {
9✔
286
  mixed_bold_line([help_part(text)], light)
9✔
287
}
9✔
288

289
pub fn key_hints(keys: &[Key]) -> String {
9✔
290
  keys
9✔
291
    .iter()
9✔
292
    .map(ToString::to_string)
9✔
293
    .collect::<Vec<_>>()
9✔
294
    .join("/")
9✔
295
}
9✔
296

297
pub fn action_hint(action: &str, key: Key) -> String {
65✔
298
  format!("{} {}", action, key)
65✔
299
}
65✔
300

301
pub fn describe_and_yaml_hint() -> String {
6✔
302
  format!(
6✔
303
    "{} | {} ",
304
    action_hint("describe", DEFAULT_KEYBINDING.describe_resource.key),
6✔
305
    action_hint("yaml", DEFAULT_KEYBINDING.resource_yaml.key)
6✔
306
  )
307
}
6✔
308

309
pub fn describe_yaml_and_logs_hint() -> String {
5✔
310
  format!(
5✔
311
    "{} | {} ",
312
    describe_and_yaml_hint().trim_end(),
5✔
313
    action_hint("logs", DEFAULT_KEYBINDING.aggregate_logs.key)
5✔
314
  )
315
}
5✔
316

317
pub fn describe_yaml_logs_and_esc_hint() -> String {
×
318
  format!(
×
319
    "{} | back {} ",
320
    describe_yaml_and_logs_hint().trim_end(),
×
321
    DEFAULT_KEYBINDING.esc.key
×
322
  )
323
}
×
324

325
pub fn describe_yaml_and_esc_hint() -> String {
×
326
  format!(
×
327
    "{} | back {} ",
328
    describe_and_yaml_hint().trim_end(),
×
329
    DEFAULT_KEYBINDING.esc.key
×
330
  )
331
}
×
332

333
pub fn describe_yaml_decode_and_esc_hint() -> String {
×
334
  format!(
×
335
    "{} | {} | back {} ",
336
    describe_and_yaml_hint().trim_end(),
×
337
    action_hint("decode", DEFAULT_KEYBINDING.decode_secret.key),
×
338
    DEFAULT_KEYBINDING.esc.key
×
339
  )
340
}
×
341

342
pub fn filter_cursor_position(area: Rect, prefix_width: usize, filter: &str) -> Position {
7✔
343
  Position {
7✔
344
    x: area.x
7✔
345
      + (prefix_width as u16 + 1 + filter.chars().count() as u16).min(area.width.saturating_sub(2)),
7✔
346
    y: area.y,
7✔
347
  }
7✔
348
}
7✔
349

350
fn styled_line<'a, I>(parts: I, light: bool, bold: bool) -> Line<'a>
113✔
351
where
113✔
352
  I: IntoIterator<Item = LinePart<'a>>,
113✔
353
{
354
  Line::from(
113✔
355
    parts
113✔
356
      .into_iter()
113✔
357
      .map(|part| {
229✔
358
        let style = line_part_style(&part, light, bold);
229✔
359
        match part {
229✔
360
          LinePart::Default(text) | LinePart::Help(text) => Span::styled(text, style),
229✔
361
        }
362
      })
229✔
363
      .collect::<Vec<_>>(),
113✔
364
  )
365
}
113✔
366

367
pub fn get_gauge_symbol(enhanced_graphics: bool) -> &'static str {
12✔
368
  if enhanced_graphics {
12✔
369
    symbols::line::THICK_HORIZONTAL
4✔
370
  } else {
371
    symbols::line::HORIZONTAL
8✔
372
  }
373
}
12✔
374

375
pub fn table_header_style(cells: Vec<&str>, light: bool) -> Row<'_> {
9✔
376
  Row::new(cells).style(style_text(light)).bottom_margin(0)
9✔
377
}
9✔
378

379
pub fn horizontal_chunks(constraints: Vec<Constraint>, size: Rect) -> Rc<[Rect]> {
3✔
380
  Layout::default()
3✔
381
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
3✔
382
      &constraints,
3✔
383
    ))
3✔
384
    .direction(Direction::Horizontal)
3✔
385
    .split(size)
3✔
386
}
3✔
387

388
pub fn horizontal_chunks_with_margin(
6✔
389
  constraints: Vec<Constraint>,
6✔
390
  size: Rect,
6✔
391
  margin: u16,
6✔
392
) -> Rc<[Rect]> {
6✔
393
  Layout::default()
6✔
394
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
6✔
395
      &constraints,
6✔
396
    ))
6✔
397
    .direction(Direction::Horizontal)
6✔
398
    .margin(margin)
6✔
399
    .split(size)
6✔
400
}
6✔
401

402
pub fn vertical_chunks(constraints: Vec<Constraint>, size: Rect) -> Rc<[Rect]> {
11✔
403
  Layout::default()
11✔
404
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
11✔
405
      &constraints,
11✔
406
    ))
11✔
407
    .direction(Direction::Vertical)
11✔
408
    .split(size)
11✔
409
}
11✔
410

411
pub fn vertical_chunks_with_margin(
8✔
412
  constraints: Vec<Constraint>,
8✔
413
  size: Rect,
8✔
414
  margin: u16,
8✔
415
) -> Rc<[Rect]> {
8✔
416
  Layout::default()
8✔
417
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
8✔
418
      &constraints,
8✔
419
    ))
8✔
420
    .direction(Direction::Vertical)
8✔
421
    .margin(margin)
8✔
422
    .split(size)
8✔
423
}
8✔
424

425
pub fn layout_block(title: Span<'_>) -> Block<'_> {
8✔
426
  Block::default().borders(Borders::ALL).title(title)
8✔
427
}
8✔
428

429
pub fn layout_block_default(title: &str) -> Block<'_> {
8✔
430
  layout_block(title_style(title))
8✔
431
}
8✔
432

433
pub fn layout_block_default_line(title: Line<'_>) -> Block<'_> {
11✔
434
  Block::default().borders(Borders::ALL).title(title)
11✔
435
}
11✔
436

437
pub fn layout_block_active_line(title: Line<'_>, light: bool) -> Block<'_> {
5✔
438
  Block::default()
5✔
439
    .borders(Borders::ALL)
5✔
440
    .title(title)
5✔
441
    .style(style_secondary(light))
5✔
442
}
5✔
443

444
pub fn layout_block_active_span(title: Line<'_>, light: bool) -> Block<'_> {
2✔
445
  layout_block_active_line(title, light)
2✔
446
}
2✔
447

448
pub fn layout_block_top_border(title: Line<'_>) -> Block<'_> {
9✔
449
  Block::default().borders(Borders::TOP).title(title)
9✔
450
}
9✔
451

452
enum FilterDisplayState<'a> {
453
  Inactive,
454
  EditingEmpty,
455
  Value { filter: &'a str, active: bool },
456
}
457

458
fn filter_display_state(filter: &str, active: bool) -> FilterDisplayState<'_> {
15✔
459
  if active && filter.is_empty() {
15✔
460
    FilterDisplayState::EditingEmpty
×
461
  } else if !filter.is_empty() {
15✔
462
    FilterDisplayState::Value { filter, active }
6✔
463
  } else {
464
    FilterDisplayState::Inactive
9✔
465
  }
466
}
15✔
467

468
fn filter_display_parts(filter: &str, active: bool) -> Vec<LinePart<'_>> {
15✔
469
  let state = filter_display_state(filter, active);
15✔
470
  let inactive_text = action_hint("filter", DEFAULT_KEYBINDING.filter.key);
15✔
471
  let clear_suffix = format!(" | clear {} ", DEFAULT_KEYBINDING.esc.key);
15✔
472
  let edit_suffix = format!(" | edit {} ", DEFAULT_KEYBINDING.filter.key);
15✔
473

474
  match state {
15✔
475
    FilterDisplayState::Inactive => vec![help_part(inactive_text)],
9✔
476
    FilterDisplayState::EditingEmpty => {
477
      vec![help_part("[type to filter]"), help_part(clear_suffix)]
×
478
    }
479
    FilterDisplayState::Value {
480
      filter,
4✔
481
      active: true,
482
    } => vec![
4✔
483
      default_part(format!("[{}]", filter)),
4✔
484
      help_part(clear_suffix),
4✔
485
    ],
486
    FilterDisplayState::Value {
487
      filter,
2✔
488
      active: false,
489
    } => vec![
2✔
490
      default_part(format!("[{}]", filter)),
2✔
491
      help_part(edit_suffix),
2✔
492
    ],
493
  }
494
}
15✔
495

496
pub fn filter_status_parts(filter: &str, active: bool) -> Vec<LinePart<'_>> {
6✔
497
  filter_display_parts(filter, active)
6✔
498
}
6✔
499

500
pub fn owned_filter_status_parts(filter: &str, active: bool) -> Vec<LinePart<'static>> {
9✔
501
  filter_display_parts(filter, active)
9✔
502
    .into_iter()
9✔
503
    .map(|part| match part {
13✔
504
      LinePart::Default(text) => default_part(text.into_owned()),
4✔
505
      LinePart::Help(text) => help_part(text.into_owned()),
9✔
506
    })
13✔
507
    .collect()
9✔
508
}
9✔
509

510
pub fn title_with_dual_style<'a>(part_1: String, part_2: Line<'a>, light: bool) -> Line<'a> {
11✔
511
  let mut spans = vec![Span::styled(
11✔
512
    part_1,
11✔
513
    style_secondary(light).add_modifier(Modifier::BOLD),
11✔
514
  )];
515
  spans.extend(part_2.spans);
11✔
516
  Line::from(spans)
11✔
517
}
11✔
518

519
pub fn copy_and_escape_title_line<'a, S: Into<Cow<'a, str>>>(_target: S, light: bool) -> Line<'a> {
×
520
  mixed_bold_line(
×
521
    [
×
522
      help_part(format!(
×
523
        "{} | ",
×
524
        action_hint("copy", DEFAULT_KEYBINDING.copy_to_clipboard.key)
×
525
      )),
×
526
      help_part(format!("back {} ", DEFAULT_KEYBINDING.esc.key)),
×
527
    ],
×
528
    light,
×
529
  )
530
}
×
531

532
pub fn copy_scroll_and_escape_title_line<'a, S: Into<Cow<'a, str>>>(
×
533
  _target: S,
×
534
  auto_scroll: bool,
×
535
  light: bool,
×
536
) -> Line<'a> {
×
537
  let auto_scroll_action = if auto_scroll {
×
538
    "pause scroll"
×
539
  } else {
540
    "resume scroll"
×
541
  };
542
  mixed_bold_line(
×
543
    [
×
544
      help_part(format!(
×
545
        "{} | {} | ",
×
546
        action_hint("copy", DEFAULT_KEYBINDING.copy_to_clipboard.key),
×
547
        action_hint(auto_scroll_action, DEFAULT_KEYBINDING.log_auto_scroll.key)
×
548
      )),
×
549
      help_part(format!("back {} ", DEFAULT_KEYBINDING.esc.key)),
×
550
    ],
×
551
    light,
×
552
  )
553
}
×
554

555
pub fn split_hint_suffix(text: &str) -> (&str, Option<&str>) {
79✔
556
  if let Some(pos) = text.rfind(" <") {
79✔
557
    (&text[..pos], Some(&text[(pos + 1)..]))
79✔
558
  } else {
559
    (text, None)
×
560
  }
561
}
79✔
562

563
/// helper function to create a centered rect using up
564
/// certain percentage of the available rect `r`
565
pub fn centered_rect(width: u16, height: u16, r: Rect) -> Rect {
4✔
566
  let Rect {
567
    width: grid_width,
4✔
568
    height: grid_height,
4✔
569
    ..
570
  } = r;
4✔
571
  let outer_height = (grid_height / 2).saturating_sub(height / 2);
4✔
572

573
  let popup_layout = Layout::default()
4✔
574
    .direction(Direction::Vertical)
4✔
575
    .constraints(
4✔
576
      [
4✔
577
        Constraint::Length(outer_height),
4✔
578
        Constraint::Length(height),
4✔
579
        Constraint::Length(outer_height),
4✔
580
      ]
4✔
581
      .as_ref(),
4✔
582
    )
4✔
583
    .split(r);
4✔
584

585
  let outer_width = (grid_width / 2).saturating_sub(width / 2);
4✔
586

587
  Layout::default()
4✔
588
    .direction(Direction::Horizontal)
4✔
589
    .constraints(
4✔
590
      [
4✔
591
        Constraint::Length(outer_width),
4✔
592
        Constraint::Length(width),
4✔
593
        Constraint::Length(outer_width),
4✔
594
      ]
4✔
595
      .as_ref(),
4✔
596
    )
4✔
597
    .split(popup_layout[1])[1]
4✔
598
}
4✔
599

600
pub fn loading(f: &mut Frame<'_>, block: Block<'_>, area: Rect, is_loading: bool, light: bool) {
9✔
601
  if is_loading {
9✔
602
    let text = "\n\n Loading ...\n\n".to_owned();
×
603
    let text = Text::from(text);
×
604
    let text = text.patch_style(style_secondary(light));
×
605

×
606
    // Contains the text
×
607
    let paragraph = Paragraph::new(text)
×
608
      .style(style_secondary(light))
×
609
      .block(block);
×
610
    f.render_widget(paragraph, area);
×
611
  } else {
×
612
    f.render_widget(block, area)
9✔
613
  }
614
}
9✔
615

616
// using a macro to reuse code as generics will make handling lifetimes a PITA
617
#[macro_export]
618
macro_rules! draw_resource_tab {
619
  ($title:expr, $block:expr, $f:expr, $app:expr, $area:expr, $fn1:expr, $fn2:expr, $res:expr) => {
620
    match $block {
621
      ActiveBlock::Describe => draw_describe_block(
622
        $f,
623
        $app,
624
        $area,
625
        title_with_dual_style(
626
          get_resource_title($app, $title, get_describe_active($block), $res.items.len()),
627
          $crate::ui::utils::copy_and_escape_title_line($title, $app.light_theme),
628
          $app.light_theme,
629
        ),
630
      ),
631
      ActiveBlock::Yaml => draw_yaml_block(
632
        $f,
633
        $app,
634
        $area,
635
        title_with_dual_style(
636
          get_resource_title($app, $title, get_describe_active($block), $res.items.len()),
637
          $crate::ui::utils::copy_and_escape_title_line($title, $app.light_theme),
638
          $app.light_theme,
639
        ),
640
      ),
641
      ActiveBlock::Pods => $crate::app::pods::draw_block_as_sub($f, $app, $area),
642
      ActiveBlock::Containers => $crate::app::pods::draw_containers_block($f, $app, $area),
643
      ActiveBlock::Logs => $crate::app::pods::draw_logs_block($f, $app, $area),
644
      ActiveBlock::Namespaces => $fn1($app.get_prev_route().active_block, $f, $app, $area),
645
      _ => $fn2($f, $app, $area),
646
    };
647
  };
648
}
649

650
pub struct ResourceTableProps<'a, T> {
651
  pub title: String,
652
  pub inline_help: Line<'a>,
653
  pub resource: &'a mut StatefulTable<T>,
654
  pub table_headers: Vec<&'a str>,
655
  pub column_widths: Vec<Constraint>,
656
}
657
/// common for all resources
658
pub fn draw_describe_block(f: &mut Frame<'_>, app: &mut App, area: Rect, title: Line<'_>) {
×
659
  draw_yaml_block(f, app, area, title);
×
660
}
×
661

662
/// common for all resources
663
pub fn draw_yaml_block(f: &mut Frame<'_>, app: &mut App, area: Rect, title: Line<'_>) {
×
664
  let block = layout_block_top_border(title);
×
665

666
  let txt = app.data.describe_out.get_txt();
×
667
  if !txt.is_empty() {
×
668
    // Re-highlight only when the cache is empty or the theme changed.
669
    if app.data.describe_out.highlighted_lines.is_empty()
×
670
      || app.data.describe_out.highlight_light_theme != app.light_theme
×
671
    {
672
      let ss = get_syntax_set();
×
673
      let syntax = get_yaml_syntax_reference();
×
674
      let theme = if app.light_theme {
×
675
        &get_yaml_themes().light
×
676
      } else {
677
        &get_yaml_themes().dark
×
678
      };
679
      let mut h = syntect::easy::HighlightLines::new(syntax, theme);
×
680
      let lines: Vec<_> = syntect::util::LinesWithEndings::from(txt)
×
681
        .filter_map(|line| match h.highlight_line(line, ss) {
×
682
          Ok(segments) => {
×
683
            let line_spans: Vec<_> = segments
×
684
              .into_iter()
×
685
              .filter_map(syntect_to_ratatui_span_owned)
×
686
              .collect();
×
687
            Some(ratatui::text::Line::from(line_spans))
×
688
          }
689
          Err(_) => None,
×
690
        })
×
691
        .collect();
×
692
      app.data.describe_out.highlighted_lines = lines;
×
693
      app.data.describe_out.highlight_light_theme = app.light_theme;
×
694
    }
×
695

696
    // Extract only a window of source lines around the visible region.
697
    // The scroll offset is bounded by the source-line count, so it maps roughly to source-line indices.
NEW
698
    let offset = app.data.describe_out.offset;
×
NEW
699
    let total = app.data.describe_out.highlighted_lines.len();
×
700
    // Subtract 2 for the top-border of the block
NEW
701
    let view_h = area.height.saturating_sub(2) as usize;
×
702
    // Take a generous window: some lines before `offset` (to cover
703
    // wrapping that shifts content up) and several screen-heights after.
NEW
704
    let slice_start = offset.saturating_sub(view_h);
×
NEW
705
    let slice_end = total.min(offset + view_h * 3);
×
NEW
706
    let visible_lines = app.data.describe_out.highlighted_lines[slice_start..slice_end].to_vec();
×
NEW
707
    let adjusted_offset = (offset - slice_start).min(u16::MAX as usize) as u16;
×
708

NEW
709
    let paragraph = Paragraph::new(visible_lines)
×
710
      .block(block)
×
711
      .wrap(Wrap { trim: false })
×
NEW
712
      .scroll((adjusted_offset, 0));
×
713
    f.render_widget(paragraph, area);
×
714
  } else {
×
715
    loading(f, block, area, app.is_loading(), app.light_theme);
×
716
  }
×
717
}
×
718

719
fn draw_resource_table<'a, T: KubeResource<U>, F, U: Serialize>(
10✔
720
  f: &mut Frame<'_>,
10✔
721
  area: Rect,
10✔
722
  table_props: ResourceTableProps<'a, T>,
10✔
723
  row_cell_mapper: F,
10✔
724
  light_theme: bool,
10✔
725
  is_loading: bool,
10✔
726
  block: Block<'a>,
10✔
727
) where
10✔
728
  F: Fn(&T) -> Row<'a>,
10✔
729
{
730
  if !table_props.resource.items.is_empty() {
10✔
731
    let filter = table_props.resource.filter.to_lowercase();
7✔
732
    let has_filter = !filter.is_empty();
7✔
733
    let mut filtered_indices: Vec<usize> = Vec::new();
7✔
734

735
    // Apply filter and collect filtered indices.
736
    let filtered_items: Vec<(usize, &T)> = table_props
7✔
737
      .resource
7✔
738
      .items
7✔
739
      .iter()
7✔
740
      .enumerate()
7✔
741
      .filter(|(_, c)| filter.is_empty() || filter_by_name(&filter, *c))
32✔
742
      .inspect(|(idx, _)| {
29✔
743
        if has_filter {
29✔
744
          filtered_indices.push(*idx);
5✔
745
        }
24✔
746
      })
29✔
747
      .collect();
7✔
748

749
    if has_filter {
7✔
750
      let max = filtered_items.len().saturating_sub(1);
4✔
751
      if let Some(sel) = table_props.resource.state.selected() {
4✔
752
        if sel > max {
4✔
753
          table_props.resource.state.select(Some(max));
×
754
        }
4✔
755
      }
×
756
    }
3✔
757
    table_props.resource.filtered_indices = filtered_indices;
7✔
758

759
    // Determine the visible row range to avoid expensive row_cell_mapper
760
    // calls for off-screen items.  Subtract 3 for header + borders.
761
    let selected = table_props.resource.state.selected().unwrap_or(0);
7✔
762
    let view_h = area.height.saturating_sub(3) as usize;
7✔
763
    let visible_start = selected.saturating_sub(view_h);
7✔
764
    let visible_end = (selected + view_h * 2).min(filtered_items.len());
7✔
765

766
    // Build Row widgets, using the expensive mapper only for
767
    // rows in or near the visible viewport.
768
    let rows: Vec<Row<'a>> = filtered_items
7✔
769
      .iter()
7✔
770
      .enumerate()
7✔
771
      .map(|(fi, (_orig_idx, item))| {
29✔
772
        if fi >= visible_start && fi < visible_end {
29✔
773
          row_cell_mapper(item)
29✔
774
        } else {
NEW
775
          Row::default()
×
776
        }
777
      })
29✔
778
      .collect();
7✔
779

780
    let table = Table::new(rows, &table_props.column_widths)
7✔
781
      .header(table_header_style(table_props.table_headers, light_theme))
7✔
782
      .block(block)
7✔
783
      .row_highlight_style(style_highlight())
7✔
784
      .highlight_symbol(HIGHLIGHT);
7✔
785

786
    f.render_stateful_widget(table, area, &mut table_props.resource.state);
7✔
787
  } else {
3✔
788
    loading(f, block, area, is_loading, light_theme);
3✔
789
  }
3✔
790
}
10✔
791

792
/// Draw a kubernetes resource overview tab
793
pub fn draw_resource_block<'a, T: KubeResource<U>, F, U: Serialize>(
9✔
794
  f: &mut Frame<'_>,
9✔
795
  area: Rect,
9✔
796
  table_props: ResourceTableProps<'a, T>,
9✔
797
  row_cell_mapper: F,
9✔
798
  light_theme: bool,
9✔
799
  is_loading: bool,
9✔
800
) where
9✔
801
  F: Fn(&T) -> Row<'a>,
9✔
802
{
803
  let ResourceTableProps {
804
    title,
9✔
805
    inline_help,
9✔
806
    resource,
9✔
807
    table_headers,
9✔
808
    column_widths,
9✔
809
  } = table_props;
9✔
810
  let filter = resource.filter.clone();
9✔
811
  let filter_active = resource.filter_active;
9✔
812
  if filter_active {
9✔
813
    let title_width = title.chars().count();
2✔
814
    let title = title_with_dual_style(
2✔
815
      title,
2✔
816
      mixed_bold_line(owned_filter_status_parts(&filter, true), light_theme),
2✔
817
      light_theme,
2✔
818
    );
819
    let block = layout_block_top_border(title);
2✔
820
    draw_resource_table(
2✔
821
      f,
2✔
822
      area,
2✔
823
      ResourceTableProps {
2✔
824
        title: String::new(),
2✔
825
        inline_help: Line::default(),
2✔
826
        resource,
2✔
827
        table_headers,
2✔
828
        column_widths,
2✔
829
      },
2✔
830
      row_cell_mapper,
2✔
831
      light_theme,
2✔
832
      is_loading,
2✔
833
      block,
2✔
834
    );
835
    f.set_cursor_position(filter_cursor_position(area, title_width, &filter));
2✔
836
    return;
2✔
837
  }
7✔
838

839
  let inline_help_text = inline_help
7✔
840
    .spans
7✔
841
    .iter()
7✔
842
    .map(|span| span.content.as_ref())
7✔
843
    .collect::<String>();
7✔
844
  let containers_prefix = format!(
7✔
845
    "{} | ",
846
    action_hint("containers", DEFAULT_KEYBINDING.submit.key)
7✔
847
  );
848
  let mut help_parts = Vec::new();
7✔
849
  if let Some(rest) = inline_help_text.strip_prefix(&containers_prefix) {
7✔
850
    help_parts.push(help_part(containers_prefix.clone()));
4✔
851
    help_parts.extend(owned_filter_status_parts(&filter, filter_active));
4✔
852
    if !rest.is_empty() {
4✔
853
      help_parts.push(help_part(" | "));
4✔
854
      help_parts.push(help_part(rest.to_string()));
4✔
855
    }
4✔
856
  } else {
857
    help_parts.extend(owned_filter_status_parts(&filter, filter_active));
3✔
858
    if !inline_help_text.is_empty() {
3✔
859
      help_parts.push(help_part(" | "));
3✔
860
      help_parts.push(help_part(inline_help_text));
3✔
861
    }
3✔
862
  }
863
  let title = title_with_dual_style(title, mixed_bold_line(help_parts, light_theme), light_theme);
7✔
864
  let block = layout_block_top_border(title);
7✔
865
  draw_resource_table(
7✔
866
    f,
7✔
867
    area,
7✔
868
    ResourceTableProps {
7✔
869
      title: String::new(),
7✔
870
      inline_help: Line::default(),
7✔
871
      resource,
7✔
872
      table_headers,
7✔
873
      column_widths,
7✔
874
    },
7✔
875
    row_cell_mapper,
7✔
876
    light_theme,
7✔
877
    is_loading,
7✔
878
    block,
7✔
879
  );
880
}
9✔
881

882
pub fn draw_route_resource_block<'a, T: KubeResource<U>, F, U: Serialize>(
1✔
883
  f: &mut Frame<'_>,
1✔
884
  area: Rect,
1✔
885
  table_props: ResourceTableProps<'a, T>,
1✔
886
  row_cell_mapper: F,
1✔
887
  light_theme: bool,
1✔
888
  is_loading: bool,
1✔
889
) where
1✔
890
  F: Fn(&T) -> Row<'a>,
1✔
891
{
892
  let ResourceTableProps {
893
    title,
1✔
894
    inline_help,
1✔
895
    resource,
1✔
896
    table_headers,
1✔
897
    column_widths,
1✔
898
  } = table_props;
1✔
899
  let title = title_with_dual_style(title, inline_help, light_theme);
1✔
900
  let block = layout_block_active_span(title, light_theme);
1✔
901
  draw_resource_table(
1✔
902
    f,
1✔
903
    area,
1✔
904
    ResourceTableProps {
1✔
905
      title: String::new(),
1✔
906
      inline_help: Line::default(),
1✔
907
      resource,
1✔
908
      table_headers,
1✔
909
      column_widths,
1✔
910
    },
1✔
911
    row_cell_mapper,
1✔
912
    light_theme,
1✔
913
    is_loading,
1✔
914
    block,
1✔
915
  );
916
}
1✔
917

918
pub fn filter_by_resource_name<T: KubeResource<U>, U: Serialize>(
7✔
919
  filter: &str,
7✔
920
  res: &T,
7✔
921
  row_cell_mapper: Row<'static>,
7✔
922
) -> Option<Row<'static>> {
7✔
923
  if filter.is_empty() || filter_by_name(filter, res) {
7✔
924
    Some(row_cell_mapper)
7✔
925
  } else {
926
    None
×
927
  }
928
}
7✔
929

930
pub fn text_matches_filter(filter: &str, value: &str) -> bool {
198✔
931
  let filter = filter.to_lowercase();
198✔
932
  let value = value.to_lowercase();
198✔
933
  filter.is_empty() || glob_match(&filter, &value) || value.contains(&filter)
198✔
934
}
198✔
935

936
fn filter_by_name<T: KubeResource<U>, U: Serialize>(ft: &str, res: &T) -> bool {
9✔
937
  text_matches_filter(ft, res.get_name())
9✔
938
}
9✔
939

940
pub fn get_cluster_wide_resource_title<S: AsRef<str>>(
2✔
941
  title: S,
2✔
942
  items_len: usize,
2✔
943
  suffix: S,
2✔
944
) -> String {
2✔
945
  format!(" {} [{}] {}", title.as_ref(), items_len, suffix.as_ref())
2✔
946
}
2✔
947

948
pub fn get_resource_title<S: AsRef<str>>(
9✔
949
  app: &App,
9✔
950
  title: S,
9✔
951
  suffix: S,
9✔
952
  items_len: usize,
9✔
953
) -> String {
9✔
954
  format!(
9✔
955
    " {} {}",
956
    title_with_ns(
9✔
957
      title.as_ref(),
9✔
958
      app
9✔
959
        .data
9✔
960
        .selected
9✔
961
        .ns
9✔
962
        .as_ref()
9✔
963
        .unwrap_or(&String::from("all")),
9✔
964
      items_len
9✔
965
    ),
966
    suffix.as_ref(),
9✔
967
  )
968
}
9✔
969

970
static DESCRIBE_ACTIVE: &str = "-> Describe ";
971
static YAML_ACTIVE: &str = "-> YAML ";
972

973
pub fn get_describe_active<'a>(block: ActiveBlock) -> &'a str {
×
974
  match block {
×
975
    ActiveBlock::Describe => DESCRIBE_ACTIVE,
×
976
    _ => YAML_ACTIVE,
×
977
  }
978
}
×
979

980
pub fn title_with_ns(title: &str, ns: &str, length: usize) -> String {
10✔
981
  format!("{} (ns: {}) [{}]", title, ns, length)
10✔
982
}
10✔
983

984
#[cfg(test)]
985
mod tests {
986
  use ratatui::{
987
    backend::TestBackend, buffer::Buffer, layout::Position, style::Modifier, widgets::Cell,
988
    Terminal,
989
  };
990

991
  use super::*;
992
  use crate::ui::utils::{MACCHIATO_BLUE, MACCHIATO_MAUVE, MACCHIATO_TEXT, MACCHIATO_YELLOW};
993

994
  #[test]
995
  fn test_draw_resource_block() {
1✔
996
    let backend = TestBackend::new(100, 6);
1✔
997
    let mut terminal = Terminal::new(backend).unwrap();
1✔
998

999
    struct RenderTest {
1000
      pub name: String,
1001
      pub namespace: String,
1002
      pub data: i32,
1003
      pub age: String,
1004
    }
1005

1006
    impl KubeResource<Option<String>> for RenderTest {
1007
      fn get_name(&self) -> &String {
×
1008
        &self.name
×
1009
      }
×
1010
      fn get_k8s_obj(&self) -> &Option<String> {
×
1011
        &None
×
1012
      }
×
1013
    }
1014
    terminal
1✔
1015
      .draw(|f| {
1✔
1016
        let size = f.area();
1✔
1017
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1018
        resource.set_items(vec![
1✔
1019
          RenderTest {
1✔
1020
            name: "Test 1".into(),
1✔
1021
            namespace: "Test ns".into(),
1✔
1022
            age: "65h3m".into(),
1✔
1023
            data: 5,
1✔
1024
          },
1✔
1025
          RenderTest {
1✔
1026
            name: "Test long name that should be truncated from view".into(),
1✔
1027
            namespace: "Test ns".into(),
1✔
1028
            age: "65h3m".into(),
1✔
1029
            data: 3,
1✔
1030
          },
1✔
1031
          RenderTest {
1✔
1032
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1033
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1034
            age: "65h3m".into(),
1✔
1035
            data: 6,
1✔
1036
          },
1✔
1037
        ]);
1038
        draw_resource_block(
1✔
1039
          f,
1✔
1040
          size,
1✔
1041
          ResourceTableProps {
1✔
1042
            title: "Test".into(),
1✔
1043
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1044
            resource: &mut resource,
1✔
1045
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1046
            column_widths: vec![
1✔
1047
              Constraint::Percentage(30),
1✔
1048
              Constraint::Percentage(40),
1✔
1049
              Constraint::Percentage(15),
1✔
1050
              Constraint::Percentage(15),
1✔
1051
            ],
1✔
1052
          },
1✔
1053
          |c| {
3✔
1054
            Row::new(vec![
3✔
1055
              Cell::from(c.namespace.to_owned()),
3✔
1056
              Cell::from(c.name.to_owned()),
3✔
1057
              Cell::from(c.data.to_string()),
3✔
1058
              Cell::from(c.age.to_owned()),
3✔
1059
            ])
1060
            .style(style_primary(false))
3✔
1061
          },
3✔
1062
          false,
1063
          false,
1064
        );
1065
      })
1✔
1066
      .unwrap();
1✔
1067

1068
    let mut expected = Buffer::with_lines(vec![
1✔
1069
        "Testfilter </> | -> yaml <y>────────────────────────────────────────────────────────────────────────",
1070
        "   Namespace                     Name                                 Data           Age            ",
1✔
1071
        "=> Test ns                       Test 1                               5              65h3m          ",
1✔
1072
        "   Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1073
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1074
        "                                                                                                    ",
1✔
1075
      ]);
1076
    // set row styles
1077
    // First row heading style
1078
    for col in 0..=99 {
100✔
1079
      match col {
100✔
1080
        0..=3 => {
100✔
1081
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1082
            Style::default()
4✔
1083
              .fg(MACCHIATO_YELLOW)
4✔
1084
              .add_modifier(Modifier::BOLD),
4✔
1085
          );
4✔
1086
        }
4✔
1087
        4..=27 => {
96✔
1088
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
24✔
1089
            Style::default()
24✔
1090
              .fg(MACCHIATO_BLUE)
24✔
1091
              .add_modifier(Modifier::BOLD),
24✔
1092
          );
24✔
1093
        }
24✔
1094
        _ => {}
72✔
1095
      }
1096
    }
1097

1098
    // Second row table header style
1099
    for col in 0..=99 {
100✔
1100
      expected
100✔
1101
        .cell_mut(Position::new(col, 1))
100✔
1102
        .unwrap()
100✔
1103
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1104
    }
100✔
1105
    // first table data row style
1106
    for col in 0..=99 {
100✔
1107
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1108
        Style::default()
100✔
1109
          .fg(MACCHIATO_MAUVE)
100✔
1110
          .add_modifier(Modifier::REVERSED),
100✔
1111
      );
100✔
1112
    }
100✔
1113
    // remaining table data row style
1114
    for row in 3..=4 {
2✔
1115
      for col in 0..=99 {
200✔
1116
        expected
200✔
1117
          .cell_mut(Position::new(col, row))
200✔
1118
          .unwrap()
200✔
1119
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
200✔
1120
      }
200✔
1121
    }
1122

1123
    terminal.backend().assert_buffer(&expected);
1✔
1124
  }
1✔
1125

1126
  #[test]
1127
  fn test_draw_resource_block_filter() {
1✔
1128
    let backend = TestBackend::new(100, 6);
1✔
1129
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1130

1131
    struct RenderTest {
1132
      pub name: String,
1133
      pub namespace: String,
1134
      pub data: i32,
1135
      pub age: String,
1136
    }
1137
    impl KubeResource<Option<String>> for RenderTest {
1138
      fn get_name(&self) -> &String {
3✔
1139
        &self.name
3✔
1140
      }
3✔
1141
      fn get_k8s_obj(&self) -> &Option<String> {
×
1142
        &None
×
1143
      }
×
1144
    }
1145

1146
    terminal
1✔
1147
      .draw(|f| {
1✔
1148
        let size = f.area();
1✔
1149
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1150
        resource.set_items(vec![
1✔
1151
          RenderTest {
1✔
1152
            name: "Test 1".into(),
1✔
1153
            namespace: "Test ns".into(),
1✔
1154
            age: "65h3m".into(),
1✔
1155
            data: 5,
1✔
1156
          },
1✔
1157
          RenderTest {
1✔
1158
            name: "Test long name that should be truncated from view".into(),
1✔
1159
            namespace: "Test ns".into(),
1✔
1160
            age: "65h3m".into(),
1✔
1161
            data: 3,
1✔
1162
          },
1✔
1163
          RenderTest {
1✔
1164
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1165
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1166
            age: "65h3m".into(),
1✔
1167
            data: 6,
1✔
1168
          },
1✔
1169
        ]);
1170
        resource.filter = "truncated".to_string();
1✔
1171
        draw_resource_block(
1✔
1172
          f,
1✔
1173
          size,
1✔
1174
          ResourceTableProps {
1✔
1175
            title: "Test".into(),
1✔
1176
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1177
            resource: &mut resource,
1✔
1178
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1179
            column_widths: vec![
1✔
1180
              Constraint::Percentage(30),
1✔
1181
              Constraint::Percentage(40),
1✔
1182
              Constraint::Percentage(15),
1✔
1183
              Constraint::Percentage(15),
1✔
1184
            ],
1✔
1185
          },
1✔
1186
          |c| {
2✔
1187
            Row::new(vec![
2✔
1188
              Cell::from(c.namespace.to_owned()),
2✔
1189
              Cell::from(c.name.to_owned()),
2✔
1190
              Cell::from(c.data.to_string()),
2✔
1191
              Cell::from(c.age.to_owned()),
2✔
1192
            ])
1193
            .style(style_primary(false))
2✔
1194
          },
2✔
1195
          false,
1196
          false,
1197
        );
1198
      })
1✔
1199
      .unwrap();
1✔
1200

1201
    let mut expected = Buffer::with_lines(vec![
1✔
1202
        "Test[truncated] | edit </>  | -> yaml <y>───────────────────────────────────────────────────────────",
1203
        "   Namespace                     Name                                 Data           Age            ",
1✔
1204
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1205
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1206
        "                                                                                                    ",
1✔
1207
        "                                                                                                    ",
1✔
1208
      ]);
1209
    // set row styles
1210
    // First row heading style
1211
    for col in 0..=99 {
100✔
1212
      match col {
100✔
1213
        0..=3 => {
100✔
1214
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1215
            Style::default()
4✔
1216
              .fg(MACCHIATO_YELLOW)
4✔
1217
              .add_modifier(Modifier::BOLD),
4✔
1218
          );
4✔
1219
        }
4✔
1220
        4..=14 => {
96✔
1221
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
11✔
1222
            Style::default()
11✔
1223
              .fg(MACCHIATO_TEXT)
11✔
1224
              .add_modifier(Modifier::BOLD),
11✔
1225
          );
11✔
1226
        }
11✔
1227
        15..=40 => {
85✔
1228
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
26✔
1229
            Style::default()
26✔
1230
              .fg(MACCHIATO_BLUE)
26✔
1231
              .add_modifier(Modifier::BOLD),
26✔
1232
          );
26✔
1233
        }
26✔
1234
        _ => {}
59✔
1235
      }
1236
    }
1237

1238
    // Second row table header style
1239
    for col in 0..=99 {
100✔
1240
      expected
100✔
1241
        .cell_mut(Position::new(col, 1))
100✔
1242
        .unwrap()
100✔
1243
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1244
    }
100✔
1245
    // first table data row style
1246
    for col in 0..=99 {
100✔
1247
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1248
        Style::default()
100✔
1249
          .fg(MACCHIATO_MAUVE)
100✔
1250
          .add_modifier(Modifier::REVERSED),
100✔
1251
      );
100✔
1252
    }
100✔
1253
    // remaining table data row style
1254
    for row in 3..=3 {
1✔
1255
      for col in 0..=99 {
100✔
1256
        expected
100✔
1257
          .cell_mut(Position::new(col, row))
100✔
1258
          .unwrap()
100✔
1259
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1260
      }
100✔
1261
    }
1262

1263
    terminal.backend().assert_buffer(&expected);
1✔
1264
  }
1✔
1265

1266
  #[test]
1267
  fn test_draw_resource_block_filter_glob() {
1✔
1268
    let backend = TestBackend::new(100, 6);
1✔
1269
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1270

1271
    struct RenderTest {
1272
      pub name: String,
1273
      pub namespace: String,
1274
      pub data: i32,
1275
      pub age: String,
1276
    }
1277
    impl KubeResource<Option<String>> for RenderTest {
1278
      fn get_name(&self) -> &String {
3✔
1279
        &self.name
3✔
1280
      }
3✔
1281
      fn get_k8s_obj(&self) -> &Option<String> {
×
1282
        &None
×
1283
      }
×
1284
    }
1285

1286
    terminal
1✔
1287
      .draw(|f| {
1✔
1288
        let size = f.area();
1✔
1289
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1290
        resource.set_items(vec![
1✔
1291
          RenderTest {
1✔
1292
            name: "Test 1".into(),
1✔
1293
            namespace: "Test ns".into(),
1✔
1294
            age: "65h3m".into(),
1✔
1295
            data: 5,
1✔
1296
          },
1✔
1297
          RenderTest {
1✔
1298
            name: "Test long name that should be truncated from view".into(),
1✔
1299
            namespace: "Test ns".into(),
1✔
1300
            age: "65h3m".into(),
1✔
1301
            data: 3,
1✔
1302
          },
1✔
1303
          RenderTest {
1✔
1304
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1305
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1306
            age: "65h3m".into(),
1✔
1307
            data: 6,
1✔
1308
          },
1✔
1309
        ]);
1310
        resource.filter = "*long*truncated*".to_string();
1✔
1311
        draw_resource_block(
1✔
1312
          f,
1✔
1313
          size,
1✔
1314
          ResourceTableProps {
1✔
1315
            title: "Test".into(),
1✔
1316
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1317
            resource: &mut resource,
1✔
1318
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1319
            column_widths: vec![
1✔
1320
              Constraint::Percentage(30),
1✔
1321
              Constraint::Percentage(40),
1✔
1322
              Constraint::Percentage(15),
1✔
1323
              Constraint::Percentage(15),
1✔
1324
            ],
1✔
1325
          },
1✔
1326
          |c| {
2✔
1327
            Row::new(vec![
2✔
1328
              Cell::from(c.namespace.to_owned()),
2✔
1329
              Cell::from(c.name.to_owned()),
2✔
1330
              Cell::from(c.data.to_string()),
2✔
1331
              Cell::from(c.age.to_owned()),
2✔
1332
            ])
1333
            .style(style_primary(false))
2✔
1334
          },
2✔
1335
          false,
1336
          false,
1337
        );
1338
      })
1✔
1339
      .unwrap();
1✔
1340

1341
    let mut expected = Buffer::with_lines(vec![
1✔
1342
        "Test[*long*truncated*] | edit </>  | -> yaml <y>────────────────────────────────────────────────────",
1343
        "   Namespace                     Name                                 Data           Age            ",
1✔
1344
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1345
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1346
        "                                                                                                    ",
1✔
1347
        "                                                                                                    ",
1✔
1348
      ]);
1349
    // set row styles
1350
    // First row heading style
1351
    for col in 0..=99 {
100✔
1352
      match col {
100✔
1353
        0..=3 => {
100✔
1354
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1355
            Style::default()
4✔
1356
              .fg(MACCHIATO_YELLOW)
4✔
1357
              .add_modifier(Modifier::BOLD),
4✔
1358
          );
4✔
1359
        }
4✔
1360
        4..=21 => {
96✔
1361
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
18✔
1362
            Style::default()
18✔
1363
              .fg(MACCHIATO_TEXT)
18✔
1364
              .add_modifier(Modifier::BOLD),
18✔
1365
          );
18✔
1366
        }
18✔
1367
        22..=47 => {
78✔
1368
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
26✔
1369
            Style::default()
26✔
1370
              .fg(MACCHIATO_BLUE)
26✔
1371
              .add_modifier(Modifier::BOLD),
26✔
1372
          );
26✔
1373
        }
26✔
1374
        _ => {}
52✔
1375
      }
1376
    }
1377

1378
    // Second row table header style
1379
    for col in 0..=99 {
100✔
1380
      expected
100✔
1381
        .cell_mut(Position::new(col, 1))
100✔
1382
        .unwrap()
100✔
1383
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1384
    }
100✔
1385
    // first table data row style
1386
    for col in 0..=99 {
100✔
1387
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1388
        Style::default()
100✔
1389
          .fg(MACCHIATO_MAUVE)
100✔
1390
          .add_modifier(Modifier::REVERSED),
100✔
1391
      );
100✔
1392
    }
100✔
1393
    // remaining table data row style
1394
    for row in 3..=3 {
1✔
1395
      for col in 0..=99 {
100✔
1396
        expected
100✔
1397
          .cell_mut(Position::new(col, row))
100✔
1398
          .unwrap()
100✔
1399
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1400
      }
100✔
1401
    }
1402

1403
    terminal.backend().assert_buffer(&expected);
1✔
1404
  }
1✔
1405

1406
  #[test]
1407
  fn test_get_resource_title() {
1✔
1408
    let app = App::default();
1✔
1409
    assert_eq!(
1✔
1410
      get_resource_title(&app, "Title", "-> hello", 5),
1✔
1411
      " Title (ns: all) [5] -> hello"
1412
    );
1413
  }
1✔
1414

1415
  #[test]
1416
  fn test_draw_resource_block_filter_hides_other_hints_when_active() {
1✔
1417
    let backend = TestBackend::new(100, 4);
1✔
1418
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1419

1420
    struct RenderTest {
1421
      pub name: String,
1422
    }
1423

1424
    impl KubeResource<Option<String>> for RenderTest {
1425
      fn get_name(&self) -> &String {
1✔
1426
        &self.name
1✔
1427
      }
1✔
1428

1429
      fn get_k8s_obj(&self) -> &Option<String> {
×
1430
        &None
×
1431
      }
×
1432
    }
1433

1434
    terminal
1✔
1435
      .draw(|f| {
1✔
1436
        let size = f.area();
1✔
1437
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1438
        resource.set_items(vec![RenderTest {
1✔
1439
          name: "test".into(),
1✔
1440
        }]);
1✔
1441
        resource.filter = "pod".into();
1✔
1442
        resource.filter_active = true;
1✔
1443
        draw_resource_block(
1✔
1444
          f,
1✔
1445
          size,
1✔
1446
          ResourceTableProps {
1✔
1447
            title: "Test".into(),
1✔
1448
            inline_help: help_bold_line("describe <d> | back <Esc>", false),
1✔
1449
            resource: &mut resource,
1✔
1450
            table_headers: vec!["Name"],
1✔
1451
            column_widths: vec![Constraint::Percentage(100)],
1✔
1452
          },
1✔
UNCOV
1453
          |c| Row::new(vec![Cell::from(c.name.to_owned())]).style(style_primary(false)),
×
1454
          false,
1455
          false,
1456
        );
1457
      })
1✔
1458
      .unwrap();
1✔
1459

1460
    let first_line = (0..terminal.backend().buffer().area.width)
1✔
1461
      .map(|col| terminal.backend().buffer()[(col, 0)].symbol())
100✔
1462
      .collect::<String>();
1✔
1463
    assert!(first_line.contains("[pod]"));
1✔
1464
    assert!(first_line.contains("clear <Esc>"));
1✔
1465
    assert!(!first_line.contains("describe <d>"));
1✔
1466
    assert!(!first_line.contains("back <Esc>"));
1✔
1467
  }
1✔
1468

1469
  #[test]
1470
  fn test_title_with_ns() {
1✔
1471
    assert_eq!(title_with_ns("Title", "hello", 3), "Title (ns: hello) [3]");
1✔
1472
  }
1✔
1473

1474
  #[test]
1475
  fn test_get_cluster_wide_resource_title() {
1✔
1476
    assert_eq!(
1✔
1477
      get_cluster_wide_resource_title("Cluster Resource", 3, ""),
1✔
1478
      " Cluster Resource [3] "
1479
    );
1480
    assert_eq!(
1✔
1481
      get_cluster_wide_resource_title("Nodes", 10, "-> hello"),
1✔
1482
      " Nodes [10] -> hello"
1483
    );
1484
  }
1✔
1485
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc