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

veeso / tui-realm-stdlib / 13283025409

12 Feb 2025 10:15AM UTC coverage: 68.369% (-4.7%) from 73.043%
13283025409

push

github

web-flow
Fix coverage tui (stdlib) (#29)

* chore(workflows/coverage): replace "actions-rs/toolchain" with "dtolnay/rust-toolchain"

* chore(workflows/ratatui): remove unknown option "override"

* chore(workflows/coverage): update "coverallsapp/github-action" to 2.x

* chore(workflows/coverage): replace coverage generation with "cargo-llvm-cov"

3279 of 4796 relevant lines covered (68.37%)

1.64 hits per line

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

75.04
/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
9✔
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
10✔
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
    pub fn calc_max_step_ahead(&self, max: usize) -> usize {
2✔
93
        let remaining: usize = match self.list_len {
2✔
94
            0 => 0,
×
95
            len => len - 1 - self.list_index,
2✔
96
        };
97
        if remaining > max {
2✔
98
            max
1✔
99
        } else {
100
            remaining
1✔
101
        }
102
    }
2✔
103

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

116
// -- Component
117

118
/// ## Table
119
///
120
/// represents a read-only text component without any container.
121
#[derive(Default)]
122
pub struct Table {
123
    props: Props,
124
    pub states: TableStates,
125
    hg_str: Option<String>, // CRAP CRAP CRAP
126
    headers: Vec<String>,   // CRAP CRAP CRAP
127
}
128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

277
impl MockComponent for Table {
278
    fn view(&mut self, render: &mut Frame, area: Rect) {
×
279
        if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) {
×
280
            let foreground = self
×
281
                .props
×
282
                .get_or(Attribute::Foreground, AttrValue::Color(Color::Reset))
×
283
                .unwrap_color();
×
284
            let background = self
×
285
                .props
×
286
                .get_or(Attribute::Background, AttrValue::Color(Color::Reset))
×
287
                .unwrap_color();
×
288
            let modifiers = self
×
289
                .props
×
290
                .get_or(
×
291
                    Attribute::TextProps,
×
292
                    AttrValue::TextModifiers(TextModifiers::empty()),
×
293
                )
×
294
                .unwrap_text_modifiers();
×
295
            let title = self
×
296
                .props
×
297
                .get_or(
×
298
                    Attribute::Title,
×
299
                    AttrValue::Title((String::default(), Alignment::Center)),
×
300
                )
×
301
                .unwrap_title();
×
302
            let borders = self
×
303
                .props
×
304
                .get_or(Attribute::Borders, AttrValue::Borders(Borders::default()))
×
305
                .unwrap_borders();
×
306
            let focus = self
×
307
                .props
×
308
                .get_or(Attribute::Focus, AttrValue::Flag(false))
×
309
                .unwrap_flag();
×
310
            let inactive_style = self
×
311
                .props
×
312
                .get(Attribute::FocusStyle)
×
313
                .map(|x| x.unwrap_style());
×
314
            let row_height = self
×
315
                .props
×
316
                .get_or(Attribute::Height, AttrValue::Size(1))
×
317
                .unwrap_size();
×
318
            // Make rows
319
            let rows: Vec<Row> = match self.props.get(Attribute::Content).map(|x| x.unwrap_table())
×
320
            {
321
                Some(table) => table
×
322
                    .iter()
×
323
                    .map(|row| {
×
324
                        let columns: Vec<Cell> = row
×
325
                            .iter()
×
326
                            .map(|col| {
×
327
                                let (fg, bg, modifiers) =
×
328
                                    crate::utils::use_or_default_styles(&self.props, col);
×
329
                                Cell::from(Span::styled(
×
330
                                    col.content.clone(),
×
331
                                    Style::default().add_modifier(modifiers).fg(fg).bg(bg),
×
332
                                ))
×
333
                            })
×
334
                            .collect();
×
335
                        Row::new(columns).height(row_height)
×
336
                    })
×
337
                    .collect(), // Make List item from TextSpan
×
338
                _ => Vec::new(),
×
339
            };
340
            let highlighted_color = self
×
341
                .props
×
342
                .get(Attribute::HighlightedColor)
×
343
                .map(|x| x.unwrap_color());
×
344
            let widths: Vec<Constraint> = self.layout();
×
345

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

411
    fn query(&self, attr: Attribute) -> Option<AttrValue> {
×
412
        self.props.get(attr)
×
413
    }
×
414

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

436
    fn state(&self) -> State {
10✔
437
        match self.is_scrollable() {
10✔
438
            true => State::One(StateValue::Usize(self.states.list_index)),
9✔
439
            false => State::None,
1✔
440
        }
441
    }
10✔
442

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

514
#[cfg(test)]
515
mod tests {
516

517
    use super::*;
518
    use pretty_assertions::assert_eq;
519
    use tuirealm::props::{TableBuilder, TextSpan};
520

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

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

679
    #[test]
680
    fn test_component_table_with_empty_rows_and_no_width_set() {
1✔
681
        // Make component
1✔
682
        let component = Table::default().table(TableBuilder::default().build());
1✔
683

1✔
684
        assert_eq!(component.states.list_len, 1);
1✔
685
        assert_eq!(component.states.list_index, 0);
1✔
686
        // calculating layout would fail if no widths and using "empty" TableBuilder
687
        assert_eq!(component.layout().len(), 0);
1✔
688
    }
1✔
689

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

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