table_demo/
table_demo.rs

1use nu_ansi_term::{Color, Style};
2use nu_color_config::TextStyle;
3use nu_table::{NuTable, TableTheme};
4use tabled::grid::records::vec_records::Text;
5
6fn main() {
7    let args: Vec<_> = std::env::args().collect();
8    let mut width = 0;
9
10    if args.len() > 1 {
11        width = args[1].parse::<usize>().expect("Need a width in columns");
12    }
13
14    if width < 4 {
15        println!("Width must be greater than or equal to 4, setting width to 80");
16        width = 80;
17    }
18
19    let (table_headers, row_data) = make_table_data();
20
21    let headers = to_cell_info_vec(&table_headers);
22    let rows = to_cell_info_vec(&row_data);
23
24    let mut table = NuTable::new(4, 3);
25    table.set_row(0, headers);
26
27    for i in 0..3 {
28        table.set_row(i + 1, rows.clone());
29    }
30
31    table.set_data_style(TextStyle::basic_left());
32    table.set_header_style(TextStyle::basic_center().style(Style::new().on(Color::Blue)));
33    table.set_theme(TableTheme::rounded());
34    table.set_structure(false, true, false);
35
36    let output_table = table
37        .draw(width)
38        .unwrap_or_else(|| format!("Couldn't fit table into {width} columns!"));
39
40    println!("{output_table}")
41}
42
43fn make_table_data() -> (Vec<&'static str>, Vec<&'static str>) {
44    let table_headers = vec![
45        "category",
46        "description",
47        "emoji",
48        "ios_version",
49        "unicode_version",
50        "aliases",
51        "tags",
52        "category2",
53        "description2",
54        "emoji2",
55        "ios_version2",
56        "unicode_version2",
57        "aliases2",
58        "tags2",
59    ];
60
61    let row_data = vec![
62        "Smileys & Emotion",
63        "grinning face",
64        "😀",
65        "6",
66        "6.1",
67        "grinning",
68        "smile",
69        "Smileys & Emotion",
70        "grinning face",
71        "😀",
72        "6",
73        "6.1",
74        "grinning",
75        "smile",
76    ];
77
78    (table_headers, row_data)
79}
80
81fn to_cell_info_vec(data: &[&str]) -> Vec<Text<String>> {
82    let mut v = vec![];
83    for x in data {
84        v.push(Text::new(String::from(*x)));
85    }
86
87    v
88}