Skip to main content

codeberg_cli/render/
table.rs

1use comfy_table::*;
2
3#[derive(Debug)]
4pub struct TableWrapper {
5    table: Table,
6    pub(crate) max_width: Option<u16>,
7}
8
9impl Default for TableWrapper {
10    fn default() -> Self {
11        Self {
12            table: Table::new(),
13            max_width: None,
14        }
15    }
16}
17
18impl TableWrapper {
19    pub fn load_preset(mut self, preset: &'static str) -> Self {
20        self.table.load_preset(preset);
21        self
22    }
23
24    pub fn set_header<T>(mut self, header: impl IntoIterator<Item = T>) -> Self
25    where
26        T: std::fmt::Display,
27    {
28        self.table.set_header(
29            header
30                .into_iter()
31                .map(|x| x.to_string())
32                .collect::<Vec<_>>(),
33        );
34        self
35    }
36
37    pub fn add_error(mut self, error: impl Into<String>) -> Self {
38        self.table.add_row(vec![
39            comfy_table::Cell::new(error.into()).fg(comfy_table::Color::Red),
40        ]);
41        self
42    }
43
44    pub fn add_row<T>(mut self, row: impl IntoIterator<Item = T>) -> Self
45    where
46        T: std::fmt::Display,
47    {
48        let cols = row.into_iter().collect::<Vec<_>>();
49        let width_per_col = self.max_width.unwrap_or(10000) as usize / cols.len();
50        self.table.add_row(
51            cols.into_iter()
52                .map(|x| x.to_string())
53                .map(|x| {
54                    x.replace("```", "\n```\n")
55                        .lines()
56                        .map(|l| textwrap::refill(l, width_per_col))
57                        .collect::<Vec<_>>()
58                        .join("\n")
59                })
60                .collect::<Vec<_>>(),
61        );
62        self
63    }
64
65    pub fn add_rows(self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
66        rows.into_iter()
67            .fold(self, move |table, row| table.add_row(row))
68    }
69
70    pub fn show(self) -> String {
71        let Self { table, .. } = self;
72        format!("{table}")
73    }
74}