use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;
use crate::ansi::{Piece, Pieces};
use crate::measure::Width;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Align {
#[default]
Left,
Center,
Right,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Sizing {
#[default]
Auto,
Fixed(usize),
Max(usize),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Border {
#[default]
Light,
Heavy,
Ascii,
Markdown,
None,
}
impl Border {
fn glyphs(self) -> Option<[&'static str; 11]> {
Some(match self {
Border::Light => ["─", "│", "┌", "┬", "┐", "├", "┼", "┤", "└", "┴", "┘"],
Border::Heavy => ["━", "┃", "┏", "┳", "┓", "┣", "╋", "┫", "┗", "┻", "┛"],
Border::Ascii => ["-", "|", "+", "+", "+", "+", "+", "+", "+", "+", "+"],
Border::Markdown => ["-", "|", "", "", "", "|", "|", "|", "", "", ""],
Border::None => return None,
})
}
}
#[derive(Clone, Debug)]
struct Column {
header: String,
align: Align,
sizing: Sizing,
}
#[derive(Clone, Debug, Default)]
pub struct Table {
columns: Vec<Column>,
rows: Vec<Vec<String>>,
border: Border,
width: Width,
padding: usize,
header: bool,
}
impl Table {
pub fn new() -> Self {
Table {
columns: Vec::new(),
rows: Vec::new(),
border: Border::Light,
width: Width::DEFAULT,
padding: 1,
header: true,
}
}
pub fn column(self, header: impl Into<String>) -> Self {
self.column_with(header, Align::Left, Sizing::Auto)
}
pub fn column_aligned(self, header: impl Into<String>, align: Align) -> Self {
self.column_with(header, align, Sizing::Auto)
}
pub fn column_with(mut self, header: impl Into<String>, align: Align, sizing: Sizing) -> Self {
self.columns.push(Column {
header: header.into(),
align,
sizing,
});
self
}
pub fn row<I, S>(mut self, cells: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let mut row: Vec<String> = cells.into_iter().map(Into::into).collect();
row.truncate(self.columns.len());
while row.len() < self.columns.len() {
row.push(String::new());
}
self.rows.push(row);
self
}
pub fn border(mut self, border: Border) -> Self {
self.border = border;
self
}
pub fn padding(mut self, cells: usize) -> Self {
self.padding = cells;
self
}
pub fn with_header(mut self, show: bool) -> Self {
self.header = show;
self
}
pub fn measured_by(mut self, width: Width) -> Self {
self.width = width;
self
}
}
impl Table {
fn cell_text<'b>(&self, s: &'b str) -> Cow<'b, str> {
if s.bytes().all(|b| b == b'\n' || (0x20..0x7F).contains(&b)) {
return Cow::Borrowed(s);
}
let mut cur = self.sanitise(s);
loop {
let next = self.sanitise(&cur);
if next == cur {
return Cow::Owned(cur);
}
cur = next;
}
}
fn sanitise(&self, s: &str) -> String {
let mut out = String::with_capacity(s.len() + 8);
let mut col = 0;
for piece in Pieces::new(s) {
match piece {
Piece::Escape(e) if e.contains('\n') || e.contains('\r') => {}
Piece::Escape(e) => out.push_str(e),
Piece::Text(t) => {
for g in crate::grapheme::Graphemes::new(t) {
if g.chars().all(|c| c.is_control() && c != '\n' && c != '\t') {
continue;
}
if g == "\t" {
let advance = self.width.of_at("\t", col).max(1);
for _ in 0..advance {
out.push(' ');
}
col += advance;
} else {
out.push_str(g);
col += self.width.of_at(g, col);
}
}
}
}
}
if out
.chars()
.next()
.is_some_and(crate::grapheme::attaches_to_previous)
{
out.insert(0, '\u{25CC}');
}
out
}
pub fn render(&self, max_width: Option<usize>) -> String {
if self.columns.is_empty() {
return String::new();
}
let widths = self.resolve_widths(max_width);
let g = self.border.glyphs();
let pad = self.padding;
let mut out = String::new();
let rule = |left: &str, mid: &str, right: &str, h: &str| -> String {
let mut r = String::from(left);
for (i, w) in widths.iter().enumerate() {
for _ in 0..w + pad * 2 {
r.push_str(h);
}
r.push_str(if i + 1 == widths.len() { right } else { mid });
}
r
};
if let Some(gl) = g {
if self.border != Border::Markdown {
out.push_str(&rule(gl[2], gl[3], gl[4], gl[0]));
out.push('\n');
}
}
if self.header {
let cells: Vec<&str> = self.columns.iter().map(|c| c.header.as_str()).collect();
self.push_row(&mut out, &cells, &widths, g);
if let Some(gl) = g {
out.push_str(&rule(gl[5], gl[6], gl[7], gl[0]));
out.push('\n');
}
}
for row in &self.rows {
let cells: Vec<&str> = row.iter().map(String::as_str).collect();
self.push_row(&mut out, &cells, &widths, g);
}
if let Some(gl) = g {
if self.border != Border::Markdown {
out.push_str(&rule(gl[8], gl[9], gl[10], gl[0]));
out.push('\n');
}
}
while out.ends_with('\n') {
out.pop();
}
out
}
fn push_row(
&self,
out: &mut String,
cells: &[&str],
widths: &[usize],
g: Option<[&'static str; 11]>,
) {
let wrapped: Vec<Vec<String>> = cells
.iter()
.zip(widths)
.map(|(c, &w)| self.width.wrap(&self.cell_text(c), w.max(1)))
.collect();
let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
for line in 0..height {
if let Some(gl) = g {
out.push_str(gl[1]);
}
for (i, &w) in widths.iter().enumerate() {
let text = wrapped[i].get(line).map(String::as_str).unwrap_or("");
if g.is_some() {
for _ in 0..self.padding {
out.push(' ');
}
} else if i > 0 {
out.push_str(" ");
}
out.push_str(&self.align_cell(text, w, self.columns[i].align));
if let Some(gl) = g {
for _ in 0..self.padding {
out.push(' ');
}
out.push_str(gl[1]);
}
}
out.push('\n');
}
}
fn align_cell<'b>(&self, text: &'b str, w: usize, align: Align) -> Cow<'b, str> {
let fitted = self.width.cell(text, w);
match align {
Align::Left => fitted,
Align::Right => {
let have = self.width.of(text);
if have >= w {
fitted
} else {
self.width.pad_start(text, w)
}
}
Align::Center => {
let have = self.width.of(text);
if have >= w {
fitted
} else {
self.width.center(text, w)
}
}
}
}
fn resolve_widths(&self, max_width: Option<usize>) -> Vec<usize> {
let n = self.columns.len();
let mut widths: Vec<usize> = self
.columns
.iter()
.enumerate()
.map(|(i, c)| {
let header = if self.header {
self.width.of(&self.cell_text(&c.header))
} else {
0
};
let body = self
.rows
.iter()
.map(|r| self.width.of(&self.cell_text(&r[i])))
.max()
.unwrap_or(0);
match c.sizing {
Sizing::Fixed(w) => w,
Sizing::Max(w) => header.max(body).min(w),
Sizing::Auto => header.max(body),
}
})
.collect();
let Some(limit) = max_width else {
return widths;
};
let chrome = match self.border {
Border::None => 2 * n.saturating_sub(1),
_ => (n + 1) + 2 * self.padding * n,
};
let mut total: usize = widths.iter().sum::<usize>() + chrome;
if total <= limit {
return widths;
}
let floor = 1;
while let Some((i, _)) = widths
.iter()
.enumerate()
.filter(|(i, &w)| w > floor && !matches!(self.columns[*i].sizing, Sizing::Fixed(_)))
.max_by_key(|(_, &w)| w)
{
widths[i] -= 1;
total -= 1;
if total <= limit {
break;
}
}
widths
}
}