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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Print column-aligned text to the console.
//!
//! Example:
//! ```
//! use radicle_term::table::*;
//!
//! let mut t = Table::new(TableOptions::default());
//! t.push(["pest", "biological control"]);
//! t.push(["aphid", "lacewing"]);
//! t.push(["spider mite", "ladybug"]);
//! t.print();
//! ```
//! Output:
//! ``` plain
//! pest        biological control
//! aphid       ladybug
//! spider mite persimilis
//! ```
use std::fmt;

use crate::cell::Cell;
use crate::{self as term, Style};
use crate::{Color, Constraint, Line, Paint, Size};

pub use crate::Element;

#[derive(Debug)]
pub struct TableOptions {
    /// Whether the table should be allowed to overflow.
    pub overflow: bool,
    /// Horizontal spacing between table cells.
    pub spacing: usize,
    /// Table border.
    pub border: Option<Color>,
}

impl Default for TableOptions {
    fn default() -> Self {
        Self {
            overflow: false,
            spacing: 1,
            border: None,
        }
    }
}

impl TableOptions {
    pub fn bordered() -> Self {
        Self {
            border: Some(term::colors::FAINT),
            spacing: 3,
            ..Self::default()
        }
    }
}

#[derive(Debug)]
enum Row<const W: usize, T> {
    Header([T; W]),
    Data([T; W]),
    Divider,
}

#[derive(Debug)]
pub struct Table<const W: usize, T> {
    rows: Vec<Row<W, T>>,
    widths: [usize; W],
    opts: TableOptions,
}

impl<const W: usize, T> Default for Table<W, T> {
    fn default() -> Self {
        Self {
            rows: Vec::new(),
            widths: [0; W],
            opts: TableOptions::default(),
        }
    }
}

impl<const W: usize, T: Cell + fmt::Debug + Send + Sync> Element for Table<W, T>
where
    T::Padded: Into<Line>,
{
    fn size(&self, parent: Constraint) -> Size {
        Table::size(self, parent)
    }

    fn render(&self, parent: Constraint) -> Vec<Line> {
        let mut lines = Vec::new();
        let border = self.opts.border;
        let inner = self.inner(parent);
        let cols = inner.cols;

        if let Some(color) = border {
            lines.push(
                Line::default()
                    .item(Paint::new("╭").fg(color))
                    .item(Paint::new("─".repeat(cols)).fg(color))
                    .item(Paint::new("╮").fg(color)),
            );
        }

        for row in &self.rows {
            let mut line = Line::default();

            match row {
                Row::Header(cells) | Row::Data(cells) => {
                    if let Some(color) = border {
                        line.push(Paint::new("│ ").fg(color));
                    }
                    for (i, cell) in cells.iter().enumerate() {
                        let pad = if i == cells.len() - 1 {
                            0
                        } else {
                            self.widths[i] + self.opts.spacing
                        };
                        line = line.extend(
                            cell.pad(pad)
                                .into()
                                .style(Style::default().bg(cell.background())),
                        );
                    }
                    Line::pad(&mut line, cols);
                    Line::truncate(&mut line, cols, "…");

                    if let Some(color) = border {
                        line.push(Paint::new(" │").fg(color));
                    }
                    lines.push(line);
                }
                Row::Divider => {
                    if let Some(color) = border {
                        lines.push(
                            Line::default()
                                .item(Paint::new("├").fg(color))
                                .item(Paint::new("─".repeat(cols)).fg(color))
                                .item(Paint::new("┤").fg(color)),
                        );
                    } else {
                        lines.push(Line::default());
                    }
                }
            }
        }
        if let Some(color) = border {
            lines.push(
                Line::default()
                    .item(Paint::new("╰").fg(color))
                    .item(Paint::new("─".repeat(cols)).fg(color))
                    .item(Paint::new("╯").fg(color)),
            );
        }
        lines
    }
}

impl<const W: usize, T: Cell> Table<W, T> {
    pub fn new(opts: TableOptions) -> Self {
        Self {
            rows: Vec::new(),
            widths: [0; W],
            opts,
        }
    }

    pub fn size(&self, parent: Constraint) -> Size {
        self.outer(parent)
    }

    pub fn divider(&mut self) {
        self.rows.push(Row::Divider);
    }

    pub fn push(&mut self, row: [T; W]) {
        for (i, cell) in row.iter().enumerate() {
            self.widths[i] = self.widths[i].max(cell.width());
        }
        self.rows.push(Row::Data(row));
    }

    pub fn header(&mut self, row: [T; W]) {
        for (i, cell) in row.iter().enumerate() {
            self.widths[i] = self.widths[i].max(cell.width());
        }
        self.rows.push(Row::Header(row));
    }

    pub fn extend(&mut self, rows: impl IntoIterator<Item = [T; W]>) {
        for row in rows.into_iter() {
            self.push(row);
        }
    }

    pub fn is_empty(&self) -> bool {
        !self.rows.iter().any(|r| matches!(r, Row::Data { .. }))
    }

    fn inner(&self, c: Constraint) -> Size {
        let mut outer = self.outer(c);

        if self.opts.border.is_some() {
            outer.cols -= 2;
            outer.rows -= 2;
        }
        outer
    }

    fn outer(&self, c: Constraint) -> Size {
        let mut cols = self.widths.iter().sum::<usize>() + (W - 1) * self.opts.spacing;
        let mut rows = self.rows.len();
        let padding = 2;

        // Account for outer borders.
        if self.opts.border.is_some() {
            cols += 2 + padding;
            rows += 2;
        }
        Size::new(cols, rows).constrain(c)
    }
}

#[cfg(test)]
mod test {
    use crate::Element;

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_truncate() {
        assert_eq!("🍍".truncate(1, "…"), String::from("…"));
        assert_eq!("🍍".truncate(1, ""), String::from(""));
        assert_eq!("🍍🍍".truncate(2, "…"), String::from("…"));
        assert_eq!("🍍🍍".truncate(3, "…"), String::from("🍍…"));
        assert_eq!("🍍".truncate(1, "🍎"), String::from(""));
        assert_eq!("🍍".truncate(2, "🍎"), String::from("🍍"));
        assert_eq!("🍍🍍".truncate(3, "🍎"), String::from("🍎"));
        assert_eq!("🍍🍍🍍".truncate(4, "🍎"), String::from("🍍🍎"));
        assert_eq!("hello".truncate(3, "…"), String::from("he…"));
    }

    #[test]
    fn test_table() {
        let mut t = Table::new(TableOptions::default());

        t.push(["pineapple", "rosemary"]);
        t.push(["apples", "pears"]);

        #[rustfmt::skip]
        assert_eq!(
            t.display(Constraint::UNBOUNDED),
            [
                "pineapple rosemary\n",
                "apples    pears   \n"
            ].join("")
        );
    }

    #[test]
    fn test_table_border() {
        let mut t = Table::new(TableOptions {
            border: Some(Color::Unset),
            spacing: 3,
            ..TableOptions::default()
        });

        t.push(["Country", "Population", "Code"]);
        t.divider();
        t.push(["France", "60M", "FR"]);
        t.push(["Switzerland", "7M", "CH"]);
        t.push(["Germany", "80M", "DE"]);

        let inner = t.inner(Constraint::UNBOUNDED);
        assert_eq!(inner.cols, 33);
        assert_eq!(inner.rows, 5);

        let outer = t.outer(Constraint::UNBOUNDED);
        assert_eq!(outer.cols, 35);
        assert_eq!(outer.rows, 7);

        assert_eq!(
            t.display(Constraint::UNBOUNDED),
            r#"
╭─────────────────────────────────╮
│ Country       Population   Code │
├─────────────────────────────────┤
│ France        60M          FR   │
│ Switzerland   7M           CH   │
│ Germany       80M          DE   │
╰─────────────────────────────────╯
"#
            .trim_start()
        );
    }

    #[test]
    fn test_table_border_truncated() {
        let mut t = Table::new(TableOptions {
            border: Some(Color::Unset),
            spacing: 3,
            ..TableOptions::default()
        });

        t.push(["Code", "Name"]);
        t.divider();
        t.push(["FR", "France"]);
        t.push(["CH", "Switzerland"]);
        t.push(["DE", "Germany"]);

        let constrain = Constraint::max(Size {
            cols: 19,
            rows: usize::MAX,
        });
        let outer = t.outer(constrain);
        assert_eq!(outer.cols, 19);
        assert_eq!(outer.rows, 7);

        let inner = t.inner(constrain);
        assert_eq!(inner.cols, 17);
        assert_eq!(inner.rows, 5);

        assert_eq!(
            t.display(constrain),
            r#"
╭─────────────────╮
│ Code   Name     │
├─────────────────┤
│ FR     France   │
│ CH     Switzer… │
│ DE     Germany  │
╰─────────────────╯
"#
            .trim_start()
        );
    }

    #[test]
    fn test_table_border_maximized() {
        let mut t = Table::new(TableOptions {
            border: Some(Color::Unset),
            spacing: 3,
            ..TableOptions::default()
        });

        t.push(["Code", "Name"]);
        t.divider();
        t.push(["FR", "France"]);
        t.push(["CH", "Switzerland"]);
        t.push(["DE", "Germany"]);

        let constrain = Constraint::new(
            Size { cols: 26, rows: 0 },
            Size {
                cols: 26,
                rows: usize::MAX,
            },
        );
        let outer = t.outer(constrain);
        assert_eq!(outer.cols, 26);
        assert_eq!(outer.rows, 7);

        let inner = t.inner(constrain);
        assert_eq!(inner.cols, 24);
        assert_eq!(inner.rows, 5);

        assert_eq!(
            t.display(constrain),
            r#"
╭────────────────────────╮
│ Code   Name            │
├────────────────────────┤
│ FR     France          │
│ CH     Switzerland     │
│ DE     Germany         │
╰────────────────────────╯
"#
            .trim_start()
        );
    }

    #[test]
    fn test_table_truncate() {
        let mut t = Table::default();
        let constrain = Constraint::new(
            Size::MIN,
            Size {
                cols: 16,
                rows: usize::MAX,
            },
        );

        t.push(["pineapple", "rosemary"]);
        t.push(["apples", "pears"]);

        #[rustfmt::skip]
        assert_eq!(
            t.display(constrain),
            [
                "pineapple rosem…\n",
                "apples    pears \n"
            ].join("")
        );
    }

    #[test]
    fn test_table_unicode() {
        let mut t = Table::new(TableOptions::default());

        t.push(["🍍pineapple", "__rosemary", "__sage"]);
        t.push(["__pears", "🍎apples", "🍌bananas"]);

        #[rustfmt::skip]
        assert_eq!(
            t.display(Constraint::UNBOUNDED),
            [
                "🍍pineapple __rosemary __sage   \n",
                "__pears     🍎apples   🍌bananas\n"
            ].join("")
        );
    }

    #[test]
    fn test_table_unicode_truncate() {
        let mut t = Table::new(TableOptions {
            ..TableOptions::default()
        });
        let constrain = Constraint::max(Size {
            cols: 16,
            rows: usize::MAX,
        });
        t.push(["🍍pineapple", "__rosemary"]);
        t.push(["__pears", "🍎apples"]);

        #[rustfmt::skip]
        assert_eq!(
            t.display(constrain),
            [
                "🍍pineapple __r…\n",
                "__pears     🍎a…\n"
            ].join("")
        );
    }
}