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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use crate::style::{Separator, Styled, Styles};
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::ops::Deref;

#[derive(Default)]
pub struct Table {
    styles: Styles,
    cols: Vec<Col>,
    rows: Vec<Row>,
}

impl Styled for Table {
    fn styles(&self) -> &Styles {
        &self.styles
    }
}

impl Table {
    pub fn new(styles: Styles, cols: Vec<Col>, rows: Vec<Row>) -> Self {
        Self { styles, cols, rows }
    }

    pub fn with_styles(styles: Styles) -> Self {
        Self::new(styles, Vec::default(), Vec::default())
    }

    #[must_use]
    pub fn with_cols(mut self, cols: Vec<Col>) -> Self {
        self.set_cols(cols);
        self
    }

    #[must_use]
    pub fn with_row<R: Into<Row>>(mut self, row: R) -> Self {
        self.push_row(row);
        self
    }

    /// Assigns columns to the table. The number of columns cannot be less (but may exceed)
    /// the number of cells in the widest row.
    ///
    /// # Panics
    /// If the number of columns is fewer than the number of cells in the widest row.
    pub fn set_cols(&mut self, cols: Vec<Col>) {
        let widest_row = self.compute_widest_row();
        assert!(
            cols.len() >= widest_row,
            "cannot assign fewer than {widest_row} columns"
        );
        self.cols = cols;
    }

    pub fn push_row<R: Into<Row>>(&mut self, row: R) {
        let row = row.into();
        while self.cols.len() < row.1.len() {
            self.cols.push(Col::new(Styles::default()));
        }
        self.rows.push(row);
    }

    pub fn push_rows<I: IntoIterator<Item = Row>>(&mut self, it: I) {
        for row in it {
            self.push_row(row);
        }
    }

    pub fn num_rows(&self) -> usize {
        self.rows.len()
    }

    pub fn num_cols(&self) -> usize {
        self.cols.len()
    }

    fn compute_widest_row(&self) -> usize {
        self.rows.iter().map(|row| row.1.len()).max().unwrap_or(0)
    }

    pub fn col(&self, col: usize) -> Element<Col> {
        let parent_styles = vec![&self.styles];
        let col = self.cols.get(col);
        Element {
            parent_styles,
            element: col,
        }
    }

    pub fn row(&self, row_idx: usize) -> Element<Row> {
        let parent_styles = vec![&self.styles];
        let row = self.rows.get(row_idx);
        Element {
            parent_styles,
            element: row,
        }
    }

    pub fn cell(&self, col_idx: usize, row_idx: usize) -> Element<Cell> {
        let col = self.cols.get(col_idx);
        let row = self.rows.get(row_idx);
        let mut parent_styles = vec![&self.styles];

        if let Some(col) = col {
            parent_styles.push(col.styles());
        }

        let cell = match row {
            None => None,
            Some(row) => {
                parent_styles.push(row.styles());
                row.1.get(col_idx)
            }
        };

        Element {
            parent_styles,
            element: cell,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.num_rows() == 0 || self.num_cols() == 0
    }
}

#[derive(Default)]
pub struct Col(Styles);

impl Col {
    pub fn new(styles: Styles) -> Self {
        styles.assert_assignability::<Self>(|assignability| assignability.at_col());
        Self(styles)
    }

    pub fn separator() -> Self {
        Self::new(Styles::default().with(Separator(true)))
    }
}

impl Styled for Col {
    fn styles(&self) -> &Styles {
        &self.0
    }
}

#[derive(Default)]
pub struct Row(Styles, Vec<Cell>);

impl Row {
    pub fn new(styles: Styles, cells: Vec<Cell>) -> Self {
        styles.assert_assignability::<Self>(|assignability| assignability.at_row());
        Self(styles, cells)
    }

    #[must_use]
    pub fn with_styles(mut self, styles: Styles) -> Self {
        styles.assert_assignability::<Self>(|assignability| assignability.at_row());
        self.0 = styles;
        self
    }

    pub fn separator() -> Self {
        Self::new(Styles::default().with(Separator(true)), vec![])
    }

    pub fn cells(&self) -> &[Cell] {
        &self.1
    }
}

impl Styled for Row {
    fn styles(&self) -> &Styles {
        &self.0
    }
}

impl<I> From<I> for Row where I: IntoIterator, I::Item: ToString {
    fn from(it: I) -> Self {
        Self(
            Styles::default(),
            it.into_iter().map(Cell::from).collect(),
        )
    }
}

pub struct Cell {
    styles: Styles,
    data: Content,
}

impl Styled for Cell {
    fn styles(&self) -> &Styles {
        &self.styles
    }
}

impl Cell {
    pub fn new(styles: Styles, data: Content) -> Self {
        styles.assert_assignability::<Self>(|assignability| assignability.at_cell());
        Self { styles, data }
    }

    pub fn data(&self) -> &Content {
        &self.data
    }
}

impl From<Content> for Cell {
    fn from(data: Content) -> Self {
        Self::new(Styles::default(), data)
    }
}

impl From<Table> for Cell {
    fn from(table: Table) -> Self {
        Self::new(Styles::default(), table.into())
    }
}

impl<S: ToString> From<S> for Cell {
    fn from(data: S) -> Self {
        Content::from(data).into()
    }
}

pub enum Content {
    Label(String),
    Computed(Box<dyn Fn() -> String>),
    Nested(Table),
    Composite(Vec<Content>),
}

impl<S: ToString> From<S> for Content {
    fn from(data: S) -> Self {
        Self::Label(data.to_string())
    }
}

impl From<Table> for Content {
    fn from(table: Table) -> Self {
        Self::Nested(table)
    }
}

pub struct Element<'a, T: Styled> {
    parent_styles: Vec<&'a Styles>,
    element: Option<&'a T>,
}

impl<'a, T: Styled> Element<'a, T> {
    pub fn parent_styles(&self) -> &[&'a Styles] {
        &self.parent_styles
    }

    pub fn blended_styles(&self) -> Styles {
        let mut styles = Styles::default();
        for &s in &self.parent_styles {
            styles.insert_all(s);
        }
        if let Some(element) = self.element {
            styles.insert_all(element.styles());
        }
        styles
    }
}

impl<'a, T: Styled> Deref for Element<'a, T> {
    type Target = Option<&'a T>;

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

#[cfg(test)]
mod tests;