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
use term_table::row::Row;
use term_table::{TableBuilder, TableStyle};
use crate::render::table::def::BergTable;
use crate::render::table::text::wrap_text_for_table;
use crate::render::table::MAXIMUM_TABLE_WIDTH;
#[derive(Debug, Clone, Default)]
pub struct BergTableBuilder<'a> {
pub(crate) max_column_width: Option<usize>,
pub(crate) style: Option<TableStyle>,
pub(crate) rows: Vec<Row<'a>>,
}
impl<'a> BergTableBuilder<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn with_max_column_width(mut self, witdh: usize) -> Self {
self.max_column_width.replace(witdh);
self
}
pub fn with_style(mut self, style: TableStyle) -> Self {
self.style.replace(style);
self
}
pub fn add_row(self, row: Row<'a>) -> Self {
self.add_rows([row])
}
fn table_wrap_width(&self) -> usize {
self.max_column_width
.unwrap_or(MAXIMUM_TABLE_WIDTH)
.saturating_sub(4)
}
pub fn add_rows<RI>(mut self, rows: RI) -> Self
where
RI: IntoIterator<Item = Row<'a>>,
{
let wrap_width = self.table_wrap_width();
let wrapped_rows = rows.into_iter().map(|mut row| {
row.cells.iter_mut().for_each(|mut cell| {
cell.data = wrap_text_for_table(cell.data.as_ref(), wrap_width).into();
});
row
});
self.rows.extend(wrapped_rows);
self
}
pub fn build(self) -> BergTable<'a> {
let BergTableBuilder {
max_column_width,
style,
rows,
} = self;
BergTable {
table: TableBuilder::new()
.max_column_width(max_column_width.unwrap_or(MAXIMUM_TABLE_WIDTH))
.style(style.unwrap_or_else(TableStyle::elegant))
.rows(rows)
.build(),
}
}
}