nestable 0.1.2

Unicode-aware text table rendering with support for nested tables
Documentation
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
//! Rust implementation of a nested table renderer for terminals and fixed
//! font size displays

use std::cmp::{max, min};
use std::fmt;
use std::fmt::Formatter;
use unicode_width::UnicodeWidthChar;

#[derive(Debug)]
pub struct Style {
    pub top: [&'static str; 4],
    pub row: [&'static str; 4],
    pub sep: [&'static str; 4],
    pub bot: [&'static str; 4],
}

#[derive(Clone, Debug)]
pub struct Row {
    cells: Vec<String>,
}

#[derive(Clone, Debug)]
pub struct Table<'a> {
    rows: Vec<Row>,
    style: &'a Style,
    invert_header: bool,
}

#[derive(Clone, Debug)]
struct LayoutLine {
    line: String,
    width: usize,
}

#[derive(Clone, Debug)]
struct LayoutCell {
    lines: Vec<LayoutLine>,
    width: usize,
}

#[derive(Clone, Debug)]
struct LayoutRow {
    cells: Vec<LayoutCell>,
    height: usize,
}

#[derive(Clone, Debug)]
struct LayoutTable<'a> {
    rows: Vec<LayoutRow>,
    widths: Vec<usize>,
    style: &'a Style,
    invert_header: bool,
}

pub mod styles {
    use super::Style;

    pub const ASCII_BORDER: Style = Style {
        top: ["+", "-", "+", "+"],
        row: ["|", "-", "|", "|"],
        sep: ["+", "-", "+", "+"],
        bot: ["+", "-", "+", "+"],
    };

    pub const ASCII_NO_BORDER: Style = Style {
        top: ["", "", "", ""],
        row: ["", " ", "|", ""],
        sep: ["", "-", "+", ""],
        bot: ["", "", "", ""],
    };

    pub const ASCII_NO_ROW_SEPARATOR: Style = Style {
        top: ["", "", "", ""],
        row: ["", " ", "|", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };

    pub const GLYPHS_SQUARE: Style = Style {
        top: ["", "", "", ""],
        row: ["", "", "", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };

    pub const GLYPHS_ROUNDED: Style = Style {
        top: ["", "", "", ""],
        row: ["", "", "", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };

    pub const GLYPHS_NO_BORDER: Style = Style {
        top: ["", "", "", ""],
        row: ["", "", "", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };

    pub const GLYPHS_NO_ROW_SEPARATOR: Style = Style {
        top: ["", "", "", ""],
        row: ["", " ", "", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };

    pub const SPACE: Style = Style {
        top: ["", "", "", ""],
        row: ["", " ", "", ""],
        sep: ["", "", "", ""],
        bot: ["", "", "", ""],
    };
}

const DEFAULT_STYLE: &Style = &styles::GLYPHS_ROUNDED;
const DEFAULT_INVERT_HEADER: bool = true;

const ANSI_REVERSE: &str = "\x1b[7m";
const ANSI_REVERSE_OFF: &str = "\x1b[27m";

pub fn display_width(input: &str) -> usize {
    let mut chars = input.chars().peekable();
    let mut width = 0;

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Try to parse CSI: ESC [
            if let Some('[') = chars.peek().copied() {
                chars.next(); // consume '['

                // Consume until final byte (@ to ~)
                let mut found_final = false;

                while let Some(next) = chars.next() {
                    if ('@'..='~').contains(&next) {
                        found_final = true;
                        break;
                    }
                }

                if !found_final {
                    eprintln!("Warning: unterminated ANSI escape sequence");
                }

                continue;
            } else {
                eprintln!("Warning: unsupported ANSI escape sequence");
                continue;
            }
        }

        // Normal character width
        match UnicodeWidthChar::width(c) {
            Some(w) => width += w,
            None => {
                // Fallback pictograph hack
                width += if ('\u{1F300}'..='\u{1FAFF}').contains(&c) {
                    2
                } else {
                    1
                };
            }
        }
    }

    width
}

impl Row {
    pub fn empty() -> Self {
        Self { cells: Vec::new() }
    }

    pub fn new<I, S>(input: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let cells = input.into_iter().map(Into::into).collect();

        Self { cells: cells }
    }
}

fn empty_rows() -> impl Iterator<Item = Vec<String>> {
    std::iter::empty()
}

impl<'a> Table<'a> {
    pub fn empty() -> Self {
        Self::with_style(&DEFAULT_STYLE, DEFAULT_INVERT_HEADER, empty_rows())
    }

    pub fn new<I, R, S>(input: I) -> Self
    where
        I: IntoIterator<Item = R>,
        R: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self::with_style(&DEFAULT_STYLE, DEFAULT_INVERT_HEADER, input)
    }

    pub fn with_style<I, R, S>(style: &'a Style, invert_header: bool, input: I) -> Self
    where
        I: IntoIterator<Item = R>,
        R: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            rows: input.into_iter().map(|r| Row::new(r)).collect(),
            style: style,
            invert_header: invert_header,
        }
    }

    pub fn push_row<I, S>(&mut self, input: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rows.push(Row::new(input));
    }
}

impl LayoutLine {
    fn new(line: &str) -> Self {
        let width = display_width(&line);
        Self {
            line: line.to_string(),
            width: width,
        }
    }
}

impl LayoutCell {
    pub fn new(line: &str) -> Self {
        let mut max_width = 0;

        let lines: Vec<LayoutLine> = line
            .lines()
            .map(|l| {
                let layout_line = LayoutLine::new(&l);
                max_width = max(layout_line.width, max_width);
                layout_line
            })
            .collect();

        Self {
            lines: lines,
            width: max_width,
        }
    }
}

impl LayoutRow {
    // This simply splits the incoming Row (containing cells with linefeed
    // delimited lines) into LayoutCells
    pub fn new(row: &Row) -> Self {
        let mut max_height = 0;

        let cells: Vec<LayoutCell> = row
            .cells
            .iter()
            .map(|c| {
                let cell = LayoutCell::new(&c);
                max_height = max(cell.lines.len(), max_height);
                cell
            })
            .collect();

        Self {
            cells: cells,
            height: max_height,
        }
    }
}

impl<'a> LayoutTable<'a> {
    // This constructor converts a simple table to a layout table - it ensures
    // all column widths are correctly calculated to fit the widest cell, and
    // it additionally ensures that rows which do not have a uniform number of
    // columns only affect the width of the left and columns unless their
    // content overflows the width of all the columns it spans.
    fn new(table: &Table<'a>) -> Self {
        let mut max_cols = 0;
        let mut min_cols = usize::MAX;

        // Convert table.row to layout.rows and determine the maximum number of columns on any row
        let rows: Vec<LayoutRow> = table
            .rows
            .iter()
            .map(|r| {
                let row = LayoutRow::new(&r);
                max_cols = max(max_cols, row.cells.len());
                min_cols = min(min_cols, row.cells.len());
                row
            })
            .collect();

        // Allocate the column width vector
        let mut widths = Vec::with_capacity(max_cols);
        widths.resize(max_cols, 0);

        // For each row which matches the number of entries in widths, populate with the maximum width
        for row in &rows {
            if row.cells.len() == max_cols {
                for cell_index in 0..row.cells.len() {
                    widths[cell_index] = max(widths[cell_index], row.cells[cell_index].width);
                }
            }
        }

        // Process rows in decreasing column count to resolve implicit spans.
        // Shorter rows represent colspan-to-end, so widths are propagated
        // in stages to converge on correct column sizes.
        for index in 0..max_cols - min_cols {
            for row in &rows {
                if row.cells.len() == max_cols - index {
                    for cell_index in 0..row.cells.len() {
                        widths[cell_index] = max(widths[cell_index], row.cells[cell_index].width);
                    }
                }
            }
        }

        Self {
            rows: rows,
            widths: widths,
            style: table.style,
            invert_header: table.invert_header,
        }
    }
}

impl fmt::Display for Table<'_> {
    // This displays a Table by first converting to a LayoutTable and then
    // iterating through each row to render all the individual cells and
    // ensuring the broder style is applied

    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let table = LayoutTable::new(self);
        if table.rows.len() > 0 && table.widths.len() > 0 {
            // The draw lambda is responsible from drawing the borders and inter row separators.
            // it's a no-op if all of the entries are empty strings
            let draw =
                |f: &mut Formatter<'_>, style: &[&str; 4], widths: &Vec<usize>| -> fmt::Result {
                    if style[0].len() + style[1].len() + style[2].len() + style[3].len() > 0 {
                        for (index, width) in widths.iter().enumerate() {
                            let pos = if index == 0 { 0 } else { 2 };
                            write!(f, "{}", style[pos])?;
                            write!(f, "{}", style[1].repeat(*width))?;
                        }
                        writeln!(f, "{}", style[3])?;
                    }
                    Ok(())
                };

            // This sizes the column separator in use
            let colsep_width = display_width(table.style.row[2]);

            // This calculates the full width of the row
            let full_width = |colsep_width: usize, widths: &Vec<usize>| -> usize {
                let mut width = 0;
                for w in widths {
                    width += w + colsep_width;
                }
                width
            }(colsep_width, &table.widths);

            // This loop renders the entire table
            for (index, row) in table.rows.iter().enumerate() {
                if index == 0 {
                    draw(f, &table.style.top, &table.widths)?;
                } else {
                    draw(f, &table.style.sep, &table.widths)?;
                };
                for i in 0..row.height {
                    let mut remaining = full_width;
                    for (col, cell) in row.cells.iter().enumerate() {
                        let pos = if col == 0 { 0 } else { 2 };
                        write!(f, "{}", table.style.row[pos])?;
                        if index == 0 && table.invert_header {
                            write!(f, "{}", ANSI_REVERSE)?;
                        }
                        let mut displayed = 0;
                        if i < cell.lines.len() {
                            write!(f, "{}", cell.lines[i].line)?;
                            displayed += cell.lines[i].width;
                        }
                        if row.cells.len() == table.widths.len() || col < row.cells.len() - 1 {
                            let padding = table.widths[col] - displayed;
                            write!(f, "{}{}", " ".repeat(padding), ANSI_REVERSE_OFF)?;
                            remaining -= table.widths[col] + colsep_width;
                        } else {
                            remaining -= displayed + colsep_width;
                        }
                    }
                    write!(
                        f,
                        "{}{}{}\n",
                        " ".repeat(remaining),
                        ANSI_REVERSE_OFF,
                        table.style.row[3]
                    )?;
                }
            }
            draw(f, &table.style.bot, &table.widths)?;
        }
        Ok(())
    }
}