codeberg_cli/render/
table.rs

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
use comfy_table::*;

#[derive(Debug)]
pub struct TableWrapper {
    table: Table,
    pub(crate) max_width: Option<u16>,
}

impl Default for TableWrapper {
    fn default() -> Self {
        Self {
            table: Table::new(),
            max_width: None,
        }
    }
}

impl std::ops::Deref for TableWrapper {
    type Target = Table;

    fn deref(&self) -> &Self::Target {
        &self.table
    }
}

impl std::ops::DerefMut for TableWrapper {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.table
    }
}

impl TableWrapper {
    pub fn show(self) -> String {
        let Self {
            mut table,
            max_width,
        } = self;
        let widths = max_width
            .map(|width| width.min(table.column_max_content_widths().iter().sum::<u16>()))
            .map(|width| (width - 2) / table.column_count() as u16)
            .into_iter()
            .map(Width::Fixed)
            .map(ColumnConstraint::Absolute)
            .cycle()
            .chain(
                max_width
                    .is_none()
                    .then_some(ColumnConstraint::ContentWidth)
                    .into_iter()
                    .cycle(),
            );

        table.set_constraints(widths);
        format!("{table}")
    }
}