Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287use crate::block::{Block, BorderStyle};use crate::style::{self, Align, Line, Span, Style};
/// How to size a table column.#[derive(Debug, Clone)]pub enum ColumnWidth { /// Exactly this many characters wide. Fixed(usize), /// Fit the widest content (header or cell). Auto, /// Take a proportional share of leftover space after Fixed/Auto columns. Flex(usize),}
/// A table with optional headers, rows, configurable column widths, and borders.#[derive(Debug, Clone)]pub struct Table { headers: Option<Vec<Line>>, rows: Vec<Vec<Line>>, column_widths: Vec<ColumnWidth>, border: BorderStyle, header_style: Option<Style>,}
impl Table { pub fn new(rows: Vec<Vec<Line>>) -> Self { Table { headers: None, rows, column_widths: Vec::new(), border: BorderStyle::NoBorder, header_style: None, } }
pub fn headers(self, headers: Vec<Line>) -> Self { Self { headers: Some(headers), ..self } }
pub fn column_widths(self, widths: Vec<ColumnWidth>) -> Self { Self { column_widths: widths, ..self } }
pub fn border(self, border: BorderStyle) -> Self { Self { border, ..self } }
pub fn header_style(self, style: Style) -> Self { Self { header_style: Some(style), ..self } }
/// Render the table into a Block at `available_width` columns. pub fn to_block(&self, available_width: usize) -> Block { let num_cols = self.column_count(); if num_cols == 0 { return Block::text(vec![]); }
let resolved = self.resolve_widths(available_width, num_cols); let mut lines: Vec<Line> = Vec::new();
// Render header row if let Some(headers) = &self.headers { let header_style = self .header_style .clone() .unwrap_or_else(|| Style::new().bold()); let row_line = render_row(headers, &resolved, Some(&header_style)); lines.push(row_line);
// Separator line let sep: String = resolved .iter() .map(|&w| "-".repeat(w)) .collect::<Vec<_>>() .join("-"); lines.push(vec![Span::plain(sep)]); }
// Render data rows for row in &self.rows { lines.push(render_row(row, &resolved, None)); }
let content = Block::text(lines); match &self.border { BorderStyle::NoBorder => content, b => Block::boxed(content, b.clone(), None), } }
fn column_count(&self) -> usize { let from_headers = self.headers.as_ref().map(|h| h.len()).unwrap_or(0); let from_rows = self.rows.iter().map(|r| r.len()).max().unwrap_or(0); from_headers.max(from_rows) }
fn resolve_widths(&self, available: usize, num_cols: usize) -> Vec<usize> { // Build per-column natural widths (max of header + all cells). let mut natural: Vec<usize> = vec![0; num_cols]; if let Some(headers) = &self.headers { for (i, h) in headers.iter().enumerate().take(num_cols) { natural[i] = natural[i].max(style::measure_line(h)); } } for row in &self.rows { for (i, cell) in row.iter().enumerate().take(num_cols) { natural[i] = natural[i].max(style::measure_line(cell)); } }
let specs: Vec<&ColumnWidth> = if self.column_widths.len() >= num_cols { self.column_widths[..num_cols].iter().collect() } else { // Pad missing specs with Auto let mut v: Vec<&ColumnWidth> = self.column_widths.iter().collect(); let auto_fallback = &ColumnWidth::Auto; while v.len() < num_cols { v.push(auto_fallback); } v };
// Gap between columns (1 space separator per gap) let gap_total = num_cols.saturating_sub(1); let total_content = available.saturating_sub(gap_total);
// Pass 1: Fixed and Auto. let mut resolved = vec![0usize; num_cols]; let mut used = 0usize; let mut flex_total_weight = 0usize;
for (i, spec) in specs.iter().enumerate() { match spec { ColumnWidth::Fixed(w) => { resolved[i] = *w; used += w; } ColumnWidth::Auto => { resolved[i] = natural[i]; used += natural[i]; } ColumnWidth::Flex(w) => { flex_total_weight += w; } } }
// Pass 2: Flex columns split the remainder. let remaining = total_content.saturating_sub(used); if flex_total_weight > 0 { let mut distributed = 0; let mut last_flex = usize::MAX; for (i, spec) in specs.iter().enumerate() { if let ColumnWidth::Flex(w) = spec { if i == specs.len() - 1 || last_flex == usize::MAX { last_flex = i; } let share = (remaining * w) / flex_total_weight; resolved[i] = share.max(1); distributed += resolved[i]; } } // Give any rounding remainder to the last flex column. if last_flex < num_cols && distributed < remaining { resolved[last_flex] += remaining - distributed; } }
resolved }}
fn render_row(cells: &[Line], widths: &[usize], style_override: Option<&Style>) -> Line { let mut line: Line = Vec::new(); for (i, w) in widths.iter().enumerate() { if i > 0 { line.push(Span::plain(" ")); } let cell = cells.get(i).cloned().unwrap_or_default(); let truncated = style::truncate_line(&cell, *w); let padded = style::pad_line(&truncated, *w, Align::Left); if let Some(s) = style_override { for span in padded { line.push(Span::styled(span.text().to_string(), s.clone())); } } else { line.extend(padded); } } line}
#[cfg(test)]mod tests { use super::*;
fn pl(s: &str) -> Line { vec![Span::plain(s)] }
fn rows(data: &[&[&str]]) -> Vec<Vec<Line>> { data.iter() .map(|row| row.iter().map(|cell| pl(cell)).collect()) .collect() }
#[test] fn basic_render() { let t = Table::new(rows(&[&["Alice", "30"], &["Bob", "25"]])); let block = t.to_block(20); let lines = block.render(20); assert_eq!(lines.len(), 2); assert!(lines[0].contains("Alice")); assert!(lines[1].contains("Bob")); }
#[test] fn with_headers() { let t = Table::new(rows(&[&["Alice", "30"]])).headers(vec![pl("Name"), pl("Age")]); let block = t.to_block(20); let lines = block.render(20); // Header + separator + 1 data row = 3 lines assert_eq!(lines.len(), 3); assert!(lines[0].contains("Name")); assert!(lines[1].contains("---")); }
#[test] fn fixed_column_width() { let t = Table::new(rows(&[&["hi", "there"]])) .column_widths(vec![ColumnWidth::Fixed(5), ColumnWidth::Fixed(8)]); let block = t.to_block(30); let lines = block.render(30); // First cell padded to 5, gap, second to 8 = "hi there " (5+1+8=14 chars) let stripped: String = lines[0].chars().take(14).collect(); assert_eq!(stripped, "hi there "); }
#[test] fn auto_column_width() { let t = Table::new(rows(&[&["short", "longer text"]])) .column_widths(vec![ColumnWidth::Auto, ColumnWidth::Auto]); let block = t.to_block(40); let lines = block.render(40); assert!(lines[0].contains("short")); assert!(lines[0].contains("longer text")); }
#[test] fn flex_columns_share_space() { let t = Table::new(rows(&[&["a", "b"]])) .column_widths(vec![ColumnWidth::Flex(1), ColumnWidth::Flex(1)]); let block = t.to_block(20); let lines = block.render(20); // Should render without panicking and produce 1 line assert_eq!(lines.len(), 1); }
#[test] fn with_border() { let t = Table::new(rows(&[&["hello"]])).border(BorderStyle::Single); let block = t.to_block(15); let lines = block.render(15); // top border + content + bottom border assert_eq!(lines.len(), 3); assert!(lines[0].starts_with('┌')); }
#[test] fn empty_table() { let t = Table::new(vec![]); let block = t.to_block(20); let lines = block.render(20); assert_eq!(lines.len(), 0); }}