summaryrefslogtreecommitdiffstats
path: root/vendor/tabled/examples/colored_padding.rs
blob: 96a3a717f57b9ac04a8e56a9d5a8aaeff372dfa8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//! This example demonstrates using the [`Padding::colorize()`] function in several ways
//! to give a [`Table`] display a vibrant asthetic.
//!
//! * 🚩 This example requires the `color` feature.
//!
//! * Note how the [`Color`] [setting](tabled::settings) is used to simplify creating
//! reusable themes for text, backgrounds, padded whitespace, and borders.
//!
//! * Note how a unique color can be set for each direction.

use std::convert::TryFrom;

use owo_colors::OwoColorize;

use tabled::{
    grid::{
        config::{ColoredConfig, Entity},
        dimension::SpannedGridDimension,
        records::{
            vec_records::{Cell, VecRecords},
            ExactRecords, PeekableRecords, Records,
        },
        util::string::string_width_multiline,
    },
    settings::{
        object::{Columns, Object, Rows, Segment},
        Alignment, CellOption, Color, Format, Margin, Modify, Padding, Style,
    },
    Table, Tabled,
};

#[derive(Tabled)]
#[tabled(rename_all = "PascalCase")]
struct Fundamental {
    quantity: &'static str,
    symbol: &'static str,
    value: &'static str,
    unit: &'static str,
}

impl Fundamental {
    fn new(
        quantity: &'static str,
        symbol: &'static str,
        value: &'static str,
        unit: &'static str,
    ) -> Self {
        Self {
            quantity,
            symbol,
            value,
            unit,
        }
    }
}

fn main() {
    // data source: https://www.britannica.com/science/physical-constant
    let data = [
        Fundamental::new(
            "constant of gravitation",
            "G",
            "6.67384 × 10⁻¹¹",
            "cubic metre per second squared per kilogram",
        ),
        Fundamental::new(
            "speed of light (in a vacuum)",
            "c",
            "2.99792458 × 10⁻⁸",
            "metres per second",
        ),
        Fundamental::new(
            "Planck's constant",
            "h",
            "6.626070040 × 10⁻³⁴",
            "joule second",
        ),
        Fundamental::new(
            "Boltzmann constant",
            "k",
            "1.38064852 × 10⁻²³",
            "joule per kelvin",
        ),
        Fundamental::new(
            "Faraday constant",
            "F",
            "9.648533289 × 10⁴",
            "coulombs per mole",
        ),
    ];

    let pane_color = Color::try_from(' '.bg_rgb::<220, 220, 220>().to_string()).unwrap();
    let border_color = Color::try_from(' '.bg_rgb::<200, 200, 220>().bold().to_string()).unwrap();
    let data_color = Color::try_from(' '.bg_rgb::<200, 200, 220>().to_string()).unwrap();

    let header_settings = Modify::new(Rows::first())
        .with(Padding::new(1, 1, 2, 2).colorize(
            Color::BG_GREEN,
            Color::BG_YELLOW,
            Color::BG_MAGENTA,
            Color::BG_CYAN,
        ))
        .with(MakeMaxPadding)
        .with(Format::content(|s| s.on_black().white().to_string()));

    let data_settings = Modify::new(Rows::first().inverse())
        .with(Alignment::left())
        .with(MakeMaxPadding)
        .with(Padding::new(1, 1, 0, 0).colorize(
            Color::default(),
            Color::default(),
            data_color.clone(),
            data_color.clone(),
        ));

    let symbol_settings = Modify::new(Columns::single(1).not(Rows::first()))
        .with(Format::content(|s| s.bold().to_string()));

    let unit_settings = Modify::new(Columns::single(3).not(Rows::first()))
        .with(Format::content(|s| s.italic().to_string()));

    let table = Table::new(data)
        .with(Style::rounded())
        .with(Margin::new(1, 2, 1, 1).colorize(
            pane_color.clone(),
            pane_color.clone(),
            pane_color.clone(),
            pane_color,
        ))
        .with(border_color)
        .with(Modify::new(Segment::all()).with(data_color))
        .with(header_settings)
        .with(data_settings)
        .with(symbol_settings)
        .with(unit_settings)
        .to_string();

    println!("\n\n{table}\n\n");
}

#[derive(Debug, Clone)]
struct MakeMaxPadding;

impl<T> CellOption<VecRecords<T>, ColoredConfig> for MakeMaxPadding
where
    T: Cell + AsRef<str>,
{
    fn change(self, records: &mut VecRecords<T>, cfg: &mut ColoredConfig, entity: Entity) {
        let widths = SpannedGridDimension::width(&*records, cfg);

        let count_rows = records.count_rows();
        let count_cols = records.count_columns();

        for (row, col) in entity.iter(count_rows, count_cols) {
            let column_width = widths[col];
            let text = records.get_text((row, col));
            let width = string_width_multiline(text);

            if width < column_width {
                let available_width = column_width - width;
                let left = available_width / 2;
                let right = available_width - left;

                let pos = (row, col).into();
                let mut pad = cfg.get_padding(pos);
                pad.left.size = left;
                pad.right.size = right;

                cfg.set_padding(pos, pad);
            }
        }
    }
}