tinsel 0.4.1

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and more.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use std::cmp::Ordering;
use std::fmt;

use crate::block::Block;
use crate::style::palette::{BLUSH, LINE, MUTED, ROSE, TEXT, TRACK};
use crate::style::{Rgb, bold, mix, on_bg, paint};
use crate::text;

/// Which side of a column cells hug.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
    /// Text hugs the left edge: the default for words.
    Left,
    /// Text hugs the right edge: the default for numbers.
    Right,
}

/// How a [`Table`] is framed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Border {
    /// No frame: a dotted rule under the header and space between columns. The default.
    #[default]
    None,
    /// A soft rounded frame around the whole table, with space (not lines) between columns.
    Rounded,
    /// A grid: square corners and lines between every column, for when cells need edges.
    Square,
}

/// What to do with a cell wider than its column's limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Overflow {
    Truncate,
    Wrap,
}

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

/// Rows under a header, columns sized to their widest cell. Columns of numbers right-align
/// on their own; cells can be styled (badges, coloured text) and still line up.
///
/// ```no_run
/// use tinsel::{Border, Table};
///
/// Table::new(["app", "status", "size"])
///     .row(["core", "live", "34.2 MB"])
///     .row(["queue", "building", "12.8 MB"])
///     .sort_by(2)               // numerically, units and all
///     .highlight(0)             // the first row, after sorting
///     .footer(["2 services", "", "47.0 MB"])
///     .border(Border::Rounded)
///     .print();
/// ```
#[derive(Clone, Debug, Default)]
pub struct Table {
    headers: Vec<String>,
    rows: Vec<Row>,
    footer: Option<Vec<String>>,
    align: Vec<Option<Align>>,
    limits: Vec<Option<(usize, Overflow)>>,
    border: Border,
    title: Option<String>,
    striped: bool,
    blank: bool,
}

impl Table {
    /// A table with these column headers.
    pub fn new<S: Into<String>>(headers: impl IntoIterator<Item = S>) -> Self {
        Table {
            headers: headers.into_iter().map(Into::into).collect(),
            ..Self::default()
        }
    }

    /// Add a row of cells. Cells can be plain or styled (a [`badge`](crate::badge), say).
    /// A row can have fewer cells than there are headers (the rest show `·`), but not more:
    /// debug builds stop there and say so.
    pub fn row<S: Into<String>>(mut self, cells: impl IntoIterator<Item = S>) -> Self {
        let cells: Vec<String> = cells.into_iter().map(Into::into).collect();
        check_row("Table", &self.headers, cells.len(), self.rows.len());
        self.rows.push(Row {
            cells,
            highlight: false,
        });
        self
    }

    /// A closing row under a rule, for totals.
    pub fn footer<S: Into<String>>(mut self, cells: impl IntoIterator<Item = S>) -> Self {
        self.footer = Some(cells.into_iter().map(Into::into).collect());
        self
    }

    /// Override the automatic alignment of one column.
    pub fn align(mut self, column: usize, align: Align) -> Self {
        set(&mut self.align, column, Some(align));
        self
    }

    /// Cut cells in a column to at most `cols` wide, ending in `…`.
    pub fn max_width(mut self, column: usize, cols: usize) -> Self {
        set(&mut self.limits, column, Some((cols.max(1), Overflow::Truncate)));
        self
    }

    /// Wrap cells in a column onto more lines once they're wider than `cols`.
    pub fn wrap(mut self, column: usize, cols: usize) -> Self {
        set(&mut self.limits, column, Some((cols.max(1), Overflow::Wrap)));
        self
    }

    /// Draw a frame around the table (default: [`Border::None`]).
    pub fn border(mut self, border: Border) -> Self {
        self.border = border;
        self
    }

    /// A title, set into the top border (or above the table, without one).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Tint every other row faintly, to help the eye along wide tables.
    pub fn striped(mut self) -> Self {
        self.striped = true;
        self
    }

    /// Leave empty body cells blank, instead of marking each with a muted `·`.
    ///
    /// ```
    /// use tinsel::Table;
    ///
    /// tinsel::set_color_mode(tinsel::ColorMode::None);
    /// let table = Table::new(["name", "note"]).row(["api", ""]).blank_cells();
    /// assert_eq!(table.lines().plain(), "  name   note\n  ┈┈┈┈┈┈┈┈┈┈┈\n  api");
    /// ```
    pub fn blank_cells(mut self) -> Self {
        self.blank = true;
        self
    }

    /// Pick out row `index` (counting rows added so far, from 0) in the accent colour, on a
    /// soft tint, with a little `✦` beside it. Highlighted rows stay highlighted when sorted.
    pub fn highlight(mut self, index: usize) -> Self {
        if let Some(row) = self.rows.get_mut(index) {
            row.highlight = true;
        }
        self
    }

    /// Sort the rows added so far by a column, smallest first. Columns of numbers sort by
    /// value, understanding units: `900 KB` comes before `1.2 MB`, `45s` before `2m`.
    pub fn sort_by(mut self, column: usize) -> Self {
        self.sort(column, false);
        self
    }

    /// Like [`sort_by`](Table::sort_by), largest first.
    pub fn sort_by_desc(mut self, column: usize) -> Self {
        self.sort(column, true);
        self
    }

    fn sort(&mut self, column: usize, desc: bool) {
        let numeric = self.column_align(column) == Align::Right;
        let cell = |r: &Row| text::strip_ansi(r.cells.get(column).map_or("", String::as_str));
        self.rows.sort_by(|a, b| {
            let (a, b) = (cell(a), cell(b));
            let order = if numeric {
                // cells that aren't numbers go last whichever way round
                match (parse_number(&a), parse_number(&b)) {
                    (Some(x), Some(y)) => x.total_cmp(&y),
                    (Some(_), None) => return Ordering::Less,
                    (None, Some(_)) => return Ordering::Greater,
                    (None, None) => Ordering::Equal,
                }
            } else {
                a.to_lowercase().cmp(&b.to_lowercase())
            };
            if desc { order.reverse() } else { order }
        });
    }

    fn column_align(&self, col: usize) -> Align {
        if let Some(Some(a)) = self.align.get(col) {
            return *a;
        }
        let numeric = self
            .rows
            .iter()
            .filter_map(|r| r.cells.get(col))
            .map(|c| text::strip_ansi(c))
            .all(|c| {
                let c = c.trim();
                c.is_empty() || c.starts_with(|ch: char| ch.is_ascii_digit() || ch == '-' || ch == '$')
            });
        if numeric && !self.rows.is_empty() {
            Align::Right
        } else {
            Align::Left
        }
    }

    /// A cell's lines once its column's limit is applied.
    fn fit(&self, col: usize, raw: &str) -> Vec<String> {
        match self.limits.get(col).copied().flatten() {
            Some((cols, _)) if text::width(raw) <= cols => vec![raw.to_string()],
            Some((cols, Overflow::Truncate)) => vec![text::truncate(&text::strip_ansi(raw), cols)],
            Some((cols, Overflow::Wrap)) => text::wrap(&text::strip_ansi(raw), cols),
            None => vec![raw.to_string()],
        }
    }

    /// The table as lines.
    pub fn lines(&self) -> Block {
        let layout = self.layout();
        match self.border {
            Border::Square => self.grid(&layout),
            Border::None | Border::Rounded => self.soft(&layout),
        }
        .into()
    }

    /// Every cell fitted to its column, and how wide and which way round each column is.
    fn layout(&self) -> Layout {
        let cols = self
            .rows
            .iter()
            .map(|r| r.cells.len())
            .chain([self.headers.len()])
            .chain(self.footer.as_ref().map(Vec::len))
            .max()
            .unwrap_or(0);
        let fitted = |cells: &[String]| -> Vec<Vec<String>> {
            (0..cols)
                .map(|c| self.fit(c, cells.get(c).map_or("", String::as_str)))
                .collect()
        };
        let header = fitted(&self.headers);
        let rows: Vec<(Vec<Vec<String>>, bool)> = self.rows.iter().map(|r| (fitted(&r.cells), r.highlight)).collect();
        let footer = self.footer.as_deref().map(fitted);
        let widths: Vec<usize> = (0..cols)
            .map(|c| {
                let all = rows
                    .iter()
                    .map(|(r, _)| &r[c])
                    .chain([&header[c]])
                    .chain(footer.iter().map(|f| &f[c]));
                all.flat_map(|lines| lines.iter().map(|l| text::width(l)))
                    .max()
                    .unwrap_or(0)
                    .max(1)
            })
            .collect();
        let aligns = (0..cols).map(|c| self.column_align(c)).collect();
        Layout {
            cols,
            header,
            rows,
            footer,
            widths,
            aligns,
        }
    }

    /// The band behind body row `n`: a pink tint when highlighted, a faint one on alternate
    /// rows when striped.
    fn band(&self, n: usize, marked: bool) -> Option<Rgb> {
        if marked {
            Some(mix(STRIPE, ROSE, 0.2))
        } else if self.striped && n % 2 == 1 {
            Some(STRIPE)
        } else {
            None
        }
    }

    /// The default look, framed or not: space between columns, a dotted line under the
    /// header, soft pink edges, and a little ✦ beside highlighted rows.
    fn soft(&self, l: &Layout) -> Vec<String> {
        let boxed = self.border == Border::Rounded;
        let inner = l.widths.iter().sum::<usize>() + 3 * l.cols.saturating_sub(1);
        let frame = |s: &str| paint(mix(LINE, ROSE, 0.35), s);
        let dots = |s: &str| paint(mix(BLUSH, TRACK, 0.55), s);
        // what goes between the frame's edges: a 2-column lead (where ✦ goes), the row, 2 spaces
        let wrap = |lead: &str, inside: String, band: Option<Rgb>| {
            if boxed {
                let inside = format!("{lead}{}  ", text::pad(&inside, inner));
                let inside = band.map_or_else(|| inside.clone(), |b| on_bg(b, &inside));
                format!("  {} {inside}{}", frame("│"), frame("│"))
            } else if let Some(b) = band {
                format!("{lead}{}", on_bg(b, &text::pad(&inside, inner)))
            } else {
                format!("{lead}{}", inside.trim_end())
            }
        };
        let blank = || wrap("  ", String::new(), None);
        let rule = || wrap("  ", dots(&"┈".repeat(inner)), None);
        let mut out = Vec::new();

        let title = self.title.as_deref().map(|t| bold(&paint(ROSE, &format!("✦ {t}"))));
        if boxed {
            let across = inner + 5;
            out.push(match &title {
                Some(t) => {
                    let t = text::truncate(&text::strip_ansi(t), across.saturating_sub(4));
                    let rest = across.saturating_sub(text::width(&t) + 3);
                    format!(
                        "  {}{}{}",
                        frame("╭─ "),
                        bold(&paint(ROSE, &t)),
                        frame(&format!(" {}╮", "─".repeat(rest)))
                    )
                }
                None => format!("  {}", frame(&format!("╭{}╮", "─".repeat(across)))),
            });
        } else if let Some(t) = &title {
            out.push(format!("  {t}"));
        }

        let heading = Look::heading();
        for line in self.cells(l, &l.header, &heading, "   ") {
            out.push(wrap("  ", line, None));
        }
        out.push(rule());
        // once any row wraps, a blank line between rows shows where each one ends
        let divided = l.rows.iter().any(|(r, _)| height(r) > 1);
        for (n, (cells, marked)) in l.rows.iter().enumerate() {
            if divided && n > 0 {
                out.push(blank());
            }
            let look = Look::body(*marked);
            let band = self.band(n, *marked);
            for (i, line) in self.cells(l, cells, &look, "   ").into_iter().enumerate() {
                let lead = if *marked && i == 0 {
                    format!("{} ", paint(ROSE, "✦"))
                } else {
                    "  ".into()
                };
                out.push(wrap(&lead, line, band));
            }
        }
        if let Some(footer) = &l.footer {
            out.push(rule());
            for line in self.cells(l, footer, &Look::footer(), "   ") {
                out.push(wrap("  ", line, None));
            }
        }
        if boxed {
            out.push(format!("  {}", frame(&format!("╰{}╯", "─".repeat(inner + 5)))));
        }
        out
    }

    /// The grid look: every column edged, square corners.
    fn grid(&self, l: &Layout) -> Vec<String> {
        let frame = |s: &str| paint(LINE, s);
        let inner = |s: &str| paint(mix(LINE, TRACK, 0.55), s);
        let faint = |s: &str| paint(mix(LINE, TRACK, 0.8), s);
        let sep = format!(" {} ", inner("│"));
        let row = |line: String, band: Option<Rgb>| {
            let inside = format!(" {line} ");
            let inside = band.map_or_else(|| inside.clone(), |b| on_bg(b, &inside));
            format!("  {}{inside}{}", frame("│"), frame("│"))
        };
        let rule = |left: &str, mid: &str, right: &str, line: &str, paint_it: &dyn Fn(&str) -> String| {
            let segs: Vec<String> = l.widths.iter().map(|w| line.repeat(w + 2)).collect();
            format!("  {}{}{}", frame(left), paint_it(&segs.join(mid)), frame(right))
        };
        let mut out = Vec::new();
        if let Some(t) = &self.title {
            out.push(format!("  {}", bold(&paint(ROSE, &format!("✦ {t}")))));
        }
        out.push(rule("┌", "┬", "┐", "─", &frame));
        for line in self.cells(l, &l.header, &Look::heading(), &sep) {
            out.push(row(line, None));
        }
        out.push(rule("├", "┼", "┤", "─", &frame));
        let divided = l.rows.iter().any(|(r, _)| height(r) > 1);
        for (n, (cells, marked)) in l.rows.iter().enumerate() {
            if divided && n > 0 {
                out.push(rule("├", &faint("┼"), "┤", "┄", &faint));
            }
            let band = self.band(n, *marked);
            for line in self.cells(l, cells, &Look::body(*marked), &sep) {
                out.push(row(line, band));
            }
        }
        if let Some(footer) = &l.footer {
            out.push(rule("├", "┼", "┤", "─", &inner));
            for line in self.cells(l, footer, &Look::footer(), &sep) {
                out.push(row(line, None));
            }
        }
        out.push(rule("└", "┴", "┘", "─", &frame));
        out
    }

    /// One table row as lines (several if a column wraps), cells padded and joined by `sep`.
    fn cells(&self, l: &Layout, cells: &[Vec<String>], look: &Look, sep: &str) -> Vec<String> {
        (0..height(cells))
            .map(|i| {
                let parts: Vec<String> = (0..l.cols)
                    .map(|c| {
                        let raw = cells[c].get(i).map_or("", String::as_str);
                        // plain cells get the row's colour; styled ones keep their own; an
                        // empty body cell gets a quiet dot, so it reads as empty, not missing,
                        // unless the table asks for blanks
                        let cell = if raw.contains('\x1b') {
                            raw.to_string()
                        } else if look.body && !self.blank && i == 0 && cells[c].iter().all(String::is_empty) {
                            paint(MUTED, "·")
                        } else if look.bold {
                            bold(&paint(look.color, raw))
                        } else {
                            paint(look.color, raw)
                        };
                        match l.aligns[c] {
                            Align::Left => text::pad(&cell, l.widths[c]),
                            Align::Right => text::pad_left(&cell, l.widths[c]),
                        }
                    })
                    .collect();
                parts.join(sep)
            })
            .collect()
    }

    /// Print the table.
    pub fn print(&self) {
        self.lines().print();
    }
}

/// The faint tint behind striped rows (redrawn light on light terminals).
const STRIPE: Rgb = Rgb(38, 32, 36);

struct Layout {
    cols: usize,
    header: Vec<Vec<String>>,
    rows: Vec<(Vec<Vec<String>>, bool)>,
    footer: Option<Vec<Vec<String>>>,
    widths: Vec<usize>,
    aligns: Vec<Align>,
}

/// How a row's plain cells are drawn.
struct Look {
    color: Rgb,
    bold: bool,
    /// Body rows show `·` in empty cells; headers and footers leave them blank.
    body: bool,
}

impl Look {
    fn heading() -> Look {
        Look {
            color: BLUSH,
            bold: true,
            body: false,
        }
    }

    fn body(marked: bool) -> Look {
        Look {
            color: if marked { ROSE } else { TEXT },
            bold: false,
            body: true,
        }
    }

    fn footer() -> Look {
        Look {
            color: TEXT,
            bold: true,
            body: false,
        }
    }
}

/// How many lines a row takes.
fn height(cells: &[Vec<String>]) -> usize {
    cells.iter().map(Vec::len).max().unwrap_or(1).max(1)
}

fn set<T: Clone + Default>(v: &mut Vec<T>, i: usize, value: T) {
    if i >= v.len() {
        v.resize(i + 1, T::default());
    }
    v[i] = value;
}

/// A cell as a number, scaled by its unit if it has one: `$1,200` → 1200, `1.5 MB` →
/// 1 500 000, `2m` → 120, `84ms` → 0.084.
fn parse_number(cell: &str) -> Option<f64> {
    let s: String = cell
        .trim()
        .trim_start_matches('$')
        .chars()
        .filter(|&c| c != ',')
        .collect();
    let end = s
        .char_indices()
        .find(|&(i, c)| !(c.is_ascii_digit() || c == '.' || (i == 0 && (c == '-' || c == '+'))))
        .map_or(s.len(), |(i, _)| i);
    let value: f64 = s[..end].parse().ok()?;
    let scale = match s[end..].trim() {
        "" | "%" | "B" | "s" | "x" | "×" => 1.0,
        "k" | "K" | "KB" | "kB" => 1e3,
        "M" | "MB" => 1e6,
        "G" | "GB" => 1e9,
        "T" | "TB" => 1e12,
        "KiB" => 1024.0,
        "MiB" => 1024f64.powi(2),
        "GiB" => 1024f64.powi(3),
        "TiB" => 1024f64.powi(4),
        "ns" => 1e-9,
        "µs" | "us" => 1e-6,
        "ms" => 1e-3,
        "m" | "min" => 60.0,
        "h" => 3600.0,
        "d" => 86400.0,
        _ => 1.0,
    };
    Some(value * scale)
}

impl fmt::Display for Table {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.lines().fmt(f)
    }
}

/// In debug builds, stop at a row with more cells than the table has headers: the extras
/// would be drawn under no header, which is never what was meant. Release builds draw them.
pub(crate) fn check_row(kind: &str, headers: &[String], cells: usize, row: usize) {
    debug_assert!(
        headers.is_empty() || cells <= headers.len(),
        "{kind} row {row} has {cells} cells, but the {kind} has {} headers ({}): add a header for each \
         extra cell, or leave the cell out",
        headers.len(),
        headers.join(", ")
    );
}

#[cfg(test)]
mod tests {
    use super::{Border, Table, parse_number};
    use crate::style::{ColorMode, set_color_mode};

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "Table row 1 has 3 cells, but the Table has 2 headers (app, size)")]
    fn a_row_wider_than_the_headers_is_stopped_in_debug_builds() {
        let _ = Table::new(["app", "size"])
            .row(["core", "34 MB"])
            .row(["web", "12 MB", "extra"]);
    }

    #[test]
    fn short_rows_and_headerless_tables_are_fine() {
        set_color_mode(ColorMode::None);
        let short = Table::new(["a", "b"]).row(["1"]).lines().plain();
        assert!(short.ends_with("1   ·"), "{short}");
        let none: [&str; 0] = [];
        let _ = Table::new(none).row(["any", "number", "of", "cells"]);
    }

    #[test]
    fn empty_cells_get_a_dot_unless_blank() {
        set_color_mode(ColorMode::None);
        let table = || {
            Table::new(["name", "owner", "n"])
                .row(["api", "", "1"])
                .row(["web", "ops", ""])
        };
        assert_eq!(
            table().lines().plain(),
            "  name   owner   n\n  ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈\n  api    ·       1\n  web    ops     ·"
        );
        assert_eq!(
            table().blank_cells().lines().plain(),
            "  name   owner   n\n  ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈\n  api            1\n  web    ops"
        );
        let grid = table().blank_cells().border(Border::Square).lines().plain();
        assert!(!grid.contains('·'), "{grid}");
    }

    #[test]
    fn numbers_understand_units() {
        assert_eq!(parse_number("$1,200"), Some(1200.0));
        assert_eq!(parse_number("1.5 MB"), Some(1.5e6));
        assert!(parse_number("900 KB") < parse_number("1.2 MB"));
        assert!(parse_number("45s") < parse_number("2m"));
        assert_eq!(parse_number("84ms"), Some(0.084));
        assert_eq!(parse_number("-3"), Some(-3.0));
        assert_eq!(parse_number("n/a"), None);
    }

    #[test]
    fn sorts_numbers_by_value_with_non_numbers_last() {
        set_color_mode(ColorMode::None);
        let names = |t: Table| -> Vec<String> {
            t.lines()
                .plain()
                .lines()
                .skip(2)
                .map(|l| l.split_whitespace().next().unwrap().to_string())
                .collect()
        };
        let table = || {
            Table::new(["name", "size"])
                .row(["a", "2 MB"])
                .row(["b", "n/a"])
                .row(["c", "900 KB"])
                .row(["d", "-"])
                .row(["e", "1 GiB"])
        };
        let table = || table().align(1, super::Align::Right);
        assert_eq!(names(table().sort_by(1)), ["c", "a", "e", "b", "d"]);
        assert_eq!(names(table().sort_by_desc(1)), ["e", "a", "c", "b", "d"]);
        assert_eq!(names(table().sort_by_desc(0)), ["e", "d", "c", "b", "a"]);
    }

    #[test]
    fn understands_every_unit() {
        let cases = [
            ("1 G", 1e9),
            ("1TB", 1e12),
            ("1 KiB", 1024.0),
            ("1MiB", 1024.0 * 1024.0),
            ("1 GiB", 1024f64.powi(3)),
            ("1 TiB", 1024f64.powi(4)),
            ("1ns", 1e-9),
            ("1µs", 1e-6),
            ("1 us", 1e-6),
            ("2h", 7200.0),
            ("1d", 86400.0),
            ("3 apples", 3.0),
        ];
        for (cell, want) in cases {
            assert_eq!(parse_number(cell), Some(want), "{cell}");
        }
    }

    #[test]
    fn titles_stripes_highlights_and_wrapped_grids() {
        set_color_mode(ColorMode::None);
        let table = Table::new(["name", "notes"])
            .row(["api", "short"])
            .row(["web", "a note long enough that it has to wrap onto another line"])
            .row(["db", "x"])
            .wrap(1, 20)
            .title("services")
            .striped()
            .highlight(0)
            .highlight(99);
        let plain = table.lines().plain();
        assert!(
            plain.starts_with("  ✦ services\n") && plain.contains("✦ api"),
            "{plain}"
        );
        let grid = table.clone().border(Border::Square).lines().plain();
        assert!(grid.starts_with("  ✦ services\n  ┌") && grid.contains("├┄"), "{grid}");
        let striped = crate::style::with_color_mode(ColorMode::TrueColor, || table.lines());
        assert!(striped.lines().iter().filter(|l| l.contains("\x1b[48;")).count() >= 2);
        assert_eq!(table.to_string(), table.lines().to_string());
        assert!(crate::output::capture(|| table.print()).contains("services"));
    }

    #[test]
    fn rounded_tables_box_plain_rows() {
        set_color_mode(ColorMode::None);
        let boxed = Table::new(["a"]).row(["1"]).border(Border::Rounded).lines().plain();
        assert!(boxed.contains("│") && boxed.contains("1"), "{boxed}");
    }

    #[test]
    fn boxed_and_square_tables_with_titles_stripes_and_footers() {
        set_color_mode(ColorMode::None);
        let table = || {
            Table::new(["name", "n"])
                .row(["a", "1"])
                .row(["b", "2"])
                .footer(["total", "3"])
                .title("counts")
                .striped()
        };
        let rounded = table().border(Border::Rounded).lines().plain();
        assert!(
            rounded.contains("╭─ ✦ counts") && rounded.contains("total"),
            "{rounded}"
        );
        let square = table().border(Border::Square).lines().plain();
        assert!(square.contains("total"), "{square}");
        let soft = table().lines().plain();
        assert!(soft.contains("total"), "{soft}");
        let painted = crate::style::with_color_mode(ColorMode::TrueColor, || table().border(Border::Rounded).lines());
        assert!(painted.lines().iter().any(|l| l.contains("\x1b[48;")));
    }
}