fast-rich 0.3.2

A Rust port of Python's Rich library for beautiful terminal formatting
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
//! Tables for displaying structured data.
//!
//! Tables support headers, multiple columns with alignment and width control,
//! and various border styles.

use crate::box_drawing::Line;
use crate::console::RenderContext;
use crate::panel::BorderStyle;
use crate::renderable::{Renderable, Segment};
use crate::style::Style;
use crate::text::{Span, Text};
use unicode_width::UnicodeWidthStr;

/// Column alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColumnAlign {
    #[default]
    Left,
    Center,
    Right,
}

/// Column width specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColumnWidth {
    /// Automatic width based on content
    #[default]
    Auto,
    /// Fixed width
    Fixed(usize),
    /// Min width
    Min(usize),
    /// Max width
    Max(usize),
}

/// A table column definition.
#[derive(Debug, Clone)]
pub struct Column {
    /// Column header
    pub header: String,
    /// Column alignment
    pub align: ColumnAlign,
    /// Column width
    pub width: ColumnWidth,
    /// Header style
    pub header_style: Style,
    /// Cell style
    pub style: Style,
    /// Whether to wrap content
    pub wrap: bool,
    /// Minimum width (computed, reserved for future use)
    #[allow(dead_code)]
    min_width: usize,
    /// Maximum width (computed, reserved for future use)
    #[allow(dead_code)]
    max_width: usize,
}

impl Column {
    /// Create a new column with a header.
    pub fn new(header: &str) -> Self {
        let header_width = UnicodeWidthStr::width(header);
        Column {
            header: header.to_string(),
            align: ColumnAlign::Left,
            width: ColumnWidth::Auto,
            header_style: Style::new().bold(),
            style: Style::new(),
            wrap: true,
            min_width: header_width,
            max_width: header_width,
        }
    }

    /// Set the column alignment.
    pub fn align(mut self, align: ColumnAlign) -> Self {
        self.align = align;
        self
    }

    /// Set the column width.
    pub fn width(mut self, width: ColumnWidth) -> Self {
        self.width = width;
        self
    }

    /// Set the header style.
    pub fn header_style(mut self, style: Style) -> Self {
        self.header_style = style;
        self
    }

    /// Set the cell style.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set whether to wrap content.
    pub fn wrap(mut self, wrap: bool) -> Self {
        self.wrap = wrap;
        self
    }

    /// Center align shorthand.
    pub fn center(self) -> Self {
        self.align(ColumnAlign::Center)
    }

    /// Right align shorthand.
    pub fn right(self) -> Self {
        self.align(ColumnAlign::Right)
    }
}

/// A row of table cells.
#[derive(Debug, Clone)]
pub struct Row {
    cells: Vec<Text>,
    style: Option<Style>,
}

impl Row {
    /// Create a new row with cells.
    pub fn new<I, T>(cells: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Text>,
    {
        Row {
            cells: cells.into_iter().map(Into::into).collect(),
            style: None,
        }
    }

    /// Set a style for the entire row.
    pub fn style(mut self, style: Style) -> Self {
        self.style = Some(style);
        self
    }
}

// Removed TableBorderChars struct and implementation

/// A table for displaying structured data.
#[derive(Debug, Clone)]
pub struct Table {
    /// Column definitions
    columns: Vec<Column>,
    /// Data rows
    rows: Vec<Row>,
    /// Border style
    border_style: BorderStyle,
    /// Border style (colors etc)
    style: Style,
    /// Show header row
    show_header: bool,
    /// Show border
    show_border: bool,
    /// Show row separators
    show_row_lines: bool,
    /// Padding in cells
    padding: usize,
    /// Title
    title: Option<String>,
    /// Expand to full width
    expand: bool,
}

impl Default for Table {
    fn default() -> Self {
        Self::new()
    }
}

impl Table {
    /// Create a new empty table.
    pub fn new() -> Self {
        Table {
            columns: Vec::new(),
            rows: Vec::new(),
            border_style: BorderStyle::Rounded,
            style: Style::new(),
            show_header: true,
            show_border: true,
            show_row_lines: false,
            padding: 1,
            title: None,
            expand: false,
        }
    }

    /// Add a column to the table.
    pub fn add_column<C: Into<Column>>(&mut self, column: C) -> &mut Self {
        self.columns.push(column.into());
        self
    }

    /// Add a column by header name.
    pub fn column(mut self, header: &str) -> Self {
        self.columns.push(Column::new(header));
        self
    }

    /// Add multiple columns by header names.
    pub fn columns<I, S>(mut self, headers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for header in headers {
            self.columns.push(Column::new(header.as_ref()));
        }
        self
    }

    /// Add a row to the table.
    pub fn add_row<I, T>(&mut self, cells: I) -> &mut Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Text>,
    {
        self.rows.push(Row::new(cells));
        self
    }

    /// Add a row from string slices (convenience method).
    pub fn add_row_strs(&mut self, cells: &[&str]) -> &mut Self {
        let text_cells: Vec<Text> = cells.iter().map(|s| Text::plain(s.to_string())).collect();
        self.rows.push(Row {
            cells: text_cells,
            style: None,
        });
        self
    }

    /// Add a Row object to the table.
    pub fn add_row_obj(&mut self, row: Row) -> &mut Self {
        self.rows.push(row);
        self
    }

    /// Set the border style.
    pub fn border_style(mut self, style: BorderStyle) -> Self {
        self.border_style = style;
        self
    }

    /// Set the table style (border colors).
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set the table title.
    pub fn set_title(mut self, title: &str) -> Self {
        self.title = Some(title.to_string());
        self
    }

    /// Set whether to show the header.
    pub fn show_header(mut self, show: bool) -> Self {
        self.show_header = show;
        self
    }

    /// Set whether to show the border.
    pub fn show_border(mut self, show: bool) -> Self {
        self.show_border = show;
        self
    }

    /// Set whether to show row separator lines.
    pub fn show_row_lines(mut self, show: bool) -> Self {
        self.show_row_lines = show;
        self
    }

    /// Set cell padding.
    pub fn padding(mut self, padding: usize) -> Self {
        self.padding = padding;
        self
    }

    /// Set the table title.
    pub fn title(mut self, title: &str) -> Self {
        self.title = Some(title.to_string());
        self
    }

    /// Set whether to expand to full width.
    pub fn expand(mut self, expand: bool) -> Self {
        self.expand = expand;
        self
    }

    /// Calculate column widths based on content.
    fn calculate_widths(&self, available_width: usize) -> Vec<usize> {
        let num_cols = self.columns.len();
        if num_cols == 0 {
            return vec![];
        }

        // Calculate content widths
        let mut max_widths: Vec<usize> = self
            .columns
            .iter()
            .map(|c| UnicodeWidthStr::width(c.header.as_str()))
            .collect();

        for row in &self.rows {
            for (i, cell) in row.cells.iter().enumerate() {
                if i < max_widths.len() {
                    max_widths[i] = max_widths[i].max(cell.width());
                }
            }
        }

        // Calculate overhead (borders, padding)
        let overhead = if self.show_border {
            1 + num_cols + 1 + (self.padding * 2 * num_cols)
        } else {
            (num_cols - 1) + (self.padding * 2 * num_cols)
        };

        let content_width = available_width.saturating_sub(overhead);

        // Simple proportional distribution
        let total_content: usize = max_widths.iter().sum();
        if total_content == 0 {
            return vec![content_width / num_cols.max(1); num_cols];
        }

        if total_content <= content_width {
            // Everything fits
            if self.expand {
                // Distribute extra space
                let extra = content_width - total_content;
                let per_col = extra / num_cols;
                max_widths.iter().map(|w| w + per_col).collect()
            } else {
                max_widths
            }
        } else {
            // Need to shrink - proportional distribution
            max_widths
                .iter()
                .map(|w| {
                    let ratio = *w as f64 / total_content as f64;
                    ((content_width as f64 * ratio) as usize).max(1)
                })
                .collect()
        }
    }

    fn render_horizontal_line(&self, widths: &[usize], line: &Line) -> Segment {
        let mut spans = vec![Span::styled(line.left.to_string(), self.style)];

        for (i, &width) in widths.iter().enumerate() {
            let cell_width = width + self.padding * 2;
            spans.push(Span::styled(
                line.mid.to_string().repeat(cell_width),
                self.style,
            ));
            if i < widths.len() - 1 {
                spans.push(Span::styled(line.cross.to_string(), self.style));
            }
        }

        spans.push(Span::styled(line.right.to_string(), self.style));
        Segment::line(spans)
    }

    fn render_row(
        &self,
        cells: &[Text],
        widths: &[usize],
        line: &Line,
        cell_styles: &[Style],
    ) -> Vec<Segment> {
        // For simplicity, render single-line rows
        // A full implementation would handle wrapping
        let mut spans = Vec::new();

        if self.show_border {
            spans.push(Span::styled(line.left.to_string(), self.style));
        }

        for (i, width) in widths.iter().enumerate() {
            let cell = cells.get(i);
            let content = cell.map(|c| c.plain_text()).unwrap_or_default();
            let _content_width = UnicodeWidthStr::width(content.as_str());
            let cell_style = cell_styles.get(i).copied().unwrap_or_default();

            let align = self.columns.get(i).map(|c| c.align).unwrap_or_default();
            let padded = pad_string(&content, *width, align);

            // Add padding
            spans.push(Span::raw(" ".repeat(self.padding)));
            spans.push(Span::styled(padded, cell_style));
            spans.push(Span::raw(" ".repeat(self.padding)));

            if i < widths.len() - 1 {
                spans.push(Span::styled(line.cross.to_string(), self.style));
            } else if self.show_border {
                spans.push(Span::styled(line.right.to_string(), self.style));
            }
        }

        vec![Segment::line(spans)]
    }
}

fn pad_string(s: &str, width: usize, align: ColumnAlign) -> String {
    let content_width = UnicodeWidthStr::width(s);
    if content_width >= width {
        return truncate_string(s, width);
    }

    let padding = width - content_width;
    match align {
        ColumnAlign::Left => format!("{}{}", s, " ".repeat(padding)),
        ColumnAlign::Right => format!("{}{}", " ".repeat(padding), s),
        ColumnAlign::Center => {
            let left = padding / 2;
            let right = padding - left;
            format!("{}{}{}", " ".repeat(left), s, " ".repeat(right))
        }
    }
}

fn truncate_string(s: &str, width: usize) -> String {
    use unicode_segmentation::UnicodeSegmentation;

    let mut result = String::new();
    let mut current_width = 0;

    for grapheme in s.graphemes(true) {
        let grapheme_width = UnicodeWidthStr::width(grapheme);
        if current_width + grapheme_width > width {
            if width > 1 && current_width < width {
                result.push('…');
            }
            break;
        }
        result.push_str(grapheme);
        current_width += grapheme_width;
    }

    // Pad if shorter
    while current_width < width {
        result.push(' ');
        current_width += 1;
    }

    result
}

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

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

impl Renderable for Table {
    fn render(&self, context: &RenderContext) -> Vec<Segment> {
        if self.columns.is_empty() {
            return vec![];
        }

        let box_chars = self.border_style.to_box();
        let widths = self.calculate_widths(context.width);
        let mut segments = Vec::new();

        // Calculate total table width for title centering
        let content_width: usize = widths.iter().map(|w| w + self.padding * 2).sum();
        let border_overhead = if self.show_border {
            widths.len() + 1
        } else {
            widths.len() - 1
        };
        let table_width = content_width + border_overhead;

        // Title
        if let Some(title) = &self.title {
            let title_width = UnicodeWidthStr::width(title.as_str());
            if title_width <= table_width {
                let padding = table_width - title_width;
                let left_pad = padding / 2;
                let right_pad = padding - left_pad;

                let mut spans = Vec::new();
                if left_pad > 0 {
                    spans.push(Span::raw(" ".repeat(left_pad)));
                }
                spans.push(Span::styled(title.clone(), Style::new().bold()));
                if right_pad > 0 {
                    spans.push(Span::raw(" ".repeat(right_pad)));
                }
                segments.push(Segment::line(spans));
            } else {
                // Truncate or just print? Just print for now.
                segments.push(Segment::line(vec![Span::styled(
                    title.clone(),
                    Style::new().bold(),
                )]));
            }
        }

        // Top border
        if self.show_border {
            segments.push(self.render_horizontal_line(&widths, &box_chars.top));
        }

        // Header row
        if self.show_header {
            let header_cells: Vec<Text> = self
                .columns
                .iter()
                .map(|c| Text::styled(c.header.clone(), c.header_style))
                .collect();
            let header_styles: Vec<Style> = self.columns.iter().map(|c| c.header_style).collect();
            // Use header box line for vertical separators in header
            segments.extend(self.render_row(
                &header_cells,
                &widths,
                &box_chars.header,
                &header_styles,
            ));

            // Header separator
            if self.show_border || self.show_row_lines {
                segments.push(self.render_horizontal_line(&widths, &box_chars.head));
            }
        }

        // Data rows
        for (row_idx, row) in self.rows.iter().enumerate() {
            let cell_styles: Vec<Style> = self.columns.iter().map(|c| c.style).collect();
            // Use cell box line for vertical separators in body
            segments.extend(self.render_row(&row.cells, &widths, &box_chars.cell, &cell_styles));

            // Row separator
            if self.show_row_lines && row_idx < self.rows.len() - 1 {
                segments.push(self.render_horizontal_line(&widths, &box_chars.mid));
            }
        }

        // Bottom border
        if self.show_border {
            segments.push(self.render_horizontal_line(&widths, &box_chars.bottom));
        }

        segments
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_table_basic() {
        let mut table = Table::new();
        table.add_column("Name");
        table.add_column("Age");
        table.add_row_strs(&["Alice", "30"]);
        table.add_row_strs(&["Bob", "25"]);

        let context = RenderContext {
            width: 40,
            height: None,
        };
        let segments = table.render(&context);

        assert!(!segments.is_empty());

        // Check that output contains our data
        let text: String = segments.iter().map(|s| s.plain_text()).collect();
        assert!(text.contains("Name"));
        assert!(text.contains("Alice"));
        assert!(text.contains("Bob"));
    }

    #[test]
    fn test_table_builder() {
        let table = Table::new()
            .columns(["A", "B", "C"])
            .border_style(BorderStyle::Square);

        assert_eq!(table.columns.len(), 3);
    }

    #[test]
    fn test_pad_string() {
        assert_eq!(pad_string("hi", 5, ColumnAlign::Left), "hi   ");
        assert_eq!(pad_string("hi", 5, ColumnAlign::Right), "   hi");
        assert_eq!(pad_string("hi", 5, ColumnAlign::Center), " hi  ");
    }
}