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

kdash-rs / kdash / 24896397183

24 Apr 2026 03:02PM UTC coverage: 73.009% (-0.1%) from 73.15%
24896397183

Pull #515

github

web-flow
Merge 8f46812f6 into 6a1cbe609
Pull Request #515: feat(ui): more efficient redraw

79 of 164 new or added lines in 3 files covered. (48.17%)

4 existing lines in 2 files now uncovered.

10238 of 14023 relevant lines covered (73.01%)

138.99 hits per line

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

78.73
/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

13
use super::HIGHLIGHT;
14
use crate::app::{
15
  key_binding::DEFAULT_KEYBINDING,
16
  models::{Named, StatefulTable},
17
  ActiveBlock, App,
18
};
19
use crate::event::Key;
20
use crate::ui::theme::override_color;
21
// Viewport width thresholds for responsive column display
22
pub const COMPACT_WIDTH_THRESHOLD: u16 = 120;
23
pub const WIDE_WIDTH_THRESHOLD: u16 = 180;
24

25
/// Which responsive tier the current view is in.
26
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
27
pub enum ViewTier {
28
  Compact,
29
  Standard,
30
  Wide,
31
}
32

33
impl ViewTier {
34
  pub fn from_width(area_width: u16, force_wide: bool) -> Self {
5✔
35
    if force_wide || area_width >= WIDE_WIDTH_THRESHOLD {
5✔
36
      Self::Wide
×
37
    } else if area_width >= COMPACT_WIDTH_THRESHOLD {
5✔
38
      Self::Standard
1✔
39
    } else {
40
      Self::Compact
4✔
41
    }
42
  }
5✔
43
}
44

45
/// Declarative column definition with per-tier width percentages.
46
/// A `None` width means the column is hidden at that tier.
47
pub struct ColumnDef {
48
  pub label: &'static str,
49
  pub compact: Option<u16>,
50
  pub standard: Option<u16>,
51
  pub wide: Option<u16>,
52
}
53

54
impl ColumnDef {
55
  /// Column visible at all tiers with different widths.
56
  pub const fn all(label: &'static str, compact: u16, standard: u16, wide: u16) -> Self {
×
57
    Self {
×
58
      label,
×
59
      compact: Some(compact),
×
60
      standard: Some(standard),
×
61
      wide: Some(wide),
×
62
    }
×
63
  }
×
64

65
  /// Column visible only at Standard and Wide tiers.
66
  pub const fn standard(label: &'static str, standard: u16, wide: u16) -> Self {
×
67
    Self {
×
68
      label,
×
69
      compact: None,
×
70
      standard: Some(standard),
×
71
      wide: Some(wide),
×
72
    }
×
73
  }
×
74

75
  /// Column visible only at Wide tier.
76
  pub const fn wide(label: &'static str, wide: u16) -> Self {
×
77
    Self {
×
78
      label,
×
79
      compact: None,
×
80
      standard: None,
×
81
      wide: Some(wide),
×
82
    }
×
83
  }
×
84
}
85

86
/// Given column definitions and a view tier, return the visible headers and widths.
87
pub fn responsive_columns(columns: &[ColumnDef], tier: ViewTier) -> (Vec<&str>, Vec<Constraint>) {
7✔
88
  columns
7✔
89
    .iter()
7✔
90
    .filter_map(|col| {
55✔
91
      let w = match tier {
55✔
92
        ViewTier::Wide => col.wide,
×
93
        ViewTier::Standard => col.standard,
8✔
94
        ViewTier::Compact => col.compact,
47✔
95
      };
96
      w.map(|w| (col.label, Constraint::Percentage(w)))
55✔
97
    })
55✔
98
    .unzip()
7✔
99
}
7✔
100

101
// Utils
102

103
#[derive(Clone, Debug, PartialEq, Eq)]
104
pub enum LinePart<'a> {
105
  Default(Cow<'a, str>),
106
  Help(Cow<'a, str>),
107
}
108

109
// Catppuccin Macchiato (dark)
110
pub const MACCHIATO_BASE: Color = Color::Rgb(36, 39, 58);
111
pub const MACCHIATO_BLUE: Color = Color::Rgb(138, 173, 244);
112
pub const MACCHIATO_GREEN: Color = Color::Rgb(166, 218, 149);
113
pub const MACCHIATO_RED: Color = Color::Rgb(237, 135, 150);
114
pub const MACCHIATO_YELLOW: Color = Color::Rgb(238, 212, 159);
115
pub const MACCHIATO_PEACH: Color = Color::Rgb(245, 169, 127);
116
pub const MACCHIATO_TEXT: Color = Color::Rgb(202, 211, 245);
117
pub const MACCHIATO_MAUVE: Color = Color::Rgb(198, 160, 246);
118
// Catppuccin Latte (light)
119
pub const LATTE_MAUVE: Color = Color::Rgb(136, 57, 239);
120
pub const LATTE_TEXT: Color = Color::Rgb(76, 79, 105);
121
pub const LATTE_BLUE: Color = Color::Rgb(30, 102, 245);
122
pub const LATTE_MAROON: Color = Color::Rgb(230, 69, 83);
123
pub const LATTE_GREEN: Color = Color::Rgb(64, 160, 43);
124
pub const LATTE_RED: Color = Color::Rgb(210, 15, 57);
125
pub const LATTE_PEACH: Color = Color::Rgb(254, 100, 11);
126
pub const LATTE_BASE: Color = Color::Rgb(239, 241, 245);
127
const CATPPUCCIN_MACCHIATO_THEME: &[u8] =
128
  include_bytes!("../../assets/themes/CatppuccinMacchiato.tmTheme");
129
const CATPPUCCIN_LATTE_THEME: &[u8] = include_bytes!("../../assets/themes/CatppuccinLatte.tmTheme");
130

131
/// Convert a syntect highlight segment into an owned ratatui Span.
132
fn syntect_to_ratatui_span_owned(
×
133
  (style, content): (syntect::highlighting::Style, &str),
×
134
) -> Option<Span<'static>> {
×
135
  use syntect::highlighting::FontStyle;
136
  let fg = if style.foreground.a > 0 {
×
137
    Some(Color::Rgb(
×
138
      style.foreground.r,
×
139
      style.foreground.g,
×
140
      style.foreground.b,
×
141
    ))
×
142
  } else {
143
    None
×
144
  };
145
  let bg = if style.background.a > 0 {
×
146
    Some(Color::Rgb(
×
147
      style.background.r,
×
148
      style.background.g,
×
149
      style.background.b,
×
150
    ))
×
151
  } else {
152
    None
×
153
  };
154
  let modifier = {
×
155
    let fs = style.font_style;
×
156
    let mut m = Modifier::empty();
×
157
    if fs.contains(FontStyle::BOLD) {
×
158
      m |= Modifier::BOLD;
×
159
    }
×
160
    if fs.contains(FontStyle::ITALIC) {
×
161
      m |= Modifier::ITALIC;
×
162
    }
×
163
    if fs.contains(FontStyle::UNDERLINE) {
×
164
      m |= Modifier::UNDERLINED;
×
165
    }
×
166
    m
×
167
  };
168
  let ratatui_style = Style::default()
×
169
    .fg(fg.unwrap_or_default())
×
170
    .bg(bg.unwrap_or_default())
×
171
    .add_modifier(modifier);
×
172
  Some(Span::styled(content.to_owned(), ratatui_style))
×
173
}
×
174

175
fn get_syntax_set() -> &'static syntect::parsing::SyntaxSet {
×
176
  static SYNTAX_SET: OnceLock<syntect::parsing::SyntaxSet> = OnceLock::new();
177
  SYNTAX_SET.get_or_init(syntect::parsing::SyntaxSet::load_defaults_newlines)
×
178
}
×
179

180
fn get_yaml_syntax_reference() -> &'static syntect::parsing::SyntaxReference {
×
181
  static YAML_SYNTAX_REFERENCE: OnceLock<syntect::parsing::SyntaxReference> = OnceLock::new();
182
  YAML_SYNTAX_REFERENCE.get_or_init(|| {
×
183
    get_syntax_set()
×
184
      .find_syntax_by_extension("yaml")
×
185
      .unwrap()
×
186
      .clone()
×
187
  })
×
188
}
×
189

190
struct YamlThemes {
191
  dark: syntect::highlighting::Theme,
192
  light: syntect::highlighting::Theme,
193
}
194

195
fn get_yaml_themes() -> &'static YamlThemes {
×
196
  static YAML_THEMES: OnceLock<YamlThemes> = OnceLock::new();
197
  YAML_THEMES.get_or_init(|| {
×
198
    let dark = load_embedded_theme(CATPPUCCIN_MACCHIATO_THEME);
×
199
    let light = load_embedded_theme(CATPPUCCIN_LATTE_THEME);
×
200
    YamlThemes { dark, light }
×
201
  })
×
202
}
×
203

204
fn load_embedded_theme(theme_bytes: &[u8]) -> syntect::highlighting::Theme {
×
205
  syntect::highlighting::ThemeSet::load_from_reader(&mut Cursor::new(theme_bytes))
×
206
    .expect("embedded theme should load")
×
207
}
×
208

209
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
210
pub enum Styles {
211
  Text,
212
  Failure,
213
  Warning,
214
  Success,
215
  Primary,
216
  Secondary,
217
  Help,
218
  Background,
219
}
220

221
pub fn theme_styles(light: bool) -> BTreeMap<Styles, Style> {
435✔
222
  let mut styles = if light {
435✔
223
    BTreeMap::from([
×
224
      (Styles::Text, Style::default().fg(LATTE_TEXT)),
×
225
      (Styles::Failure, Style::default().fg(LATTE_RED)),
×
226
      (Styles::Warning, Style::default().fg(LATTE_PEACH)),
×
227
      (Styles::Success, Style::default().fg(LATTE_GREEN)),
×
228
      (Styles::Primary, Style::default().fg(LATTE_MAUVE)),
×
229
      (Styles::Secondary, Style::default().fg(LATTE_MAROON)),
×
230
      (Styles::Help, Style::default().fg(LATTE_BLUE)),
×
231
      (
×
232
        Styles::Background,
×
233
        Style::default().bg(LATTE_BASE).fg(LATTE_TEXT),
×
234
      ),
×
235
    ])
×
236
  } else {
237
    BTreeMap::from([
435✔
238
      (Styles::Text, Style::default().fg(MACCHIATO_TEXT)),
435✔
239
      (Styles::Failure, Style::default().fg(MACCHIATO_RED)),
435✔
240
      (Styles::Warning, Style::default().fg(MACCHIATO_PEACH)),
435✔
241
      (Styles::Success, Style::default().fg(MACCHIATO_GREEN)),
435✔
242
      (Styles::Primary, Style::default().fg(MACCHIATO_MAUVE)),
435✔
243
      (Styles::Secondary, Style::default().fg(MACCHIATO_YELLOW)),
435✔
244
      (Styles::Help, Style::default().fg(MACCHIATO_BLUE)),
435✔
245
      (
435✔
246
        Styles::Background,
435✔
247
        Style::default().bg(MACCHIATO_BASE).fg(MACCHIATO_TEXT),
435✔
248
      ),
435✔
249
    ])
435✔
250
  };
251

252
  apply_theme_override(&mut styles, Styles::Text, "text", false, light);
435✔
253
  apply_theme_override(&mut styles, Styles::Failure, "failure", false, light);
435✔
254
  apply_theme_override(&mut styles, Styles::Warning, "warning", false, light);
435✔
255
  apply_theme_override(&mut styles, Styles::Success, "success", false, light);
435✔
256
  apply_theme_override(&mut styles, Styles::Primary, "primary", false, light);
435✔
257
  apply_theme_override(&mut styles, Styles::Secondary, "secondary", false, light);
435✔
258
  apply_theme_override(&mut styles, Styles::Help, "help", false, light);
435✔
259
  apply_theme_override(&mut styles, Styles::Background, "background", true, light);
435✔
260

261
  styles
435✔
262
}
435✔
263

264
pub fn title_style(txt: &str) -> Span<'_> {
8✔
265
  Span::styled(txt, style_bold())
8✔
266
}
8✔
267

268
pub fn default_part<'a, S: Into<Cow<'a, str>>>(text: S) -> LinePart<'a> {
104✔
269
  LinePart::Default(text.into())
104✔
270
}
104✔
271

272
pub fn help_part<'a, S: Into<Cow<'a, str>>>(text: S) -> LinePart<'a> {
166✔
273
  LinePart::Help(text.into())
166✔
274
}
166✔
275

276
pub fn style_header(light: bool) -> Style {
14✔
277
  style_primary(light).add_modifier(Modifier::REVERSED)
14✔
278
}
14✔
279

280
pub fn style_bold() -> Style {
8✔
281
  Style::default().add_modifier(Modifier::BOLD)
8✔
282
}
8✔
283

284
pub fn style_text(light: bool) -> Style {
112✔
285
  *theme_styles(light).get(&Styles::Text).unwrap()
112✔
286
}
112✔
287
pub fn style_logo(light: bool) -> Style {
3✔
288
  style_primary(light)
3✔
289
}
3✔
290
pub fn style_failure(light: bool) -> Style {
10✔
291
  *theme_styles(light).get(&Styles::Failure).unwrap()
10✔
292
}
10✔
293
pub fn style_warning(light: bool) -> Style {
2✔
294
  *theme_styles(light).get(&Styles::Warning).unwrap()
2✔
295
}
2✔
296
pub fn style_caution(light: bool) -> Style {
2✔
297
  style_warning(light)
2✔
298
}
2✔
299
pub fn style_success(light: bool) -> Style {
4✔
300
  *theme_styles(light).get(&Styles::Success).unwrap()
4✔
301
}
4✔
302
pub fn style_primary(light: bool) -> Style {
105✔
303
  *theme_styles(light).get(&Styles::Primary).unwrap()
105✔
304
}
105✔
305
pub fn style_help(light: bool) -> Style {
152✔
306
  *theme_styles(light).get(&Styles::Help).unwrap()
152✔
307
}
152✔
308

309
pub fn style_secondary(light: bool) -> Style {
43✔
310
  *theme_styles(light).get(&Styles::Secondary).unwrap()
43✔
311
}
43✔
312

313
pub fn style_main_background(light: bool) -> Style {
7✔
314
  *theme_styles(light).get(&Styles::Background).unwrap()
7✔
315
}
7✔
316

317
pub fn style_highlight() -> Style {
16✔
318
  Style::default().add_modifier(Modifier::REVERSED)
16✔
319
}
16✔
320

321
fn line_part_style(part: &LinePart<'_>, light: bool, bold: bool) -> Style {
251✔
322
  let style = match part {
251✔
323
    LinePart::Default(_) => style_text(light),
99✔
324
    LinePart::Help(_) => style_help(light),
152✔
325
  };
326
  if bold {
251✔
327
    style.add_modifier(Modifier::BOLD)
102✔
328
  } else {
329
    style
149✔
330
  }
331
}
251✔
332

333
fn apply_theme_override(
3,480✔
334
  styles: &mut BTreeMap<Styles, Style>,
3,480✔
335
  slot: Styles,
3,480✔
336
  config_key: &str,
3,480✔
337
  background: bool,
3,480✔
338
  light: bool,
3,480✔
339
) {
3,480✔
340
  if let Some(color) = override_color(config_key, light) {
3,480✔
341
    let style = styles.entry(slot).or_default();
×
342
    *style = if background {
×
343
      style.bg(color)
×
344
    } else {
345
      style.fg(color)
×
346
    };
347
  }
3,480✔
348
}
3,480✔
349

350
pub fn mixed_line<'a, I>(parts: I, light: bool) -> Line<'a>
78✔
351
where
78✔
352
  I: IntoIterator<Item = LinePart<'a>>,
78✔
353
{
354
  styled_line(parts, light, false)
78✔
355
}
78✔
356

357
pub fn mixed_bold_line<'a, I>(parts: I, light: bool) -> Line<'a>
47✔
358
where
47✔
359
  I: IntoIterator<Item = LinePart<'a>>,
47✔
360
{
361
  styled_line(parts, light, true)
47✔
362
}
47✔
363

364
pub fn help_bold_line<'a, S: Into<Cow<'a, str>>>(text: S, light: bool) -> Line<'a> {
11✔
365
  mixed_bold_line([help_part(text)], light)
11✔
366
}
11✔
367

368
pub fn key_hints(keys: &[Key]) -> String {
10✔
369
  keys
10✔
370
    .iter()
10✔
371
    .map(ToString::to_string)
10✔
372
    .collect::<Vec<_>>()
10✔
373
    .join("/")
10✔
374
}
10✔
375

376
pub fn action_hint(action: &str, key: Key) -> String {
82✔
377
  format!("{} {}", action, key)
82✔
378
}
82✔
379

380
pub fn describe_and_yaml_hint() -> String {
6✔
381
  format!(
6✔
382
    "{} | {} ",
383
    action_hint("describe", DEFAULT_KEYBINDING.describe_resource.key),
6✔
384
    action_hint("yaml", DEFAULT_KEYBINDING.resource_yaml.key)
6✔
385
  )
386
}
6✔
387

388
pub fn describe_yaml_and_logs_hint() -> String {
5✔
389
  format!(
5✔
390
    "{} | {} ",
391
    describe_and_yaml_hint().trim_end(),
5✔
392
    action_hint("logs", DEFAULT_KEYBINDING.aggregate_logs.key)
5✔
393
  )
394
}
5✔
395

396
pub fn describe_yaml_logs_and_esc_hint() -> String {
×
397
  format!(
×
398
    "{} | back {} ",
399
    describe_yaml_and_logs_hint().trim_end(),
×
400
    DEFAULT_KEYBINDING.esc.key
×
401
  )
402
}
×
403

404
pub fn describe_yaml_and_esc_hint() -> String {
×
405
  format!(
×
406
    "{} | back {} ",
407
    describe_and_yaml_hint().trim_end(),
×
408
    DEFAULT_KEYBINDING.esc.key
×
409
  )
410
}
×
411

412
pub fn describe_yaml_decode_and_esc_hint() -> String {
×
413
  format!(
×
414
    "{} | {} | back {} ",
415
    describe_and_yaml_hint().trim_end(),
×
416
    action_hint("decode", DEFAULT_KEYBINDING.decode_secret.key),
×
417
    DEFAULT_KEYBINDING.esc.key
×
418
  )
419
}
×
420

421
pub fn wide_hint() -> String {
5✔
422
  format!("wide {}", DEFAULT_KEYBINDING.toggle_wide_columns.key)
5✔
423
}
5✔
424

425
pub fn filter_cursor_position(area: Rect, prefix_width: usize, filter: &str) -> Position {
7✔
426
  Position {
7✔
427
    x: area.x
7✔
428
      + (prefix_width as u16 + 1 + filter.chars().count() as u16).min(area.width.saturating_sub(2)),
7✔
429
    y: area.y,
7✔
430
  }
7✔
431
}
7✔
432

433
fn styled_line<'a, I>(parts: I, light: bool, bold: bool) -> Line<'a>
125✔
434
where
125✔
435
  I: IntoIterator<Item = LinePart<'a>>,
125✔
436
{
437
  Line::from(
125✔
438
    parts
125✔
439
      .into_iter()
125✔
440
      .map(|part| {
251✔
441
        let style = line_part_style(&part, light, bold);
251✔
442
        match part {
251✔
443
          LinePart::Default(text) | LinePart::Help(text) => Span::styled(text, style),
251✔
444
        }
445
      })
251✔
446
      .collect::<Vec<_>>(),
125✔
447
  )
448
}
125✔
449

450
pub fn get_gauge_symbol(enhanced_graphics: bool) -> &'static str {
12✔
451
  if enhanced_graphics {
12✔
452
    symbols::line::THICK_HORIZONTAL
4✔
453
  } else {
454
    symbols::line::HORIZONTAL
8✔
455
  }
456
}
12✔
457

458
pub fn table_header_style(cells: Vec<&str>, light: bool) -> Row<'_> {
10✔
459
  Row::new(cells).style(style_text(light)).bottom_margin(0)
10✔
460
}
10✔
461

462
pub fn horizontal_chunks(constraints: Vec<Constraint>, size: Rect) -> Rc<[Rect]> {
3✔
463
  Layout::default()
3✔
464
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
3✔
465
      &constraints,
3✔
466
    ))
3✔
467
    .direction(Direction::Horizontal)
3✔
468
    .split(size)
3✔
469
}
3✔
470

471
pub fn horizontal_chunks_with_margin(
7✔
472
  constraints: Vec<Constraint>,
7✔
473
  size: Rect,
7✔
474
  margin: u16,
7✔
475
) -> Rc<[Rect]> {
7✔
476
  Layout::default()
7✔
477
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
7✔
478
      &constraints,
7✔
479
    ))
7✔
480
    .direction(Direction::Horizontal)
7✔
481
    .margin(margin)
7✔
482
    .split(size)
7✔
483
}
7✔
484

485
pub fn vertical_chunks(constraints: Vec<Constraint>, size: Rect) -> Rc<[Rect]> {
12✔
486
  Layout::default()
12✔
487
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
12✔
488
      &constraints,
12✔
489
    ))
12✔
490
    .direction(Direction::Vertical)
12✔
491
    .split(size)
12✔
492
}
12✔
493

494
pub fn vertical_chunks_with_margin(
8✔
495
  constraints: Vec<Constraint>,
8✔
496
  size: Rect,
8✔
497
  margin: u16,
8✔
498
) -> Rc<[Rect]> {
8✔
499
  Layout::default()
8✔
500
    .constraints(<Vec<Constraint> as AsRef<[Constraint]>>::as_ref(
8✔
501
      &constraints,
8✔
502
    ))
8✔
503
    .direction(Direction::Vertical)
8✔
504
    .margin(margin)
8✔
505
    .split(size)
8✔
506
}
8✔
507

508
pub fn layout_block(title: Span<'_>) -> Block<'_> {
8✔
509
  Block::default().borders(Borders::ALL).title(title)
8✔
510
}
8✔
511

512
pub fn layout_block_default(title: &str) -> Block<'_> {
8✔
513
  layout_block(title_style(title))
8✔
514
}
8✔
515

516
pub fn layout_block_default_line(title: Line<'_>) -> Block<'_> {
11✔
517
  Block::default().borders(Borders::ALL).title(title)
11✔
518
}
11✔
519

520
pub fn layout_block_active_line(title: Line<'_>, light: bool) -> Block<'_> {
5✔
521
  Block::default()
5✔
522
    .borders(Borders::ALL)
5✔
523
    .title(title)
5✔
524
    .style(style_secondary(light))
5✔
525
}
5✔
526

527
pub fn layout_block_active_span(title: Line<'_>, light: bool) -> Block<'_> {
2✔
528
  layout_block_active_line(title, light)
2✔
529
}
2✔
530

531
pub fn layout_block_top_border(title: Line<'_>) -> Block<'_> {
10✔
532
  Block::default().borders(Borders::TOP).title(title)
10✔
533
}
10✔
534

535
enum FilterDisplayState<'a> {
536
  Inactive,
537
  EditingEmpty,
538
  Value { filter: &'a str, active: bool },
539
}
540

541
fn filter_display_state(filter: &str, active: bool) -> FilterDisplayState<'_> {
20✔
542
  if active && filter.is_empty() {
20✔
543
    FilterDisplayState::EditingEmpty
×
544
  } else if !filter.is_empty() {
20✔
545
    FilterDisplayState::Value { filter, active }
7✔
546
  } else {
547
    FilterDisplayState::Inactive
13✔
548
  }
549
}
20✔
550

551
fn filter_display_parts(filter: &str, active: bool) -> Vec<LinePart<'_>> {
20✔
552
  let state = filter_display_state(filter, active);
20✔
553
  let inactive_text = action_hint("filter", DEFAULT_KEYBINDING.filter.key);
20✔
554
  let clear_suffix = format!(" | clear {} ", DEFAULT_KEYBINDING.esc.key);
20✔
555
  let edit_suffix = format!(" | edit {} ", DEFAULT_KEYBINDING.filter.key);
20✔
556

557
  match state {
20✔
558
    FilterDisplayState::Inactive => vec![help_part(inactive_text)],
13✔
559
    FilterDisplayState::EditingEmpty => {
560
      vec![help_part("[type to filter]"), help_part(clear_suffix)]
×
561
    }
562
    FilterDisplayState::Value {
563
      filter,
4✔
564
      active: true,
565
    } => vec![
4✔
566
      default_part(format!("[{}]", filter)),
4✔
567
      help_part(clear_suffix),
4✔
568
    ],
569
    FilterDisplayState::Value {
570
      filter,
3✔
571
      active: false,
572
    } => vec![
3✔
573
      default_part(format!("[{}]", filter)),
3✔
574
      help_part(edit_suffix),
3✔
575
    ],
576
  }
577
}
20✔
578

579
pub fn filter_status_parts(filter: &str, active: bool) -> Vec<LinePart<'_>> {
6✔
580
  filter_display_parts(filter, active)
6✔
581
}
6✔
582

583
pub fn owned_filter_status_parts(filter: &str, active: bool) -> Vec<LinePart<'static>> {
14✔
584
  filter_display_parts(filter, active)
14✔
585
    .into_iter()
14✔
586
    .map(|part| match part {
19✔
587
      LinePart::Default(text) => default_part(text.into_owned()),
5✔
588
      LinePart::Help(text) => help_part(text.into_owned()),
14✔
589
    })
19✔
590
    .collect()
14✔
591
}
14✔
592

593
pub fn title_with_dual_style<'a>(part_1: String, part_2: Line<'a>, light: bool) -> Line<'a> {
12✔
594
  let mut spans = vec![Span::styled(
12✔
595
    part_1,
12✔
596
    style_secondary(light).add_modifier(Modifier::BOLD),
12✔
597
  )];
598
  spans.extend(part_2.spans);
12✔
599
  Line::from(spans)
12✔
600
}
12✔
601

602
pub fn copy_and_escape_title_line<'a, S: Into<Cow<'a, str>>>(_target: S, light: bool) -> Line<'a> {
×
603
  mixed_bold_line(
×
604
    [
×
605
      help_part(format!(
×
606
        "{} | ",
×
607
        action_hint("copy", DEFAULT_KEYBINDING.copy_to_clipboard.key)
×
608
      )),
×
609
      help_part(format!("back {} ", DEFAULT_KEYBINDING.esc.key)),
×
610
    ],
×
611
    light,
×
612
  )
613
}
×
614

615
pub fn copy_scroll_and_escape_title_line<'a, S: Into<Cow<'a, str>>>(
×
616
  _target: S,
×
617
  auto_scroll: bool,
×
618
  light: bool,
×
619
) -> Line<'a> {
×
620
  let auto_scroll_action = if auto_scroll {
×
621
    "pause scroll"
×
622
  } else {
623
    "resume scroll"
×
624
  };
625
  mixed_bold_line(
×
626
    [
×
627
      help_part(format!(
×
628
        "{} | {} | ",
×
629
        action_hint("copy", DEFAULT_KEYBINDING.copy_to_clipboard.key),
×
630
        action_hint(auto_scroll_action, DEFAULT_KEYBINDING.log_auto_scroll.key)
×
631
      )),
×
632
      help_part(format!("back {} ", DEFAULT_KEYBINDING.esc.key)),
×
633
    ],
×
634
    light,
×
635
  )
636
}
×
637

638
pub fn split_hint_suffix(text: &str) -> (&str, Option<&str>) {
83✔
639
  if let Some(pos) = text.rfind(" <") {
83✔
640
    (&text[..pos], Some(&text[(pos + 1)..]))
83✔
641
  } else {
642
    (text, None)
×
643
  }
644
}
83✔
645

646
/// helper function to create a centered rect using up
647
/// certain percentage of the available rect `r`
648
pub fn centered_rect(width: u16, height: u16, r: Rect) -> Rect {
4✔
649
  let Rect {
650
    width: grid_width,
4✔
651
    height: grid_height,
4✔
652
    ..
653
  } = r;
4✔
654
  let outer_height = (grid_height / 2).saturating_sub(height / 2);
4✔
655

656
  let popup_layout = Layout::default()
4✔
657
    .direction(Direction::Vertical)
4✔
658
    .constraints(
4✔
659
      [
4✔
660
        Constraint::Length(outer_height),
4✔
661
        Constraint::Length(height),
4✔
662
        Constraint::Length(outer_height),
4✔
663
      ]
4✔
664
      .as_ref(),
4✔
665
    )
4✔
666
    .split(r);
4✔
667

668
  let outer_width = (grid_width / 2).saturating_sub(width / 2);
4✔
669

670
  Layout::default()
4✔
671
    .direction(Direction::Horizontal)
4✔
672
    .constraints(
4✔
673
      [
4✔
674
        Constraint::Length(outer_width),
4✔
675
        Constraint::Length(width),
4✔
676
        Constraint::Length(outer_width),
4✔
677
      ]
4✔
678
      .as_ref(),
4✔
679
    )
4✔
680
    .split(popup_layout[1])[1]
4✔
681
}
4✔
682

683
pub fn loading(f: &mut Frame<'_>, block: Block<'_>, area: Rect, is_loading: bool, light: bool) {
9✔
684
  if is_loading {
9✔
685
    let text = "\n\n Loading ...\n\n".to_owned();
×
686
    let text = Text::from(text);
×
687
    let text = text.patch_style(style_secondary(light));
×
688

×
689
    // Contains the text
×
690
    let paragraph = Paragraph::new(text)
×
691
      .style(style_secondary(light))
×
692
      .block(block);
×
693
    f.render_widget(paragraph, area);
×
694
  } else {
×
695
    f.render_widget(block, area)
9✔
696
  }
697
}
9✔
698

699
// using a macro to reuse code as generics will make handling lifetimes a PITA
700
#[macro_export]
701
macro_rules! draw_resource_tab {
702
  ($title:expr, $block:expr, $f:expr, $app:expr, $area:expr, $fn1:expr, $fn2:expr, $res:expr) => {
703
    match $block {
704
      ActiveBlock::Describe => draw_describe_block(
705
        $f,
706
        $app,
707
        $area,
708
        title_with_dual_style(
709
          get_resource_title($app, $title, get_describe_active($block), $res.items.len()),
710
          $crate::ui::utils::copy_and_escape_title_line($title, $app.light_theme),
711
          $app.light_theme,
712
        ),
713
      ),
714
      ActiveBlock::Yaml => draw_yaml_block(
715
        $f,
716
        $app,
717
        $area,
718
        title_with_dual_style(
719
          get_resource_title($app, $title, get_describe_active($block), $res.items.len()),
720
          $crate::ui::utils::copy_and_escape_title_line($title, $app.light_theme),
721
          $app.light_theme,
722
        ),
723
      ),
724
      ActiveBlock::Pods => $crate::app::pods::draw_block_as_sub($f, $app, $area),
725
      ActiveBlock::Containers => $crate::app::pods::draw_containers_block($f, $app, $area),
726
      ActiveBlock::Logs => $crate::app::pods::draw_logs_block($f, $app, $area),
727
      ActiveBlock::Namespaces => $fn1($app.get_prev_route().active_block, $f, $app, $area),
728
      _ => $fn2($f, $app, $area),
729
    };
730
  };
731
}
732

733
pub struct ResourceTableProps<'a, T> {
734
  pub title: String,
735
  pub inline_help: Line<'a>,
736
  pub resource: &'a mut StatefulTable<T>,
737
  pub table_headers: Vec<&'a str>,
738
  pub column_widths: Vec<Constraint>,
739
}
740
/// common for all resources
741
pub fn draw_describe_block(f: &mut Frame<'_>, app: &mut App, area: Rect, title: Line<'_>) {
×
742
  draw_yaml_block(f, app, area, title);
×
743
}
×
744

745
/// Refreshes the syntax-highlight cache when empty or the theme changed.
746
/// Returns `false` when there is no content to highlight.
NEW
747
fn ensure_highlight_cache(app: &mut App) -> bool {
×
NEW
748
  if app.data.describe_out.get_txt().is_empty() {
×
NEW
749
    return false;
×
NEW
750
  }
×
NEW
751
  if app.data.describe_out.highlighted_lines.is_empty()
×
NEW
752
    || app.data.describe_out.highlight_light_theme != app.light_theme
×
753
  {
NEW
754
    let ss = get_syntax_set();
×
NEW
755
    let syntax = get_yaml_syntax_reference();
×
NEW
756
    let theme = if app.light_theme {
×
NEW
757
      &get_yaml_themes().light
×
758
    } else {
NEW
759
      &get_yaml_themes().dark
×
760
    };
NEW
761
    let mut h = syntect::easy::HighlightLines::new(syntax, theme);
×
NEW
762
    let txt = app.data.describe_out.get_txt();
×
NEW
763
    let lines: Vec<_> = syntect::util::LinesWithEndings::from(txt)
×
NEW
764
      .filter_map(|line| match h.highlight_line(line, ss) {
×
NEW
765
        Ok(segments) => {
×
NEW
766
          let line_spans: Vec<_> = segments
×
NEW
767
            .into_iter()
×
NEW
768
            .filter_map(syntect_to_ratatui_span_owned)
×
NEW
769
            .collect();
×
NEW
770
          Some(ratatui::text::Line::from(line_spans))
×
771
        }
NEW
772
        Err(_) => None,
×
NEW
773
      })
×
NEW
774
      .collect();
×
NEW
775
    app.data.describe_out.highlighted_lines = lines;
×
NEW
776
    app.data.describe_out.highlight_light_theme = app.light_theme;
×
NEW
777
  }
×
NEW
778
  true
×
NEW
779
}
×
780

781
/// common for all resources
782
pub fn draw_yaml_block(f: &mut Frame<'_>, app: &mut App, area: Rect, title: Line<'_>) {
×
783
  let block = layout_block_top_border(title);
×
NEW
784
  if ensure_highlight_cache(app) {
×
NEW
785
    let offset = app.data.describe_out.offset;
×
NEW
786
    let total = app.data.describe_out.highlighted_lines.len();
×
NEW
787
    // Subtract 2 for the top-border of the block.
×
NEW
788
    let view_h = area.height.saturating_sub(2) as usize;
×
NEW
789
    // Take a generous window around the visible region.
×
NEW
790
    let slice_start = offset.saturating_sub(view_h);
×
NEW
791
    let slice_end = total.min(offset + view_h * 3);
×
NEW
792
    let adjusted_offset = (offset - slice_start).min(u16::MAX as usize) as u16;
×
NEW
793
    let visible_lines = app.data.describe_out.highlighted_lines[slice_start..slice_end].to_vec();
×
NEW
794
    let paragraph = Paragraph::new(visible_lines)
×
795
      .block(block)
×
796
      .wrap(Wrap { trim: false })
×
NEW
797
      .scroll((adjusted_offset, 0));
×
798
    f.render_widget(paragraph, area);
×
799
  } else {
×
800
    loading(f, block, area, app.is_loading(), app.light_theme);
×
801
  }
×
802
}
×
803

804
fn draw_resource_table<'a, T: Named, F>(
11✔
805
  f: &mut Frame<'_>,
11✔
806
  area: Rect,
11✔
807
  table_props: ResourceTableProps<'a, T>,
11✔
808
  row_cell_mapper: F,
11✔
809
  light_theme: bool,
11✔
810
  is_loading: bool,
11✔
811
  block: Block<'a>,
11✔
812
) where
11✔
813
  F: Fn(&T) -> Row<'a>,
11✔
814
{
815
  if !table_props.resource.items.is_empty() {
11✔
816
    let filter = table_props.resource.filter.to_lowercase();
8✔
817
    let has_filter = !filter.is_empty();
8✔
818
    let mut filtered_indices: Vec<usize> = Vec::new();
8✔
819

820
    let filtered_items: Vec<(usize, &T)> = table_props
8✔
821
      .resource
8✔
822
      .items
8✔
823
      .iter()
8✔
824
      .enumerate()
8✔
825
      .filter(|(_, c)| filter.is_empty() || filter_by_name(&filter, *c))
33✔
826
      .inspect(|(idx, _)| {
30✔
827
        if has_filter {
30✔
828
          filtered_indices.push(*idx);
5✔
829
        }
25✔
830
      })
30✔
831
      .collect();
8✔
832

833
    if has_filter {
8✔
834
      let max = filtered_items.len().saturating_sub(1);
4✔
835
      if let Some(sel) = table_props.resource.state.selected() {
4✔
836
        if sel > max {
4✔
837
          table_props.resource.state.select(Some(max));
×
838
        }
4✔
839
      }
×
840
    }
4✔
841
    table_props.resource.filtered_indices = filtered_indices;
8✔
842

843
    // Determine the visible row range to avoid expensive row_cell_mapper
844
    // calls for off-screen items.  Subtract 3 for header + borders.
845
    let selected = table_props.resource.state.selected().unwrap_or(0);
8✔
846
    let view_h = area.height.saturating_sub(3) as usize;
8✔
847
    let visible_start = selected.saturating_sub(view_h);
8✔
848
    let visible_end = (selected + view_h * 2).min(filtered_items.len());
8✔
849

850
    let rows: Vec<Row<'a>> = filtered_items
8✔
851
      .iter()
8✔
852
      .enumerate()
8✔
853
      .map(|(fi, (_orig_idx, item))| {
30✔
854
        if fi >= visible_start && fi < visible_end {
30✔
855
          row_cell_mapper(item)
30✔
856
        } else {
NEW
857
          Row::default()
×
858
        }
859
      })
30✔
860
      .collect();
8✔
861

862
    let table = Table::new(rows, &table_props.column_widths)
8✔
863
      .header(table_header_style(table_props.table_headers, light_theme))
8✔
864
      .block(block)
8✔
865
      .row_highlight_style(style_highlight())
8✔
866
      .highlight_symbol(HIGHLIGHT);
8✔
867

868
    f.render_stateful_widget(table, area, &mut table_props.resource.state);
8✔
869
  } else {
3✔
870
    loading(f, block, area, is_loading, light_theme);
3✔
871
  }
3✔
872
}
11✔
873

874
/// Builds the help `Line` for a resource block title, weaving filter status
875
/// into any existing inline help (placing it after a "containers" prefix when present).
876
fn build_resource_help_line(
12✔
877
  inline_help: Line<'_>,
12✔
878
  filter: &str,
12✔
879
  filter_active: bool,
12✔
880
  light_theme: bool,
12✔
881
) -> Line<'static> {
12✔
882
  let inline_help_text = inline_help
12✔
883
    .spans
12✔
884
    .iter()
12✔
885
    .map(|span| span.content.as_ref())
12✔
886
    .collect::<String>();
12✔
887
  let containers_prefix = format!(
12✔
888
    "{} | ",
889
    action_hint("containers", DEFAULT_KEYBINDING.submit.key)
12✔
890
  );
891
  let mut help_parts: Vec<LinePart<'static>> = Vec::new();
12✔
892
  if let Some(rest) = inline_help_text.strip_prefix(&containers_prefix) {
12✔
893
    help_parts.push(help_part(containers_prefix));
5✔
894
    help_parts.extend(owned_filter_status_parts(filter, filter_active));
5✔
895
    if !rest.is_empty() {
5✔
896
      help_parts.push(help_part(" | ".to_string()));
4✔
897
      help_parts.push(help_part(rest.to_string()));
4✔
898
    }
4✔
899
  } else {
900
    help_parts.extend(owned_filter_status_parts(filter, filter_active));
7✔
901
    if !inline_help_text.is_empty() {
7✔
902
      help_parts.push(help_part(" | ".to_string()));
5✔
903
      help_parts.push(help_part(inline_help_text));
5✔
904
    }
5✔
905
  }
906
  mixed_bold_line(help_parts, light_theme)
12✔
907
}
12✔
908

909
/// Draw a kubernetes resource overview tab
910
pub fn draw_resource_block<'a, T: Named, F>(
10✔
911
  f: &mut Frame<'_>,
10✔
912
  area: Rect,
10✔
913
  table_props: ResourceTableProps<'a, T>,
10✔
914
  row_cell_mapper: F,
10✔
915
  light_theme: bool,
10✔
916
  is_loading: bool,
10✔
917
) where
10✔
918
  F: Fn(&T) -> Row<'a>,
10✔
919
{
920
  let ResourceTableProps {
921
    title,
10✔
922
    inline_help,
10✔
923
    resource,
10✔
924
    table_headers,
10✔
925
    column_widths,
10✔
926
  } = table_props;
10✔
927
  let filter = resource.filter.clone();
10✔
928
  let filter_active = resource.filter_active;
10✔
929
  if filter_active {
10✔
930
    let title_width = title.chars().count();
2✔
931
    let title = title_with_dual_style(
2✔
932
      title,
2✔
933
      mixed_bold_line(owned_filter_status_parts(&filter, true), light_theme),
2✔
934
      light_theme,
2✔
935
    );
936
    let block = layout_block_top_border(title);
2✔
937
    draw_resource_table(
2✔
938
      f,
2✔
939
      area,
2✔
940
      ResourceTableProps {
2✔
941
        title: String::new(),
2✔
942
        inline_help: Line::default(),
2✔
943
        resource,
2✔
944
        table_headers,
2✔
945
        column_widths,
2✔
946
      },
2✔
947
      row_cell_mapper,
2✔
948
      light_theme,
2✔
949
      is_loading,
2✔
950
      block,
2✔
951
    );
952
    f.set_cursor_position(filter_cursor_position(area, title_width, &filter));
2✔
953
    return;
2✔
954
  }
8✔
955

956
  let help_line = build_resource_help_line(inline_help, &filter, filter_active, light_theme);
8✔
957
  let title = title_with_dual_style(title, help_line, light_theme);
8✔
958
  let block = layout_block_top_border(title);
8✔
959
  draw_resource_table(
8✔
960
    f,
8✔
961
    area,
8✔
962
    ResourceTableProps {
8✔
963
      title: String::new(),
8✔
964
      inline_help: Line::default(),
8✔
965
      resource,
8✔
966
      table_headers,
8✔
967
      column_widths,
8✔
968
    },
8✔
969
    row_cell_mapper,
8✔
970
    light_theme,
8✔
971
    is_loading,
8✔
972
    block,
8✔
973
  );
974
}
10✔
975

976
pub fn draw_route_resource_block<'a, T: Named, F>(
1✔
977
  f: &mut Frame<'_>,
1✔
978
  area: Rect,
1✔
979
  table_props: ResourceTableProps<'a, T>,
1✔
980
  row_cell_mapper: F,
1✔
981
  light_theme: bool,
1✔
982
  is_loading: bool,
1✔
983
) where
1✔
984
  F: Fn(&T) -> Row<'a>,
1✔
985
{
986
  let ResourceTableProps {
987
    title,
1✔
988
    inline_help,
1✔
989
    resource,
1✔
990
    table_headers,
1✔
991
    column_widths,
1✔
992
  } = table_props;
1✔
993
  let filter = resource.filter.clone();
1✔
994
  let filter_active = resource.filter_active;
1✔
995
  if filter_active {
1✔
996
    let title_width = title.chars().count();
×
997
    let title = title_with_dual_style(
×
998
      title,
×
999
      mixed_bold_line(owned_filter_status_parts(&filter, true), light_theme),
×
1000
      light_theme,
×
1001
    );
1002
    let block = layout_block_active_span(title, light_theme);
×
1003
    draw_resource_table(
×
1004
      f,
×
1005
      area,
×
1006
      ResourceTableProps {
×
1007
        title: String::new(),
×
1008
        inline_help: Line::default(),
×
1009
        resource,
×
1010
        table_headers,
×
1011
        column_widths,
×
1012
      },
×
1013
      row_cell_mapper,
×
1014
      light_theme,
×
1015
      is_loading,
×
1016
      block,
×
1017
    );
1018
    f.set_cursor_position(filter_cursor_position(area, title_width, &filter));
×
1019
    return;
×
1020
  }
1✔
1021

1022
  let title = title_with_dual_style(title, inline_help, light_theme);
1✔
1023
  let block = layout_block_active_span(title, light_theme);
1✔
1024
  draw_resource_table(
1✔
1025
    f,
1✔
1026
    area,
1✔
1027
    ResourceTableProps {
1✔
1028
      title: String::new(),
1✔
1029
      inline_help: Line::default(),
1✔
1030
      resource,
1✔
1031
      table_headers,
1✔
1032
      column_widths,
1✔
1033
    },
1✔
1034
    row_cell_mapper,
1✔
1035
    light_theme,
1✔
1036
    is_loading,
1✔
1037
    block,
1✔
1038
  );
1039
}
1✔
1040

1041
pub fn filter_by_resource_name<T: Named>(
7✔
1042
  filter: &str,
7✔
1043
  res: &T,
7✔
1044
  row_cell_mapper: Row<'static>,
7✔
1045
) -> Option<Row<'static>> {
7✔
1046
  if filter.is_empty() || filter_by_name(filter, res) {
7✔
1047
    Some(row_cell_mapper)
7✔
1048
  } else {
1049
    None
×
1050
  }
1051
}
7✔
1052

1053
pub fn text_matches_filter(filter: &str, value: &str) -> bool {
202✔
1054
  let filter = filter.to_lowercase();
202✔
1055
  let value = value.to_lowercase();
202✔
1056
  filter.is_empty() || glob_match(&filter, &value) || value.contains(&filter)
202✔
1057
}
202✔
1058

1059
fn filter_by_name<T: Named>(ft: &str, res: &T) -> bool {
9✔
1060
  text_matches_filter(ft, res.get_name())
9✔
1061
}
9✔
1062

1063
pub fn get_cluster_wide_resource_title<S: AsRef<str>>(
2✔
1064
  title: S,
2✔
1065
  items_len: usize,
2✔
1066
  suffix: S,
2✔
1067
) -> String {
2✔
1068
  format!(" {} [{}] {}", title.as_ref(), items_len, suffix.as_ref())
2✔
1069
}
2✔
1070

1071
pub fn get_resource_title<S: AsRef<str>>(
10✔
1072
  app: &App,
10✔
1073
  title: S,
10✔
1074
  suffix: S,
10✔
1075
  items_len: usize,
10✔
1076
) -> String {
10✔
1077
  format!(
10✔
1078
    " {} {}",
1079
    title_with_ns(
10✔
1080
      title.as_ref(),
10✔
1081
      app
10✔
1082
        .data
10✔
1083
        .selected
10✔
1084
        .ns
10✔
1085
        .as_ref()
10✔
1086
        .unwrap_or(&String::from("all")),
10✔
1087
      items_len
10✔
1088
    ),
1089
    suffix.as_ref(),
10✔
1090
  )
1091
}
10✔
1092

1093
static DESCRIBE_ACTIVE: &str = "-> Describe ";
1094
static YAML_ACTIVE: &str = "-> YAML ";
1095

1096
pub fn get_describe_active<'a>(block: ActiveBlock) -> &'a str {
×
1097
  match block {
×
1098
    ActiveBlock::Describe => DESCRIBE_ACTIVE,
×
1099
    _ => YAML_ACTIVE,
×
1100
  }
1101
}
×
1102

1103
pub fn title_with_ns(title: &str, ns: &str, length: usize) -> String {
11✔
1104
  format!("{} (ns: {}) [{}]", title, ns, length)
11✔
1105
}
11✔
1106

1107
#[cfg(test)]
1108
mod tests {
1109
  use ratatui::{
1110
    backend::TestBackend, buffer::Buffer, layout::Position, style::Modifier, widgets::Cell,
1111
    Terminal,
1112
  };
1113

1114
  use super::*;
1115
  use crate::ui::utils::{MACCHIATO_BLUE, MACCHIATO_MAUVE, MACCHIATO_TEXT, MACCHIATO_YELLOW};
1116

1117
  #[test]
1118
  fn test_draw_resource_block() {
1✔
1119
    let backend = TestBackend::new(100, 6);
1✔
1120
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1121

1122
    struct RenderTest {
1123
      pub name: String,
1124
      pub namespace: String,
1125
      pub data: i32,
1126
      pub age: String,
1127
    }
1128

1129
    impl Named for RenderTest {
1130
      fn get_name(&self) -> &String {
×
1131
        &self.name
×
1132
      }
×
1133
    }
1134
    terminal
1✔
1135
      .draw(|f| {
1✔
1136
        let size = f.area();
1✔
1137
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1138
        resource.set_items(vec![
1✔
1139
          RenderTest {
1✔
1140
            name: "Test 1".into(),
1✔
1141
            namespace: "Test ns".into(),
1✔
1142
            age: "65h3m".into(),
1✔
1143
            data: 5,
1✔
1144
          },
1✔
1145
          RenderTest {
1✔
1146
            name: "Test long name that should be truncated from view".into(),
1✔
1147
            namespace: "Test ns".into(),
1✔
1148
            age: "65h3m".into(),
1✔
1149
            data: 3,
1✔
1150
          },
1✔
1151
          RenderTest {
1✔
1152
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1153
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1154
            age: "65h3m".into(),
1✔
1155
            data: 6,
1✔
1156
          },
1✔
1157
        ]);
1158
        draw_resource_block(
1✔
1159
          f,
1✔
1160
          size,
1✔
1161
          ResourceTableProps {
1✔
1162
            title: "Test".into(),
1✔
1163
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1164
            resource: &mut resource,
1✔
1165
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1166
            column_widths: vec![
1✔
1167
              Constraint::Percentage(30),
1✔
1168
              Constraint::Percentage(40),
1✔
1169
              Constraint::Percentage(15),
1✔
1170
              Constraint::Percentage(15),
1✔
1171
            ],
1✔
1172
          },
1✔
1173
          |c| {
3✔
1174
            Row::new(vec![
3✔
1175
              Cell::from(c.namespace.to_owned()),
3✔
1176
              Cell::from(c.name.to_owned()),
3✔
1177
              Cell::from(c.data.to_string()),
3✔
1178
              Cell::from(c.age.to_owned()),
3✔
1179
            ])
1180
            .style(style_primary(false))
3✔
1181
          },
3✔
1182
          false,
1183
          false,
1184
        );
1185
      })
1✔
1186
      .unwrap();
1✔
1187

1188
    let mut expected = Buffer::with_lines(vec![
1✔
1189
        "Testfilter </> | -> yaml <y>────────────────────────────────────────────────────────────────────────",
1190
        "   Namespace                     Name                                 Data           Age            ",
1✔
1191
        "=> Test ns                       Test 1                               5              65h3m          ",
1✔
1192
        "   Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1193
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1194
        "                                                                                                    ",
1✔
1195
      ]);
1196
    // set row styles
1197
    // First row heading style
1198
    for col in 0..=99 {
100✔
1199
      match col {
100✔
1200
        0..=3 => {
100✔
1201
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1202
            Style::default()
4✔
1203
              .fg(MACCHIATO_YELLOW)
4✔
1204
              .add_modifier(Modifier::BOLD),
4✔
1205
          );
4✔
1206
        }
4✔
1207
        4..=27 => {
96✔
1208
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
24✔
1209
            Style::default()
24✔
1210
              .fg(MACCHIATO_BLUE)
24✔
1211
              .add_modifier(Modifier::BOLD),
24✔
1212
          );
24✔
1213
        }
24✔
1214
        _ => {}
72✔
1215
      }
1216
    }
1217

1218
    // Second row table header style
1219
    for col in 0..=99 {
100✔
1220
      expected
100✔
1221
        .cell_mut(Position::new(col, 1))
100✔
1222
        .unwrap()
100✔
1223
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1224
    }
100✔
1225
    // first table data row style
1226
    for col in 0..=99 {
100✔
1227
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1228
        Style::default()
100✔
1229
          .fg(MACCHIATO_MAUVE)
100✔
1230
          .add_modifier(Modifier::REVERSED),
100✔
1231
      );
100✔
1232
    }
100✔
1233
    // remaining table data row style
1234
    for row in 3..=4 {
2✔
1235
      for col in 0..=99 {
200✔
1236
        expected
200✔
1237
          .cell_mut(Position::new(col, row))
200✔
1238
          .unwrap()
200✔
1239
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
200✔
1240
      }
200✔
1241
    }
1242

1243
    terminal.backend().assert_buffer(&expected);
1✔
1244
  }
1✔
1245

1246
  #[test]
1247
  fn test_draw_resource_block_filter() {
1✔
1248
    let backend = TestBackend::new(100, 6);
1✔
1249
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1250

1251
    struct RenderTest {
1252
      pub name: String,
1253
      pub namespace: String,
1254
      pub data: i32,
1255
      pub age: String,
1256
    }
1257
    impl Named for RenderTest {
1258
      fn get_name(&self) -> &String {
3✔
1259
        &self.name
3✔
1260
      }
3✔
1261
    }
1262

1263
    terminal
1✔
1264
      .draw(|f| {
1✔
1265
        let size = f.area();
1✔
1266
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1267
        resource.set_items(vec![
1✔
1268
          RenderTest {
1✔
1269
            name: "Test 1".into(),
1✔
1270
            namespace: "Test ns".into(),
1✔
1271
            age: "65h3m".into(),
1✔
1272
            data: 5,
1✔
1273
          },
1✔
1274
          RenderTest {
1✔
1275
            name: "Test long name that should be truncated from view".into(),
1✔
1276
            namespace: "Test ns".into(),
1✔
1277
            age: "65h3m".into(),
1✔
1278
            data: 3,
1✔
1279
          },
1✔
1280
          RenderTest {
1✔
1281
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1282
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1283
            age: "65h3m".into(),
1✔
1284
            data: 6,
1✔
1285
          },
1✔
1286
        ]);
1287
        resource.filter = "truncated".to_string();
1✔
1288
        draw_resource_block(
1✔
1289
          f,
1✔
1290
          size,
1✔
1291
          ResourceTableProps {
1✔
1292
            title: "Test".into(),
1✔
1293
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1294
            resource: &mut resource,
1✔
1295
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1296
            column_widths: vec![
1✔
1297
              Constraint::Percentage(30),
1✔
1298
              Constraint::Percentage(40),
1✔
1299
              Constraint::Percentage(15),
1✔
1300
              Constraint::Percentage(15),
1✔
1301
            ],
1✔
1302
          },
1✔
1303
          |c| {
2✔
1304
            Row::new(vec![
2✔
1305
              Cell::from(c.namespace.to_owned()),
2✔
1306
              Cell::from(c.name.to_owned()),
2✔
1307
              Cell::from(c.data.to_string()),
2✔
1308
              Cell::from(c.age.to_owned()),
2✔
1309
            ])
1310
            .style(style_primary(false))
2✔
1311
          },
2✔
1312
          false,
1313
          false,
1314
        );
1315
      })
1✔
1316
      .unwrap();
1✔
1317

1318
    let mut expected = Buffer::with_lines(vec![
1✔
1319
        "Test[truncated] | edit </>  | -> yaml <y>───────────────────────────────────────────────────────────",
1320
        "   Namespace                     Name                                 Data           Age            ",
1✔
1321
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1322
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1323
        "                                                                                                    ",
1✔
1324
        "                                                                                                    ",
1✔
1325
      ]);
1326
    // set row styles
1327
    // First row heading style
1328
    for col in 0..=99 {
100✔
1329
      match col {
100✔
1330
        0..=3 => {
100✔
1331
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1332
            Style::default()
4✔
1333
              .fg(MACCHIATO_YELLOW)
4✔
1334
              .add_modifier(Modifier::BOLD),
4✔
1335
          );
4✔
1336
        }
4✔
1337
        4..=14 => {
96✔
1338
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
11✔
1339
            Style::default()
11✔
1340
              .fg(MACCHIATO_TEXT)
11✔
1341
              .add_modifier(Modifier::BOLD),
11✔
1342
          );
11✔
1343
        }
11✔
1344
        15..=40 => {
85✔
1345
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
26✔
1346
            Style::default()
26✔
1347
              .fg(MACCHIATO_BLUE)
26✔
1348
              .add_modifier(Modifier::BOLD),
26✔
1349
          );
26✔
1350
        }
26✔
1351
        _ => {}
59✔
1352
      }
1353
    }
1354

1355
    // Second row table header style
1356
    for col in 0..=99 {
100✔
1357
      expected
100✔
1358
        .cell_mut(Position::new(col, 1))
100✔
1359
        .unwrap()
100✔
1360
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1361
    }
100✔
1362
    // first table data row style
1363
    for col in 0..=99 {
100✔
1364
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1365
        Style::default()
100✔
1366
          .fg(MACCHIATO_MAUVE)
100✔
1367
          .add_modifier(Modifier::REVERSED),
100✔
1368
      );
100✔
1369
    }
100✔
1370
    // remaining table data row style
1371
    for row in 3..=3 {
1✔
1372
      for col in 0..=99 {
100✔
1373
        expected
100✔
1374
          .cell_mut(Position::new(col, row))
100✔
1375
          .unwrap()
100✔
1376
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1377
      }
100✔
1378
    }
1379

1380
    terminal.backend().assert_buffer(&expected);
1✔
1381
  }
1✔
1382

1383
  #[test]
1384
  fn test_draw_resource_block_filter_glob() {
1✔
1385
    let backend = TestBackend::new(100, 6);
1✔
1386
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1387

1388
    struct RenderTest {
1389
      pub name: String,
1390
      pub namespace: String,
1391
      pub data: i32,
1392
      pub age: String,
1393
    }
1394
    impl Named for RenderTest {
1395
      fn get_name(&self) -> &String {
3✔
1396
        &self.name
3✔
1397
      }
3✔
1398
    }
1399

1400
    terminal
1✔
1401
      .draw(|f| {
1✔
1402
        let size = f.area();
1✔
1403
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1404
        resource.set_items(vec![
1✔
1405
          RenderTest {
1✔
1406
            name: "Test 1".into(),
1✔
1407
            namespace: "Test ns".into(),
1✔
1408
            age: "65h3m".into(),
1✔
1409
            data: 5,
1✔
1410
          },
1✔
1411
          RenderTest {
1✔
1412
            name: "Test long name that should be truncated from view".into(),
1✔
1413
            namespace: "Test ns".into(),
1✔
1414
            age: "65h3m".into(),
1✔
1415
            data: 3,
1✔
1416
          },
1✔
1417
          RenderTest {
1✔
1418
            name: "test_long_name_that_should_be_truncated_from_view".into(),
1✔
1419
            namespace: "Test ns long value check that should be truncated".into(),
1✔
1420
            age: "65h3m".into(),
1✔
1421
            data: 6,
1✔
1422
          },
1✔
1423
        ]);
1424
        resource.filter = "*long*truncated*".to_string();
1✔
1425
        draw_resource_block(
1✔
1426
          f,
1✔
1427
          size,
1✔
1428
          ResourceTableProps {
1✔
1429
            title: "Test".into(),
1✔
1430
            inline_help: help_bold_line("-> yaml <y>", false),
1✔
1431
            resource: &mut resource,
1✔
1432
            table_headers: vec!["Namespace", "Name", "Data", "Age"],
1✔
1433
            column_widths: vec![
1✔
1434
              Constraint::Percentage(30),
1✔
1435
              Constraint::Percentage(40),
1✔
1436
              Constraint::Percentage(15),
1✔
1437
              Constraint::Percentage(15),
1✔
1438
            ],
1✔
1439
          },
1✔
1440
          |c| {
2✔
1441
            Row::new(vec![
2✔
1442
              Cell::from(c.namespace.to_owned()),
2✔
1443
              Cell::from(c.name.to_owned()),
2✔
1444
              Cell::from(c.data.to_string()),
2✔
1445
              Cell::from(c.age.to_owned()),
2✔
1446
            ])
1447
            .style(style_primary(false))
2✔
1448
          },
2✔
1449
          false,
1450
          false,
1451
        );
1452
      })
1✔
1453
      .unwrap();
1✔
1454

1455
    let mut expected = Buffer::with_lines(vec![
1✔
1456
        "Test[*long*truncated*] | edit </>  | -> yaml <y>────────────────────────────────────────────────────",
1457
        "   Namespace                     Name                                 Data           Age            ",
1✔
1458
        "=> Test ns                       Test long name that should be trunca 3              65h3m          ",
1✔
1459
        "   Test ns long value check that test_long_name_that_should_be_trunca 6              65h3m          ",
1✔
1460
        "                                                                                                    ",
1✔
1461
        "                                                                                                    ",
1✔
1462
      ]);
1463
    // set row styles
1464
    // First row heading style
1465
    for col in 0..=99 {
100✔
1466
      match col {
100✔
1467
        0..=3 => {
100✔
1468
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
4✔
1469
            Style::default()
4✔
1470
              .fg(MACCHIATO_YELLOW)
4✔
1471
              .add_modifier(Modifier::BOLD),
4✔
1472
          );
4✔
1473
        }
4✔
1474
        4..=21 => {
96✔
1475
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
18✔
1476
            Style::default()
18✔
1477
              .fg(MACCHIATO_TEXT)
18✔
1478
              .add_modifier(Modifier::BOLD),
18✔
1479
          );
18✔
1480
        }
18✔
1481
        22..=47 => {
78✔
1482
          expected.cell_mut(Position::new(col, 0)).unwrap().set_style(
26✔
1483
            Style::default()
26✔
1484
              .fg(MACCHIATO_BLUE)
26✔
1485
              .add_modifier(Modifier::BOLD),
26✔
1486
          );
26✔
1487
        }
26✔
1488
        _ => {}
52✔
1489
      }
1490
    }
1491

1492
    // Second row table header style
1493
    for col in 0..=99 {
100✔
1494
      expected
100✔
1495
        .cell_mut(Position::new(col, 1))
100✔
1496
        .unwrap()
100✔
1497
        .set_style(Style::default().fg(MACCHIATO_TEXT));
100✔
1498
    }
100✔
1499
    // first table data row style
1500
    for col in 0..=99 {
100✔
1501
      expected.cell_mut(Position::new(col, 2)).unwrap().set_style(
100✔
1502
        Style::default()
100✔
1503
          .fg(MACCHIATO_MAUVE)
100✔
1504
          .add_modifier(Modifier::REVERSED),
100✔
1505
      );
100✔
1506
    }
100✔
1507
    // remaining table data row style
1508
    for row in 3..=3 {
1✔
1509
      for col in 0..=99 {
100✔
1510
        expected
100✔
1511
          .cell_mut(Position::new(col, row))
100✔
1512
          .unwrap()
100✔
1513
          .set_style(Style::default().fg(MACCHIATO_MAUVE));
100✔
1514
      }
100✔
1515
    }
1516

1517
    terminal.backend().assert_buffer(&expected);
1✔
1518
  }
1✔
1519

1520
  #[test]
1521
  fn test_get_resource_title() {
1✔
1522
    let app = App::default();
1✔
1523
    assert_eq!(
1✔
1524
      get_resource_title(&app, "Title", "-> hello", 5),
1✔
1525
      " Title (ns: all) [5] -> hello"
1526
    );
1527
  }
1✔
1528

1529
  #[test]
1530
  fn test_draw_resource_block_filter_hides_other_hints_when_active() {
1✔
1531
    let backend = TestBackend::new(100, 4);
1✔
1532
    let mut terminal = Terminal::new(backend).unwrap();
1✔
1533

1534
    struct RenderTest {
1535
      pub name: String,
1536
    }
1537

1538
    impl Named for RenderTest {
1539
      fn get_name(&self) -> &String {
1✔
1540
        &self.name
1✔
1541
      }
1✔
1542
    }
1543

1544
    terminal
1✔
1545
      .draw(|f| {
1✔
1546
        let size = f.area();
1✔
1547
        let mut resource: StatefulTable<RenderTest> = StatefulTable::new();
1✔
1548
        resource.set_items(vec![RenderTest {
1✔
1549
          name: "test".into(),
1✔
1550
        }]);
1✔
1551
        resource.filter = "pod".into();
1✔
1552
        resource.filter_active = true;
1✔
1553
        draw_resource_block(
1✔
1554
          f,
1✔
1555
          size,
1✔
1556
          ResourceTableProps {
1✔
1557
            title: "Test".into(),
1✔
1558
            inline_help: help_bold_line("describe <d> | back <Esc>", false),
1✔
1559
            resource: &mut resource,
1✔
1560
            table_headers: vec!["Name"],
1✔
1561
            column_widths: vec![Constraint::Percentage(100)],
1✔
1562
          },
1✔
UNCOV
1563
          |c| Row::new(vec![Cell::from(c.name.to_owned())]).style(style_primary(false)),
×
1564
          false,
1565
          false,
1566
        );
1567
      })
1✔
1568
      .unwrap();
1✔
1569

1570
    let first_line = (0..terminal.backend().buffer().area.width)
1✔
1571
      .map(|col| terminal.backend().buffer()[(col, 0)].symbol())
100✔
1572
      .collect::<String>();
1✔
1573
    assert!(first_line.contains("[pod]"));
1✔
1574
    assert!(first_line.contains("clear <Esc>"));
1✔
1575
    assert!(!first_line.contains("describe <d>"));
1✔
1576
    assert!(!first_line.contains("back <Esc>"));
1✔
1577
  }
1✔
1578

1579
  #[test]
1580
  fn test_title_with_ns() {
1✔
1581
    assert_eq!(title_with_ns("Title", "hello", 3), "Title (ns: hello) [3]");
1✔
1582
  }
1✔
1583

1584
  #[test]
1585
  fn test_get_cluster_wide_resource_title() {
1✔
1586
    assert_eq!(
1✔
1587
      get_cluster_wide_resource_title("Cluster Resource", 3, ""),
1✔
1588
      " Cluster Resource [3] "
1589
    );
1590
    assert_eq!(
1✔
1591
      get_cluster_wide_resource_title("Nodes", 10, "-> hello"),
1✔
1592
      " Nodes [10] -> hello"
1593
    );
1594
  }
1✔
1595

1596
  #[test]
1597
  fn test_build_resource_help_line() {
1✔
1598
    // Case 1: Empty inline_help, empty filter, filter_active=false
1599
    // -> line text should contain the inactive "filter <key>" action hint
1600
    let line = build_resource_help_line(Line::default(), "", false, false);
1✔
1601
    let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
1✔
1602
    let expected_filter_hint = action_hint("filter", DEFAULT_KEYBINDING.filter.key);
1✔
1603
    assert!(
1✔
1604
      text.contains(&expected_filter_hint),
1✔
1605
      "Case 1: expected '{text}' to contain '{expected_filter_hint}'"
1606
    );
1607

1608
    // Case 2: Non-empty inline_help, empty filter, filter_active=false
1609
    // -> line text should contain the inline help hint after " | "
1610
    let line2 = build_resource_help_line(help_bold_line("-> yaml <y>", false), "", false, false);
1✔
1611
    let text2: String = line2.spans.iter().map(|s| s.content.as_ref()).collect();
3✔
1612
    assert!(
1✔
1613
      text2.contains("-> yaml <y>"),
1✔
1614
      "Case 2: expected '{text2}' to contain '-> yaml <y>'"
1615
    );
1616

1617
    // Case 3: inline_help starting with the containers prefix
1618
    // -> line text should start with the containers hint
1619
    let containers_prefix_str = format!(
1✔
1620
      "{} | ",
1621
      action_hint("containers", DEFAULT_KEYBINDING.submit.key)
1✔
1622
    );
1623
    let line3 = build_resource_help_line(
1✔
1624
      help_bold_line(containers_prefix_str.as_str(), false),
1✔
1625
      "",
1✔
1626
      false,
1627
      false,
1628
    );
1629
    let text3: String = line3.spans.iter().map(|s| s.content.as_ref()).collect();
2✔
1630
    let containers_hint = action_hint("containers", DEFAULT_KEYBINDING.submit.key);
1✔
1631
    assert!(
1✔
1632
      text3.starts_with(&containers_hint),
1✔
1633
      "Case 3: expected '{text3}' to start with '{containers_hint}'"
1634
    );
1635

1636
    // Case 4: Empty inline_help, filter="foo", filter_active=false
1637
    // -> line text should contain "[foo]"
1638
    let line4 = build_resource_help_line(Line::default(), "foo", false, false);
1✔
1639
    let text4: String = line4.spans.iter().map(|s| s.content.as_ref()).collect();
2✔
1640
    assert!(
1✔
1641
      text4.contains("[foo]"),
1✔
1642
      "Case 4: expected '{text4}' to contain '[foo]'"
1643
    );
1644
  }
1✔
1645
}
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