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

kdash-rs / kdash / 24121312965

07 Apr 2026 10:13PM UTC coverage: 64.777% (+1.5%) from 63.284%
24121312965

push

github

deepu105
feat: Error log dump to file (fix #358)

110 of 112 new or added lines in 4 files covered. (98.21%)

762 existing lines in 11 files now uncovered.

7884 of 12171 relevant lines covered (64.78%)

145.47 hits per line

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

64.99
/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> {
98✔
143
  let mut styles = if light {
98✔
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([
98✔
159
      (Styles::Text, Style::default().fg(MACCHIATO_TEXT)),
98✔
160
      (Styles::Failure, Style::default().fg(MACCHIATO_RED)),
98✔
161
      (Styles::Warning, Style::default().fg(MACCHIATO_PEACH)),
98✔
162
      (Styles::Success, Style::default().fg(MACCHIATO_GREEN)),
98✔
163
      (Styles::Primary, Style::default().fg(MACCHIATO_MAUVE)),
98✔
164
      (Styles::Secondary, Style::default().fg(MACCHIATO_YELLOW)),
98✔
165
      (Styles::Help, Style::default().fg(MACCHIATO_BLUE)),
98✔
166
      (
98✔
167
        Styles::Background,
98✔
168
        Style::default().bg(MACCHIATO_BASE).fg(MACCHIATO_TEXT),
98✔
169
      ),
98✔
170
    ])
98✔
171
  };
172

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

182
  styles
98✔
183
}
98✔
184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

317
pub fn describe_yaml_logs_and_esc_hint() -> String {
×
318
  format!(
×
319
    "{} | back to menu {} ",
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 to menu {} ",
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 to menu {} ",
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 {
1✔
343
  Position {
1✔
344
    x: area.x
1✔
345
      + (prefix_width as u16 + 1 + filter.chars().count() as u16).min(area.width.saturating_sub(2)),
1✔
346
    y: area.y,
1✔
347
  }
1✔
348
}
1✔
349

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

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

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

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

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

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

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

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

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

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

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

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

448
pub fn layout_block_top_border(title: Line<'_>) -> Block<'_> {
5✔
449
  Block::default().borders(Borders::TOP).title(title)
5✔
450
}
5✔
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<'_> {
3✔
459
  if active && filter.is_empty() {
3✔
460
    FilterDisplayState::EditingEmpty
×
461
  } else if !filter.is_empty() {
3✔
462
    FilterDisplayState::Value { filter, active }
1✔
463
  } else {
464
    FilterDisplayState::Inactive
2✔
465
  }
466
}
3✔
467

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

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

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

500
pub fn filter_bar_title<'a>(filter: &'a str, active: bool, light: bool) -> Line<'a> {
1✔
501
  let mut parts = vec![help_part(" ")];
1✔
502
  parts.extend(filter_display_parts(filter, active));
1✔
503
  parts.push(help_part(" "));
1✔
504
  mixed_line(parts, light)
1✔
505
}
1✔
506

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

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

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

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

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

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

584
  let outer_width = (grid_width / 2).saturating_sub(width / 2);
×
585

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

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

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

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

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

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

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

UNCOV
695
    let paragraph = Paragraph::new(app.data.describe_out.highlighted_lines.clone())
×
UNCOV
696
      .block(block)
×
UNCOV
697
      .wrap(Wrap { trim: false })
×
UNCOV
698
      .scroll((
×
UNCOV
699
        app.data.describe_out.offset.min(u16::MAX as usize) as u16,
×
UNCOV
700
        0,
×
UNCOV
701
      ));
×
UNCOV
702
    f.render_widget(paragraph, area);
×
UNCOV
703
  } else {
×
UNCOV
704
    loading(f, block, area, app.is_loading(), app.light_theme);
×
UNCOV
705
  }
×
UNCOV
706
}
×
707

708
fn draw_resource_table<'a, T: KubeResource<U>, F, U: Serialize>(
4✔
709
  f: &mut Frame<'_>,
4✔
710
  area: Rect,
4✔
711
  table_props: ResourceTableProps<'a, T>,
4✔
712
  row_cell_mapper: F,
4✔
713
  light_theme: bool,
4✔
714
  is_loading: bool,
4✔
715
  block: Block<'a>,
4✔
716
) where
4✔
717
  F: Fn(&T) -> Row<'a>,
4✔
718
{
719
  if !table_props.resource.items.is_empty() {
4✔
720
    let filter = table_props.resource.filter.to_lowercase();
4✔
721
    let has_filter = !filter.is_empty();
4✔
722
    let mut filtered_indices: Vec<usize> = Vec::new();
4✔
723
    let rows: Vec<Row<'a>> = table_props
4✔
724
      .resource
4✔
725
      .items
4✔
726
      .iter()
4✔
727
      .enumerate()
4✔
728
      .filter_map(|(idx, c)| {
10✔
729
        let mapper = row_cell_mapper(c);
10✔
730
        if filter.is_empty() || filter_by_name(&filter, c) {
10✔
731
          Some((idx, mapper))
8✔
732
        } else {
733
          None
2✔
734
        }
735
      })
10✔
736
      .map(|(idx, row)| {
8✔
737
        if has_filter {
8✔
738
          filtered_indices.push(idx);
4✔
739
        }
4✔
740
        row
8✔
741
      })
8✔
742
      .collect();
4✔
743

744
    if has_filter {
4✔
745
      let max = filtered_indices.len().saturating_sub(1);
2✔
746
      if let Some(sel) = table_props.resource.state.selected() {
2✔
747
        if sel > max {
2✔
UNCOV
748
          table_props.resource.state.select(Some(max));
×
749
        }
2✔
UNCOV
750
      }
×
751
    }
2✔
752
    table_props.resource.filtered_indices = filtered_indices;
4✔
753

754
    let table = Table::new(rows, &table_props.column_widths)
4✔
755
      .header(table_header_style(table_props.table_headers, light_theme))
4✔
756
      .block(block)
4✔
757
      .row_highlight_style(style_highlight())
4✔
758
      .highlight_symbol(HIGHLIGHT);
4✔
759

760
    f.render_stateful_widget(table, area, &mut table_props.resource.state);
4✔
UNCOV
761
  } else {
×
UNCOV
762
    loading(f, block, area, is_loading, light_theme);
×
UNCOV
763
  }
×
764
}
4✔
765

766
/// Draw a kubernetes resource overview tab
767
pub fn draw_resource_block<'a, T: KubeResource<U>, F, U: Serialize>(
4✔
768
  f: &mut Frame<'_>,
4✔
769
  area: Rect,
4✔
770
  table_props: ResourceTableProps<'a, T>,
4✔
771
  row_cell_mapper: F,
4✔
772
  light_theme: bool,
4✔
773
  is_loading: bool,
4✔
774
) where
4✔
775
  F: Fn(&T) -> Row<'a>,
4✔
776
{
777
  let ResourceTableProps {
778
    title,
4✔
779
    inline_help,
4✔
780
    resource,
4✔
781
    table_headers,
4✔
782
    column_widths,
4✔
783
  } = table_props;
4✔
784
  let title = title_with_dual_style(title, inline_help, light_theme);
4✔
785
  let block = layout_block_top_border(title);
4✔
786
  draw_resource_table(
4✔
787
    f,
4✔
788
    area,
4✔
789
    ResourceTableProps {
4✔
790
      title: String::new(),
4✔
791
      inline_help: Line::default(),
4✔
792
      resource,
4✔
793
      table_headers,
4✔
794
      column_widths,
4✔
795
    },
4✔
796
    row_cell_mapper,
4✔
797
    light_theme,
4✔
798
    is_loading,
4✔
799
    block,
4✔
800
  );
801
}
4✔
802

803
pub fn draw_route_resource_block<'a, T: KubeResource<U>, F, U: Serialize>(
×
804
  f: &mut Frame<'_>,
×
805
  area: Rect,
×
806
  table_props: ResourceTableProps<'a, T>,
×
807
  row_cell_mapper: F,
×
808
  light_theme: bool,
×
809
  is_loading: bool,
×
810
) where
×
811
  F: Fn(&T) -> Row<'a>,
×
812
{
813
  let ResourceTableProps {
UNCOV
814
    title,
×
815
    inline_help,
×
816
    resource,
×
817
    table_headers,
×
818
    column_widths,
×
819
  } = table_props;
×
820
  let title = title_with_dual_style(title, inline_help, light_theme);
×
821
  let block = layout_block_active_span(title, light_theme);
×
UNCOV
822
  draw_resource_table(
×
823
    f,
×
UNCOV
824
    area,
×
825
    ResourceTableProps {
×
UNCOV
826
      title: String::new(),
×
UNCOV
827
      inline_help: Line::default(),
×
UNCOV
828
      resource,
×
UNCOV
829
      table_headers,
×
UNCOV
830
      column_widths,
×
UNCOV
831
    },
×
UNCOV
832
    row_cell_mapper,
×
UNCOV
833
    light_theme,
×
UNCOV
834
    is_loading,
×
UNCOV
835
    block,
×
836
  );
UNCOV
837
}
×
838

UNCOV
839
pub fn filter_by_resource_name<T: KubeResource<U>, U: Serialize>(
×
UNCOV
840
  filter: &str,
×
UNCOV
841
  res: &T,
×
UNCOV
842
  row_cell_mapper: Row<'static>,
×
UNCOV
843
) -> Option<Row<'static>> {
×
UNCOV
844
  if filter.is_empty() || filter_by_name(filter, res) {
×
UNCOV
845
    Some(row_cell_mapper)
×
846
  } else {
UNCOV
847
    None
×
848
  }
UNCOV
849
}
×
850

851
pub fn text_matches_filter(filter: &str, value: &str) -> bool {
191✔
852
  let filter = filter.to_lowercase();
191✔
853
  let value = value.to_lowercase();
191✔
854
  filter.is_empty() || glob_match(&filter, &value) || value.contains(&filter)
191✔
855
}
191✔
856

857
fn filter_by_name<T: KubeResource<U>, U: Serialize>(ft: &str, res: &T) -> bool {
6✔
858
  text_matches_filter(ft, res.get_name())
6✔
859
}
6✔
860

861
pub fn get_cluster_wide_resource_title<S: AsRef<str>>(
2✔
862
  title: S,
2✔
863
  items_len: usize,
2✔
864
  suffix: S,
2✔
865
) -> String {
2✔
866
  format!(" {} [{}] {}", title.as_ref(), items_len, suffix.as_ref())
2✔
867
}
2✔
868

869
pub fn get_resource_title<S: AsRef<str>>(
5✔
870
  app: &App,
5✔
871
  title: S,
5✔
872
  suffix: S,
5✔
873
  items_len: usize,
5✔
874
) -> String {
5✔
875
  format!(
5✔
876
    " {} {}",
877
    title_with_ns(
5✔
878
      title.as_ref(),
5✔
879
      app
5✔
880
        .data
5✔
881
        .selected
5✔
882
        .ns
5✔
883
        .as_ref()
5✔
884
        .unwrap_or(&String::from("all")),
5✔
885
      items_len
5✔
886
    ),
887
    suffix.as_ref(),
5✔
888
  )
889
}
5✔
890

891
static DESCRIBE_ACTIVE: &str = "-> Describe ";
892
static YAML_ACTIVE: &str = "-> YAML ";
893

UNCOV
894
pub fn get_describe_active<'a>(block: ActiveBlock) -> &'a str {
×
UNCOV
895
  match block {
×
UNCOV
896
    ActiveBlock::Describe => DESCRIBE_ACTIVE,
×
UNCOV
897
    _ => YAML_ACTIVE,
×
898
  }
UNCOV
899
}
×
900

901
pub fn title_with_ns(title: &str, ns: &str, length: usize) -> String {
6✔
902
  format!("{} (ns: {}) [{}]", title, ns, length)
6✔
903
}
6✔
904

905
#[cfg(test)]
906
mod tests {
907
  use ratatui::{
908
    backend::TestBackend, buffer::Buffer, layout::Position, style::Modifier, widgets::Cell,
909
    Terminal,
910
  };
911

912
  use super::*;
913
  use crate::ui::utils::{MACCHIATO_BLUE, MACCHIATO_MAUVE, MACCHIATO_TEXT, MACCHIATO_YELLOW};
914

915
  #[test]
916
  fn test_draw_resource_block() {
1✔
917
    let backend = TestBackend::new(100, 6);
1✔
918
    let mut terminal = Terminal::new(backend).unwrap();
1✔
919

920
    struct RenderTest {
921
      pub name: String,
922
      pub namespace: String,
923
      pub data: i32,
924
      pub age: String,
925
    }
926

927
    impl KubeResource<Option<String>> for RenderTest {
UNCOV
928
      fn get_name(&self) -> &String {
×
UNCOV
929
        &self.name
×
UNCOV
930
      }
×
UNCOV
931
      fn get_k8s_obj(&self) -> &Option<String> {
×
UNCOV
932
        &None
×
UNCOV
933
      }
×
934
    }
935
    terminal
1✔
936
      .draw(|f| {
1✔
937
        let size = f.area();
1✔
938
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
939
        resource.set_items(vec![
1✔
940
          RenderTest {
1✔
941
            name: "Test 1".into(),
1✔
942
            namespace: "Test ns".into(),
1✔
943
            age: "65h3m".into(),
1✔
944
            data: 5,
1✔
945
          },
1✔
946
          RenderTest {
1✔
947
            name: "Test long name that should be truncated from view".into(),
1✔
948
            namespace: "Test ns".into(),
1✔
949
            age: "65h3m".into(),
1✔
950
            data: 3,
1✔
951
          },
1✔
952
          RenderTest {
1✔
953
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
954
            namespace: "Test ns long value check that should be truncated".into(),
1✔
955
            age: "65h3m".into(),
1✔
956
            data: 6,
1✔
957
          },
1✔
958
        ]);
959
        draw_resource_block(
1✔
960
          f,
1✔
961
          size,
1✔
962
          ResourceTableProps {
1✔
963
            title: "Test".into(),
1✔
964
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
965
            resource: &mut resource,
1✔
966
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
967
            column_widths: vec![
1✔
968
              Constraint::Percentage(30),
1✔
969
              Constraint::Percentage(40),
1✔
970
              Constraint::Percentage(15),
1✔
971
              Constraint::Percentage(15),
1✔
972
            ],
1✔
973
          },
1✔
974
          |c| {
3✔
975
            Row::new(vec![
3✔
976
              Cell::from(c.namespace.to_owned()),
3✔
977
              Cell::from(c.name.to_owned()),
3✔
978
              Cell::from(c.data.to_string()),
3✔
979
              Cell::from(c.age.to_owned()),
3✔
980
            ])
981
            .style(style_primary(false))
3✔
982
          },
3✔
983
          false,
984
          false,
985
        );
986
      })
1✔
987
      .unwrap();
1✔
988

989
    let mut expected = Buffer::with_lines(vec![
1✔
990
        "Test-> yaml <y>─────────────────────────────────────────────────────────────────────────────────────",
991
        "   Namespace                     Name                                 Data           Age            ",
1✔
992
        "=> Test ns                       Test 1                               5              65h3m          ",
1✔
993
        "   Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
994
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
995
        "                                                                                                    ",
1✔
996
      ]);
997
    // set row styles
998
    // First row heading style
999
    for col in 0..=99 {
100✔
1000
      match col {
100✔
1001
        0..=3 => {
100✔
1002
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1003
            Style::default()
4✔
1004
              .fg(MACCHIATO_YELLOW)
4✔
1005
              .add_modifier(Modifier::BOLD),
4✔
1006
          );
4✔
1007
        }
4✔
1008
        4..=14 => {
96✔
1009
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
11✔
1010
            Style::default()
11✔
1011
              .fg(MACCHIATO_BLUE)
11✔
1012
              .add_modifier(Modifier::BOLD),
11✔
1013
          );
11✔
1014
        }
11✔
1015
        _ => {}
85✔
1016
      }
1017
    }
1018

1019
    // Second row table header style
1020
    for col in 0..=99 {
100✔
1021
      expected
100✔
1022
        .cell_mut(Position::new(col, 1))
100✔
1023
        .unwrap()
100✔
1024
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1025
    }
100✔
1026
    // first table data row style
1027
    for col in 0..=99 {
100✔
1028
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1029
        Style::default()
100✔
1030
          .fg(MACCHIATO_MAUVE)
100✔
1031
          .add_modifier(Modifier::REVERSED),
100✔
1032
      );
100✔
1033
    }
100✔
1034
    // remaining table data row style
1035
    for row in 3..=4 {
2✔
1036
      for col in 0..=99 {
200✔
1037
        expected
200✔
1038
          .cell_mut(Position::new(col, row))
200✔
1039
          .unwrap()
200✔
1040
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
200✔
1041
      }
200✔
1042
    }
1043

1044
    terminal.backend().assert_buffer(&expected);
1✔
1045
  }
1✔
1046

1047
  #[test]
1048
  fn test_draw_resource_block_filter() {
1✔
1049
    let backend = TestBackend::new(100, 6);
1✔
1050
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1051

1052
    struct RenderTest {
1053
      pub name: String,
1054
      pub namespace: String,
1055
      pub data: i32,
1056
      pub age: String,
1057
    }
1058
    impl KubeResource<Option<String>> for RenderTest {
1059
      fn get_name(&self) -> &String {
3✔
1060
        &self.name
3✔
1061
      }
3✔
UNCOV
1062
      fn get_k8s_obj(&self) -> &Option<String> {
×
UNCOV
1063
        &None
×
UNCOV
1064
      }
×
1065
    }
1066

1067
    terminal
1✔
1068
      .draw(|f| {
1✔
1069
        let size = f.area();
1✔
1070
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1071
        resource.set_items(vec![
1✔
1072
          RenderTest {
1✔
1073
            name: "Test 1".into(),
1✔
1074
            namespace: "Test ns".into(),
1✔
1075
            age: "65h3m".into(),
1✔
1076
            data: 5,
1✔
1077
          },
1✔
1078
          RenderTest {
1✔
1079
            name: "Test long name that should be truncated from view".into(),
1✔
1080
            namespace: "Test ns".into(),
1✔
1081
            age: "65h3m".into(),
1✔
1082
            data: 3,
1✔
1083
          },
1✔
1084
          RenderTest {
1✔
1085
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1086
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1087
            age: "65h3m".into(),
1✔
1088
            data: 6,
1✔
1089
          },
1✔
1090
        ]);
1091
        resource.filter = "truncated".to_string();
1✔
1092
        draw_resource_block(
1✔
1093
          f,
1✔
1094
          size,
1✔
1095
          ResourceTableProps {
1✔
1096
            title: "Test".into(),
1✔
1097
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1098
            resource: &mut resource,
1✔
1099
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1100
            column_widths: vec![
1✔
1101
              Constraint::Percentage(30),
1✔
1102
              Constraint::Percentage(40),
1✔
1103
              Constraint::Percentage(15),
1✔
1104
              Constraint::Percentage(15),
1✔
1105
            ],
1✔
1106
          },
1✔
1107
          |c| {
3✔
1108
            Row::new(vec![
3✔
1109
              Cell::from(c.namespace.to_owned()),
3✔
1110
              Cell::from(c.name.to_owned()),
3✔
1111
              Cell::from(c.data.to_string()),
3✔
1112
              Cell::from(c.age.to_owned()),
3✔
1113
            ])
1114
            .style(style_primary(false))
3✔
1115
          },
3✔
1116
          false,
1117
          false,
1118
        );
1119
      })
1✔
1120
      .unwrap();
1✔
1121

1122
    let mut expected = Buffer::with_lines(vec![
1✔
1123
        "Test-> yaml <y>─────────────────────────────────────────────────────────────────────────────────────",
1124
        "   Namespace                     Name                                 Data           Age            ",
1✔
1125
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1126
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1127
        "                                                                                                    ",
1✔
1128
        "                                                                                                    ",
1✔
1129
      ]);
1130
    // set row styles
1131
    // First row heading style
1132
    for col in 0..=99 {
100✔
1133
      match col {
100✔
1134
        0..=3 => {
100✔
1135
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1136
            Style::default()
4✔
1137
              .fg(MACCHIATO_YELLOW)
4✔
1138
              .add_modifier(Modifier::BOLD),
4✔
1139
          );
4✔
1140
        }
4✔
1141
        4..=14 => {
96✔
1142
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
11✔
1143
            Style::default()
11✔
1144
              .fg(MACCHIATO_BLUE)
11✔
1145
              .add_modifier(Modifier::BOLD),
11✔
1146
          );
11✔
1147
        }
11✔
1148
        _ => {}
85✔
1149
      }
1150
    }
1151

1152
    // Second row table header style
1153
    for col in 0..=99 {
100✔
1154
      expected
100✔
1155
        .cell_mut(Position::new(col, 1))
100✔
1156
        .unwrap()
100✔
1157
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1158
    }
100✔
1159
    // first table data row style
1160
    for col in 0..=99 {
100✔
1161
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1162
        Style::default()
100✔
1163
          .fg(MACCHIATO_MAUVE)
100✔
1164
          .add_modifier(Modifier::REVERSED),
100✔
1165
      );
100✔
1166
    }
100✔
1167
    // remaining table data row style
1168
    for row in 3..=3 {
1✔
1169
      for col in 0..=99 {
100✔
1170
        expected
100✔
1171
          .cell_mut(Position::new(col, row))
100✔
1172
          .unwrap()
100✔
1173
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1174
      }
100✔
1175
    }
1176

1177
    terminal.backend().assert_buffer(&expected);
1✔
1178
  }
1✔
1179

1180
  #[test]
1181
  fn test_draw_resource_block_filter_glob() {
1✔
1182
    let backend = TestBackend::new(100, 6);
1✔
1183
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1184

1185
    struct RenderTest {
1186
      pub name: String,
1187
      pub namespace: String,
1188
      pub data: i32,
1189
      pub age: String,
1190
    }
1191
    impl KubeResource<Option<String>> for RenderTest {
1192
      fn get_name(&self) -> &String {
3✔
1193
        &self.name
3✔
1194
      }
3✔
UNCOV
1195
      fn get_k8s_obj(&self) -> &Option<String> {
×
UNCOV
1196
        &None
×
UNCOV
1197
      }
×
1198
    }
1199

1200
    terminal
1✔
1201
      .draw(|f| {
1✔
1202
        let size = f.area();
1✔
1203
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1204
        resource.set_items(vec![
1✔
1205
          RenderTest {
1✔
1206
            name: "Test 1".into(),
1✔
1207
            namespace: "Test ns".into(),
1✔
1208
            age: "65h3m".into(),
1✔
1209
            data: 5,
1✔
1210
          },
1✔
1211
          RenderTest {
1✔
1212
            name: "Test long name that should be truncated from view".into(),
1✔
1213
            namespace: "Test ns".into(),
1✔
1214
            age: "65h3m".into(),
1✔
1215
            data: 3,
1✔
1216
          },
1✔
1217
          RenderTest {
1✔
1218
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1219
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1220
            age: "65h3m".into(),
1✔
1221
            data: 6,
1✔
1222
          },
1✔
1223
        ]);
1224
        resource.filter = "*long*truncated*".to_string();
1✔
1225
        draw_resource_block(
1✔
1226
          f,
1✔
1227
          size,
1✔
1228
          ResourceTableProps {
1✔
1229
            title: "Test".into(),
1✔
1230
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1231
            resource: &mut resource,
1✔
1232
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1233
            column_widths: vec![
1✔
1234
              Constraint::Percentage(30),
1✔
1235
              Constraint::Percentage(40),
1✔
1236
              Constraint::Percentage(15),
1✔
1237
              Constraint::Percentage(15),
1✔
1238
            ],
1✔
1239
          },
1✔
1240
          |c| {
3✔
1241
            Row::new(vec![
3✔
1242
              Cell::from(c.namespace.to_owned()),
3✔
1243
              Cell::from(c.name.to_owned()),
3✔
1244
              Cell::from(c.data.to_string()),
3✔
1245
              Cell::from(c.age.to_owned()),
3✔
1246
            ])
1247
            .style(style_primary(false))
3✔
1248
          },
3✔
1249
          false,
1250
          false,
1251
        );
1252
      })
1✔
1253
      .unwrap();
1✔
1254

1255
    let mut expected = Buffer::with_lines(vec![
1✔
1256
        "Test-> yaml <y>─────────────────────────────────────────────────────────────────────────────────────",
1257
        "   Namespace                     Name                                 Data           Age            ",
1✔
1258
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1259
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1260
        "                                                                                                    ",
1✔
1261
        "                                                                                                    ",
1✔
1262
      ]);
1263
    // set row styles
1264
    // First row heading style
1265
    for col in 0..=99 {
100✔
1266
      match col {
100✔
1267
        0..=3 => {
100✔
1268
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1269
            Style::default()
4✔
1270
              .fg(MACCHIATO_YELLOW)
4✔
1271
              .add_modifier(Modifier::BOLD),
4✔
1272
          );
4✔
1273
        }
4✔
1274
        4..=14 => {
96✔
1275
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
11✔
1276
            Style::default()
11✔
1277
              .fg(MACCHIATO_BLUE)
11✔
1278
              .add_modifier(Modifier::BOLD),
11✔
1279
          );
11✔
1280
        }
11✔
1281
        _ => {}
85✔
1282
      }
1283
    }
1284

1285
    // Second row table header style
1286
    for col in 0..=99 {
100✔
1287
      expected
100✔
1288
        .cell_mut(Position::new(col, 1))
100✔
1289
        .unwrap()
100✔
1290
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1291
    }
100✔
1292
    // first table data row style
1293
    for col in 0..=99 {
100✔
1294
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1295
        Style::default()
100✔
1296
          .fg(MACCHIATO_MAUVE)
100✔
1297
          .add_modifier(Modifier::REVERSED),
100✔
1298
      );
100✔
1299
    }
100✔
1300
    // remaining table data row style
1301
    for row in 3..=3 {
1✔
1302
      for col in 0..=99 {
100✔
1303
        expected
100✔
1304
          .cell_mut(Position::new(col, row))
100✔
1305
          .unwrap()
100✔
1306
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1307
      }
100✔
1308
    }
1309

1310
    terminal.backend().assert_buffer(&expected);
1✔
1311
  }
1✔
1312

1313
  #[test]
1314
  fn test_get_resource_title() {
1✔
1315
    let app = App::default();
1✔
1316
    assert_eq!(
1✔
1317
      get_resource_title(&app, "Title", "-> hello", 5),
1✔
1318
      " Title (ns: all) [5] -> hello"
1319
    );
1320
  }
1✔
1321

1322
  #[test]
1323
  fn test_title_with_ns() {
1✔
1324
    assert_eq!(title_with_ns("Title", "hello", 3), "Title (ns: hello) [3]");
1✔
1325
  }
1✔
1326

1327
  #[test]
1328
  fn test_get_cluster_wide_resource_title() {
1✔
1329
    assert_eq!(
1✔
1330
      get_cluster_wide_resource_title("Cluster Resource", 3, ""),
1✔
1331
      " Cluster Resource [3] "
1332
    );
1333
    assert_eq!(
1✔
1334
      get_cluster_wide_resource_title("Nodes", 10, "-> hello"),
1✔
1335
      " Nodes [10] -> hello"
1336
    );
1337
  }
1✔
1338
}
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