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

veeso / tui-realm-stdlib / 11316405772

13 Oct 2024 05:35PM UTC coverage: 73.26% (-0.2%) from 73.477%
11316405772

push

github

veeso
feat: tuirealm 2.x

0 of 7 new or added lines in 5 files covered. (0.0%)

16 existing lines in 6 files now uncovered.

2726 of 3721 relevant lines covered (73.26%)

1.98 hits per line

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

78.66
/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)]
10✔
23
pub struct TableStates {
24
    pub list_index: usize, // Index of selected item in textarea
5✔
25
    pub list_len: usize,   // Lines in text area
5✔
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 {
2✔
44
            self.list_index = 0;
1✔
45
        }
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 {
2✔
56
            self.list_index = self.list_len - 1;
1✔
57
        }
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
        }
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 {
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)]
8✔
122
pub struct Table {
123
    props: Props,
4✔
124
    pub states: TableStates,
4✔
125
    hg_str: Option<String>, // CRAP CRAP CRAP
4✔
126
    headers: Vec<String>,   // CRAP CRAP CRAP
4✔
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: AsRef<str>>(mut self, t: S, a: Alignment) -> Self {
3✔
156
        self.attr(
3✔
157
            Attribute::Title,
3✔
158
            AttrValue::Title((t.as_ref().to_string(), a)),
3✔
159
        );
160
        self
3✔
161
    }
3✔
162

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

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

173
    pub fn highlighted_str<S: AsRef<str>>(mut self, s: S) -> Self {
3✔
174
        self.attr(
3✔
175
            Attribute::HighlightedStr,
3✔
176
            AttrValue::String(s.as_ref().to_string()),
3✔
177
        );
178
        self
3✔
179
    }
3✔
180

181
    pub fn highlighted_color(mut self, c: Color) -> Self {
3✔
182
        self.attr(Attribute::HighlightedColor, AttrValue::Color(c));
3✔
183
        self
3✔
184
    }
3✔
185

186
    pub fn column_spacing(mut self, w: u16) -> Self {
2✔
187
        self.attr(Attribute::Custom(TABLE_COLUMN_SPACING), AttrValue::Size(w));
2✔
188
        self
2✔
189
    }
2✔
190

191
    pub fn row_height(mut self, h: u16) -> Self {
2✔
192
        self.attr(Attribute::Height, AttrValue::Size(h));
2✔
193
        self
2✔
194
    }
2✔
195

196
    pub fn widths(mut self, w: &[u16]) -> Self {
2✔
197
        self.attr(
2✔
198
            Attribute::Width,
2✔
199
            AttrValue::Payload(PropPayload::Vec(
2✔
200
                w.iter().map(|x| PropValue::U16(*x)).collect(),
9✔
201
            )),
202
        );
203
        self
2✔
204
    }
2✔
205

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

219
    pub fn table(mut self, t: PropTable) -> Self {
4✔
220
        self.attr(Attribute::Content, AttrValue::Table(t));
4✔
221
        self
4✔
222
    }
4✔
223

224
    pub fn rewind(mut self, r: bool) -> Self {
×
225
        self.attr(Attribute::Rewind, AttrValue::Flag(r));
×
226
        self
×
227
    }
×
228

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

239
    /// ### scrollable
240
    ///
241
    /// returns the value of the scrollable flag; by default is false
242
    fn is_scrollable(&self) -> bool {
12✔
243
        self.props
24✔
244
            .get_or(Attribute::Scroll, AttrValue::Flag(false))
12✔
245
            .unwrap_flag()
246
    }
12✔
247

248
    fn rewindable(&self) -> bool {
2✔
249
        self.props
4✔
250
            .get_or(Attribute::Rewind, AttrValue::Flag(false))
2✔
251
            .unwrap_flag()
252
    }
2✔
253

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

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

UNCOV
352
            let mut table = TuiTable::new(rows, &widths).block(crate::utils::get_block(
×
353
                borders,
354
                Some(title),
×
355
                focus,
356
                inactive_style,
357
            ));
358
            if let Some(highlighted_color) = highlighted_color {
×
359
                table = table.highlight_style(Style::default().fg(highlighted_color).add_modifier(
×
360
                    match focus {
×
361
                        true => modifiers | TextModifiers::REVERSED,
×
362
                        false => modifiers,
×
363
                    },
364
                ));
365
            }
366
            // Highlighted symbol
367
            self.hg_str = self
×
368
                .props
369
                .get(Attribute::HighlightedStr)
×
370
                .map(|x| x.unwrap_string());
×
371
            if let Some(hg_str) = &self.hg_str {
×
372
                table = table.highlight_symbol(hg_str.as_str());
×
373
            }
374
            // Col spacing
375
            if let Some(spacing) = self
×
376
                .props
377
                .get(Attribute::Custom(TABLE_COLUMN_SPACING))
×
378
                .map(|x| x.unwrap_size())
×
379
            {
380
                table = table.column_spacing(spacing);
×
381
            }
382
            // Header
383
            self.headers = self
×
384
                .props
385
                .get(Attribute::Text)
×
386
                .map(|x| {
×
387
                    x.unwrap_payload()
×
388
                        .unwrap_vec()
389
                        .into_iter()
390
                        .map(|x| x.unwrap_str())
×
391
                        .collect()
392
                })
×
393
                .unwrap_or_default();
394
            if !self.headers.is_empty() {
×
395
                let headers: Vec<&str> = self.headers.iter().map(|x| x.as_str()).collect();
×
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(
10✔
426
                match self.props.get(Attribute::Content).map(|x| x.unwrap_table()) {
10✔
427
                    Some(spans) => spans.len(),
5✔
428
                    _ => 0,
×
429
                },
430
            );
5✔
431
            self.states.fix_list_index();
5✔
432
        } else if matches!(attr, Attribute::Value) && self.is_scrollable() {
34✔
433
            self.states.list_index = self
4✔
434
                .props
435
                .get(Attribute::Value)
2✔
436
                .map(|x| x.unwrap_payload().unwrap_one().unwrap_usize())
2✔
437
                .unwrap_or(0);
438
            self.states.fix_list_index();
2✔
439
        }
440
    }
39✔
441

442
    fn state(&self) -> State {
10✔
443
        match self.is_scrollable() {
10✔
444
            true => State::One(StateValue::Usize(self.states.list_index)),
9✔
445
            false => State::None,
1✔
446
        }
447
    }
10✔
448

449
    fn perform(&mut self, cmd: Cmd) -> CmdResult {
8✔
450
        match cmd {
8✔
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✔
455
                    CmdResult::Changed(self.state())
1✔
456
                } else {
457
                    CmdResult::None
×
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✔
464
                    CmdResult::Changed(self.state())
1✔
465
                } else {
466
                    CmdResult::None
×
467
                }
468
            }
469
            Cmd::Scroll(Direction::Down) => {
470
                let prev = self.states.list_index;
2✔
471
                let step = self
4✔
472
                    .props
473
                    .get_or(Attribute::ScrollStep, AttrValue::Length(8))
2✔
474
                    .unwrap_length();
475
                let step: usize = self.states.calc_max_step_ahead(step);
2✔
476
                (0..step).for_each(|_| self.states.incr_list_index(false));
7✔
477
                if prev != self.states.list_index {
2✔
478
                    CmdResult::Changed(self.state())
2✔
479
                } else {
480
                    CmdResult::None
×
481
                }
482
            }
483
            Cmd::Scroll(Direction::Up) => {
484
                let prev = self.states.list_index;
2✔
485
                let step = self
4✔
486
                    .props
487
                    .get_or(Attribute::ScrollStep, AttrValue::Length(8))
2✔
488
                    .unwrap_length();
489
                let step: usize = self.states.calc_max_step_behind(step);
2✔
490
                (0..step).for_each(|_| self.states.decr_list_index(false));
8✔
491
                if prev != self.states.list_index {
2✔
492
                    CmdResult::Changed(self.state())
2✔
493
                } else {
494
                    CmdResult::None
×
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✔
501
                    CmdResult::Changed(self.state())
1✔
502
                } else {
503
                    CmdResult::None
×
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✔
510
                    CmdResult::Changed(self.state())
1✔
511
                } else {
512
                    CmdResult::None
×
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() {
2✔
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
    }
2✔
560

561
    #[test]
562
    fn test_component_table_scrolling() {
2✔
563
        // Make component
564
        let mut component = Table::default()
7✔
565
            .foreground(Color::Red)
1✔
566
            .background(Color::Blue)
1✔
567
            .highlighted_color(Color::Yellow)
1✔
568
            .highlighted_str("🚀")
569
            .modifiers(TextModifiers::BOLD)
570
            .scroll(true)
571
            .step(4)
572
            .borders(Borders::default())
1✔
573
            .title("events", Alignment::Center)
1✔
574
            .column_spacing(4)
575
            .widths(&[25, 25, 25, 25])
576
            .row_height(3)
577
            .headers(&["Event", "Message", "Behaviour", "???"])
578
            .table(
579
                TableBuilder::default()
23✔
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()
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()
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()
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()
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()
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()
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(),
609
            );
1✔
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()
4✔
673
                    .add_col(TextSpan::from("name"))
1✔
674
                    .add_col(TextSpan::from("age"))
1✔
675
                    .add_col(TextSpan::from("birthdate"))
1✔
676
                    .build(),
677
            ),
678
        );
1✔
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
    }
2✔
684

685
    #[test]
686
    fn test_component_table_with_empty_rows_and_no_width_set() {
2✔
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
    }
2✔
695

696
    #[test]
697
    fn test_components_table() {
2✔
698
        // Make component
699
        let component = Table::default()
7✔
700
            .foreground(Color::Red)
1✔
701
            .background(Color::Blue)
1✔
702
            .highlighted_color(Color::Yellow)
1✔
703
            .highlighted_str("🚀")
704
            .modifiers(TextModifiers::BOLD)
705
            .borders(Borders::default())
1✔
706
            .title("events", Alignment::Center)
1✔
707
            .column_spacing(4)
708
            .widths(&[33, 33, 33])
709
            .row_height(3)
710
            .headers(&["Event", "Message", "Behaviour"])
711
            .table(
712
                TableBuilder::default()
22✔
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()
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()
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()
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()
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()
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()
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(),
741
            );
1✔
742
        // Get value (not scrollable)
743
        assert_eq!(component.state(), State::None);
1✔
744
    }
2✔
745

746
    #[test]
747
    fn should_init_list_value() {
2✔
748
        let mut component = Table::default()
7✔
749
            .foreground(Color::Red)
1✔
750
            .background(Color::Blue)
1✔
751
            .highlighted_color(Color::Yellow)
1✔
752
            .highlighted_str("🚀")
753
            .modifiers(TextModifiers::BOLD)
754
            .borders(Borders::default())
1✔
755
            .title("events", Alignment::Center)
1✔
756
            .table(
757
                TableBuilder::default()
22✔
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()
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()
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()
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()
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()
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()
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(),
786
            )
787
            .scroll(true)
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
    }
2✔
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