use std::num::NonZeroU16;
use unicode_segmentation::UnicodeSegmentation;
use crate::layout::display_width;
use crate::{Doc, HumanText, TokenId, tokens};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Cell {
pub text: HumanText,
pub token: TokenId,
}
impl Cell {
pub fn new(text: impl AsRef<str>, token: TokenId) -> Self {
Self {
text: HumanText::sanitize(text),
token,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Alignment {
Left,
Center,
Right,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Overflow {
Clip,
TruncateEnd,
TruncateMiddle,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FixedColumn {
pub width: NonZeroU16,
pub alignment: Alignment,
pub overflow: Overflow,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FixedTableOptions {
pub gutter_width: u16,
}
impl Default for FixedTableOptions {
fn default() -> Self {
Self { gutter_width: 1 }
}
}
pub struct FixedTable<const N: usize> {
pub(crate) columns: [FixedColumn; N],
pub(crate) options: FixedTableOptions,
pub(crate) header: Option<[Cell; N]>,
pub(crate) rows: Vec<[Cell; N]>,
}
impl<const N: usize> FixedTable<N> {
pub fn new(columns: [FixedColumn; N], options: FixedTableOptions) -> Result<Self, TableError> {
if N == 0 {
return Err(TableError::NoColumns);
}
Ok(Self {
columns,
options,
header: None,
rows: Vec::new(),
})
}
pub fn header(&mut self, cells: [Cell; N]) -> &mut Self {
self.header = Some(cells);
self
}
pub fn row(&mut self, cells: [Cell; N]) -> &mut Self {
self.rows.push(cells);
self
}
pub fn to_doc(&self) -> Doc {
records_doc(
fixed_records(self)
.into_iter()
.map(|record| (record.header, record.cells)),
" ".repeat(usize::from(self.options.gutter_width)),
)
}
}
pub(crate) struct FixedRecord {
pub(crate) header: bool,
pub(crate) cells: Vec<(String, TokenId)>,
}
pub(crate) fn fixed_records<const N: usize>(table: &FixedTable<N>) -> Vec<FixedRecord> {
let mut records = Vec::with_capacity(table.rows.len() + usize::from(table.header.is_some()));
if let Some(header) = &table.header {
records.push(fixed_record(header, &table.columns, true));
}
records.extend(
table
.rows
.iter()
.map(|row| fixed_record(row, &table.columns, false)),
);
records
}
fn fixed_record<const N: usize>(
cells: &[Cell; N],
columns: &[FixedColumn; N],
header: bool,
) -> FixedRecord {
let mut rendered = Vec::with_capacity(N);
for index in 0..N {
let final_cell = index + 1 == N;
let value = format_cell(cells[index].text.as_str(), columns[index], final_cell);
let token = if header {
tokens::TABLE_HEADER
} else {
cells[index].token.clone()
};
rendered.push((value, token));
}
FixedRecord {
header,
cells: rendered,
}
}
fn records_doc(
records: impl IntoIterator<Item = (bool, Vec<(String, TokenId)>)>,
separator: String,
) -> Doc {
let separator = Doc::token_text(tokens::TABLE_SEPARATOR, separator);
let rows = records
.into_iter()
.map(|(header, cells)| {
let cells = cells.into_iter().map(|(text, token)| {
let roles = if header {
vec![tokens::TABLE_HEADER_CELL, tokens::TABLE_HEADER]
} else {
vec![tokens::TABLE_CELL, token]
};
Doc::tokens(roles, Doc::text(text))
});
let role = if header {
tokens::TABLE_HEADER_ROW
} else {
tokens::TABLE_ROW
};
Doc::token(role, Doc::join(separator.clone(), cells))
})
.collect::<Vec<_>>();
if rows.is_empty() {
Doc::empty()
} else {
Doc::token(tokens::TABLE, Doc::join(Doc::hard_line(), rows))
}
}
fn format_cell(value: &str, column: FixedColumn, final_cell: bool) -> String {
let width = usize::from(column.width.get());
let value = match column.overflow {
Overflow::Clip => clip(value, width),
Overflow::TruncateEnd => truncate_end(value, width),
Overflow::TruncateMiddle => truncate_middle(value, width),
};
let padding = width.saturating_sub(display_width(&value));
let (left, right) = match column.alignment {
Alignment::Left => (0, padding),
Alignment::Center => (padding.div_ceil(2), padding / 2),
Alignment::Right => (padding, 0),
};
let mut formatted = String::with_capacity(value.len() + padding);
formatted.push_str(&" ".repeat(left));
formatted.push_str(&value);
formatted.push_str(&" ".repeat(right));
if final_cell {
formatted.truncate(formatted.trim_end_matches(' ').len());
}
formatted
}
fn clip(value: &str, width: usize) -> String {
take_prefix(value, width).0
}
fn truncate_end(value: &str, width: usize) -> String {
if display_width(value) <= width {
return value.to_owned();
}
let marker = "…";
let marker_width = display_width(marker);
if width < marker_width {
return clip(value, width);
}
let (mut prefix, _) = take_prefix(value, width - marker_width);
prefix.push_str(marker);
prefix
}
fn truncate_middle(value: &str, width: usize) -> String {
if display_width(value) <= width {
return value.to_owned();
}
let marker = "…";
let marker_width = display_width(marker);
if width < marker_width {
return clip(value, width);
}
let graphemes = UnicodeSegmentation::graphemes(value, true).collect::<Vec<_>>();
let remaining = width - marker_width;
let prefix_target = remaining.div_ceil(2);
let suffix_target = remaining / 2;
let mut prefix_end = 0usize;
let mut prefix_width = 0usize;
while prefix_end < graphemes.len() {
let next_width = display_width(graphemes[prefix_end]);
if prefix_width + next_width > prefix_target {
break;
}
prefix_width += next_width;
prefix_end += 1;
}
let mut suffix_start = graphemes.len();
let mut suffix_width = 0usize;
while suffix_start > prefix_end {
let next_width = display_width(graphemes[suffix_start - 1]);
if suffix_width + next_width > suffix_target {
break;
}
suffix_start -= 1;
suffix_width += next_width;
}
let mut unused = remaining.saturating_sub(prefix_width + suffix_width);
loop {
let mut changed = false;
if prefix_end < suffix_start {
let next_width = display_width(graphemes[prefix_end]);
if next_width <= unused {
prefix_end += 1;
unused -= next_width;
changed = true;
}
}
if suffix_start > prefix_end {
let next_width = display_width(graphemes[suffix_start - 1]);
if next_width <= unused {
suffix_start -= 1;
unused -= next_width;
changed = true;
}
}
if !changed || unused == 0 {
break;
}
}
let mut truncated = String::new();
truncated.extend(graphemes[..prefix_end].iter().copied());
truncated.push_str(marker);
truncated.extend(graphemes[suffix_start..].iter().copied());
truncated
}
fn take_prefix(value: &str, width: usize) -> (String, usize) {
let mut prefix = String::new();
let mut used = 0usize;
for grapheme in UnicodeSegmentation::graphemes(value, true) {
let grapheme_width = display_width(grapheme);
if used + grapheme_width > width {
break;
}
prefix.push_str(grapheme);
used += grapheme_width;
}
(prefix, used)
}
#[cfg(feature = "adaptive-tables")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AdaptiveColumn {
pub min_width: NonZeroU16,
pub max_width: NonZeroU16,
pub alignment: Alignment,
}
#[cfg(feature = "adaptive-tables")]
pub struct AdaptiveTable {
pub(crate) columns: Vec<AdaptiveColumn>,
pub(crate) fallback_width: NonZeroU16,
pub(crate) header: Option<Vec<Cell>>,
pub(crate) rows: Vec<Vec<Cell>>,
}
#[cfg(feature = "adaptive-tables")]
impl AdaptiveTable {
pub fn new(
columns: Vec<AdaptiveColumn>,
fallback_width: NonZeroU16,
) -> Result<Self, TableError> {
if columns.is_empty() {
return Err(TableError::NoColumns);
}
for (index, column) in columns.iter().enumerate() {
if column.min_width > column.max_width {
return Err(TableError::InvalidWidthRange {
column: index,
min: column.min_width.get(),
max: column.max_width.get(),
});
}
}
Ok(Self {
columns,
fallback_width,
header: None,
rows: Vec::new(),
})
}
pub fn header(&mut self, cells: Vec<Cell>) -> Result<&mut Self, TableError> {
self.check_arity(cells.len())?;
self.header = Some(cells);
Ok(self)
}
pub fn row(&mut self, cells: Vec<Cell>) -> Result<&mut Self, TableError> {
self.check_arity(cells.len())?;
self.rows.push(cells);
Ok(self)
}
fn check_arity(&self, actual: usize) -> Result<(), TableError> {
if actual != self.columns.len() {
return Err(TableError::RowArity {
expected: self.columns.len(),
actual,
});
}
Ok(())
}
pub fn to_doc(&self, width: NonZeroU16, is_terminal: bool) -> Doc {
records_doc(
adaptive_lines(self, width, is_terminal)
.into_iter()
.map(|line| (line.header, line.cells)),
" ".to_owned(),
)
}
}
#[cfg(feature = "adaptive-tables")]
pub(crate) struct AdaptiveLine {
pub(crate) header: bool,
pub(crate) cells: Vec<(String, TokenId)>,
}
#[cfg(feature = "adaptive-tables")]
pub(crate) fn adaptive_lines(
table: &AdaptiveTable,
width: NonZeroU16,
_is_terminal: bool,
) -> Vec<AdaptiveLine> {
use comfy_table::utils::{arrangement::arrange_content, formatting::content_format};
use comfy_table::{
Cell as BackendCell, CellAlignment, ColumnConstraint, ContentArrangement,
Table as BackendTable, Width,
};
if table.header.is_none() && table.rows.is_empty() {
return Vec::new();
}
let mut backend = BackendTable::new();
backend
.load_preset(comfy_table::presets::NOTHING)
.set_width(width.get())
.set_content_arrangement(ContentArrangement::Dynamic);
let make_row = |cells: &[Cell]| {
cells
.iter()
.map(|cell| BackendCell::new(cell.text.as_str()))
.collect::<Vec<_>>()
};
if let Some(header) = &table.header {
backend.set_header(make_row(header));
}
for row in &table.rows {
backend.add_row(make_row(row));
}
backend.set_constraints(
table
.columns
.iter()
.map(|column| ColumnConstraint::Boundaries {
lower: Width::Fixed(column.min_width.get()),
upper: Width::Fixed(column.max_width.get()),
}),
);
let column_count = table.columns.len();
for (index, (backend_column, column)) in backend
.column_iter_mut()
.zip(table.columns.iter())
.enumerate()
{
backend_column.set_padding(if index + 1 == column_count {
(0, 0)
} else {
(0, 1)
});
backend_column.set_cell_alignment(match column.alignment {
Alignment::Left => CellAlignment::Left,
Alignment::Center => CellAlignment::Center,
Alignment::Right => CellAlignment::Right,
});
}
let display_info = arrange_content(&backend);
let laid_out_records = content_format::format_content(&backend, &display_info);
let mut record_tokens =
Vec::with_capacity(table.rows.len() + usize::from(table.header.is_some()));
if let Some(header) = &table.header {
record_tokens.push((true, vec![tokens::TABLE_HEADER; header.len()]));
}
record_tokens.extend(
table
.rows
.iter()
.map(|row| (false, row.iter().map(|cell| cell.token.clone()).collect())),
);
let mut lines = Vec::new();
for (record, (header, tokens)) in laid_out_records.into_iter().zip(record_tokens) {
for cells in record {
let final_index = cells.len().saturating_sub(1);
let mut semantic_cells = Vec::with_capacity(cells.len());
for (index, (mut text, token)) in cells.into_iter().zip(tokens.iter()).enumerate() {
if index == final_index {
text.truncate(text.trim_end_matches(' ').len());
} else if text.ends_with(' ') {
text.pop();
}
semantic_cells.push((text, token.clone()));
}
while semantic_cells
.last()
.is_some_and(|(text, _)| text.trim_end_matches(' ').is_empty())
{
semantic_cells.pop();
}
if let Some((text, _)) = semantic_cells.last_mut() {
text.truncate(text.trim_end_matches(' ').len());
}
lines.push(AdaptiveLine {
header,
cells: semantic_cells,
});
}
}
lines
}
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum TableError {
#[error("table must contain at least one column")]
NoColumns,
#[error("column {column} has minimum width {min} greater than maximum width {max}")]
InvalidWidthRange { column: usize, min: u16, max: u16 },
#[error("table row has {actual} cells; expected {expected}")]
RowArity { expected: usize, actual: usize },
}
#[cfg(test)]
mod tests {
use super::*;
fn column(width: u16, alignment: Alignment, overflow: Overflow) -> FixedColumn {
FixedColumn {
width: NonZeroU16::new(width).expect("nonzero test width"),
alignment,
overflow,
}
}
#[test]
fn fixed_alignment_and_all_overflow_modes_are_exact() {
assert_eq!(
format_cell("x", column(5, Alignment::Left, Overflow::Clip), false),
"x "
);
assert_eq!(
format_cell("x", column(5, Alignment::Center, Overflow::Clip), false),
" x "
);
assert_eq!(
format_cell("x", column(5, Alignment::Right, Overflow::Clip), true),
" x"
);
assert_eq!(clip("abcdef", 3), "abc");
assert_eq!(truncate_end("abcdef", 3), "ab…");
assert_eq!(truncate_middle("abcdef", 5), "ab…ef");
assert_eq!(truncate_end("abcdef", 0), "");
assert_eq!(truncate_middle("abcdef", 0), "");
}
#[test]
fn truncation_never_splits_extended_grapheme_clusters() {
let combining = "e\u{301}x";
assert_eq!(clip(combining, 1), "e\u{301}");
assert_eq!(truncate_end(combining, 2), combining);
let modifier = "👍🏽x";
assert_eq!(clip(modifier, 2), "👍🏽");
assert_eq!(truncate_end(modifier, 3), modifier);
let zwj = "👩💻x";
assert_eq!(clip(zwj, 2), "👩💻");
assert_eq!(truncate_end("👩💻abc", 3), "👩💻…");
assert_eq!(truncate_middle("ab👩💻cd", 5), "ab…cd");
}
#[cfg(feature = "adaptive-tables")]
#[test]
fn adaptive_plain_layout_is_exact_across_width_sources() {
let columns = vec![
AdaptiveColumn {
min_width: NonZeroU16::new(2).expect("nonzero"),
max_width: NonZeroU16::new(20).expect("nonzero"),
alignment: Alignment::Left,
},
AdaptiveColumn {
min_width: NonZeroU16::new(1).expect("nonzero"),
max_width: NonZeroU16::new(5).expect("nonzero"),
alignment: Alignment::Right,
},
];
let mut table = AdaptiveTable::new(columns, NonZeroU16::new(12).expect("nonzero fallback"))
.expect("table");
table
.header(vec![
Cell::new("old", tokens::STATUS_ERROR),
Cell::new("x", tokens::STATUS_ERROR),
])
.expect("old header");
table
.header(vec![
Cell::new("name", tokens::STATUS_ERROR),
Cell::new("n", tokens::STATUS_ERROR),
])
.expect("replacement header");
table
.row(vec![
Cell::new("alpha beta", tokens::ENTITY_IDENTIFIER),
Cell::new("2", tokens::DATA_COUNT),
])
.expect("first row");
table
.row(vec![
Cell::new("gamma", tokens::ENTITY_IDENTIFIER),
Cell::new("10", tokens::DATA_COUNT),
])
.expect("second row");
let render = |width, terminal| {
adaptive_lines(
&table,
NonZeroU16::new(width).expect("nonzero width"),
terminal,
)
.into_iter()
.map(|line| {
line.cells
.into_iter()
.map(|(text, _)| text)
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join("\n")
};
let narrow = render(8, true);
let wide = render(30, true);
let non_terminal = render(12, false);
assert_eq!(narrow, "name n\nalpha 2\nbeta\ngamma 10");
assert_eq!(wide, "name n\nalpha beta 2\ngamma 10");
assert_eq!(non_terminal, "name n\nalpha 2\nbeta\ngamma 10");
assert_eq!(narrow, render(8, false));
assert_eq!(non_terminal, render(12, true));
assert!(!wide.contains("old"));
assert!(wide.lines().all(|line| !line.ends_with(' ')));
}
#[cfg(feature = "adaptive-tables")]
#[test]
fn adaptive_constructor_errors_cover_zero_columns_and_bad_ranges() {
assert!(matches!(
AdaptiveTable::new(Vec::new(), NonZeroU16::new(10).expect("nonzero")),
Err(TableError::NoColumns)
));
assert!(matches!(
AdaptiveTable::new(
vec![AdaptiveColumn {
min_width: NonZeroU16::new(4).expect("nonzero"),
max_width: NonZeroU16::new(3).expect("nonzero"),
alignment: Alignment::Left,
}],
NonZeroU16::new(10).expect("nonzero")
),
Err(TableError::InvalidWidthRange {
column: 0,
min: 4,
max: 3
})
));
}
}