use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::hash::Hasher;
use core::panic::RefUnwindSafe;
use core::{fmt, ptr};
use itertools::Itertools;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Flex, Layout, Rect};
use ratatui_core::style::{Style, Styled};
use ratatui_core::text::Text;
use ratatui_core::widgets::{StatefulWidget, Widget};
use ratatui_widgets::block::{Block, BlockExt};
pub use self::cell::Cell;
pub use self::highlight_placement::HighlightPlacement;
pub use self::highlight_spacing::HighlightSpacing;
pub use self::row::Row;
pub use self::state::TableState;
mod cell;
mod highlight_placement;
mod highlight_spacing;
mod row;
mod state;
enum LazyRowHeights<'a> {
Uniform(u16),
PerRow(Arc<dyn Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a>),
}
impl LazyRowHeights<'_> {
fn height_of(&self, index: usize) -> u16 {
match self {
Self::Uniform(height) => *height,
Self::PerRow(heights) => heights(index),
}
}
}
impl fmt::Debug for LazyRowHeights<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Uniform(height) => f.debug_tuple("Uniform").field(height).finish(),
Self::PerRow(_) => f.debug_tuple("PerRow").finish(),
}
}
}
impl Clone for LazyRowHeights<'_> {
fn clone(&self) -> Self {
match self {
Self::Uniform(height) => Self::Uniform(*height),
Self::PerRow(heights) => Self::PerRow(Arc::clone(heights)),
}
}
}
impl PartialEq for LazyRowHeights<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Uniform(left), Self::Uniform(right)) => left == right,
(Self::PerRow(left), Self::PerRow(right)) => Arc::ptr_eq(left, right),
_ => false,
}
}
}
impl Eq for LazyRowHeights<'_> {}
impl core::hash::Hash for LazyRowHeights<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Uniform(height) => {
"uniform".hash(state);
height.hash(state);
}
Self::PerRow(heights) => {
"per_row".hash(state);
ptr::hash(Arc::as_ptr(heights), state);
}
}
}
}
struct LazyRowProvider<'a> {
count: usize,
heights: LazyRowHeights<'a>,
factory: Arc<dyn Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a>,
}
impl LazyRowProvider<'_> {
fn height_of(&self, index: usize) -> u16 {
self.heights.height_of(index)
}
fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
if self.count == 0 {
return (0, 0);
}
let last_row = self.count - 1;
let selected = state.selected.map(|selected| selected.min(last_row));
let mut start = state.offset.min(last_row);
if let Some(selected) = selected {
start = start.min(selected);
}
if area.height == 0 {
return (start, start);
}
let mut end = start;
let mut height = 0_u16;
while end < self.count {
let Some(filled) = height.checked_add(self.height_of(end)) else {
break;
};
if filled > area.height {
break;
}
height = filled;
end += 1;
if window_is_full(start, end, area) {
break;
}
}
if let Some(selected) = selected
&& selected >= end
{
start = selected;
end = selected + 1;
height = self.height_of(selected);
while start > 0 && !window_is_full(start, end, area) {
let Some(filled) = height.checked_add(self.height_of(start - 1)) else {
break;
};
if filled > area.height {
break;
}
height = filled;
start -= 1;
}
}
if height < area.height && end < self.count && !window_is_full(start, end, area) {
end += 1;
}
(start, end)
}
}
const fn window_is_full(start: usize, end: usize, area: Rect) -> bool {
end - start > area.height as usize
}
impl fmt::Debug for LazyRowProvider<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LazyRowProvider")
.field("count", &self.count)
.field("heights", &self.heights)
.finish_non_exhaustive()
}
}
impl Clone for LazyRowProvider<'_> {
fn clone(&self) -> Self {
Self {
count: self.count,
heights: self.heights.clone(),
factory: Arc::clone(&self.factory),
}
}
}
impl PartialEq for LazyRowProvider<'_> {
fn eq(&self, other: &Self) -> bool {
self.count == other.count
&& self.heights == other.heights
&& Arc::ptr_eq(&self.factory, &other.factory)
}
}
impl Eq for LazyRowProvider<'_> {}
impl core::hash::Hash for LazyRowProvider<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.count.hash(state);
self.heights.hash(state);
ptr::hash(Arc::as_ptr(&self.factory), state);
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Table<'a> {
rows: Vec<Row<'a>>,
header: Option<Row<'a>>,
footer: Option<Row<'a>>,
widths: Vec<Constraint>,
column_spacing: u16,
block: Option<Block<'a>>,
style: Style,
row_highlight_style: Style,
column_highlight_style: Style,
cell_highlight_style: Style,
highlight_symbol: Text<'a>,
highlight_spacing: HighlightSpacing,
highlight_placement: HighlightPlacement,
flex: Flex,
lazy: Option<LazyRowProvider<'a>>,
}
impl Default for Table<'_> {
fn default() -> Self {
Self {
rows: Vec::new(),
header: None,
footer: None,
widths: Vec::new(),
column_spacing: 1,
block: None,
style: Style::new(),
row_highlight_style: Style::new(),
column_highlight_style: Style::new(),
cell_highlight_style: Style::new(),
highlight_symbol: Text::default(),
highlight_spacing: HighlightSpacing::default(),
highlight_placement: HighlightPlacement::default(),
flex: Flex::Start,
lazy: None,
}
}
}
impl<'a> Table<'a> {
pub fn new<R, C>(rows: R, widths: C) -> Self
where
R: IntoIterator,
R::Item: Into<Row<'a>>,
C: IntoIterator,
C::Item: Into<Constraint>,
{
let widths = widths.into_iter().map(Into::into).collect_vec();
ensure_percentages_less_than_100(&widths);
let rows = rows.into_iter().map(Into::into).collect();
Self {
rows,
widths,
..Default::default()
}
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn rows<T>(mut self, rows: T) -> Self
where
T: IntoIterator<Item = Row<'a>>,
{
self.rows = rows.into_iter().collect();
self.lazy = None;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn header(mut self, header: Row<'a>) -> Self {
self.header = Some(header);
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn footer(mut self, footer: Row<'a>) -> Self {
self.footer = Some(footer);
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn widths<I>(mut self, widths: I) -> Self
where
I: IntoIterator,
I::Item: Into<Constraint>,
{
let widths = widths.into_iter().map(Into::into).collect_vec();
ensure_percentages_less_than_100(&widths);
self.widths = widths;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn column_spacing(mut self, spacing: u16) -> Self {
self.column_spacing = spacing;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
self.style = style.into();
self
}
#[must_use = "method moves the value of self and returns the modified value"]
#[deprecated(note = "use `row_highlight_style()` instead")]
pub fn highlight_style<S: Into<Style>>(self, highlight_style: S) -> Self {
self.row_highlight_style(highlight_style)
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn row_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
self.row_highlight_style = highlight_style.into();
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn column_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
self.column_highlight_style = highlight_style.into();
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn cell_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
self.cell_highlight_style = highlight_style.into();
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn highlight_symbol<T: Into<Text<'a>>>(mut self, highlight_symbol: T) -> Self {
self.highlight_symbol = highlight_symbol.into();
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn highlight_spacing(mut self, value: HighlightSpacing) -> Self {
self.highlight_spacing = value;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn highlight_placement(mut self, value: HighlightPlacement) -> Self {
self.highlight_placement = value;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn flex(mut self, flex: Flex) -> Self {
self.flex = flex;
self
}
pub fn lazy_rows<C, F>(row_count: usize, widths: C, row: F) -> Self
where
C: IntoIterator,
C::Item: Into<Constraint>,
F: Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a,
{
let widths: Vec<Constraint> = widths.into_iter().map(Into::into).collect();
ensure_percentages_less_than_100(&widths);
Self {
lazy: Some(LazyRowProvider {
count: row_count,
heights: LazyRowHeights::Uniform(1),
factory: Arc::new(row),
}),
widths,
..Default::default()
}
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn lazy_row_height(mut self, height: u16) -> Self {
if let Some(ref mut lazy) = self.lazy {
lazy.heights = LazyRowHeights::Uniform(height);
}
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub fn lazy_row_height_with<H>(mut self, height: H) -> Self
where
H: Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a,
{
if let Some(ref mut lazy) = self.lazy {
lazy.heights = LazyRowHeights::PerRow(Arc::new(height));
}
self
}
}
impl Widget for Table<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
Widget::render(&self, area, buf);
}
}
impl Widget for &Table<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let mut state = TableState::default();
StatefulWidget::render(self, area, buf, &mut state);
}
}
impl StatefulWidget for Table<'_> {
type State = TableState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
StatefulWidget::render(&self, area, buf, state);
}
}
impl StatefulWidget for &Table<'_> {
type State = TableState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
buf.set_style(area, self.style);
self.block.as_ref().render(area, buf);
let table_area = self.block.inner_if_some(area);
if table_area.is_empty() {
return;
}
let row_count = self.row_count();
if state.selected.is_some_and(|s| s >= row_count) {
state.select(Some(row_count.saturating_sub(1)));
}
if row_count == 0 {
state.select(None);
}
let column_count = self.column_count();
if state.selected_column.is_some_and(|s| s >= column_count) {
state.select_column(Some(column_count.saturating_sub(1)));
}
if column_count == 0 {
state.select_column(None);
}
let selection_width = self.selection_width(state);
let symbol_columns = self
.highlight_placement
.column_mask(state.selected_column(), column_count);
let column_widths = self.get_column_widths(
table_area.width,
selection_width,
column_count,
&symbol_columns,
);
let (header_area, rows_area, footer_area) = self.layout(table_area);
self.render_header(header_area, buf, &column_widths);
self.render_rows(
rows_area,
buf,
selection_width,
state,
&column_widths,
&symbol_columns,
);
self.render_footer(footer_area, buf, &column_widths);
}
}
impl Table<'_> {
fn layout(&self, area: Rect) -> (Rect, Rect, Rect) {
let header_top_margin = self.header.as_ref().map_or(0, |h| h.top_margin);
let header_height = self.header.as_ref().map_or(0, |h| h.height);
let header_bottom_margin = self.header.as_ref().map_or(0, |h| h.bottom_margin);
let footer_top_margin = self.footer.as_ref().map_or(0, |h| h.top_margin);
let footer_height = self.footer.as_ref().map_or(0, |f| f.height);
let footer_bottom_margin = self.footer.as_ref().map_or(0, |h| h.bottom_margin);
let layout = Layout::vertical([
Constraint::Length(header_top_margin),
Constraint::Length(header_height),
Constraint::Length(header_bottom_margin),
Constraint::Min(0),
Constraint::Length(footer_top_margin),
Constraint::Length(footer_height),
Constraint::Length(footer_bottom_margin),
])
.split(area);
let (header_area, rows_area, footer_area) = (layout[1], layout[3], layout[5]);
(header_area, rows_area, footer_area)
}
fn render_header(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
if let Some(ref header) = self.header {
buf.set_style(area, header.style);
for (cell_area, cell) in column_widths.iter().zip(header.cells.iter()) {
let new_x = area.x + cell_area.x;
let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
cell.render(area_to_render, buf);
}
}
}
fn render_footer(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
if let Some(ref footer) = self.footer {
buf.set_style(area, footer.style);
for (cell_area, cell) in column_widths.iter().zip(footer.cells.iter()) {
let new_x = area.x + cell_area.x;
let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
cell.render(area_to_render, buf);
}
}
}
fn render_rows(
&self,
area: Rect,
buf: &mut Buffer,
selection_width: u16,
state: &mut TableState,
columns_widths: &[Rect],
symbol_columns: &[bool],
) {
if let Some(ref provider) = self.lazy {
self.render_lazy_rows(
area,
buf,
selection_width,
state,
columns_widths,
symbol_columns,
provider,
);
return;
}
if self.rows.is_empty() {
return;
}
let (start_index, end_index) = self.visible_rows(state, area);
state.offset = start_index;
let mut y_offset = 0;
let mut selected_row_area = None;
for (i, row) in self
.rows
.iter()
.enumerate()
.skip(start_index)
.take(end_index - start_index)
{
let y = area.y + y_offset + row.top_margin;
let height = (y + row.height).min(area.bottom()).saturating_sub(y);
let row_area = Rect { y, height, ..area };
buf.set_style(row_area, row.style);
let is_selected = state.selected() == Some(i);
self.render_highlight_symbol(
buf,
row_area,
row,
i,
start_index,
state,
columns_widths,
symbol_columns,
selection_width,
);
self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
if is_selected {
selected_row_area = Some(row_area);
}
y_offset += row.height_with_margin();
}
self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
}
#[expect(clippy::too_many_arguments)]
fn render_lazy_rows(
&self,
area: Rect,
buf: &mut Buffer,
selection_width: u16,
state: &mut TableState,
columns_widths: &[Rect],
symbol_columns: &[bool],
provider: &LazyRowProvider,
) {
if provider.count == 0 {
return;
}
let (start_index, end_index) = provider.visible_rows(state, area);
state.offset = start_index;
let mut y = area.y;
let mut selected_row_area = None;
for index in start_index..end_index {
let row = (provider.factory)(index);
let row_height = provider.height_of(index);
let height = y
.saturating_add(row_height)
.min(area.bottom())
.saturating_sub(y);
let row_area = Rect { y, height, ..area };
buf.set_style(row_area, row.style);
let is_selected = state.selected() == Some(index);
self.render_highlight_symbol(
buf,
row_area,
&row,
index,
start_index,
state,
columns_widths,
symbol_columns,
selection_width,
);
self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
if is_selected {
selected_row_area = Some(row_area);
}
y = y.saturating_add(row_height);
}
self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
}
fn apply_highlight_styles(
&self,
buf: &mut Buffer,
area: Rect,
selected_row_area: Option<Rect>,
state: &TableState,
columns_widths: &[Rect],
) {
let selected_column_area = state.selected_column().and_then(|s| {
columns_widths.get(s).map(|cell_area| Rect {
x: cell_area.x + area.x,
width: cell_area.width,
..area
})
});
match (selected_row_area, selected_column_area) {
(Some(row_area), Some(col_area)) => {
buf.set_style(row_area, self.row_highlight_style);
buf.set_style(col_area, self.column_highlight_style);
let cell_area = row_area.intersection(col_area);
buf.set_style(cell_area, self.cell_highlight_style);
}
(Some(row_area), None) => {
buf.set_style(row_area, self.row_highlight_style);
}
(None, Some(col_area)) => {
buf.set_style(col_area, self.column_highlight_style);
}
(None, None) => (),
}
}
fn render_row_cells(
&self,
buf: &mut Buffer,
column_widths: Vec<&Rect>,
cells: &Vec<Cell>,
row_area: Rect,
) {
let mut column_widths_iterator = column_widths.into_iter();
for current_cell in cells {
if let Some(cell_area) = Self::get_cell_area(
&mut column_widths_iterator,
current_cell.column_span,
self.column_spacing,
) {
let new_x = row_area.x + cell_area.x;
let area_to_render = Rect::new(new_x, row_area.y, cell_area.width, row_area.height);
current_cell.render(area_to_render, buf);
}
}
}
#[expect(clippy::too_many_arguments)]
fn render_highlight_symbol(
&self,
buf: &mut Buffer,
row_area: Rect,
row: &Row,
row_index: usize,
first_visible_row: usize,
state: &TableState,
columns_widths: &[Rect],
symbol_columns: &[bool],
selection_width: u16,
) {
if selection_width == 0 {
return;
}
if state.selected().is_none() && state.selected_column().is_none() {
return;
}
if row_index != state.selected().unwrap_or(first_visible_row) {
return;
}
for (column_index, cell_area) in columns_widths.iter().enumerate() {
if !symbol_columns.get(column_index).copied().unwrap_or(false) {
continue;
}
let symbol_area = Rect {
x: (row_area.x + cell_area.x).saturating_sub(selection_width),
width: selection_width,
..row_area
};
buf.set_style(symbol_area, row.style);
(&self.highlight_symbol).render(symbol_area, buf);
}
}
fn get_cell_area<'a, T>(
column_widths_iterator: &mut T,
cell_column_span: u16,
column_spacing: u16,
) -> Option<Rect>
where
T: Iterator<Item = &'a Rect>,
{
if cell_column_span == 0 {
return None;
}
let first = column_widths_iterator.next()?;
let (n_columns_taken, all_columns_width) = column_widths_iterator
.take((cell_column_span - 1).into())
.map(|rect| (1, rect.width))
.fold((1, first.width), |so_far, next_column| {
(next_column.0 + so_far.0, next_column.1 + so_far.1)
});
let width = all_columns_width + (n_columns_taken - 1) * column_spacing;
Some(Rect::new(first.x, first.y, width, 1))
}
fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
let last_row = self.rows.len().saturating_sub(1);
let mut start = state.offset.min(last_row);
if let Some(selected) = state.selected {
start = start.min(selected);
}
let mut end = start;
let mut height = 0;
for item in self.rows.iter().skip(start) {
if height + item.height > area.height {
break;
}
height += item.height_with_margin();
end += 1;
}
if let Some(selected) = state.selected {
let selected = selected.min(last_row);
while selected >= end {
height = height.saturating_add(self.rows[end].height_with_margin());
end += 1;
while height > area.height {
height = height.saturating_sub(self.rows[start].height_with_margin());
start += 1;
}
}
}
if height < area.height && end < self.rows.len() {
end += 1;
}
(start, end)
}
fn get_column_widths(
&self,
max_width: u16,
selection_width: u16,
col_count: usize,
symbol_columns: &[bool],
) -> Vec<Rect> {
let widths = if self.widths.is_empty() {
vec![Constraint::Length(max_width / col_count.max(1) as u16); col_count]
} else {
self.widths.clone()
};
let slots = symbol_columns.iter().filter(|slot| **slot).count() as u16;
let content_width = max_width.saturating_sub(selection_width * slots);
let rects = Layout::horizontal(widths)
.flex(self.flex)
.spacing(self.column_spacing)
.split(Rect::new(0, 0, content_width, 1));
let mut shift = 0;
rects
.iter()
.enumerate()
.map(|(index, rect)| {
if symbol_columns.get(index).copied().unwrap_or(false) {
shift += selection_width;
}
Rect::new(rect.x + shift, 0, rect.width, 1)
})
.collect()
}
fn row_count(&self) -> usize {
self.lazy
.as_ref()
.map_or_else(|| self.rows.len(), |provider| provider.count)
}
fn column_count(&self) -> usize {
let lazy_columns = if self.lazy.is_some() {
self.widths.len()
} else {
0
};
self.rows
.iter()
.chain(self.footer.iter())
.chain(self.header.iter())
.map(|r| r.cells.len())
.chain(Some(lazy_columns))
.max()
.unwrap_or_default()
}
fn selection_width(&self, state: &TableState) -> u16 {
let has_selection = state.selected().is_some() || state.selected_column().is_some();
if self.highlight_spacing.should_add(has_selection) {
self.highlight_symbol.width() as u16
} else {
0
}
}
}
fn ensure_percentages_less_than_100(widths: &[Constraint]) {
for w in widths {
if let Constraint::Percentage(p) = w {
assert!(
*p <= 100,
"Percentages should be between 0 and 100 inclusively."
);
}
}
}
impl Styled for Table<'_> {
type Item = Self;
fn style(&self) -> Style {
self.style
}
fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
self.style(style)
}
}
impl<'a, Item> FromIterator<Item> for Table<'a>
where
Item: Into<Row<'a>>,
{
fn from_iter<Iter: IntoIterator<Item = Item>>(rows: Iter) -> Self {
let widths: [Constraint; 0] = [];
Self::new(rows, widths)
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use alloc::{format, vec};
use ratatui_core::layout::Constraint::*;
use ratatui_core::style::{Color, Modifier, Style, Stylize};
use ratatui_core::text::Line;
use rstest::{fixture, rstest};
use super::*;
use crate::table::Cell;
#[test]
fn lazy_visible_rows_do_not_overflow_the_line_total() {
let table = Table::lazy_rows(4, [Constraint::Length(1)], |_| Row::new(["x"]))
.lazy_row_height_with(|index| if index == 0 { u16::MAX } else { 1 });
let lazy = table.lazy.as_ref().expect("lazy rows");
let area = Rect::new(0, 0, 1, u16::MAX);
let state = TableState::default();
assert_eq!(lazy.visible_rows(&state, area), (0, 1));
let state = TableState::default().with_selected(3);
assert_eq!(lazy.visible_rows(&state, area), (1, 4));
}
#[test]
fn new() {
let rows = [Row::new(vec![Cell::from("")])];
let widths = [Constraint::Percentage(100)];
let table = Table::new(rows.clone(), widths);
assert_eq!(table.rows, rows);
assert_eq!(table.header, None);
assert_eq!(table.footer, None);
assert_eq!(table.widths, widths);
assert_eq!(table.column_spacing, 1);
assert_eq!(table.block, None);
assert_eq!(table.style, Style::default());
assert_eq!(table.row_highlight_style, Style::default());
assert_eq!(table.highlight_symbol, Text::default());
assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
assert_eq!(table.flex, Flex::Start);
}
#[test]
fn default() {
let table = Table::default();
assert_eq!(table.rows, []);
assert_eq!(table.header, None);
assert_eq!(table.footer, None);
assert_eq!(table.widths, []);
assert_eq!(table.column_spacing, 1);
assert_eq!(table.block, None);
assert_eq!(table.style, Style::default());
assert_eq!(table.row_highlight_style, Style::default());
assert_eq!(table.highlight_symbol, Text::default());
assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
assert_eq!(table.flex, Flex::Start);
}
#[test]
fn collect() {
let table = (0..4)
.map(|i| -> Row { (0..4).map(|j| format!("{i}*{j} = {}", i * j)).collect() })
.collect::<Table>()
.widths([Constraint::Percentage(25); 4]);
let expected_rows: Vec<Row> = vec![
Row::new(["0*0 = 0", "0*1 = 0", "0*2 = 0", "0*3 = 0"]),
Row::new(["1*0 = 0", "1*1 = 1", "1*2 = 2", "1*3 = 3"]),
Row::new(["2*0 = 0", "2*1 = 2", "2*2 = 4", "2*3 = 6"]),
Row::new(["3*0 = 0", "3*1 = 3", "3*2 = 6", "3*3 = 9"]),
];
assert_eq!(table.rows, expected_rows);
assert_eq!(table.widths, [Constraint::Percentage(25); 4]);
}
#[test]
fn widths() {
let table = Table::default().widths([Constraint::Length(100)]);
assert_eq!(table.widths, [Constraint::Length(100)]);
#[expect(clippy::needless_borrows_for_generic_args)]
let table = Table::default().widths(&[Constraint::Length(100)]);
assert_eq!(table.widths, [Constraint::Length(100)]);
let table = Table::default().widths(vec![Constraint::Length(100)]);
assert_eq!(table.widths, [Constraint::Length(100)]);
#[expect(clippy::needless_borrows_for_generic_args)]
let table = Table::default().widths(&vec![Constraint::Length(100)]);
assert_eq!(table.widths, [Constraint::Length(100)]);
let table = Table::default().widths([100].into_iter().map(Constraint::Length));
assert_eq!(table.widths, [Constraint::Length(100)]);
}
#[test]
fn rows() {
let rows = [Row::new(vec![Cell::from("")])];
let table = Table::default().rows(rows.clone());
assert_eq!(table.rows, rows);
}
#[test]
fn column_spacing() {
let table = Table::default().column_spacing(2);
assert_eq!(table.column_spacing, 2);
}
#[test]
fn block() {
let block = Block::bordered().title("Table");
let table = Table::default().block(block.clone());
assert_eq!(table.block, Some(block));
}
#[test]
fn header() {
let header = Row::new(vec![Cell::from("")]);
let table = Table::default().header(header.clone());
assert_eq!(table.header, Some(header));
}
#[test]
fn footer() {
let footer = Row::new(vec![Cell::from("")]);
let table = Table::default().footer(footer.clone());
assert_eq!(table.footer, Some(footer));
}
#[test]
#[expect(deprecated)]
fn highlight_style() {
let style = Style::default().red().italic();
let table = Table::default().highlight_style(style);
assert_eq!(table.row_highlight_style, style);
}
#[test]
fn row_highlight_style() {
let style = Style::default().red().italic();
let table = Table::default().row_highlight_style(style);
assert_eq!(table.row_highlight_style, style);
}
#[test]
fn column_highlight_style() {
let style = Style::default().red().italic();
let table = Table::default().column_highlight_style(style);
assert_eq!(table.column_highlight_style, style);
}
#[test]
fn cell_highlight_style() {
let style = Style::default().red().italic();
let table = Table::default().cell_highlight_style(style);
assert_eq!(table.cell_highlight_style, style);
}
#[test]
fn highlight_symbol() {
let table = Table::default().highlight_symbol(">>");
assert_eq!(table.highlight_symbol, Text::from(">>"));
}
#[test]
fn highlight_spacing() {
let table = Table::default().highlight_spacing(HighlightSpacing::Always);
assert_eq!(table.highlight_spacing, HighlightSpacing::Always);
}
#[test]
#[should_panic = "Percentages should be between 0 and 100 inclusively"]
fn table_invalid_percentages() {
let _ = Table::default().widths([Constraint::Percentage(110)]);
}
#[test]
fn widths_conversions() {
let array = [Constraint::Percentage(100)];
let table = Table::new(Vec::<Row>::new(), array);
assert_eq!(table.widths, [Constraint::Percentage(100)], "array");
let array_ref = &[Constraint::Percentage(100)];
let table = Table::new(Vec::<Row>::new(), array_ref);
assert_eq!(table.widths, [Constraint::Percentage(100)], "array ref");
let vec = vec![Constraint::Percentage(100)];
let slice = vec.as_slice();
let table = Table::new(Vec::<Row>::new(), slice);
assert_eq!(table.widths, [Constraint::Percentage(100)], "slice");
let vec = vec![Constraint::Percentage(100)];
let table = Table::new(Vec::<Row>::new(), vec);
assert_eq!(table.widths, [Constraint::Percentage(100)], "vec");
let vec_ref = &vec![Constraint::Percentage(100)];
let table = Table::new(Vec::<Row>::new(), vec_ref);
assert_eq!(table.widths, [Constraint::Percentage(100)], "vec ref");
}
#[cfg(test)]
mod state {
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Rect};
use ratatui_core::widgets::StatefulWidget;
use super::*;
use crate::table::{Row, Table, TableState};
#[fixture]
fn table_buf() -> Buffer {
Buffer::empty(Rect::new(0, 0, 10, 10))
}
#[rstest]
fn test_list_state_empty_list(mut table_buf: Buffer) {
let mut state = TableState::default();
let rows: Vec<Row> = Vec::new();
let widths = vec![Constraint::Percentage(100)];
let table = Table::new(rows, widths);
state.select_first();
StatefulWidget::render(table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected(), None);
assert_eq!(state.selected_column(), None);
}
#[rstest]
fn test_list_state_single_item(mut table_buf: Buffer) {
let mut state = TableState::default();
let widths = vec![Constraint::Percentage(100)];
let items = vec![Row::new(vec!["Item 1"])];
let table = Table::new(items, widths);
state.select_first();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected(), Some(0));
assert_eq!(state.selected_column(), None);
state.select_last();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected(), Some(0));
assert_eq!(state.selected_column(), None);
state.select_previous();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected(), Some(0));
assert_eq!(state.selected_column(), None);
state.select_next();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected(), Some(0));
assert_eq!(state.selected_column(), None);
let mut state = TableState::default();
state.select_first_column();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected_column(), Some(0));
assert_eq!(state.selected(), None);
state.select_last_column();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected_column(), Some(0));
assert_eq!(state.selected(), None);
state.select_previous_column();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected_column(), Some(0));
assert_eq!(state.selected(), None);
state.select_next_column();
StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
assert_eq!(state.selected_column(), Some(0));
assert_eq!(state.selected(), None);
}
}
#[cfg(test)]
mod render {
use ratatui_core::layout::Alignment;
use super::*;
#[test]
fn render_empty_area() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
let table = Table::new(rows, vec![Constraint::Length(5); 2]);
Widget::render(table, Rect::new(0, 0, 0, 0), &mut buf);
assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
}
#[test]
fn render_default() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let table = Table::default();
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
}
#[test]
fn render_with_block() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let block = Block::bordered().title("Block");
let table = Table::new(rows, vec![Constraint::Length(5); 2]).block(block);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"┌Block────────┐",
"│Cell1 Cell2 │",
"└─────────────┘",
]);
assert_eq!(buf, expected);
}
#[rstest]
#[case(15, 5, vec![
Row::new(vec![
Cell::new("Cell1").column_span(1),
Cell::new("Cell2").column_span(1),
]),
Row::new(vec![
Cell::new("Cell3").column_span(1),
Cell::new("Cell4").column_span(1),
]),
],
&Buffer::with_lines(["Cell1 Cell2 ", "Cell3 Cell4 "]))]
#[case(15, 5, vec![
Row::new(vec![
Cell::new("Cell1").column_span(0),
Cell::new("Cell2").column_span(1),
]),
Row::new(vec![
Cell::new("Cell3").column_span(1),
Cell::new("Cell4").column_span(1),
]),
], &Buffer::with_lines(["Cell2 ", "Cell3 Cell4 "]))]
#[case(15, 5, vec![
Row::new(vec![
Cell::new("Cell1").column_span(2),
Cell::new("Cell2").column_span(1),
]),
Row::new(vec![
Cell::new("Cell3").column_span(1),
Cell::new("Cell4").column_span(1),
]),
], &Buffer::with_lines(["Cell1 ", "Cell3 Cell4 "]))]
fn test_colspans_2_cols<'rows, Rows>(
#[case] width: u16,
#[case] column_width: u16,
#[case] rows: Rows,
#[case] expected: &Buffer,
) where
Rows: IntoIterator<Item = Row<'rows>>,
{
let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
let table = Table::new(rows, [Constraint::Length(column_width); 2]);
Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
assert_eq!(buf, *expected);
}
#[rstest]
#[case(17, 5, vec![
Row::new(vec![
Cell::new("Cell1").column_span(2),
Cell::new("Cell2").column_span(1),
]),
Row::new(vec![
Cell::new("Cell3").column_span(1),
Cell::new("Cell4").column_span(1),
Cell::new("Cell5").column_span(1),
]),
], &Buffer::with_lines(["Cell1 Cell2", "Cell3 Cell4 Cell5"]))]
#[case(17, 5, vec![
Row::new(vec![
Cell::new("Cell1").column_span(1),
Cell::new("Cell2").column_span(2),
Cell::new("Cell3").column_span(1),
]),
Row::new(vec![
Cell::new("Cell4").column_span(1),
Cell::new("Cell5").column_span(1),
Cell::new("Cell6").column_span(1),
]),
], &Buffer::with_lines(["Cell1 Cell2 ", "Cell4 Cell5 Cell6"]))]
#[case(15, 5, vec![
Row::new(vec![
Cell::new("11111111111111111111").column_span(2),
Cell::new("22222222222222222222").column_span(1),
]),
Row::new(vec![
Cell::new("33333333333333333333").column_span(1),
Cell::new("44444444444444444444").column_span(2),
Cell::new("55555555555555555555").column_span(1),
]),
], &Buffer::with_lines(["1111111111 2222", "3333 4444444444"]))]
fn test_colspans_3_cols<'rows, Rows>(
#[case] width: u16,
#[case] column_width: u16,
#[case] rows: Rows,
#[case] expected: &Buffer,
) where
Rows: IntoIterator<Item = Row<'rows>>,
{
let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
let table = Table::new(rows, [Constraint::Length(column_width); 3]);
Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
assert_eq!(buf, *expected);
}
#[test]
fn render_with_header() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let header = Row::new(vec!["Head1", "Head2"]);
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Head1 Head2 ",
"Cell1 Cell2 ",
"Cell3 Cell4 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_footer() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let footer = Row::new(vec!["Foot1", "Foot2"]);
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Cell1 Cell2 ",
"Cell3 Cell4 ",
"Foot1 Foot2 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_header_and_footer() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let header = Row::new(vec!["Head1", "Head2"]);
let footer = Row::new(vec!["Foot1", "Foot2"]);
let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
let table = Table::new(rows, [Constraint::Length(5); 2])
.header(header)
.footer(footer);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Head1 Head2 ",
"Cell1 Cell2 ",
"Foot1 Foot2 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_header_margin() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let header = Row::new(vec!["Head1", "Head2"]).bottom_margin(1);
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Head1 Head2 ",
" ",
"Cell1 Cell2 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_footer_margin() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let footer = Row::new(vec!["Foot1", "Foot2"]).top_margin(1);
let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Cell1 Cell2 ",
" ",
"Foot1 Foot2 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_row_margin() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]).bottom_margin(1),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2]);
Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Cell1 Cell2 ",
" ",
"Cell3 Cell4 ",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_tall_row() {
let mut buf = Buffer::empty(Rect::new(0, 0, 23, 3));
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec![
Text::raw("Cell3-Line1\nCell3-Line2\nCell3-Line3"),
Text::raw("Cell4-Line1\nCell4-Line2\nCell4-Line3"),
])
.height(3),
];
let table = Table::new(rows, [Constraint::Length(11); 2]);
Widget::render(table, Rect::new(0, 0, 23, 3), &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
"Cell1 Cell2 ",
"Cell3-Line1 Cell4-Line1",
"Cell3-Line2 Cell4-Line2",
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_alignment() {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 3));
let rows = vec![
Row::new(vec![Line::from("Left").alignment(Alignment::Left)]),
Row::new(vec![Line::from("Center").alignment(Alignment::Center)]),
Row::new(vec![Line::from("Right").alignment(Alignment::Right)]),
];
let table = Table::new(rows, [Percentage(100)]);
Widget::render(table, Rect::new(0, 0, 10, 3), &mut buf);
let expected = Buffer::with_lines(["Left ", " Center ", " Right"]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_overflow_does_not_panic() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
let table = Table::new(Vec::<Row>::new(), [Constraint::Min(20); 1])
.header(Row::new([Line::from("").alignment(Alignment::Right)]))
.footer(Row::new([Line::from("").alignment(Alignment::Right)]));
Widget::render(table, Rect::new(0, 0, 20, 3), &mut buf);
}
#[test]
fn render_with_selected_column_and_incorrect_width_count_does_not_panic() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
let table = Table::new(
vec![Row::new(vec!["Row1", "Row2", "Row3"])],
[Constraint::Length(10); 1],
);
let mut state = TableState::new().with_selected_column(2);
StatefulWidget::render(table, Rect::new(0, 0, 20, 3), &mut buf, &mut state);
}
#[test]
fn render_with_selected() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2])
.row_highlight_style(Style::new().red())
.highlight_symbol(">>");
let mut state = TableState::new().with_selected(Some(0));
StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
let expected = Buffer::with_lines([
">>Cell1 Cell2 ".red(),
" Cell3 Cell4 ".into(),
" ".into(),
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_selected_column() {
let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
let rows = vec![
Row::new(vec!["Cell1", "Cell2"]),
Row::new(vec!["Cell3", "Cell4"]),
];
let table = Table::new(rows, [Constraint::Length(5); 2])
.column_highlight_style(Style::new().blue())
.highlight_symbol(">>");
let mut state = TableState::new().with_selected_column(Some(1));
StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
let expected = Buffer::with_lines::<[Line; 3]>([
Line::from(vec![
">>Cell1".into(),
" ".into(),
"Cell2".blue(),
" ".into(),
]),
Line::from(vec![
" Cell3".into(),
" ".into(),
"Cell4".blue(),
" ".into(),
]),
Line::from(vec![" ".into(), " ".blue(), " ".into()]),
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_selected_cell() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
let rows = vec![
Row::new(vec!["Cell1", "Cell2", "Cell3"]),
Row::new(vec!["Cell4", "Cell5", "Cell6"]),
Row::new(vec!["Cell7", "Cell8", "Cell9"]),
];
let table = Table::new(rows, [Constraint::Length(5); 3])
.highlight_symbol(">>")
.cell_highlight_style(Style::new().green());
let mut state = TableState::new().with_selected_cell((1, 2));
StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
let expected = Buffer::with_lines::<[Line; 4]>([
Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".into()]),
Line::from(vec![">>Cell4 Cell5 ".into(), "Cell6".green(), " ".into()]),
Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".into()]),
Line::from(vec![" ".into()]),
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_selected_row_and_column() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
let rows = vec![
Row::new(vec!["Cell1", "Cell2", "Cell3"]),
Row::new(vec!["Cell4", "Cell5", "Cell6"]),
Row::new(vec!["Cell7", "Cell8", "Cell9"]),
];
let table = Table::new(rows, [Constraint::Length(5); 3])
.highlight_symbol(">>")
.row_highlight_style(Style::new().red())
.column_highlight_style(Style::new().blue());
let mut state = TableState::new().with_selected(1).with_selected_column(2);
StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
let expected = Buffer::with_lines::<[Line; 4]>([
Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".blue(), " ".red()]),
Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
Line::from(vec![" ".into(), " ".blue(), " ".into()]),
]);
assert_eq!(buf, expected);
}
#[test]
fn render_with_selected_row_and_column_and_cell() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
let rows = vec![
Row::new(vec!["Cell1", "Cell2", "Cell3"]),
Row::new(vec!["Cell4", "Cell5", "Cell6"]),
Row::new(vec!["Cell7", "Cell8", "Cell9"]),
];
let table = Table::new(rows, [Constraint::Length(5); 3])
.highlight_symbol(">>")
.row_highlight_style(Style::new().red())
.column_highlight_style(Style::new().blue())
.cell_highlight_style(Style::new().green());
let mut state = TableState::new().with_selected(1).with_selected_column(2);
StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
let expected = Buffer::with_lines::<[Line; 4]>([
Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".green(), " ".red()]),
Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
Line::from(vec![" ".into(), " ".blue(), " ".into()]),
]);
assert_eq!(buf, expected);
}
#[rstest]
#[case::no_selection(None, 50, ["50", "51", "52", "53", "54"])]
#[case::selection_before_offset(20, 20, ["20", "21", "22", "23", "24"])]
#[case::selection_immediately_before_offset(49, 49, ["49", "50", "51", "52", "53"])]
#[case::selection_at_start_of_offset(50, 50, ["50", "51", "52", "53", "54"])]
#[case::selection_at_end_of_offset(54, 50, ["50", "51", "52", "53", "54"])]
#[case::selection_immediately_after_offset(55, 51, ["51", "52", "53", "54", "55"])]
#[case::selection_after_offset(80, 76, ["76", "77", "78", "79", "80"])]
fn render_with_selection_and_offset<T: Into<Option<usize>>>(
#[case] selected_row: T,
#[case] expected_offset: usize,
#[case] expected_items: [&str; 5],
) {
let rows = (0..100).map(|i| Row::new([i.to_string()]));
let table = Table::new(rows, [Constraint::Length(2)]);
let mut buf = Buffer::empty(Rect::new(0, 0, 2, 5));
let mut state = TableState::new()
.with_offset(50)
.with_selected(selected_row.into());
StatefulWidget::render(table.clone(), Rect::new(0, 0, 5, 5), &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(expected_items));
assert_eq!(state.offset, expected_offset);
}
}
mod highlight_placement {
use super::*;
#[track_caller]
fn assert_render(
placement: HighlightPlacement,
selected_row: Option<usize>,
selected_column: Option<usize>,
expected: [&str; 3],
) {
let rows = [
Row::new(["A1", "A2", "A3"]),
Row::new(["B1", "B2", "B3"]),
Row::new(["C1", "C2", "C3"]),
];
let table = Table::new(rows, [Constraint::Length(2); 3])
.highlight_symbol(">>")
.highlight_placement(placement);
let mut state = TableState::new()
.with_selected(selected_row)
.with_selected_column(selected_column);
let area = Rect::new(0, 0, 24, 3);
let mut buf = Buffer::empty(area);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(expected));
}
#[test]
fn first_column_with_row_selection() {
assert_render(
HighlightPlacement::FirstColumn,
Some(1),
None,
[
" A1 A2 A3 ",
">>B1 B2 B3 ",
" C1 C2 C3 ",
],
);
}
#[test]
fn first_column_keeps_symbol_when_a_later_column_is_selected() {
assert_render(
HighlightPlacement::FirstColumn,
Some(1),
Some(2),
[
" A1 A2 A3 ",
">>B1 B2 B3 ",
" C1 C2 C3 ",
],
);
}
#[test]
fn selected_column_moves_the_slot() {
assert_render(
HighlightPlacement::SelectedColumn,
Some(1),
Some(1),
[
"A1 A2 A3 ",
"B1 >>B2 B3 ",
"C1 C2 C3 ",
],
);
}
#[test]
fn selected_column_without_a_column_falls_back_to_first() {
assert_render(
HighlightPlacement::SelectedColumn,
Some(0),
None,
[
">>A1 A2 A3 ",
" B1 B2 B3 ",
" C1 C2 C3 ",
],
);
}
#[test]
fn columns_indents_each_listed_column() {
assert_render(
HighlightPlacement::Columns(vec![1, 2]),
Some(0),
None,
[
"A1 >>A2 >>A3 ",
"B1 B2 B3 ",
"C1 C2 C3 ",
],
);
}
#[test]
fn columns_ignores_out_of_range_indices() {
assert_render(
HighlightPlacement::Columns(vec![1, 9]),
Some(0),
None,
[
"A1 >>A2 A3 ",
"B1 B2 B3 ",
"C1 C2 C3 ",
],
);
}
#[test]
fn all_columns() {
assert_render(
HighlightPlacement::AllColumns,
Some(2),
None,
[
" A1 A2 A3 ",
" B1 B2 B3 ",
">>C1 >>C2 >>C3 ",
],
);
}
#[test]
fn column_only_selection_anchors_to_the_first_visible_row() {
let rows = ["A", "B", "C", "D"].map(|label| Row::new([label, label]));
let table = Table::new(rows, [Constraint::Length(1); 2])
.highlight_symbol(">>")
.highlight_placement(HighlightPlacement::SelectedColumn);
let mut state = TableState::new().with_offset(2).with_selected_column(1);
let area = Rect::new(0, 0, 8, 2);
let mut buf = Buffer::empty(area);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(["C >>C ", "D D "]));
}
#[test]
fn never_spacing_allocates_no_slot() {
let rows = [Row::new(["A1", "A2"]), Row::new(["B1", "B2"])];
let table = Table::new(rows, [Constraint::Length(2); 2])
.highlight_symbol(">>")
.highlight_spacing(HighlightSpacing::Never)
.highlight_placement(HighlightPlacement::AllColumns);
let mut state = TableState::new().with_selected(0);
let area = Rect::new(0, 0, 12, 2);
let mut buf = Buffer::empty(area);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(["A1 A2 ", "B1 B2 "]));
}
#[test]
fn symbol_follows_columns_not_spanned_cells() {
let rows = [Row::new([
Cell::from("A1").column_span(2),
Cell::from("A3"),
])];
let table = Table::new(rows, [Constraint::Length(2); 3])
.header(Row::new(["H1", "H2", "H3"]))
.highlight_symbol(">>")
.highlight_placement(HighlightPlacement::AllColumns);
let mut state = TableState::new().with_selected(0);
let area = Rect::new(0, 0, 20, 2);
let mut buf = Buffer::empty(area);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(
buf,
Buffer::with_lines([" H1 H2 H3 ", ">>A1 >> >>A3 "])
);
}
#[test]
fn column_highlight_does_not_reach_header_or_footer() {
let rows = [Row::new(["A1", "A2"])];
let table = Table::new(rows, [Constraint::Length(2); 2])
.header(Row::new(["H1", "H2"]))
.footer(Row::new(["F1", "F2"]))
.column_highlight_style(Style::new().blue());
let mut state = TableState::new().with_selected_column(1);
let area = Rect::new(0, 0, 6, 3);
let mut buf = Buffer::empty(area);
StatefulWidget::render(table, area, &mut buf, &mut state);
let mut expected = Buffer::with_lines(["H1 H2 ", "A1 A2 ", "F1 F2 "]);
expected.set_style(Rect::new(3, 1, 2, 1), Style::new().blue());
assert_eq!(buf, expected);
}
}
mod column_widths {
use super::*;
#[test]
fn length_constraint() {
let table = Table::default().widths([Length(4), Length(4)]);
assert_eq!(
table.get_column_widths(20, 0, 0, &[]),
[Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1),]
);
let table = Table::default().widths([Length(4), Length(4)]);
assert_eq!(
table.get_column_widths(20, 3, 0, &[true]),
[Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
);
let table = Table::default().widths([Length(4), Length(4)]);
assert_eq!(
table.get_column_widths(7, 0, 0, &[]),
[Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
);
let table = Table::default().widths([Length(4), Length(4)]);
assert_eq!(
table.get_column_widths(7, 3, 0, &[true]),
[Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
);
}
#[test]
fn max_constraint() {
let table = Table::default().widths([Max(4), Max(4)]);
assert_eq!(
table.get_column_widths(20, 0, 0, &[]),
[Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1)]
);
let table = Table::default().widths([Max(4), Max(4)]);
assert_eq!(
table.get_column_widths(20, 3, 0, &[true]),
[Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
);
let table = Table::default().widths([Max(4), Max(4)]);
assert_eq!(
table.get_column_widths(7, 0, 0, &[]),
[Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
);
let table = Table::default().widths([Max(4), Max(4)]);
assert_eq!(
table.get_column_widths(7, 3, 0, &[true]),
[Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
);
}
#[test]
fn min_constraint() {
let table = Table::default().widths([Min(4), Min(4)]);
assert_eq!(
table.get_column_widths(20, 0, 0, &[]),
[Rect::new(0, 0, 10, 1), Rect::new(11, 0, 9, 1)]
);
let table = Table::default().widths([Min(4), Min(4)]);
assert_eq!(
table.get_column_widths(20, 3, 0, &[true]),
[Rect::new(3, 0, 8, 1), Rect::new(12, 0, 8, 1)]
);
let table = Table::default().widths([Min(4), Min(4)]);
assert_eq!(
table.get_column_widths(7, 0, 0, &[]),
[Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
);
let table = Table::default().widths([Min(4), Min(4)]);
assert_eq!(
table.get_column_widths(7, 3, 0, &[true]),
[Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
);
}
#[test]
fn percentage_constraint() {
let table = Table::default().widths([Percentage(30), Percentage(30)]);
assert_eq!(
table.get_column_widths(20, 0, 0, &[]),
[Rect::new(0, 0, 6, 1), Rect::new(7, 0, 6, 1)]
);
let table = Table::default().widths([Percentage(30), Percentage(30)]);
assert_eq!(
table.get_column_widths(20, 3, 0, &[true]),
[Rect::new(3, 0, 5, 1), Rect::new(9, 0, 5, 1)]
);
let table = Table::default().widths([Percentage(30), Percentage(30)]);
assert_eq!(
table.get_column_widths(7, 0, 0, &[]),
[Rect::new(0, 0, 2, 1), Rect::new(3, 0, 2, 1)]
);
let table = Table::default().widths([Percentage(30), Percentage(30)]);
assert_eq!(
table.get_column_widths(7, 3, 0, &[true]),
[Rect::new(3, 0, 1, 1), Rect::new(5, 0, 1, 1)]
);
}
#[test]
fn ratio_constraint() {
let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
assert_eq!(
table.get_column_widths(20, 0, 0, &[]),
[Rect::new(0, 0, 7, 1), Rect::new(8, 0, 6, 1)]
);
let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
assert_eq!(
table.get_column_widths(20, 3, 0, &[true]),
[Rect::new(3, 0, 6, 1), Rect::new(10, 0, 5, 1)]
);
let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
assert_eq!(
table.get_column_widths(7, 0, 0, &[]),
[Rect::new(0, 0, 2, 1), Rect::new(3, 0, 3, 1)]
);
let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
assert_eq!(
table.get_column_widths(7, 3, 0, &[true]),
[Rect::new(3, 0, 1, 1), Rect::new(5, 0, 2, 1)]
);
}
#[test]
fn underconstrained_flex() {
let table = Table::default().widths([Min(10), Min(10), Min(1)]);
assert_eq!(
table.get_column_widths(62, 0, 0, &[]),
&[
Rect::new(0, 0, 20, 1),
Rect::new(21, 0, 20, 1),
Rect::new(42, 0, 20, 1)
]
);
let table = Table::default()
.widths([Min(10), Min(10), Min(1)])
.flex(Flex::Legacy);
assert_eq!(
table.get_column_widths(62, 0, 0, &[]),
&[
Rect::new(0, 0, 10, 1),
Rect::new(11, 0, 10, 1),
Rect::new(22, 0, 40, 1)
]
);
let table = Table::default()
.widths([Min(10), Min(10), Min(1)])
.flex(Flex::SpaceBetween);
assert_eq!(
table.get_column_widths(62, 0, 0, &[]),
&[
Rect::new(0, 0, 20, 1),
Rect::new(21, 0, 20, 1),
Rect::new(42, 0, 20, 1)
]
);
}
#[test]
fn underconstrained_segment_size() {
let table = Table::default().widths([Min(10), Min(10), Min(1)]);
assert_eq!(
table.get_column_widths(62, 0, 0, &[]),
&[
Rect::new(0, 0, 20, 1),
Rect::new(21, 0, 20, 1),
Rect::new(42, 0, 20, 1)
]
);
let table = Table::default()
.widths([Min(10), Min(10), Min(1)])
.flex(Flex::Legacy);
assert_eq!(
table.get_column_widths(62, 0, 0, &[]),
&[
Rect::new(0, 0, 10, 1),
Rect::new(11, 0, 10, 1),
Rect::new(22, 0, 40, 1)
]
);
}
#[test]
fn no_constraint_with_rows() {
let table = Table::default()
.rows(vec![
Row::new(vec!["a", "b"]),
Row::new(vec!["c", "d", "e"]),
])
.header(Row::new(vec!["f", "g"]))
.footer(Row::new(vec!["h", "i"]))
.column_spacing(0);
assert_eq!(
table.get_column_widths(30, 0, 3, &[]),
&[
Rect::new(0, 0, 10, 1),
Rect::new(10, 0, 10, 1),
Rect::new(20, 0, 10, 1)
]
);
}
#[test]
fn no_constraint_with_header() {
let table = Table::default()
.rows(vec![])
.header(Row::new(vec!["f", "g"]))
.column_spacing(0);
assert_eq!(
table.get_column_widths(10, 0, 2, &[]),
[Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
);
}
#[test]
fn no_constraint_with_footer() {
let table = Table::default()
.rows(vec![])
.footer(Row::new(vec!["h", "i"]))
.column_spacing(0);
assert_eq!(
table.get_column_widths(10, 0, 2, &[]),
[Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
);
}
#[track_caller]
fn test_table_with_selection<'line, Lines>(
highlight_spacing: HighlightSpacing,
columns: u16,
spacing: u16,
selection: Option<usize>,
expected: Lines,
) where
Lines: IntoIterator,
Lines::Item: Into<Line<'line>>,
{
let table = Table::default()
.rows(vec![Row::new(vec!["ABCDE", "12345"])])
.highlight_spacing(highlight_spacing)
.highlight_symbol(">>>")
.column_spacing(spacing);
let area = Rect::new(0, 0, columns, 3);
let mut buf = Buffer::empty(area);
let mut state = TableState::default().with_selected(selection);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(expected));
}
#[test]
fn excess_area_highlight_symbol_and_column_spacing_allocation() {
test_table_with_selection(
HighlightSpacing::Never,
15, 0, None, [
"ABCDE 12345 ",
" ", " ", ],
);
let table = Table::default()
.rows(vec![Row::new(vec!["ABCDE", "12345"])])
.widths([5, 5])
.column_spacing(0);
let area = Rect::new(0, 0, 15, 3);
let mut buf = Buffer::empty(area);
Widget::render(table, area, &mut buf);
let expected = Buffer::with_lines([
"ABCDE12345 ",
" ", " ", ]);
assert_eq!(buf, expected);
test_table_with_selection(
HighlightSpacing::Never,
15, 0, Some(0), [
"ABCDE 12345 ", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
15, 0, None, [
"ABCDE 12345 ", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
15, 0, Some(0), [
">>>ABCDE 12345 ", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
15, 0, None, [
" ABCDE 12345 ", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
15, 0, Some(0), [
">>>ABCDE 12345 ", " ", " ", ],
);
}
#[expect(clippy::too_many_lines)]
#[test]
fn insufficient_area_highlight_symbol_and_column_spacing_allocation() {
test_table_with_selection(
HighlightSpacing::Never,
10, 1, None, [
"ABCDE 1234", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
10, 1, None, [
"ABCDE 1234", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
10, 1, None, [
" ABC 123", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
9, 1, None, [
" ABC 12", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
8, 1, None, [
" AB 12", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
7, 1, None, [
" AB 1", " ", " ", ],
);
let table = Table::default()
.rows(vec![Row::new(vec!["ABCDE", "12345"])])
.highlight_spacing(HighlightSpacing::Always)
.flex(Flex::Legacy)
.highlight_symbol(">>>")
.column_spacing(1);
let area = Rect::new(0, 0, 10, 3);
let mut buf = Buffer::empty(area);
Widget::render(table, area, &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
" ABCDE 1",
" ",
" ",
]);
assert_eq!(buf, expected);
let table = Table::default()
.rows(vec![Row::new(vec!["ABCDE", "12345"])])
.highlight_spacing(HighlightSpacing::Always)
.flex(Flex::Start)
.highlight_symbol(">>>")
.column_spacing(1);
let area = Rect::new(0, 0, 10, 3);
let mut buf = Buffer::empty(area);
Widget::render(table, area, &mut buf);
#[rustfmt::skip]
let expected = Buffer::with_lines([
" ABC 123",
" ",
" ",
]);
assert_eq!(buf, expected);
test_table_with_selection(
HighlightSpacing::Never,
10, 1, Some(0), [
"ABCDE 1234", " ",
" ",
],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
10, 1, Some(0), [
">>>ABC 123", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
10, 1, Some(0), [
">>>ABC 123", " ", " ", ],
);
}
#[test]
fn insufficient_area_highlight_symbol_allocation_with_no_column_spacing() {
test_table_with_selection(
HighlightSpacing::Never,
10, 0, None, [
"ABCDE12345", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
10, 0, None, [
"ABCDE12345", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
10, 0, None, [
" ABCD123", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Never,
10, 0, Some(0), [
"ABCDE12345", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::WhenSelected,
10, 0, Some(0), [
">>>ABCD123", " ", " ", ],
);
test_table_with_selection(
HighlightSpacing::Always,
10, 0, Some(0), [
">>>ABCD123", " ", " ", ],
);
}
}
#[test]
fn stylize() {
assert_eq!(
Table::new(vec![Row::new(vec![Cell::from("")])], [Percentage(100)])
.black()
.on_white()
.bold()
.not_crossed_out()
.style,
Style::default()
.fg(Color::Black)
.bg(Color::White)
.add_modifier(Modifier::BOLD)
.remove_modifier(Modifier::CROSSED_OUT)
);
}
#[rstest]
#[case::no_columns(vec![], vec![], vec![], 0)]
#[case::only_header(vec!["H1", "H2"], vec![], vec![], 2)]
#[case::only_rows(
vec![],
vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
vec![],
3
)]
#[case::only_footer(vec![], vec![], vec!["F1", "F2", "F3", "F4"], 4)]
#[case::rows_longer(
vec!["H1", "H2", "H3", "H4"],
vec![vec!["C1", "C2"],vec!["C1", "C2", "C3"]],
vec!["F1", "F2"],
4
)]
#[case::rows_longer(
vec!["H1", "H2"],
vec![vec!["C1", "C2"], vec!["C1", "C2", "C3", "C4"]],
vec!["F1", "F2"],
4
)]
#[case::footer_longer(
vec!["H1", "H2"],
vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
vec!["F1", "F2", "F3", "F4"],
4
)]
fn column_count(
#[case] header: Vec<&str>,
#[case] rows: Vec<Vec<&str>>,
#[case] footer: Vec<&str>,
#[case] expected: usize,
) {
let header = Row::new(header);
let footer = Row::new(footer);
let rows: Vec<Row> = rows.into_iter().map(Row::new).collect();
let table = Table::new(rows, Vec::<Constraint>::new())
.header(header)
.footer(footer);
let column_count = table.column_count();
assert_eq!(column_count, expected);
}
#[test]
fn render_in_minimal_buffer() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
let rows = vec![
Row::new(vec!["Cell1", "Cell2", "Cell3"]),
Row::new(vec!["Cell4", "Cell5", "Cell6"]),
];
let table = Table::new(rows, [Constraint::Length(10); 3])
.header(Row::new(vec!["Header1", "Header2", "Header3"]))
.footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
Widget::render(table, buffer.area, &mut buffer);
assert_eq!(buffer, Buffer::with_lines([" "]));
}
#[test]
fn render_in_zero_size_buffer() {
let mut buffer = Buffer::empty(Rect::ZERO);
let rows = vec![
Row::new(vec!["Cell1", "Cell2", "Cell3"]),
Row::new(vec!["Cell4", "Cell5", "Cell6"]),
];
let table = Table::new(rows, [Constraint::Length(10); 3])
.header(Row::new(vec!["Header1", "Header2", "Header3"]))
.footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
Widget::render(table, buffer.area, &mut buffer);
}
#[test]
fn get_area_for_column_span_one_no_more_columns() {
let columns = [];
let column_span = Table::get_cell_area(&mut columns.iter(), 1, 1);
assert!(column_span.is_none());
}
#[test]
fn get_area_for_column_span_two_no_more_columns() {
let columns = [];
let column_span = Table::get_cell_area(&mut columns.iter(), 2, 1);
assert!(column_span.is_none());
}
#[rstest]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5,)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 5)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 2, 2)]
#[case(&[
Rect{x: 3, width: 2, y: 0, height: 1},
Rect{x: 3, width: 2, y: 0, height: 1},
Rect{x: 3, width: 2, y: 0, height: 1},
Rect{x: 3, width: 2, y: 0, height: 1},
], 3, 8)]
#[case(&[
Rect{x: 3, width: 2, y: 0, height: 1},
Rect{x: 3, width: 2, y: 0, height: 1},
Rect{x: 3, width: 2, y: 0, height: 1},
], 3, 8)]
fn test_colspan_width_single_column_spacing(
#[case] columns: &[Rect],
#[case] column_span: u16,
#[case] expected_column_width: u16,
) {
let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 1);
assert!(column_span.is_some());
assert_eq!(column_span.unwrap().width, expected_column_width);
}
#[rstest]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 10)]
#[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 3, 2)]
fn test_colspan_width_two_column_spacing(
#[case] columns: &[Rect],
#[case] column_span: u16,
#[case] expected_column_width: u16,
) {
let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 2);
assert!(column_span.is_some());
assert_eq!(column_span.unwrap().width, expected_column_width);
}
#[rstest]
#[case(
HighlightSpacing::Always,
15, // width
1, // spacing
None, // selection
[
Cell::new("ABCDEFGHIJK").column_span(2),
Cell::new("12345678901"),
Cell::new("XYZXYZXYZXY"),
],
[
" ABCDEFGH 123",
" ", // row 2
" ", // row 3
])]
#[case(
HighlightSpacing::Always,
15, // width
1, // spacing
Some(0), // selection
[
Cell::new("ABCDEFGHIJK").column_span(2),
Cell::new("12345678901"),
Cell::new("XYZXYZXYZXY"),
],
[
">>>ABCDEFGH 123",
" ", // row 2
" ", // row 3
])]
#[case(
HighlightSpacing::WhenSelected,
15, // width
1, // spacing
None, // selection
[
Cell::new("ABCDEFGHIJK").column_span(2),
Cell::new("12345678901"),
Cell::new("XYZXYZXYZXY"),
],
[
"ABCDEFGHIJ 1234",
" ", // row 2
" ", // row 3
])]
#[case(
HighlightSpacing::WhenSelected,
15, // width
1, // spacing
Some(0), // selection
[
Cell::new("ABCDEFGHIJK").column_span(2),
Cell::new("12345678901"),
Cell::new("XYZXYZXYZXY"),
],
[
">>>ABCDEFGH 123",
" ", // row 2
" ", // row 3
])]
fn test_table_with_selection_and_column_spans<'line, 'cell, Lines, Cells>(
#[case] highlight_spacing: HighlightSpacing,
#[case] columns: u16,
#[case] spacing: u16,
#[case] selection: Option<usize>,
#[case] cells: Cells,
#[case] expected: Lines,
) where
Cells: IntoIterator,
Cells::Item: Into<Cell<'cell>>,
Lines: IntoIterator,
Lines::Item: Into<Line<'line>>,
{
let table = Table::default()
.rows(vec![Row::new(cells)])
.highlight_spacing(highlight_spacing)
.highlight_symbol(">>>")
.column_spacing(spacing);
let area = Rect::new(0, 0, columns, 3);
let mut buf = Buffer::empty(area);
let mut state = TableState::default().with_selected(selection);
StatefulWidget::render(table, area, &mut buf, &mut state);
assert_eq!(buf, Buffer::with_lines(expected));
}
}