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

veeso / tui-realm-stdlib / 13283044543

12 Feb 2025 10:16AM UTC coverage: 68.235% (-0.1%) from 68.377%
13283044543

push

github

web-flow
Remove some more clones / allocations (#30)

* style(table): use "row_highlight_style" instead of "highlight_style"

to avoid deprecation warning

* deps(tuirealm): update to 2.1.0

* refactor(components::span::Span::view): use "as_text_span" instead of manual impl

re 913b08075
Also changed behavior to not panic, and instead skip any values that are not "TextSpan"s

* refactor(components::span::Span::view): avoid further clones when getting text

* refactor(components::paragraph::Paragraph::view): avoid clones when getting text

* refactor(components::label::Label::view): avoid clones when getting text

* refactor(components::list::List::view): avoid clones when getting text

* style(components::phantom): fix reference to "Spinner"

* refactor(components::radio::Radio::view): avoid clones when getting choices

* refactor(components::select::Select::view): avoid clones when getting choices

* refactor(components::table::Table::view): avoid clones when getting rows

* refactor(components::table::Table::view): avoid clones when getting headers

also remove "Table::headers" as it is only ever written to and never actually read. (compared to a scoped-variable)

* refactor(components::table::Table::view): avoid clones when getting highlight symbol

also remove "Table::hg_str" as it is only ever written to and never actually read. (compared to a scoped-variable)

* refactor(components::textarea::Textarea::view): avoid clones when getting highlight symbol

also remove "Textarea::hg_str" as it is only ever written to and never actually read. (compared to a scoped-variable)

* refactor(components::textarea::Textarea::view): avoid clones when getting text

0 of 82 new or added lines in 8 files covered. (0.0%)

1 existing line in 1 file now uncovered.

3278 of 4804 relevant lines covered (68.23%)

1.63 hits per line

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

74.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)]
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
}
126

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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