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

veeso / tui-realm-stdlib / 15137208932

20 May 2025 12:13PM UTC coverage: 67.595% (-0.7%) from 68.289%
15137208932

push

github

web-flow
Fix clippy lints, apply some pedantic fixes and general small improvements (#32)

* style(examples): directly have values as a type instead of casting

* style(examples/utils): ignore unused warnings

* style: run clippy auto fix

and remove redundant tests from "label"

* style: apply some clippy pedantic auto fixes

* test: set specific strings for "should_panic"

So that other panics are catched as failed tests.

* style(bar_chart): remove casting to "u64" when "usize" is directly provided and needed

* refactor(table): move making rows to own function

To appease "clippy::too_many_lines" and slightly reduce nesting.

* style: add "#[must_use]" where applicable

To hint not to forget a value.

104 of 192 new or added lines in 19 files covered. (54.17%)

12 existing lines in 2 files now uncovered.

2985 of 4416 relevant lines covered (67.6%)

1.66 hits per line

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

73.96
/src/components/table.rs
1
//! ## Table
2
//!
3
//! `Table` represents a read-only textual table component which can be scrollable through arrows or inactive
4

5
use super::props::TABLE_COLUMN_SPACING;
6
use std::cmp::max;
7

8
use tuirealm::command::{Cmd, CmdResult, Direction, Position};
9
use tuirealm::props::{
10
    Alignment, AttrValue, Attribute, Borders, Color, PropPayload, PropValue, Props, Style,
11
    Table as PropTable, TextModifiers,
12
};
13
use tuirealm::ratatui::{
14
    layout::{Constraint, Rect},
15
    text::Span,
16
    widgets::{Cell, Row, Table as TuiTable, TableState},
17
};
18
use tuirealm::{Frame, MockComponent, State, StateValue};
19

20
// -- States
21

22
#[derive(Default)]
23
pub struct TableStates {
24
    pub list_index: usize, // Index of selected item in textarea
25
    pub list_len: usize,   // Lines in text area
26
}
27

28
impl TableStates {
29
    /// ### set_list_len
30
    ///
31
    /// Set list length
32
    pub fn set_list_len(&mut self, len: usize) {
7✔
33
        self.list_len = len;
7✔
34
    }
7✔
35

36
    /// ### incr_list_index
37
    ///
38
    /// Incremenet list index
39
    pub fn incr_list_index(&mut self, rewind: bool) {
9✔
40
        // Check if index is at last element
41
        if self.list_index + 1 < self.list_len {
9✔
42
            self.list_index += 1;
7✔
43
        } else if rewind {
7✔
44
            self.list_index = 0;
1✔
45
        }
1✔
46
    }
9✔
47

48
    /// ### decr_list_index
49
    ///
50
    /// Decrement list index
51
    pub fn decr_list_index(&mut self, rewind: bool) {
10✔
52
        // Check if index is bigger than 0
53
        if self.list_index > 0 {
10✔
54
            self.list_index -= 1;
8✔
55
        } else if rewind && self.list_len > 0 {
8✔
56
            self.list_index = self.list_len - 1;
1✔
57
        }
1✔
58
    }
10✔
59

60
    /// ### fix_list_index
61
    ///
62
    /// Keep index if possible, otherwise set to lenght - 1
63
    pub fn fix_list_index(&mut self) {
8✔
64
        if self.list_index >= self.list_len && self.list_len > 0 {
8✔
65
            self.list_index = self.list_len - 1;
2✔
66
        } else if self.list_len == 0 {
6✔
67
            self.list_index = 0;
×
68
        }
6✔
69
    }
8✔
70

71
    /// ### list_index_at_first
72
    ///
73
    /// Set list index to the first item in the list
74
    pub fn list_index_at_first(&mut self) {
2✔
75
        self.list_index = 0;
2✔
76
    }
2✔
77

78
    /// ### list_index_at_last
79
    ///
80
    /// Set list index at the last item of the list
81
    pub fn list_index_at_last(&mut self) {
2✔
82
        if self.list_len > 0 {
2✔
83
            self.list_index = self.list_len - 1;
2✔
84
        } else {
2✔
85
            self.list_index = 0;
×
86
        }
×
87
    }
2✔
88

89
    /// ### calc_max_step_ahead
90
    ///
91
    /// Calculate the max step ahead to scroll list
92
    #[must_use]
93
    pub fn calc_max_step_ahead(&self, max: usize) -> usize {
2✔
94
        let remaining: usize = match self.list_len {
2✔
95
            0 => 0,
×
96
            len => len - 1 - self.list_index,
2✔
97
        };
98
        if remaining > max {
2✔
99
            max
1✔
100
        } else {
101
            remaining
1✔
102
        }
103
    }
2✔
104

105
    /// ### calc_max_step_ahead
106
    ///
107
    /// Calculate the max step ahead to scroll list
108
    #[must_use]
109
    pub fn calc_max_step_behind(&self, max: usize) -> usize {
2✔
110
        if self.list_index > max {
2✔
111
            max
1✔
112
        } else {
113
            self.list_index
1✔
114
        }
115
    }
2✔
116
}
117

118
// -- Component
119

120
/// ## Table
121
///
122
/// represents a read-only text component without any container.
123
#[derive(Default)]
124
#[must_use]
125
pub struct Table {
126
    props: Props,
127
    pub states: TableStates,
128
}
129

130
impl Table {
131
    pub fn foreground(mut self, fg: Color) -> Self {
3✔
132
        self.attr(Attribute::Foreground, AttrValue::Color(fg));
3✔
133
        self
3✔
134
    }
3✔
135

136
    pub fn background(mut self, bg: Color) -> Self {
3✔
137
        self.attr(Attribute::Background, AttrValue::Color(bg));
3✔
138
        self
3✔
139
    }
3✔
140

141
    pub fn inactive(mut self, s: Style) -> Self {
×
142
        self.attr(Attribute::FocusStyle, AttrValue::Style(s));
×
143
        self
×
144
    }
×
145

146
    pub fn modifiers(mut self, m: TextModifiers) -> Self {
3✔
147
        self.attr(Attribute::TextProps, AttrValue::TextModifiers(m));
3✔
148
        self
3✔
149
    }
3✔
150

151
    pub fn borders(mut self, b: Borders) -> Self {
3✔
152
        self.attr(Attribute::Borders, AttrValue::Borders(b));
3✔
153
        self
3✔
154
    }
3✔
155

156
    pub fn title<S: Into<String>>(mut self, t: S, a: Alignment) -> Self {
3✔
157
        self.attr(Attribute::Title, AttrValue::Title((t.into(), a)));
3✔
158
        self
3✔
159
    }
3✔
160

161
    pub fn step(mut self, step: usize) -> Self {
1✔
162
        self.attr(Attribute::ScrollStep, AttrValue::Length(step));
1✔
163
        self
1✔
164
    }
1✔
165

166
    pub fn scroll(mut self, scrollable: bool) -> Self {
2✔
167
        self.attr(Attribute::Scroll, AttrValue::Flag(scrollable));
2✔
168
        self
2✔
169
    }
2✔
170

171
    pub fn highlighted_str<S: Into<String>>(mut self, s: S) -> Self {
3✔
172
        self.attr(Attribute::HighlightedStr, AttrValue::String(s.into()));
3✔
173
        self
3✔
174
    }
3✔
175

176
    pub fn highlighted_color(mut self, c: Color) -> Self {
3✔
177
        self.attr(Attribute::HighlightedColor, AttrValue::Color(c));
3✔
178
        self
3✔
179
    }
3✔
180

181
    pub fn column_spacing(mut self, w: u16) -> Self {
2✔
182
        self.attr(Attribute::Custom(TABLE_COLUMN_SPACING), AttrValue::Size(w));
2✔
183
        self
2✔
184
    }
2✔
185

186
    pub fn row_height(mut self, h: u16) -> Self {
2✔
187
        self.attr(Attribute::Height, AttrValue::Size(h));
2✔
188
        self
2✔
189
    }
2✔
190

191
    pub fn widths(mut self, w: &[u16]) -> Self {
2✔
192
        self.attr(
2✔
193
            Attribute::Width,
2✔
194
            AttrValue::Payload(PropPayload::Vec(
195
                w.iter().map(|x| PropValue::U16(*x)).collect(),
7✔
196
            )),
197
        );
198
        self
2✔
199
    }
2✔
200

201
    pub fn headers<S: AsRef<str>>(mut self, headers: &[S]) -> Self {
2✔
202
        self.attr(
2✔
203
            Attribute::Text,
2✔
204
            AttrValue::Payload(PropPayload::Vec(
205
                headers
2✔
206
                    .iter()
2✔
207
                    .map(|x| PropValue::Str(x.as_ref().to_string()))
7✔
208
                    .collect(),
2✔
209
            )),
210
        );
211
        self
2✔
212
    }
2✔
213

214
    pub fn table(mut self, t: PropTable) -> Self {
4✔
215
        self.attr(Attribute::Content, AttrValue::Table(t));
4✔
216
        self
4✔
217
    }
4✔
218

219
    pub fn rewind(mut self, r: bool) -> Self {
×
220
        self.attr(Attribute::Rewind, AttrValue::Flag(r));
×
221
        self
×
222
    }
×
223

224
    /// Set initial selected line
225
    /// This method must be called after `rows` and `scrollable` in order to work
226
    pub fn selected_line(mut self, line: usize) -> Self {
1✔
227
        self.attr(
1✔
228
            Attribute::Value,
1✔
229
            AttrValue::Payload(PropPayload::One(PropValue::Usize(line))),
1✔
230
        );
231
        self
1✔
232
    }
1✔
233

234
    /// ### scrollable
235
    ///
236
    /// returns the value of the scrollable flag; by default is false
237
    fn is_scrollable(&self) -> bool {
12✔
238
        self.props
12✔
239
            .get_or(Attribute::Scroll, AttrValue::Flag(false))
12✔
240
            .unwrap_flag()
12✔
241
    }
12✔
242

243
    fn rewindable(&self) -> bool {
2✔
244
        self.props
2✔
245
            .get_or(Attribute::Rewind, AttrValue::Flag(false))
2✔
246
            .unwrap_flag()
2✔
247
    }
2✔
248

249
    /// ### layout
250
    ///
251
    /// Returns layout based on properties.
252
    /// If layout is not set in properties, they'll be divided by rows number
253
    fn layout(&self) -> Vec<Constraint> {
2✔
254
        if let Some(PropPayload::Vec(widths)) =
1✔
255
            self.props.get(Attribute::Width).map(|x| x.unwrap_payload())
2✔
256
        {
257
            widths
1✔
258
                .iter()
1✔
259
                .cloned()
1✔
260
                .map(|x| x.unwrap_u16())
4✔
261
                .map(Constraint::Percentage)
1✔
262
                .collect()
1✔
263
        } else {
264
            // Get amount of columns (maximum len of row elements)
265
            let columns: usize = match self.props.get(Attribute::Content).map(|x| x.unwrap_table())
1✔
266
            {
267
                Some(rows) => rows.iter().map(|col| col.len()).max().unwrap_or(1),
1✔
NEW
268
                _ => 1,
×
269
            };
270
            // Calc width in equal way, make sure not to divide by zero (this can happen when rows is [[]])
271
            let width: u16 = (100 / max(columns, 1)) as u16;
1✔
272
            (0..columns)
1✔
273
                .map(|_| Constraint::Percentage(width))
1✔
274
                .collect()
1✔
275
        }
276
    }
2✔
277

278
    /// Generate [`Row`]s from a 2d vector of [`TextSpan`](tuirealm::props::TextSpan)s in props [`Attribute::Content`].
NEW
279
    fn make_rows(&self, row_height: u16) -> Vec<Row> {
×
NEW
280
        let Some(table) = self
×
NEW
281
            .props
×
NEW
282
            .get_ref(Attribute::Content)
×
NEW
283
            .and_then(|x| x.as_table())
×
284
        else {
NEW
285
            return Vec::new();
×
286
        };
287

NEW
288
        table
×
NEW
289
            .iter()
×
NEW
290
            .map(|row| {
×
NEW
291
                let columns: Vec<Cell> = row
×
NEW
292
                    .iter()
×
NEW
293
                    .map(|col| {
×
NEW
294
                        let (fg, bg, modifiers) =
×
NEW
295
                            crate::utils::use_or_default_styles(&self.props, col);
×
NEW
296
                        Cell::from(Span::styled(
×
NEW
297
                            &col.content,
×
NEW
298
                            Style::default().add_modifier(modifiers).fg(fg).bg(bg),
×
299
                        ))
NEW
300
                    })
×
NEW
301
                    .collect();
×
NEW
302
                Row::new(columns).height(row_height)
×
NEW
303
            })
×
NEW
304
            .collect() // Make List item from TextSpan
×
NEW
305
    }
×
306
}
307

308
impl MockComponent for Table {
309
    fn view(&mut self, render: &mut Frame, area: Rect) {
×
310
        if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) {
×
311
            let foreground = self
×
312
                .props
×
313
                .get_or(Attribute::Foreground, AttrValue::Color(Color::Reset))
×
314
                .unwrap_color();
×
315
            let background = self
×
316
                .props
×
317
                .get_or(Attribute::Background, AttrValue::Color(Color::Reset))
×
318
                .unwrap_color();
×
319
            let modifiers = self
×
320
                .props
×
321
                .get_or(
×
322
                    Attribute::TextProps,
×
323
                    AttrValue::TextModifiers(TextModifiers::empty()),
×
324
                )
325
                .unwrap_text_modifiers();
×
326
            let title = crate::utils::get_title_or_center(&self.props);
×
327
            let borders = self
×
328
                .props
×
329
                .get_or(Attribute::Borders, AttrValue::Borders(Borders::default()))
×
330
                .unwrap_borders();
×
331
            let focus = self
×
332
                .props
×
333
                .get_or(Attribute::Focus, AttrValue::Flag(false))
×
334
                .unwrap_flag();
×
335
            let inactive_style = self
×
336
                .props
×
337
                .get(Attribute::FocusStyle)
×
338
                .map(|x| x.unwrap_style());
×
339
            let row_height = self
×
340
                .props
×
341
                .get_or(Attribute::Height, AttrValue::Size(1))
×
342
                .unwrap_size();
×
343
            // Make rows
NEW
344
            let rows: Vec<Row> = self.make_rows(row_height);
×
345
            let highlighted_color = self
×
346
                .props
×
347
                .get(Attribute::HighlightedColor)
×
348
                .map(|x| x.unwrap_color());
×
349
            let widths: Vec<Constraint> = self.layout();
×
350

351
            let mut table = TuiTable::new(rows, &widths).block(crate::utils::get_block(
×
352
                borders,
×
353
                Some(&title),
×
354
                focus,
×
355
                inactive_style,
×
356
            ));
357
            if let Some(highlighted_color) = highlighted_color {
×
358
                table =
×
359
                    table.row_highlight_style(Style::default().fg(highlighted_color).add_modifier(
×
NEW
360
                        if focus {
×
NEW
361
                            modifiers | TextModifiers::REVERSED
×
362
                        } else {
NEW
363
                            modifiers
×
364
                        },
365
                    ));
366
            }
×
367
            // Highlighted symbol
368
            let hg_str = self
×
369
                .props
×
370
                .get_ref(Attribute::HighlightedStr)
×
371
                .and_then(|x| x.as_string());
×
372
            if let Some(hg_str) = hg_str {
×
373
                table = table.highlight_symbol(hg_str.as_str());
×
374
            }
×
375
            // Col spacing
376
            if let Some(spacing) = self
×
377
                .props
×
378
                .get(Attribute::Custom(TABLE_COLUMN_SPACING))
×
379
                .map(|x| x.unwrap_size())
×
380
            {
×
381
                table = table.column_spacing(spacing);
×
382
            }
×
383
            // Header
384
            let headers: Vec<&str> = self
×
385
                .props
×
386
                .get_ref(Attribute::Text)
×
387
                .and_then(|v| v.as_payload())
×
388
                .and_then(|v| v.as_vec())
×
389
                .map(|v| {
×
390
                    v.iter()
×
NEW
391
                        .filter_map(|v| v.as_str().map(|v| v.as_str()))
×
392
                        .collect()
×
393
                })
×
394
                .unwrap_or_default();
×
395
            if !headers.is_empty() {
×
396
                table = table.header(
×
397
                    Row::new(headers)
×
398
                        .style(
×
399
                            Style::default()
×
400
                                .fg(foreground)
×
401
                                .bg(background)
×
402
                                .add_modifier(modifiers),
×
403
                        )
×
404
                        .height(row_height),
×
405
                );
×
406
            }
×
407
            if self.is_scrollable() {
×
408
                let mut state: TableState = TableState::default();
×
409
                state.select(Some(self.states.list_index));
×
410
                render.render_stateful_widget(table, area, &mut state);
×
411
            } else {
×
412
                render.render_widget(table, area);
×
413
            }
×
414
        }
×
415
    }
×
416

417
    fn query(&self, attr: Attribute) -> Option<AttrValue> {
×
418
        self.props.get(attr)
×
419
    }
×
420

421
    fn attr(&mut self, attr: Attribute, value: AttrValue) {
39✔
422
        self.props.set(attr, value);
39✔
423
        if matches!(attr, Attribute::Content) {
39✔
424
            // Update list len and fix index
425
            self.states.set_list_len(
5✔
426
                match self.props.get(Attribute::Content).map(|x| x.unwrap_table()) {
5✔
427
                    Some(spans) => spans.len(),
5✔
428
                    _ => 0,
×
429
                },
430
            );
431
            self.states.fix_list_index();
5✔
432
        } else if matches!(attr, Attribute::Value) && self.is_scrollable() {
34✔
433
            self.states.list_index = self
2✔
434
                .props
2✔
435
                .get(Attribute::Value)
2✔
436
                .map_or(0, |x| x.unwrap_payload().unwrap_one().unwrap_usize());
2✔
437
            self.states.fix_list_index();
2✔
438
        }
32✔
439
    }
39✔
440

441
    fn state(&self) -> State {
10✔
442
        if self.is_scrollable() {
10✔
443
            State::One(StateValue::Usize(self.states.list_index))
9✔
444
        } else {
445
            State::None
1✔
446
        }
447
    }
10✔
448

449
    fn perform(&mut self, cmd: Cmd) -> CmdResult {
8✔
450
        match cmd {
2✔
451
            Cmd::Move(Direction::Down) => {
452
                let prev = self.states.list_index;
1✔
453
                self.states.incr_list_index(self.rewindable());
1✔
454
                if prev == self.states.list_index {
1✔
UNCOV
455
                    CmdResult::None
×
456
                } else {
457
                    CmdResult::Changed(self.state())
1✔
458
                }
459
            }
460
            Cmd::Move(Direction::Up) => {
461
                let prev = self.states.list_index;
1✔
462
                self.states.decr_list_index(self.rewindable());
1✔
463
                if prev == self.states.list_index {
1✔
UNCOV
464
                    CmdResult::None
×
465
                } else {
466
                    CmdResult::Changed(self.state())
1✔
467
                }
468
            }
469
            Cmd::Scroll(Direction::Down) => {
470
                let prev = self.states.list_index;
2✔
471
                let step = self
2✔
472
                    .props
2✔
473
                    .get_or(Attribute::ScrollStep, AttrValue::Length(8))
2✔
474
                    .unwrap_length();
2✔
475
                let step: usize = self.states.calc_max_step_ahead(step);
2✔
476
                (0..step).for_each(|_| self.states.incr_list_index(false));
5✔
477
                if prev == self.states.list_index {
2✔
UNCOV
478
                    CmdResult::None
×
479
                } else {
480
                    CmdResult::Changed(self.state())
2✔
481
                }
482
            }
483
            Cmd::Scroll(Direction::Up) => {
484
                let prev = self.states.list_index;
2✔
485
                let step = self
2✔
486
                    .props
2✔
487
                    .get_or(Attribute::ScrollStep, AttrValue::Length(8))
2✔
488
                    .unwrap_length();
2✔
489
                let step: usize = self.states.calc_max_step_behind(step);
2✔
490
                (0..step).for_each(|_| self.states.decr_list_index(false));
6✔
491
                if prev == self.states.list_index {
2✔
UNCOV
492
                    CmdResult::None
×
493
                } else {
494
                    CmdResult::Changed(self.state())
2✔
495
                }
496
            }
497
            Cmd::GoTo(Position::Begin) => {
498
                let prev = self.states.list_index;
1✔
499
                self.states.list_index_at_first();
1✔
500
                if prev == self.states.list_index {
1✔
UNCOV
501
                    CmdResult::None
×
502
                } else {
503
                    CmdResult::Changed(self.state())
1✔
504
                }
505
            }
506
            Cmd::GoTo(Position::End) => {
507
                let prev = self.states.list_index;
1✔
508
                self.states.list_index_at_last();
1✔
509
                if prev == self.states.list_index {
1✔
UNCOV
510
                    CmdResult::None
×
511
                } else {
512
                    CmdResult::Changed(self.state())
1✔
513
                }
514
            }
515
            _ => CmdResult::None,
×
516
        }
517
    }
8✔
518
}
519

520
#[cfg(test)]
521
mod tests {
522

523
    use super::*;
524
    use pretty_assertions::assert_eq;
525
    use tuirealm::props::{TableBuilder, TextSpan};
526

527
    #[test]
528
    fn table_states() {
1✔
529
        let mut states = TableStates::default();
1✔
530
        assert_eq!(states.list_index, 0);
1✔
531
        assert_eq!(states.list_len, 0);
1✔
532
        states.set_list_len(5);
1✔
533
        assert_eq!(states.list_index, 0);
1✔
534
        assert_eq!(states.list_len, 5);
1✔
535
        // Incr
536
        states.incr_list_index(true);
1✔
537
        assert_eq!(states.list_index, 1);
1✔
538
        states.list_index = 4;
1✔
539
        states.incr_list_index(false);
1✔
540
        assert_eq!(states.list_index, 4);
1✔
541
        states.incr_list_index(true);
1✔
542
        assert_eq!(states.list_index, 0);
1✔
543
        // Decr
544
        states.decr_list_index(false);
1✔
545
        assert_eq!(states.list_index, 0);
1✔
546
        states.decr_list_index(true);
1✔
547
        assert_eq!(states.list_index, 4);
1✔
548
        states.decr_list_index(true);
1✔
549
        assert_eq!(states.list_index, 3);
1✔
550
        // Begin
551
        states.list_index_at_first();
1✔
552
        assert_eq!(states.list_index, 0);
1✔
553
        states.list_index_at_last();
1✔
554
        assert_eq!(states.list_index, 4);
1✔
555
        // Fix
556
        states.set_list_len(3);
1✔
557
        states.fix_list_index();
1✔
558
        assert_eq!(states.list_index, 2);
1✔
559
    }
1✔
560

561
    #[test]
562
    fn test_component_table_scrolling() {
1✔
563
        // Make component
564
        let mut component = Table::default()
1✔
565
            .foreground(Color::Red)
1✔
566
            .background(Color::Blue)
1✔
567
            .highlighted_color(Color::Yellow)
1✔
568
            .highlighted_str("🚀")
1✔
569
            .modifiers(TextModifiers::BOLD)
1✔
570
            .scroll(true)
1✔
571
            .step(4)
1✔
572
            .borders(Borders::default())
1✔
573
            .title("events", Alignment::Center)
1✔
574
            .column_spacing(4)
1✔
575
            .widths(&[25, 25, 25, 25])
1✔
576
            .row_height(3)
1✔
577
            .headers(&["Event", "Message", "Behaviour", "???"])
1✔
578
            .table(
1✔
579
                TableBuilder::default()
1✔
580
                    .add_col(TextSpan::from("KeyCode::Down"))
1✔
581
                    .add_col(TextSpan::from("OnKey"))
1✔
582
                    .add_col(TextSpan::from("Move cursor down"))
1✔
583
                    .add_row()
1✔
584
                    .add_col(TextSpan::from("KeyCode::Up"))
1✔
585
                    .add_col(TextSpan::from("OnKey"))
1✔
586
                    .add_col(TextSpan::from("Move cursor up"))
1✔
587
                    .add_row()
1✔
588
                    .add_col(TextSpan::from("KeyCode::PageDown"))
1✔
589
                    .add_col(TextSpan::from("OnKey"))
1✔
590
                    .add_col(TextSpan::from("Move cursor down by 8"))
1✔
591
                    .add_row()
1✔
592
                    .add_col(TextSpan::from("KeyCode::PageUp"))
1✔
593
                    .add_col(TextSpan::from("OnKey"))
1✔
594
                    .add_col(TextSpan::from("ove cursor up by 8"))
1✔
595
                    .add_row()
1✔
596
                    .add_col(TextSpan::from("KeyCode::End"))
1✔
597
                    .add_col(TextSpan::from("OnKey"))
1✔
598
                    .add_col(TextSpan::from("Move cursor to last item"))
1✔
599
                    .add_row()
1✔
600
                    .add_col(TextSpan::from("KeyCode::Home"))
1✔
601
                    .add_col(TextSpan::from("OnKey"))
1✔
602
                    .add_col(TextSpan::from("Move cursor to first item"))
1✔
603
                    .add_row()
1✔
604
                    .add_col(TextSpan::from("KeyCode::Char(_)"))
1✔
605
                    .add_col(TextSpan::from("OnKey"))
1✔
606
                    .add_col(TextSpan::from("Return pressed key"))
1✔
607
                    .add_col(TextSpan::from("4th mysterious columns"))
1✔
608
                    .build(),
1✔
609
            );
610
        assert_eq!(component.states.list_len, 7);
1✔
611
        assert_eq!(component.states.list_index, 0);
1✔
612
        // Own funcs
613
        assert_eq!(component.layout().len(), 4);
1✔
614
        // Increment list index
615
        component.states.list_index += 1;
1✔
616
        assert_eq!(component.states.list_index, 1);
1✔
617
        // Check messages
618
        // Handle inputs
619
        assert_eq!(
1✔
620
            component.perform(Cmd::Move(Direction::Down)),
1✔
621
            CmdResult::Changed(State::One(StateValue::Usize(2)))
622
        );
623
        // Index should be incremented
624
        assert_eq!(component.states.list_index, 2);
1✔
625
        // Index should be decremented
626
        assert_eq!(
1✔
627
            component.perform(Cmd::Move(Direction::Up)),
1✔
628
            CmdResult::Changed(State::One(StateValue::Usize(1)))
629
        );
630
        // Index should be incremented
631
        assert_eq!(component.states.list_index, 1);
1✔
632
        // Index should be 2
633
        assert_eq!(
1✔
634
            component.perform(Cmd::Scroll(Direction::Down)),
1✔
635
            CmdResult::Changed(State::One(StateValue::Usize(5)))
636
        );
637
        // Index should be incremented
638
        assert_eq!(component.states.list_index, 5);
1✔
639
        assert_eq!(
1✔
640
            component.perform(Cmd::Scroll(Direction::Down)),
1✔
641
            CmdResult::Changed(State::One(StateValue::Usize(6)))
642
        );
643
        // Index should be incremented
644
        assert_eq!(component.states.list_index, 6);
1✔
645
        // Index should be 0
646
        assert_eq!(
1✔
647
            component.perform(Cmd::Scroll(Direction::Up)),
1✔
648
            CmdResult::Changed(State::One(StateValue::Usize(2)))
649
        );
650
        assert_eq!(component.states.list_index, 2);
1✔
651
        assert_eq!(
1✔
652
            component.perform(Cmd::Scroll(Direction::Up)),
1✔
653
            CmdResult::Changed(State::One(StateValue::Usize(0)))
654
        );
655
        assert_eq!(component.states.list_index, 0);
1✔
656
        // End
657
        assert_eq!(
1✔
658
            component.perform(Cmd::GoTo(Position::End)),
1✔
659
            CmdResult::Changed(State::One(StateValue::Usize(6)))
660
        );
661
        assert_eq!(component.states.list_index, 6);
1✔
662
        // Home
663
        assert_eq!(
1✔
664
            component.perform(Cmd::GoTo(Position::Begin)),
1✔
665
            CmdResult::Changed(State::One(StateValue::Usize(0)))
666
        );
667
        assert_eq!(component.states.list_index, 0);
1✔
668
        // Update
669
        component.attr(
1✔
670
            Attribute::Content,
1✔
671
            AttrValue::Table(
1✔
672
                TableBuilder::default()
1✔
673
                    .add_col(TextSpan::from("name"))
1✔
674
                    .add_col(TextSpan::from("age"))
1✔
675
                    .add_col(TextSpan::from("birthdate"))
1✔
676
                    .build(),
1✔
677
            ),
1✔
678
        );
679
        assert_eq!(component.states.list_len, 1);
1✔
680
        assert_eq!(component.states.list_index, 0);
1✔
681
        // Get value
682
        assert_eq!(component.state(), State::One(StateValue::Usize(0)));
1✔
683
    }
1✔
684

685
    #[test]
686
    fn test_component_table_with_empty_rows_and_no_width_set() {
1✔
687
        // Make component
688
        let component = Table::default().table(TableBuilder::default().build());
1✔
689

690
        assert_eq!(component.states.list_len, 1);
1✔
691
        assert_eq!(component.states.list_index, 0);
1✔
692
        // calculating layout would fail if no widths and using "empty" TableBuilder
693
        assert_eq!(component.layout().len(), 0);
1✔
694
    }
1✔
695

696
    #[test]
697
    fn test_components_table() {
1✔
698
        // Make component
699
        let component = Table::default()
1✔
700
            .foreground(Color::Red)
1✔
701
            .background(Color::Blue)
1✔
702
            .highlighted_color(Color::Yellow)
1✔
703
            .highlighted_str("🚀")
1✔
704
            .modifiers(TextModifiers::BOLD)
1✔
705
            .borders(Borders::default())
1✔
706
            .title("events", Alignment::Center)
1✔
707
            .column_spacing(4)
1✔
708
            .widths(&[33, 33, 33])
1✔
709
            .row_height(3)
1✔
710
            .headers(&["Event", "Message", "Behaviour"])
1✔
711
            .table(
1✔
712
                TableBuilder::default()
1✔
713
                    .add_col(TextSpan::from("KeyCode::Down"))
1✔
714
                    .add_col(TextSpan::from("OnKey"))
1✔
715
                    .add_col(TextSpan::from("Move cursor down"))
1✔
716
                    .add_row()
1✔
717
                    .add_col(TextSpan::from("KeyCode::Up"))
1✔
718
                    .add_col(TextSpan::from("OnKey"))
1✔
719
                    .add_col(TextSpan::from("Move cursor up"))
1✔
720
                    .add_row()
1✔
721
                    .add_col(TextSpan::from("KeyCode::PageDown"))
1✔
722
                    .add_col(TextSpan::from("OnKey"))
1✔
723
                    .add_col(TextSpan::from("Move cursor down by 8"))
1✔
724
                    .add_row()
1✔
725
                    .add_col(TextSpan::from("KeyCode::PageUp"))
1✔
726
                    .add_col(TextSpan::from("OnKey"))
1✔
727
                    .add_col(TextSpan::from("ove cursor up by 8"))
1✔
728
                    .add_row()
1✔
729
                    .add_col(TextSpan::from("KeyCode::End"))
1✔
730
                    .add_col(TextSpan::from("OnKey"))
1✔
731
                    .add_col(TextSpan::from("Move cursor to last item"))
1✔
732
                    .add_row()
1✔
733
                    .add_col(TextSpan::from("KeyCode::Home"))
1✔
734
                    .add_col(TextSpan::from("OnKey"))
1✔
735
                    .add_col(TextSpan::from("Move cursor to first item"))
1✔
736
                    .add_row()
1✔
737
                    .add_col(TextSpan::from("KeyCode::Char(_)"))
1✔
738
                    .add_col(TextSpan::from("OnKey"))
1✔
739
                    .add_col(TextSpan::from("Return pressed key"))
1✔
740
                    .build(),
1✔
741
            );
742
        // Get value (not scrollable)
743
        assert_eq!(component.state(), State::None);
1✔
744
    }
1✔
745

746
    #[test]
747
    fn should_init_list_value() {
1✔
748
        let mut component = Table::default()
1✔
749
            .foreground(Color::Red)
1✔
750
            .background(Color::Blue)
1✔
751
            .highlighted_color(Color::Yellow)
1✔
752
            .highlighted_str("🚀")
1✔
753
            .modifiers(TextModifiers::BOLD)
1✔
754
            .borders(Borders::default())
1✔
755
            .title("events", Alignment::Center)
1✔
756
            .table(
1✔
757
                TableBuilder::default()
1✔
758
                    .add_col(TextSpan::from("KeyCode::Down"))
1✔
759
                    .add_col(TextSpan::from("OnKey"))
1✔
760
                    .add_col(TextSpan::from("Move cursor down"))
1✔
761
                    .add_row()
1✔
762
                    .add_col(TextSpan::from("KeyCode::Up"))
1✔
763
                    .add_col(TextSpan::from("OnKey"))
1✔
764
                    .add_col(TextSpan::from("Move cursor up"))
1✔
765
                    .add_row()
1✔
766
                    .add_col(TextSpan::from("KeyCode::PageDown"))
1✔
767
                    .add_col(TextSpan::from("OnKey"))
1✔
768
                    .add_col(TextSpan::from("Move cursor down by 8"))
1✔
769
                    .add_row()
1✔
770
                    .add_col(TextSpan::from("KeyCode::PageUp"))
1✔
771
                    .add_col(TextSpan::from("OnKey"))
1✔
772
                    .add_col(TextSpan::from("ove cursor up by 8"))
1✔
773
                    .add_row()
1✔
774
                    .add_col(TextSpan::from("KeyCode::End"))
1✔
775
                    .add_col(TextSpan::from("OnKey"))
1✔
776
                    .add_col(TextSpan::from("Move cursor to last item"))
1✔
777
                    .add_row()
1✔
778
                    .add_col(TextSpan::from("KeyCode::Home"))
1✔
779
                    .add_col(TextSpan::from("OnKey"))
1✔
780
                    .add_col(TextSpan::from("Move cursor to first item"))
1✔
781
                    .add_row()
1✔
782
                    .add_col(TextSpan::from("KeyCode::Char(_)"))
1✔
783
                    .add_col(TextSpan::from("OnKey"))
1✔
784
                    .add_col(TextSpan::from("Return pressed key"))
1✔
785
                    .build(),
1✔
786
            )
787
            .scroll(true)
1✔
788
            .selected_line(2);
1✔
789
        assert_eq!(component.states.list_index, 2);
1✔
790
        // Index out of bounds
791
        component.attr(
1✔
792
            Attribute::Value,
1✔
793
            AttrValue::Payload(PropPayload::One(PropValue::Usize(50))),
1✔
794
        );
795
        assert_eq!(component.states.list_index, 6);
1✔
796
    }
1✔
797
}
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