sparcli 0.3.0

Lightweight, cross-platform toolkit for styled CLI output and interactive input widgets
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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Data tables with headers, footers, borders, alignment and wrapping.
//!
//! Supports per-column alignment, min/max/fixed widths, optional word wrap,
//! zebra striping, a title and horizontal column spanning (`colspan`).
//!
//! A table that fits the render width is left untouched; an overflowing one
//! shrinks its flexible columns so its borders stay within the terminal.
//! `wrap` columns reflow first, then the rest truncate; `fixed_width` columns
//! never shrink and no column falls below its `min_width`.

mod plan;
mod render;

use crate::core::border::BorderType;
use crate::core::geometry::Align;
use crate::core::render::{Renderable, Rendered};
use crate::core::style::Style;
use crate::core::text::Text;
use crate::core::theme::theme;

/// A single table column definition.
pub struct Column {
    header: Text,
    align: Align,
    min_width: usize,
    max_width: Option<usize>,
    fixed_width: Option<usize>,
    wrap: bool,
}

impl Column {
    /// Creates a column with the given header.
    pub fn new(header: impl Into<Text>) -> Self {
        Self {
            header: header.into(),
            align: Align::Left,
            min_width: 0,
            max_width: None,
            fixed_width: None,
            wrap: false,
        }
    }

    /// Sets the column alignment.
    #[must_use]
    pub fn align(mut self, align: Align) -> Self {
        self.align = align;
        self
    }

    /// Sets the minimum column width.
    #[must_use]
    pub fn min_width(mut self, width: usize) -> Self {
        self.min_width = width;
        self
    }

    /// Sets the maximum column width (content is wrapped or truncated).
    #[must_use]
    pub fn max_width(mut self, width: usize) -> Self {
        self.max_width = Some(width);
        self
    }

    /// Sets a fixed column width.
    #[must_use]
    pub fn fixed_width(mut self, width: usize) -> Self {
        self.fixed_width = Some(width);
        self
    }

    /// Enables word wrapping instead of truncation.
    #[must_use]
    pub fn wrap(mut self) -> Self {
        self.wrap = true;
        self
    }
}

impl From<&str> for Column {
    fn from(value: &str) -> Self {
        Column::new(value)
    }
}

impl From<String> for Column {
    fn from(value: String) -> Self {
        Column::new(value)
    }
}

/// A single table cell.
pub struct Cell {
    content: Text,
    align: Option<Align>,
    colspan: usize,
    rowspan: usize,
}

impl Cell {
    /// Creates a cell from content.
    pub fn new(content: impl Into<Text>) -> Self {
        Self {
            content: content.into(),
            align: None,
            colspan: 1,
            rowspan: 1,
        }
    }

    /// Overrides the cell alignment.
    #[must_use]
    pub fn align(mut self, align: Align) -> Self {
        self.align = Some(align);
        self
    }

    /// Spans this cell across `columns` columns.
    #[must_use]
    pub fn colspan(mut self, columns: usize) -> Self {
        self.colspan = columns.max(1);
        self
    }

    /// Spans this cell across `rows` rows.
    ///
    /// Cells in the rows below skip the spanned column(s); content sits in the
    /// top row. Best paired with the default (no row separators).
    #[must_use]
    pub fn rowspan(mut self, rows: usize) -> Self {
        self.rowspan = rows.max(1);
        self
    }
}

impl From<&str> for Cell {
    fn from(value: &str) -> Self {
        Cell::new(value)
    }
}

impl From<String> for Cell {
    fn from(value: String) -> Self {
        Cell::new(value)
    }
}

impl From<Text> for Cell {
    fn from(value: Text) -> Self {
        Cell::new(value)
    }
}

/// A table row of cells.
struct Row {
    cells: Vec<Cell>,
    footer: bool,
}

/// A data table.
///
/// Rendering honours the given width: a table that already fits is unchanged,
/// while an overflowing one shrinks its flexible columns (`wrap` columns reflow
/// first, then the rest truncate) so its borders stay within the terminal.
///
/// # Examples
///
/// ```
/// use sparcli::{Renderable, Table};
///
/// let out = Table::new()
///     .columns(["Name", "Status"])
///     .row(["web-1", "online"])
///     .render(40);
/// assert!(out.plain().contains("web-1"));
/// ```
pub struct Table {
    columns: Vec<Column>,
    rows: Vec<Row>,
    border: BorderType,
    border_style: Style,
    header: bool,
    header_style: Style,
    striped: bool,
    stripe_style: Style,
    title: Option<Text>,
    title_style: Style,
    pad: u16,
    row_separators: bool,
}

impl Default for Table {
    fn default() -> Self {
        let theme = theme();
        Self {
            columns: Vec::new(),
            rows: Vec::new(),
            border: theme.border,
            border_style: theme.secondary,
            header: true,
            header_style: theme.heading,
            striped: false,
            stripe_style: Style::new().dim(),
            title: None,
            title_style: theme.heading,
            pad: 1,
            row_separators: false,
        }
    }
}

impl Table {
    /// Creates an empty table.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a column.
    #[must_use]
    pub fn column(mut self, column: impl Into<Column>) -> Self {
        self.columns.push(column.into());
        self
    }

    /// Adds several columns at once.
    #[must_use]
    pub fn columns<I, C>(mut self, columns: I) -> Self
    where
        I: IntoIterator<Item = C>,
        C: Into<Column>,
    {
        self.columns.extend(columns.into_iter().map(Into::into));
        self
    }

    /// Adds a data row.
    #[must_use]
    pub fn row<I, C>(mut self, cells: I) -> Self
    where
        I: IntoIterator<Item = C>,
        C: Into<Cell>,
    {
        self.rows.push(Row {
            cells: cells.into_iter().map(Into::into).collect(),
            footer: false,
        });
        self
    }

    /// Adds a footer row (drawn after a separator).
    #[must_use]
    pub fn footer_row<I, C>(mut self, cells: I) -> Self
    where
        I: IntoIterator<Item = C>,
        C: Into<Cell>,
    {
        self.rows.push(Row {
            cells: cells.into_iter().map(Into::into).collect(),
            footer: true,
        });
        self
    }

    /// Sets the border type.
    #[must_use]
    pub fn border(mut self, border: BorderType) -> Self {
        self.border = border;
        self
    }

    /// Sets the border glyph style (e.g. its color).
    #[must_use]
    pub fn border_style(mut self, style: Style) -> Self {
        self.border_style = style;
        self
    }

    /// Enables or disables the header row.
    #[must_use]
    pub fn header(mut self, show: bool) -> Self {
        self.header = show;
        self
    }

    /// Sets the header row text style.
    #[must_use]
    pub fn header_style(mut self, style: Style) -> Self {
        self.header_style = style;
        self
    }

    /// Enables zebra striping of body rows.
    #[must_use]
    pub fn striped(mut self, striped: bool) -> Self {
        self.striped = striped;
        self
    }

    /// Sets the style (e.g. background) used for striped rows.
    #[must_use]
    pub fn stripe_style(mut self, style: Style) -> Self {
        self.stripe_style = style;
        self
    }

    /// Sets the title text style.
    #[must_use]
    pub fn title_style(mut self, style: Style) -> Self {
        self.title_style = style;
        self
    }

    /// Sets a table title.
    #[must_use]
    pub fn title(mut self, title: impl Into<Text>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the horizontal cell padding.
    #[must_use]
    pub fn pad(mut self, pad: u16) -> Self {
        self.pad = pad;
        self
    }

    /// Draws separators between body rows.
    #[must_use]
    pub fn row_separators(mut self, on: bool) -> Self {
        self.row_separators = on;
        self
    }
}

impl Renderable for Table {
    fn render(&self, max_width: u16) -> Rendered {
        if self.columns.is_empty() {
            return Rendered::empty();
        }
        let plan = plan::build_plan(&self.rows, self.columns.len());
        let widths = plan::column_widths(self, &plan, max_width as usize);
        render::Builder::new(self, &widths, &plan).build()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::text::Line;

    fn plain(rendered: &Rendered) -> Vec<String> {
        rendered.lines.iter().map(Line::plain).collect()
    }

    #[test]
    fn renders_header_and_rows_with_borders() {
        let table = Table::new()
            .columns(["A", "B"])
            .row(["1", "2"])
            .border(BorderType::Single);
        let lines = plain(&table.render(80));
        assert!(lines[0].starts_with(''));
        assert!(lines[1].contains('A') && lines[1].contains('B'));
        assert!(lines[2].starts_with(''));
        assert!(lines[3].contains('1') && lines[3].contains('2'));
        assert!(lines[4].starts_with(''));
    }

    #[test]
    fn aligns_and_pads_cells() {
        let table = Table::new()
            .header(false)
            .column(Column::new("").align(Align::Right))
            .row(["7"])
            .border(BorderType::Ascii);
        let lines = plain(&table.render(80));
        // Body row: |<pad>7<pad>| with right alignment (single col).
        assert!(lines.iter().any(|l| l.contains('7')));
    }

    #[test]
    fn truncates_overlong_cells_to_max_width() {
        let table = Table::new()
            .header(false)
            .column(Column::new("").max_width(4))
            .row(["abcdefgh"])
            .border(BorderType::Single);
        let lines = plain(&table.render(80));
        assert!(lines.iter().any(|l| l.contains('')));
    }

    #[test]
    fn rowspan_spans_following_rows() {
        let table = Table::new()
            .header(false)
            .columns(["A", "B"])
            .row([Cell::new("x").rowspan(2), Cell::new("1")])
            .row(["2"])
            .border(BorderType::Single);
        let lines = plain(&table.render(80));
        // Top span row carries both the spanning cell and the first value.
        assert!(lines.iter().any(|l| l.contains('x') && l.contains('1')));
        // The continuation row shows the next value but not the spanned cell.
        let two = lines.iter().find(|l| l.contains('2')).unwrap();
        assert!(!two.contains('x'));
    }

    #[test]
    fn colspan_widens_a_cell() {
        let table = Table::new()
            .columns(["A", "B"])
            .row([Cell::new("wide").colspan(2)])
            .border(BorderType::Single);
        let lines = plain(&table.render(80));
        assert!(lines.iter().any(|l| l.contains("wide")));
    }

    /// The widest rendered line, i.e. the table's outer width.
    fn outer_width(rendered: &Rendered) -> usize {
        plain(rendered)
            .iter()
            .map(|line| crate::width::visible_width(line))
            .max()
            .unwrap_or(0)
    }

    #[test]
    fn a_fitting_table_is_identical_regardless_of_max_width() {
        let table = Table::new()
            .columns(["A", "B"])
            .row(["1", "2"])
            .border(BorderType::Single);
        // A table that fits must render the same at any generous width, so the
        // fitting pass never touches the common case.
        assert_eq!(plain(&table.render(80)), plain(&table.render(1000)));
    }

    #[test]
    fn overflow_reflows_wrapping_columns_before_truncating() {
        let table = Table::new()
            .header(false)
            .column(Column::new("").wrap())
            .column(Column::new("").align(Align::Right))
            .row(["aaaaaaaaaaaaaaaaaaaa", "12345"])
            .border(BorderType::Single);
        let rendered = table.render(20);
        let lines = plain(&rendered);
        // The numeric column keeps its content; the wrap column reflows onto a
        // second physical line instead of losing text.
        assert!(lines.iter().any(|l| l.contains("12345")));
        assert!(!lines.iter().any(|l| l.contains('')));
        assert!(lines.len() > 3, "the wrap column produced extra lines");
        assert!(outer_width(&rendered) <= 20);
    }

    #[test]
    fn overflow_truncates_the_widest_non_wrapping_column_first() {
        let table = Table::new()
            .header(false)
            .columns(["A", "B"])
            .row(["abcdefghijklmnop", "xy"])
            .border(BorderType::Single);
        let rendered = table.render(16);
        let lines = plain(&rendered);
        // The narrow column survives; the wide one is truncated with an ellipsis.
        assert!(lines.iter().any(|l| l.contains("xy")));
        assert!(lines.iter().any(|l| l.contains('')));
        assert!(outer_width(&rendered) <= 16);
    }

    #[test]
    fn a_fixed_width_column_never_shrinks() {
        let table = Table::new()
            .header(false)
            .column(Column::new("").fixed_width(8))
            .column(Column::new("").wrap())
            .row(["FIXEDVAL", "aaaaaaaaaaaaaaaa"])
            .border(BorderType::Single);
        let rendered = table.render(20);
        let lines = plain(&rendered);
        // The fixed column keeps its full 8-character value; the flexible one
        // absorbs the whole deficit.
        assert!(lines.iter().any(|l| l.contains("FIXEDVAL")));
        assert!(outer_width(&rendered) <= 20);
    }

    #[test]
    fn a_column_never_shrinks_below_its_min_width() {
        let table = Table::new()
            .header(false)
            .column(Column::new("").min_width(10))
            .row(["x"])
            .border(BorderType::Single);
        // Even asked to fit five columns, the min-width floor wins and the
        // table overflows rather than collapse below it.
        let rendered = table.render(5);
        assert!(outer_width(&rendered) > 5);
    }

    #[test]
    fn a_colspan_cell_truncates_under_pressure_without_forcing_a_column() {
        let table = Table::new()
            .columns(["A", "B"])
            .row([Cell::new("a-very-wide-spanning-value").colspan(2)])
            .row(["1", "2"])
            .border(BorderType::Single);
        // The single-column widths derive from the colspan==1 row, so the wide
        // spanning cell truncates instead of widening either column.
        let rendered = table.render(14);
        assert!(outer_width(&rendered) <= 14);
    }
}