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

veeso / tui-realm-stdlib / 20461661064

23 Dec 2025 01:12PM UTC coverage: 70.347% (+0.2%) from 70.169%
20461661064

Pull #49

github

web-flow
Merge bdda8b81d into 9528c3045
Pull Request #49: Move `Dataset` over to `Chart` and rename to `ChartDataset`

367 of 428 new or added lines in 8 files covered. (85.75%)

3 existing lines in 2 files now uncovered.

3288 of 4674 relevant lines covered (70.35%)

2.16 hits per line

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

74.37
/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 std::cmp::max;
6

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

19
use super::props::TABLE_COLUMN_SPACING;
20
use crate::utils;
21

22
// -- States
23

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

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

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

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

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

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

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

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

103
    /// ### calc_max_step_ahead
104
    ///
105
    /// Calculate the max step ahead to scroll list
106
    #[must_use]
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
#[must_use]
123
pub struct Table {
124
    props: Props,
125
    pub states: TableStates,
126
}
127

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

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

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

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

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

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

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

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

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

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

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

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

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

199
    pub fn headers<S: Into<String>>(mut self, headers: impl IntoIterator<Item = S>) -> Self {
8✔
200
        self.attr(
8✔
201
            Attribute::Text,
8✔
202
            AttrValue::Payload(PropPayload::Vec(
203
                headers
8✔
204
                    .into_iter()
8✔
205
                    .map(|v| PropValue::Str(v.into()))
13✔
206
                    .collect(),
8✔
207
            )),
208
        );
209
        self
8✔
210
    }
8✔
211

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

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

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

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

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

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

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

286
        table
×
287
            .iter()
×
288
            .map(|row| {
×
289
                let columns: Vec<Cell> = row
×
290
                    .iter()
×
291
                    .map(|col| {
×
NEW
292
                        let line = Line::from(
×
NEW
293
                            col.spans
×
NEW
294
                                .iter()
×
NEW
295
                                .map(utils::borrow_clone_span)
×
NEW
296
                                .collect::<Vec<_>>(),
×
297
                        );
NEW
298
                        Cell::from(line)
×
299
                    })
×
300
                    .collect();
×
301
                Row::new(columns).height(row_height)
×
302
            })
×
303
            .collect() // Make List item from TextSpan
×
304
    }
×
305
}
306

307
impl MockComponent for Table {
308
    fn view(&mut self, render: &mut Frame, area: Rect) {
×
309
        if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) {
×
310
            let foreground = self
×
311
                .props
×
312
                .get_or(Attribute::Foreground, AttrValue::Color(Color::Reset))
×
313
                .unwrap_color();
×
314
            let background = self
×
315
                .props
×
316
                .get_or(Attribute::Background, AttrValue::Color(Color::Reset))
×
317
                .unwrap_color();
×
318
            let modifiers = self
×
319
                .props
×
320
                .get_or(
×
321
                    Attribute::TextProps,
×
322
                    AttrValue::TextModifiers(TextModifiers::empty()),
×
323
                )
324
                .unwrap_text_modifiers();
×
325

326
            let normal_style = Style::default()
×
327
                .fg(foreground)
×
328
                .bg(background)
×
329
                .add_modifier(modifiers);
×
330

331
            let title = crate::utils::get_title_or_center(&self.props);
×
332
            let borders = self
×
333
                .props
×
334
                .get_or(Attribute::Borders, AttrValue::Borders(Borders::default()))
×
335
                .unwrap_borders();
×
336
            let focus = self
×
337
                .props
×
338
                .get_or(Attribute::Focus, AttrValue::Flag(false))
×
339
                .unwrap_flag();
×
340
            let inactive_style = self
×
341
                .props
×
342
                .get(Attribute::FocusStyle)
×
343
                .map(|x| x.unwrap_style());
×
344
            let row_height = self
×
345
                .props
×
346
                .get_or(Attribute::Height, AttrValue::Size(1))
×
347
                .unwrap_size();
×
348
            // Make rows
349
            let rows: Vec<Row> = self.make_rows(row_height);
×
350
            let highlighted_color = self
×
351
                .props
×
352
                .get(Attribute::HighlightedColor)
×
353
                .map(|x| x.unwrap_color());
×
354
            let widths: Vec<Constraint> = self.layout();
×
355

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

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

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

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

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

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

522
    use super::*;
523
    use pretty_assertions::assert_eq;
524
    use tuirealm::props::TableBuilder;
525

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

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

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

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

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

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

797
    #[test]
798
    fn various_header_types() {
1✔
799
        // static array of static strings
800
        let _ = Table::default().headers(["hello"]);
1✔
801
        // static array of strings
802
        let _ = Table::default().headers(["hello".to_string()]);
1✔
803
        // vec of static strings
804
        let _ = Table::default().headers(vec!["hello"]);
1✔
805
        // vec of strings
806
        let _ = Table::default().headers(vec!["hello".to_string()]);
1✔
807
        // boxed array of static strings
808
        let _ = Table::default().headers(vec!["hello"].into_boxed_slice());
1✔
809
        // boxed array of strings
810
        let _ = Table::default().headers(vec!["hello".to_string()].into_boxed_slice());
1✔
811
    }
1✔
812
}
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