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

veeso / tui-realm-stdlib / 20435733121

22 Dec 2025 03:06PM UTC coverage: 70.048% (-0.1%) from 70.169%
20435733121

Pull #48

github

web-flow
Merge ad682c6d8 into 9528c3045
Pull Request #48: Apply changes for core `Title` changes

297 of 363 new or added lines in 17 files covered. (81.82%)

3 existing lines in 2 files now uncovered.

3204 of 4574 relevant lines covered (70.05%)

2.14 hits per line

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

73.98
/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
    AttrValue, Attribute, Borders, Color, PropPayload, PropValue, Props, Style, Table as PropTable,
10
    TextModifiers, Title,
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<T: Into<Title>>(mut self, title: T) -> Self {
3✔
155
        self.attr(Attribute::Title, AttrValue::Title(title.into()));
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

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

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

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

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

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

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

522
#[cfg(test)]
523
mod tests {
524

525
    use super::*;
526
    use pretty_assertions::assert_eq;
527
    use tuirealm::props::{Alignment, TableBuilder};
528

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

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

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

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

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

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

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