use makeover_layout::{CellPart, ColumnKind, ColumnRoom, Priority, Sort, Width};
use ratatui::layout::Constraint;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Cell as TrackCell, Row, Table};
use crate::Palette;
pub use makeover_layout::Sizing;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Head<'a> {
pub room: ColumnRoom<'a>,
pub sorted: Option<Sort>,
}
impl<'a> Head<'a> {
#[must_use]
pub const fn new(heading: &'a str) -> Self {
Self {
room: ColumnRoom::new(heading),
sorted: None,
}
}
#[must_use]
pub const fn name(&self) -> &'a str {
self.room.heading
}
#[must_use]
pub const fn min(mut self, ch: u16) -> Self {
self.room.min = Some(ch);
self
}
#[must_use]
pub const fn width(mut self, width: Width) -> Self {
self.room.width = width;
self
}
#[must_use]
pub const fn priority(mut self, priority: Priority) -> Self {
self.room.priority = priority;
self
}
#[must_use]
pub const fn kind(mut self, kind: ColumnKind) -> Self {
self.room.kind = kind;
self
}
#[must_use]
pub const fn sortable(mut self, sortable: bool) -> Self {
self.room.caret = sortable || self.sorted.is_some();
self
}
#[must_use]
pub const fn sorted(mut self, sort: Sort) -> Self {
self.sorted = Some(sort);
self.room.caret = true;
self
}
#[must_use]
pub const fn floor(&self) -> u16 {
self.room.floor()
}
#[must_use]
pub const fn kept_at(&self, cutoff: Priority) -> bool {
self.room.kept_at(cutoff)
}
}
fn rooms<'a>(heads: &[Head<'a>]) -> Vec<ColumnRoom<'a>> {
heads.iter().map(|head| head.room).collect()
}
#[derive(Debug, Clone)]
pub struct Cell<'a> {
pub column: &'a str,
pub part: Option<CellPart>,
pub content: Line<'a>,
}
impl<'a> Cell<'a> {
#[must_use]
pub fn new(column: &'a str, content: impl Into<Line<'a>>) -> Self {
Self {
column,
part: None,
content: content.into(),
}
}
#[must_use]
pub fn part(mut self, part: CellPart) -> Self {
self.part = Some(part);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableStyle {
pub column_spacing: u16,
pub ascending: &'static str,
pub descending: &'static str,
}
impl Default for TableStyle {
fn default() -> Self {
Self {
column_spacing: 1,
ascending: Sort::Ascending.glyph(),
descending: Sort::Descending.glyph(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableInk {
pub header: Style,
pub sorted: Style,
pub sortable: Style,
pub value: Style,
pub tokens: Style,
pub actions: Style,
pub link: Style,
pub selected: Style,
pub ground: Style,
pub stripe: Style,
pub style: TableStyle,
}
impl TableInk {
#[must_use]
pub fn new(palette: &Palette, style: &TableStyle) -> Self {
let t = &palette.tones;
let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
let bg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().bg(c));
let mut header = fg(t.secondary)
.patch(bg(t.sunken))
.add_modifier(Modifier::BOLD);
if t.sunken
.is_some_and(|sunken| !Palette::shows(sunken, t.ground.unwrap_or(palette.raised)))
{
header = header.add_modifier(Modifier::UNDERLINED);
}
Self {
header,
sorted: fg(t.content).add_modifier(Modifier::BOLD),
sortable: fg(t.secondary),
value: fg(t.content),
tokens: fg(t.secondary),
actions: fg(t.action),
link: fg(t.action).add_modifier(Modifier::UNDERLINED),
selected: match t.selected {
Some(selected) => Style::new().bg(selected).add_modifier(Modifier::BOLD),
None => Style::new().add_modifier(Modifier::REVERSED),
},
ground: bg(t.ground),
stripe: bg(t.stripe),
style: *style,
}
}
#[must_use]
pub fn for_part(&self, part: Option<CellPart>) -> Style {
match part {
Some(CellPart::Tokens) => self.tokens,
Some(CellPart::Actions) => self.actions,
Some(CellPart::Link) => self.link,
_ => self.value,
}
}
}
fn aligned<'a>(column: &Head<'_>, line: Line<'a>) -> Line<'a> {
if column.room.kind.aligns_end() {
line.right_aligned()
} else {
line
}
}
fn heading(column: &Head<'_>, style: &TableStyle) -> Line<'static> {
let label = column.name().to_uppercase();
let caret = match column.sorted {
Some(Sort::Descending) => style.descending,
Some(_) => style.ascending,
None if column.room.caret => style.ascending,
None => return Line::from(label),
};
Line::from(format!("{label} {caret}"))
}
const EDGE: Constraint = Constraint::Length(0);
fn edged<'a>(cells: impl Iterator<Item = TrackCell<'a>>) -> Vec<TrackCell<'a>> {
std::iter::once(TrackCell::new(""))
.chain(cells)
.chain(std::iter::once(TrackCell::new("")))
.collect()
}
fn measure<'a, R>(column: &Head<'_>, rows: &[R], style: &TableStyle) -> u16
where
R: AsRef<[Cell<'a>]>,
{
let widest = rows
.iter()
.filter_map(|row| {
row.as_ref()
.iter()
.find(|cell| cell.column == column.name())
.map(|cell| cell.content.width())
})
.max()
.unwrap_or(0);
u16::try_from(widest.max(heading(column, style).width())).unwrap_or(u16::MAX)
}
fn fits(budget: makeover_layout::Budget, style: &TableStyle, width: u16) -> bool {
budget.width(1.0, f32::from(style.column_spacing)) <= f32::from(width)
}
#[must_use]
pub fn cutoff_for(columns: &[Head<'_>], width: u16, style: &TableStyle) -> Priority {
ColumnRoom::cutoff_for(&rooms(columns), |budget| fits(budget, style, width))
}
#[must_use]
pub fn constraints<'a, R>(
columns: &[Head<'_>],
rows: &[R],
sizing: &Sizing<'_, u16>,
cutoff: Priority,
style: &TableStyle,
) -> Vec<Constraint>
where
R: AsRef<[Cell<'a>]>,
{
let tracks = columns
.iter()
.filter(|column| column.kept_at(cutoff))
.map(|column| match column.room.width {
Width::Content => Constraint::Length(measure(column, rows, style)),
Width::Fixed => Constraint::Length(sizing.length_for(column.name())),
_ => Constraint::Min(sizing.length_for(column.name())),
});
std::iter::once(EDGE)
.chain(tracks)
.chain(std::iter::once(EDGE))
.collect()
}
#[must_use]
pub fn row<'a>(
columns: &[Head<'_>],
cells: &[Cell<'a>],
cutoff: Priority,
ink: &TableInk,
) -> Row<'a> {
Row::new(edged(
columns
.iter()
.filter(|column| column.kept_at(cutoff))
.map(|column| {
let found = cells.iter().find(|cell| cell.column == column.name());
let part = found.and_then(|cell| cell.part);
let content = found.map_or_else(Line::default, |cell| {
crate::text::sanitise(cell.content.clone())
});
TrackCell::from(aligned(column, content)).style(ink.for_part(part))
}),
))
.style(ink.ground)
}
#[must_use]
pub fn header<'a>(columns: &[Head<'_>], cutoff: Priority, ink: &TableInk) -> Row<'a> {
Row::new(edged(
columns
.iter()
.filter(|column| column.kept_at(cutoff))
.map(|column| {
let tone = match (column.sorted, column.room.caret) {
(Some(_), _) => ink.sorted,
(None, true) => ink.sortable,
(None, false) => ink.header,
};
let head = crate::text::sanitise(heading(column, &ink.style));
TrackCell::from(aligned(column, head)).style(tone)
}),
))
.style(ink.header)
}
#[must_use]
pub fn table<'a, R>(
columns: &[Head<'_>],
rows: &[R],
sizing: &Sizing<'_, u16>,
width: u16,
ink: &TableInk,
) -> Table<'a>
where
R: AsRef<[Cell<'a>]>,
{
let cutoff = cutoff_for(columns, width, &ink.style);
let widths = constraints(columns, rows, sizing, cutoff, &ink.style);
let striped = striped(columns, cutoff);
let body: Vec<Row<'a>> = rows
.iter()
.enumerate()
.map(|(index, cells)| {
let drawn = row(columns, cells.as_ref(), cutoff, ink);
if striped && index % 2 == 1 {
drawn.style(ink.stripe)
} else {
drawn
}
})
.collect();
Table::new(body, widths)
.header(header(columns, cutoff, ink))
.column_spacing(ink.style.column_spacing)
.row_highlight_style(ink.selected)
}
#[must_use]
pub fn striped(columns: &[Head<'_>], cutoff: Priority) -> bool {
!columns
.iter()
.any(|column| column.kept_at(cutoff) && column.room.kind == ColumnKind::Code)
}
#[must_use]
pub fn overflows(columns: &[Head<'_>], width: u16, style: &TableStyle) -> bool {
!fits(
ColumnRoom::budget(&rooms(columns), Priority::Essential),
style,
width,
)
}
#[cfg(test)]
mod tests {
use super::*;
fn columns() -> Vec<Head<'static>> {
vec![
Head::new("name")
.width(Width::Fill)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(true)
.sorted(Sort::Ascending),
Head::new("size")
.width(Width::Fixed)
.priority(Priority::Secondary)
.kind(ColumnKind::Text)
.sortable(true),
Head::new("note")
.width(Width::Content)
.priority(Priority::Optional)
.kind(ColumnKind::Text)
.sortable(false),
]
}
fn sizing() -> Sizing<'static, u16> {
Sizing::new(&[("name", 10), ("size", 6)], 4)
}
fn ink_of(style: &TableStyle) -> TableInk {
let palette = crate::Palette::new(
Color::Reset,
Color::Reset,
Color::Reset,
Color::Reset,
Color::Reset,
crate::Fidelity::TrueColor,
);
TableInk::new(&palette, style)
}
fn ink_with(tones: crate::Tones) -> TableInk {
let palette = crate::Palette::new(
Color::Reset,
Color::Reset,
Color::Reset,
Color::Reset,
Color::Reset,
crate::Fidelity::TrueColor,
)
.tones(tones);
TableInk::new(&palette, &TableStyle::default())
}
fn rows() -> Vec<Vec<Cell<'static>>> {
vec![
vec![
Cell::new("name", "alpha"),
Cell::new("size", "1kb"),
Cell::new("note", "a longer note"),
],
vec![Cell::new("name", "beta"), Cell::new("size", "2kb")],
]
}
fn cell_text(row: &Row<'_>) -> Vec<String> {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
Table::new(vec![row.clone()], tracks())
.column_spacing(1)
.render(Rect::new(0, 0, 60, 1), &mut buf);
(0..3)
.map(|i| {
let start = 1 + i * 19;
(start..start + 18)
.map(|x| buf[(x as u16, 0)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect()
}
fn cell_colors(row: &Row<'_>) -> Vec<Option<ratatui::style::Color>> {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
Table::new(vec![row.clone()], tracks())
.column_spacing(1)
.render(Rect::new(0, 0, 60, 1), &mut buf);
(0..3).map(|i| buf[(1 + i * 19, 0)].fg).map(Some).collect()
}
fn tracks() -> [Constraint; 5] {
[
EDGE,
Constraint::Length(18),
Constraint::Length(18),
Constraint::Length(18),
EDGE,
]
}
#[test]
fn cells_are_ordered_by_the_columns_and_not_by_the_row() {
let cols = columns();
let out_of_order = vec![
Cell::new("note", "third"),
Cell::new("name", "first"),
Cell::new("size", "second"),
];
let drawn = row(
&cols,
&out_of_order,
Priority::Optional,
&ink_of(&TableStyle::default()),
);
assert_eq!(cell_text(&drawn), vec!["first", "second", "third"]);
}
#[test]
fn a_cell_naming_no_column_is_dropped_and_a_column_with_no_cell_keeps_its_place() {
let cols = columns();
let cells = vec![Cell::new("note", "kept"), Cell::new("nonesuch", "lost")];
let drawn = row(
&cols,
&cells,
Priority::Optional,
&ink_of(&TableStyle::default()),
);
assert_eq!(cell_text(&drawn), vec!["", "", "kept"]);
}
#[test]
fn a_content_column_is_measured_from_its_widest_cell() {
let style = TableStyle::default();
let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
assert_eq!(widths[3], Constraint::Length("a longer note".len() as u16));
}
#[test]
fn a_content_column_never_truncates_its_own_heading() {
let cols = vec![
Head::new("duration")
.width(Width::Content)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(false),
];
let rows = vec![vec![Cell::new("duration", "3s")]];
let widths = constraints(
&cols,
&rows,
&sizing(),
Priority::Optional,
&TableStyle::default(),
);
assert_eq!(widths[1], Constraint::Length(8));
}
#[test]
fn a_caret_is_part_of_what_a_heading_costs() {
let cols = vec![
Head::new("size")
.width(Width::Content)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(true)
.sorted(Sort::Descending),
];
let rows: Vec<Vec<Cell<'_>>> = vec![];
let style = TableStyle::default();
let widths = constraints(&cols, &rows, &sizing(), Priority::Optional, &style);
assert_eq!(
widths[1],
Constraint::Length(6),
"size plus a space and a caret"
);
}
#[test]
fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
let style = TableStyle::default();
let cols = columns();
assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
assert_eq!(cutoff_for(&cols, 35, &style), Priority::Secondary);
assert_eq!(cutoff_for(&cols, 27, &style), Priority::Secondary);
assert_eq!(cutoff_for(&cols, 26, &style), Priority::Essential);
assert_eq!(cutoff_for(&cols, 18, &style), Priority::Essential);
assert_eq!(cutoff_for(&cols, 2, &style), Priority::Essential);
assert!(overflows(&cols, 2, &style));
assert!(!overflows(&cols, 18, &style));
}
#[test]
fn a_declared_minimum_moves_the_cut_and_a_measured_cell_does_not() {
let style = TableStyle::default();
let mut cols = columns();
assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
cols[2] = cols[2].min(20);
assert_eq!(cutoff_for(&cols, 36, &style), Priority::Secondary);
assert_eq!(cutoff_for(&cols, 48, &style), Priority::Optional);
}
#[test]
fn a_column_inserted_left_of_the_cut_does_not_change_what_drops() {
let dropped = |cols: &[Head<'_>], cutoff| -> Vec<String> {
cols.iter()
.filter(|c| !c.kept_at(cutoff))
.map(|c| c.name().to_owned())
.collect()
};
let before = columns();
let mut after = vec![
Head::new("mark")
.width(Width::Fixed)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(false),
];
after.extend(columns());
for &cutoff in Priority::RAISING {
assert_eq!(
dropped(&before, cutoff),
dropped(&after, cutoff),
"inserting a column changed what {cutoff:?} drops"
);
}
assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
}
#[test]
fn a_column_never_outlives_a_more_essential_one() {
let style = TableStyle::default();
let cols = columns();
for width in 0..48u16 {
let cutoff = cutoff_for(&cols, width, &style);
let kept: Vec<&str> = cols
.iter()
.filter(|c| c.kept_at(cutoff))
.map(Head::name)
.collect();
assert!(
kept.contains(&"name"),
"the essential column left at {width}"
);
if kept.contains(&"note") {
assert!(
kept.contains(&"size"),
"optional outlived secondary at {width}"
);
}
}
}
#[test]
fn a_dropped_column_takes_its_track_with_it() {
let style = TableStyle::default();
let widths = constraints(&columns(), &rows(), &sizing(), Priority::Secondary, &style);
assert_eq!(widths.len(), 4, "two columns and the two edges");
let drawn = row(&columns(), &rows()[0], Priority::Secondary, &ink_of(&style));
assert_eq!(cell_text(&drawn), vec!["alpha", "1kb", ""]);
}
#[test]
fn a_fill_column_keeps_its_floor_while_taking_the_slack() {
let style = TableStyle::default();
let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
assert_eq!(widths[1], Constraint::Min(10));
assert_eq!(widths[2], Constraint::Length(6));
}
#[test]
fn a_column_with_no_length_of_its_own_takes_the_fallback() {
let cols = vec![
Head::new("unlisted")
.width(Width::Fixed)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(false),
];
let rows: Vec<Vec<Cell<'_>>> = vec![];
let widths = constraints(
&cols,
&rows,
&sizing(),
Priority::Optional,
&TableStyle::default(),
);
assert_eq!(widths[1], Constraint::Length(4));
}
#[test]
fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
let style = TableStyle::default();
let head = header(&columns(), Priority::Optional, &ink_of(&style));
assert_eq!(
cell_text(&head),
vec!["NAME \u{25B2}", "SIZE \u{25B2}", "NOTE"],
"in force and offering both carry one; not a control carries none"
);
}
#[test]
fn the_three_states_of_a_heading_are_three_tones() {
let mut ink = ink_of(&TableStyle::default());
ink.sorted = Style::new().fg(Color::Red);
ink.sortable = Style::new().fg(Color::Green);
ink.header = Style::new().fg(Color::Blue);
let drawn = cell_colors(&header(&columns(), Priority::Optional, &ink));
assert_eq!(
drawn,
vec![Some(Color::Red), Some(Color::Green), Some(Color::Blue)]
);
let house = TableStyle::default();
let plain = cell_colors(&header(&columns(), Priority::Optional, &ink_of(&house)));
assert_eq!(plain[0], plain[1], "no colour to spend, so none is claimed");
}
#[test]
fn pressing_a_heading_does_not_move_the_columns_after_it() {
let style = TableStyle::default();
let offering = Head::new("size")
.width(Width::Content)
.priority(Priority::Secondary)
.kind(ColumnKind::Text)
.sortable(true);
let in_force = offering.sorted(Sort::Descending);
let rows: Vec<Vec<Cell<'_>>> = vec![];
assert_eq!(
measure(&offering, &rows, &style),
measure(&in_force, &rows, &style)
);
let inert = offering.sortable(false);
assert!(measure(&inert, &rows, &style) < measure(&offering, &rows, &style));
}
#[test]
fn a_column_sorted_without_being_sortable_still_draws_its_caret() {
let cols = vec![
Head::new("rank")
.width(Width::Content)
.priority(Priority::Essential)
.kind(ColumnKind::Text)
.sortable(false)
.sorted(Sort::Descending),
];
let head = header(&cols, Priority::Optional, &ink_of(&TableStyle::default()));
assert_eq!(cell_text(&head), vec!["RANK \u{25BC}", "", ""]);
}
#[test]
fn the_parts_a_cell_can_be_are_styled_apart() {
let style = ink_of(&TableStyle::default());
assert_eq!(style.for_part(Some(CellPart::Value)), style.value);
assert_eq!(style.for_part(Some(CellPart::Tokens)), style.tokens);
assert_eq!(style.for_part(Some(CellPart::Actions)), style.actions);
assert_eq!(style.for_part(Some(CellPart::Link)), style.link);
assert_ne!(style.for_part(Some(CellPart::Link)), style.value);
assert_eq!(style.for_part(None), style.value);
}
#[test]
fn a_table_narrows_itself_from_the_width_it_is_given() {
let style = TableStyle::default();
let wide = table(&columns(), &rows(), &sizing(), 40, &ink_of(&style));
let narrow = table(&columns(), &rows(), &sizing(), 20, &ink_of(&style));
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 40, 3));
wide.render(Rect::new(0, 0, 40, 3), &mut buf);
let head: String = (0..40).map(|x| buf[(x, 0)].symbol()).collect();
assert!(head.contains("NOTE"));
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 20, 3));
narrow.render(Rect::new(0, 0, 20, 3), &mut buf);
let head: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
assert!(!head.contains("NOTE"), "the optional column is gone");
assert!(head.contains("NAME"), "the essential one is not");
}
#[test]
fn selection_is_carried_by_the_background_alone() {
assert!(ink_of(&TableStyle::default()).selected.fg.is_none());
let coloured = ink_with(crate::Tones::NONE.selected(Color::Blue));
assert_eq!(coloured.selected.bg, Some(Color::Blue));
assert!(coloured.selected.fg.is_none());
}
#[test]
fn a_number_column_aligns_its_cells_and_heading_to_the_end() {
let mut amount = Head::new("Amount");
amount.room.kind = ColumnKind::Number;
let prose = Head::new("Buyer");
assert_eq!(
aligned(&amount, Line::from("9.99")).alignment,
Some(ratatui::layout::Alignment::Right)
);
assert_eq!(aligned(&prose, Line::from("ada")).alignment, None);
}
#[test]
fn a_row_keeps_a_cell_of_ground_at_either_end() {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let cols = vec![Head::new("a").min(2), {
let mut n = Head::new("n").min(2);
n.room.kind = ColumnKind::Number;
n.room.width = Width::Fill;
n
}];
let rows = vec![vec![Cell::new("a", "x"), Cell::new("n", "9")]];
let drawn = table(&cols, &rows, &sizing(), 12, &ink_of(&TableStyle::default()));
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 12, 2));
drawn.render(Rect::new(0, 0, 12, 2), &mut buf);
let body: String = (0..12).map(|x| buf[(x, 1)].symbol()).collect();
assert!(body.starts_with(" x"), "{body:?}");
assert!(body.ends_with("9 "), "{body:?}");
}
#[test]
fn every_second_row_takes_the_stripe_and_a_code_table_takes_none() {
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
let ink = ink_with(crate::Tones::NONE.ground(Color::Blue).stripe(Color::Green));
let grounds = |cols: &[Head<'_>]| -> Vec<Color> {
let rows: Vec<Vec<Cell<'_>>> = (0..3).map(|_| vec![Cell::new("a", "x")]).collect();
let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 8, 4));
table(cols, &rows, &sizing(), 8, &ink).render(Rect::new(0, 0, 8, 4), &mut buf);
(1..4).map(|y| buf[(0, y)].bg).collect()
};
let records = vec![Head::new("a").min(2)];
assert_eq!(
grounds(&records),
vec![Color::Blue, Color::Green, Color::Blue]
);
let mut code = Head::new("a").min(2);
code.room.kind = ColumnKind::Code;
assert_eq!(grounds(&[code]), vec![Color::Blue; 3]);
}
}