#![no_std]
extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;
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 ratatui_widgets::table::{HighlightSpacing, TableState};
pub use self::cell::Cell;
pub use self::row::Row;
mod cell;
mod row;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[derive(Debug)]
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,
flex: Flex,
scroll_padding: usize,
}
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(),
flex: Flex::Start,
scroll_padding: 0,
}
}
}
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
}
#[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"]
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 const fn flex(mut self, flex: Flex) -> Self {
self.flex = flex;
self
}
#[must_use = "method moves the value of self and returns the modified value"]
pub const fn scroll_padding(mut self, padding: usize) -> Self {
self.scroll_padding = padding;
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;
}
if state.selected().is_some_and(|s| s >= self.rows.len()) {
state.select(Some(self.rows.len().saturating_sub(1)));
}
if self.rows.is_empty() {
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 column_widths = self.get_column_widths(table_area.width, selection_width, column_count);
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);
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],
) {
if self.rows.is_empty() {
return;
}
let (start_index, end_index) = self.visible_rows(state, area);
*state.offset_mut() = 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
.saturating_add(y_offset)
.saturating_add(row.top_margin);
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().is_some_and(|index| index == i);
if selection_width > 0 && is_selected {
self.set_selection_style(buf, selection_width, row_area, row);
}
self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
if is_selected {
selected_row_area = Some(row_area);
}
y_offset = y_offset.saturating_add(row.height_with_margin());
}
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)
.intersection(row_area);
current_cell.render(area_to_render, buf);
}
}
}
fn set_selection_style(
&self,
buf: &mut Buffer,
selection_width: u16,
row_area: Rect,
row: &Row,
) {
let selection_area = Rect {
width: selection_width,
..row_area
}
.intersection(row_area);
buf.set_style(selection_area, row.style);
(&self.highlight_symbol).render(selection_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, u32::from(rect.width)))
.fold((1, u32::from(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) * u32::from(column_spacing);
let width = u16::try_from(width).unwrap_or(u16::MAX);
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: u16 = 0;
for item in self.rows.iter().skip(start) {
if height.saturating_add(item.height) > area.height {
break;
}
height = height.saturating_add(item.height_with_margin());
end += 1;
}
if let Some(selected) = state.selected() {
let selected = selected.min(last_row);
let index_to_display = self.apply_scroll_padding_to_selected_index(
selected,
area.height as usize,
start,
end,
);
while index_to_display >= 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;
}
}
while index_to_display < start {
start -= 1;
height = height.saturating_add(self.rows[start].height_with_margin());
while height > area.height {
end -= 1;
height = height.saturating_sub(self.rows[end].height_with_margin());
}
}
}
if height < area.height && end < self.rows.len() {
end += 1;
}
(start, end)
}
fn apply_scroll_padding_to_selected_index(
&self,
selected: usize,
max_height: usize,
first_visible_index: usize,
last_visible_index: usize,
) -> usize {
let last_valid_index = self.rows.len().saturating_sub(1);
if self.scroll_padding == 0 {
return selected;
}
let mut scroll_padding = self.scroll_padding.min(last_valid_index);
let pad_start = selected.saturating_sub(scroll_padding);
let pad_end = selected
.saturating_add(scroll_padding)
.min(last_valid_index);
let mut height_around_selected = self.rows[pad_start..=pad_end]
.iter()
.map(|row| row.height_with_margin() as usize)
.sum::<usize>();
while scroll_padding > 0 && height_around_selected > max_height {
if let Some(index) = selected.checked_sub(scroll_padding) {
height_around_selected = height_around_selected
.saturating_sub(self.rows[index].height_with_margin() as usize);
}
if let Some(index) = selected
.checked_add(scroll_padding)
.filter(|&index| index <= last_valid_index)
{
height_around_selected = height_around_selected
.saturating_sub(self.rows[index].height_with_margin() as usize);
}
scroll_padding -= 1;
}
let selected_after_padding = selected
.saturating_add(scroll_padding)
.min(last_valid_index);
if selected_after_padding >= last_visible_index {
selected_after_padding
} else if selected.saturating_sub(scroll_padding) < first_visible_index {
selected.saturating_sub(scroll_padding)
} else {
selected
}
}
fn get_column_widths(
&self,
max_width: u16,
selection_width: u16,
col_count: usize,
) -> 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 [_selection_area, columns_area] =
Layout::horizontal([Constraint::Length(selection_width), Constraint::Fill(0)])
.areas(Rect::new(0, 0, max_width, 1));
let rects = Layout::horizontal(widths)
.flex(self.flex)
.spacing(self.column_spacing)
.split(columns_area);
rects
.iter()
.map(|c| Rect::new(c.x, 0, c.width, 1))
.collect()
}
fn column_count(&self) -> usize {
self.rows
.iter()
.chain(self.footer.iter())
.chain(self.header.iter())
.map(|r| r.cells.len())
.max()
.unwrap_or_default()
}
fn selection_width(&self, state: &TableState) -> u16 {
let should_add = match self.highlight_spacing {
HighlightSpacing::Always => true,
HighlightSpacing::WhenSelected => state.selected().is_some(),
HighlightSpacing::Never => false,
};
if should_add {
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)
}
}