makeover_tui/table.rs
1//! Column layout and row structure for tables.
2//!
3//! `makeover-webview`'s `list` module in the shape a terminal allows. It owns
4//! the same four things: which columns exist, how wide they are, which ones
5//! survive a narrow viewport, and what each part of a cell is. It does not own
6//! what goes in a cell, for the reason that module states: a cell holds whatever
7//! the app builds, and a description expressive enough to emit a task row's five
8//! nested spans is a templating language wearing a description's name.
9//!
10//! # What ratatui already answers
11//!
12//! Most of the drawing. [`ratatui::widgets::Table`] lays tracks out from
13//! [`Constraint`]s, draws a header, highlights a selected row and scrolls
14//! through [`TableState`](ratatui::widgets::TableState). So this is a mapping
15//! layer over it rather than a second table implementation, and it hands back a
16//! `Table` instead of painting one: selection and scroll belong to the app's
17//! state, and a function that painted would have to take that state to give it
18//! back.
19//!
20//! Two things ratatui does not answer, and they are what this module is:
21//!
22//! - **Content measurement.** There is no track that sizes to what is in it, so
23//! [`Width::Content`] is measured here from the cells and the heading.
24//! - **Narrowing.** A terminal window is resized far more often than a browser
25//! one, and [`Priority`] is how a column earns its place. See below.
26//!
27//! # Why positions are the bug
28//!
29//! The mistake is not a CSS one. Hiding columns by position (`nth-child(n+5)`
30//! against a seven-column table) means inserting a column left of the cut hides
31//! the wrong one, silently, because nothing in the rule knows what column five
32//! *is*. A renderer narrows by raising a cutoff and never by counting, which is
33//! the whole reason [`Priority`] exists. `a_column_inserted_left_of_the_cut_does_not_change_what_drops`
34//! is that bug as a test.
35//!
36//! # What it costs when nothing fits
37//!
38//! [`Priority::Essential`] never drops, so a window narrower than the essential
39//! columns leaves them overflowing rather than emptying the table. That is
40//! deliberate: a row that cannot identify itself is not a narrower row, it is a
41//! different one, and ratatui truncates a cell it cannot fit. Truncated and
42//! present beats absent.
43//!
44//! # The table model in cells
45//!
46//! Wiki `table-model`, which the webview renderer draws in pixels. A cell is
47//! one line tall and an edge occupies a whole cell, so three of its facts are
48//! translated rather than copied:
49//!
50//! - **No hairlines and no frame.** A rule between rows costs a row, which
51//! halves what a screen shows. The stripe separates rows alone.
52//! - **No 45px row.** A row is one line. The block padding survives as a cell
53//! of ground at either end, [`TableStyle::column_spacing`] wide, the way
54//! `gap-group` pads both ends of a webview row.
55//! - **A cursor row.** A terminal has a cursor where a browser has a hover, and
56//! it has to read over the stripe at a glance; see [`TableInk::selected`].
57//!
58//! The rest carries over as it is: rows on the raised ground with a stripe on
59//! alternate rows, the header as a sunken strip in secondary ink, and a table
60//! holding code keeping its header while dropping the stripe.
61
62use makeover_layout::{CellPart, ColumnKind, ColumnRoom, Priority, Sort, Width};
63use ratatui::layout::Constraint;
64use ratatui::style::{Color, Modifier, Style};
65use ratatui::text::Line;
66use ratatui::widgets::{Cell as TrackCell, Row, Table};
67
68use crate::Palette;
69
70/// The lengths a description defers, looked up by column name: terminal cells
71/// here, as `Sizing<'_, u16>`.
72pub use makeover_layout::Sizing;
73
74/// One column of a table: the room it asks the sizer for, and the order in
75/// force on it, if any.
76///
77/// The table's own column input. The sizing half is
78/// [`ColumnRoom`], the record every host sizes a
79/// table from, so a column drops at one declared width on every renderer; the
80/// order in force is the one fact a heading draws that sizing does not need.
81/// Whether the column offers to be reordered is [`ColumnRoom::caret`]: a caret
82/// sits beside a heading that is sortable or is the one the table is ordered by.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub struct Head<'a> {
85 /// What the column asks of the sizer, and whether its heading has a caret.
86 pub room: ColumnRoom<'a>,
87 /// The order in force on this column, when the table is ordered by it.
88 pub sorted: Option<Sort>,
89}
90
91impl<'a> Head<'a> {
92 /// A text column under `heading` that fills and is essential, the defaults
93 /// [`ColumnRoom::new`] gives.
94 #[must_use]
95 pub const fn new(heading: &'a str) -> Self {
96 Self {
97 room: ColumnRoom::new(heading),
98 sorted: None,
99 }
100 }
101
102 /// The heading, which is also the name a [`Cell`] fills the column by.
103 #[must_use]
104 pub const fn name(&self) -> &'a str {
105 self.room.heading
106 }
107
108 /// The same column, declaring the narrowest it may be before it drops.
109 #[must_use]
110 pub const fn min(mut self, ch: u16) -> Self {
111 self.room.min = Some(ch);
112 self
113 }
114
115 /// The same column, asking for this much room.
116 #[must_use]
117 pub const fn width(mut self, width: Width) -> Self {
118 self.room.width = width;
119 self
120 }
121
122 /// The same column, worth this much when room runs out.
123 #[must_use]
124 pub const fn priority(mut self, priority: Priority) -> Self {
125 self.room.priority = priority;
126 self
127 }
128
129 /// The same column, holding this kind of value.
130 #[must_use]
131 pub const fn kind(mut self, kind: ColumnKind) -> Self {
132 self.room.kind = kind;
133 self
134 }
135
136 /// The same column, reorderable by the user or not. A column the table is
137 /// ordered by keeps its caret either way.
138 #[must_use]
139 pub const fn sortable(mut self, sortable: bool) -> Self {
140 self.room.caret = sortable || self.sorted.is_some();
141 self
142 }
143
144 /// The same column, the one the table is ordered by, in this direction.
145 #[must_use]
146 pub const fn sorted(mut self, sort: Sort) -> Self {
147 self.sorted = Some(sort);
148 self.room.caret = true;
149 self
150 }
151
152 /// The narrowest this column is drawn, in `ch`. See [`ColumnRoom::floor`].
153 #[must_use]
154 pub const fn floor(&self) -> u16 {
155 self.room.floor()
156 }
157
158 /// Whether this column is kept at `cutoff`.
159 #[must_use]
160 pub const fn kept_at(&self, cutoff: Priority) -> bool {
161 self.room.kept_at(cutoff)
162 }
163}
164
165/// The sizing records for `heads`, in order.
166fn rooms<'a>(heads: &[Head<'a>]) -> Vec<ColumnRoom<'a>> {
167 heads.iter().map(|head| head.room).collect()
168}
169
170/// One cell of a row.
171///
172/// The contents are a ratatui [`Line`] rather than a string, which is this
173/// crate's version of the webview `Cell` holding markup: the app owns what goes
174/// in the cell, spans and all, and says which column it belongs to by name.
175#[derive(Debug, Clone)]
176pub struct Cell<'a> {
177 /// Which column this fills, by name.
178 pub column: &'a str,
179 /// What the cell holds, when the whole cell is one thing.
180 ///
181 /// `None` for a cell mixing parts. A cell holding a value *and* a strip of
182 /// tokens *and* a control is three parts in one cell, and a terminal cell
183 /// has one style to give, so the app styles the spans itself. This field is
184 /// for the single-part case, which is the common one.
185 pub part: Option<CellPart>,
186 /// The contents.
187 pub content: Line<'a>,
188}
189
190impl<'a> Cell<'a> {
191 /// A cell with no cell part.
192 #[must_use]
193 pub fn new(column: &'a str, content: impl Into<Line<'a>>) -> Self {
194 Self {
195 column,
196 part: None,
197 content: content.into(),
198 }
199 }
200
201 /// The same cell, saying which part it is.
202 #[must_use]
203 pub fn part(mut self, part: CellPart) -> Self {
204 self.part = Some(part);
205 self
206 }
207}
208
209/// The metrics and marks a table draws with.
210///
211/// No colours: those are the [`Palette`]'s, and [`TableInk`] is the two
212/// resolved together, the split `makeover-immediate` draws between its palette
213/// and its styles.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215#[non_exhaustive]
216pub struct TableStyle {
217 /// Cells between columns, and the ground at either end of a row. Counted
218 /// when deciding what fits, so a table that narrows and a table that draws
219 /// agree about the room available.
220 pub column_spacing: u16,
221 /// The caret drawn after the heading of an ascending column.
222 ///
223 /// Defaults to [`Sort::glyph`]. A knob because a terminal is the one host
224 /// that may not be able to draw it: a font without the geometric-shapes
225 /// block leaves a box, and `"^"` is a better caret than a tofu.
226 ///
227 /// Bare, with no leading space: the gap is the heading's, written once for
228 /// all three states.
229 pub ascending: &'static str,
230 /// The caret drawn after the heading of a descending column.
231 pub descending: &'static str,
232}
233
234impl Default for TableStyle {
235 fn default() -> Self {
236 Self {
237 column_spacing: 1,
238 ascending: Sort::Ascending.glyph(),
239 descending: Sort::Descending.glyph(),
240 }
241 }
242}
243
244/// A [`Palette`] and a [`TableStyle`], resolved into the styles a table draws
245/// with.
246///
247/// The table model (wiki `table-model`): rows on the raised ground with a
248/// stripe, the heading a sunken strip in bold secondary ink with the ordered
249/// column brought up to primary, each cell part in the ink
250/// [`CellPart::intent`] names, and selection carried by the background alone.
251///
252/// Where the palette has no colour for a role the table says it with a
253/// modifier: a bold heading, a reversed cursor row. Where
254/// the terminal cannot tell the strip from the ground, the heading is
255/// underlined as well, since the separation is what the strip is for.
256///
257/// Selection carries no foreground on purpose. A row can be red for a failed
258/// upload or green for a published item, and repainting its text on selection
259/// loses that on exactly the row the user is looking at.
260///
261/// Public for a caller assembling its own [`Table`], which takes
262/// [`stripe`](Self::stripe) and [`selected`](Self::selected) from here.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264#[non_exhaustive]
265pub struct TableInk {
266 /// The heading row.
267 pub header: Style,
268 /// The heading of the column the table is ordered by.
269 pub sorted: Style,
270 /// The heading of a column that offers to reorder and is not doing it now.
271 ///
272 /// The middle of three tones (wiki `three-tone-convention`): it answers a
273 /// press, so it is neither the emphasised thing nor the inert one.
274 pub sortable: Style,
275 /// A cell that is text.
276 pub value: Style,
277 /// A cell holding badges or chips. They carry their own tone, so this is
278 /// what shows through the gaps rather than what paints them.
279 pub tokens: Style,
280 /// A cell holding controls. They carry their own ink, so this is what an
281 /// unstyled run beside them takes.
282 pub actions: Style,
283 /// A cell whose value is itself a link: its row's title, in the ink the
284 /// values beside it take and with no underline, since the row is what
285 /// activates.
286 pub link: Style,
287 /// The row under the cursor, for a caller rendering with a
288 /// [`TableState`](ratatui::widgets::TableState).
289 pub selected: Style,
290 /// What a row sits on.
291 pub ground: Style,
292 /// What every second row sits on, counting from the first body row.
293 ///
294 /// Not drawn in a table holding a [`ColumnKind::Code`] column, which is
295 /// read as source: one row per line, where a stripe breaks the reading.
296 pub stripe: Style,
297 /// The metrics and marks.
298 pub style: TableStyle,
299}
300
301impl TableInk {
302 /// Resolve `palette`'s tones under `style`'s metrics.
303 #[must_use]
304 pub fn new(palette: &Palette, style: &TableStyle) -> Self {
305 let t = &palette.tones;
306 let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
307 let bg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().bg(c));
308 let mut header = fg(t.secondary)
309 .patch(bg(t.sunken))
310 .add_modifier(Modifier::BOLD);
311 if t.sunken
312 .is_some_and(|sunken| !Palette::shows(sunken, t.ground.unwrap_or(palette.raised)))
313 {
314 header = header.add_modifier(Modifier::UNDERLINED);
315 }
316 Self {
317 header,
318 sorted: fg(t.content).add_modifier(Modifier::BOLD),
319 // The strip's own ink. Offering and inert differ by the idle caret,
320 // which is the webview's split too.
321 sortable: fg(t.secondary),
322 value: fg(intent_tone(t, CellPart::Value.intent())),
323 tokens: fg(intent_tone(t, CellPart::Tokens.intent())),
324 actions: fg(intent_tone(t, CellPart::Actions.intent())),
325 link: fg(intent_tone(t, CellPart::Link.intent())),
326 selected: match t.selected {
327 Some(selected) => Style::new().bg(selected).add_modifier(Modifier::BOLD),
328 None => Style::new().add_modifier(Modifier::REVERSED),
329 },
330 ground: bg(t.ground),
331 stripe: bg(t.stripe),
332 style: *style,
333 }
334 }
335
336 /// The style a cell of this part takes.
337 ///
338 /// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
339 /// [`value`](Self::value): a part this renderer has not learned draws as
340 /// text, which is a cell rendering plainly rather than a build that stops.
341 #[must_use]
342 pub fn for_part(&self, part: Option<CellPart>) -> Style {
343 match part {
344 Some(CellPart::Tokens) => self.tokens,
345 Some(CellPart::Actions) => self.actions,
346 Some(CellPart::Link) => self.link,
347 _ => self.value,
348 }
349 }
350}
351
352/// The tone a content intent names, from makeover-layout's `content*` set.
353///
354/// An intent outside that set takes `content`, so a part makeover-layout gives
355/// a new intent draws as text until this renderer learns it.
356fn intent_tone(t: &crate::Tones, intent: &str) -> Option<Color> {
357 match intent {
358 "content-secondary" => t.secondary,
359 "content-muted" => t.muted,
360 _ => t.content,
361 }
362}
363
364/// A line placed the way its column's kind says, wiki `table-model`.
365///
366/// Alignment is the one kind fact a terminal has to act on. Every cell is
367/// already the monospace face with even figures, and a terminal wraps nothing
368/// it is not told to, so a number or an actions column aligning to its end is
369/// what is left. The heading takes the same, so a label sits over its figures.
370fn aligned<'a>(column: &Head<'_>, line: Line<'a>) -> Line<'a> {
371 if column.room.kind.aligns_end() {
372 line.right_aligned()
373 } else {
374 line
375 }
376}
377
378/// The heading, in capitals, with the caret if this column is ordered by or
379/// offers to be.
380///
381/// Capitals because the strip's label is set that way at every host. The
382/// webview sets it small and tracked as well, and a cell has neither to give,
383/// so the strip and the weight carry the rest.
384///
385/// A column [`sorted`](Head::sorted) but not
386/// [`sortable`](Head::sortable) still gets its caret. Both combinations mean
387/// something, which is why the description holds the two fields apart: a list
388/// ordered by a key the user cannot change is a real thing, and the caret is how
389/// it says so.
390///
391/// A column sortable and *not* sorted draws the idle mark, in the ascending
392/// spelling because that is the direction a first press takes. The tone is what
393/// separates it from the column in force, and [`header`] picks that; here the
394/// point is the width. This is what closes the reflow: pressing a heading used
395/// to widen its column by two cells and shift every column after it, because
396/// [`measure`] sizes from this function and the caret appeared with the press.
397fn heading(column: &Head<'_>, style: &TableStyle) -> Line<'static> {
398 let label = column.name().to_uppercase();
399 let caret = match column.sorted {
400 Some(Sort::Descending) => style.descending,
401 // Ascending, and an order this renderer has not learned, which reads
402 // as the direction a first press takes.
403 Some(_) => style.ascending,
404 None if column.room.caret => style.ascending,
405 None => return Line::from(label),
406 };
407 // The gap, once, rather than inside each of the two style strings. A
408 // consumer swapping the glyph for an ASCII one does not have to remember to
409 // bring a space with it.
410 Line::from(format!("{label} {caret}"))
411}
412
413/// The ground at either end of a row: a track of no width, which the table's
414/// column spacing then separates from the first and last columns.
415///
416/// A track rather than a space in the first and last cells, because which
417/// columns are first and last moves as the table narrows, and an end-aligned
418/// last column would have to know to leave its space behind.
419const EDGE: Constraint = Constraint::Length(0);
420
421/// A row's cells between its two edges.
422///
423/// `Cell::new("")` and never `Cell::default()`: ratatui derives the default
424/// with a column span of zero, and a cell spanning nothing takes no track, so
425/// every cell after it lands one column to the left.
426fn edged<'a>(cells: impl Iterator<Item = TrackCell<'a>>) -> Vec<TrackCell<'a>> {
427 std::iter::once(TrackCell::new(""))
428 .chain(cells)
429 .chain(std::iter::once(TrackCell::new("")))
430 .collect()
431}
432
433/// The cell column `at` draws from a row's cells.
434///
435/// By name, and by place among the columns sharing that name: the second
436/// column called `y` takes the second cell called `y`. Matching on the name
437/// alone would hand every same-named column the first such cell, and the
438/// second `y` would never be drawn.
439fn cell_of<'c, 'a>(columns: &[Head<'_>], at: usize, cells: &'c [Cell<'a>]) -> Option<&'c Cell<'a>> {
440 let name = columns.get(at)?.name();
441 let nth = columns[..at]
442 .iter()
443 .filter(|column| column.name() == name)
444 .count();
445 cells.iter().filter(|cell| cell.column == name).nth(nth)
446}
447
448/// The widest cell column `at` holds across `rows`, in cells, heading not
449/// included.
450///
451/// What [`table`] measures a [`Width::Content`] column with. A caller drawing
452/// a [`Window`] of a long table hands [`table_window`] its own answer to this
453/// question instead, worked out without building the rows it is not drawing.
454#[must_use]
455pub fn widest_cell<'a, R>(columns: &[Head<'_>], at: usize, rows: &[R]) -> u16
456where
457 R: AsRef<[Cell<'a>]>,
458{
459 let widest = rows
460 .iter()
461 .filter_map(|row| cell_of(columns, at, row.as_ref()).map(|cell| cell.content.width()))
462 .max()
463 .unwrap_or(0);
464 u16::try_from(widest).unwrap_or(u16::MAX)
465}
466
467/// The widest thing in a column: its widest cell or its heading.
468///
469/// The heading counts because it is drawn: a column sized to its cells alone
470/// truncates its own name, and a two-character column called `duration` reads as
471/// `du`. The caret counts for the same reason, which is why this measures
472/// [`heading`] rather than [`Head::name`].
473fn measure(column: &Head<'_>, widest: u16, style: &TableStyle) -> u16 {
474 widest.max(u16::try_from(heading(column, style).width()).unwrap_or(u16::MAX))
475}
476
477/// Whether a budget fits in `width` cells.
478///
479/// A floor is counted in `ch` and a cell is one `ch`, so the budget is
480/// [`Budget::width`](makeover_layout::Budget::width) at one cell per `ch`, with
481/// the column spacing as the gap between columns and at either end.
482fn fits(budget: makeover_layout::Budget, style: &TableStyle, width: u16) -> bool {
483 budget.width(1.0, f32::from(style.column_spacing)) <= f32::from(width)
484}
485
486/// The weakest cutoff whose columns fit in `width` cells.
487///
488/// [`ColumnRoom::cutoff_for`] with this renderer's unit filled in, which is
489/// the one thing it adds: the narrowing rule and the gap model are the
490/// description's, so all three renderers drop a column at one declared width.
491#[must_use]
492pub fn cutoff_for(columns: &[Head<'_>], width: u16, style: &TableStyle) -> Priority {
493 ColumnRoom::cutoff_for(&rooms(columns), |budget| fits(budget, style, width))
494}
495
496/// The tracks for the columns kept at `cutoff`.
497///
498/// Only the surviving tracks, which is what keeps the track list and the hiding
499/// in agreement. A caller that dropped a cell but left its track would get a
500/// column of empty space.
501///
502/// Bracketed by the two edge tracks, which [`row`] and [`header`] fill, so the
503/// list is two longer than the columns kept.
504#[must_use]
505pub fn constraints<'a, R>(
506 columns: &[Head<'_>],
507 rows: &[R],
508 sizing: &Sizing<'_, u16>,
509 cutoff: Priority,
510 style: &TableStyle,
511) -> Vec<Constraint>
512where
513 R: AsRef<[Cell<'a>]>,
514{
515 constraints_from(
516 columns,
517 |at| widest_cell(columns, at, rows),
518 sizing,
519 cutoff,
520 style,
521 )
522}
523
524/// [`constraints`], with each [`Width::Content`] column's widest cell answered
525/// by `widest`, which takes the column's index in `columns`.
526///
527/// Asked only of the content columns kept at `cutoff`. The heading is still
528/// measured here, so `widest` answers for the cells alone, as
529/// [`widest_cell`] does.
530#[must_use]
531pub fn constraints_from(
532 columns: &[Head<'_>],
533 mut widest: impl FnMut(usize) -> u16,
534 sizing: &Sizing<'_, u16>,
535 cutoff: Priority,
536 style: &TableStyle,
537) -> Vec<Constraint> {
538 let tracks = columns
539 .iter()
540 .enumerate()
541 .filter(|(_, column)| column.kept_at(cutoff))
542 .map(|(at, column)| match column.room.width {
543 // Takes what it needs and no more, which is a fixed track once the
544 // needing has been measured.
545 Width::Content => Constraint::Length(measure(column, widest(at), style)),
546 Width::Fixed => Constraint::Length(sizing.length_for(column.name())),
547 // `Min` and not `Fill`: a fill column absorbs the slack *and* keeps
548 // its floor. `Fill` would let it collapse below the floor when a
549 // fixed column takes the room.
550 _ => Constraint::Min(sizing.length_for(column.name())),
551 })
552 .collect::<Vec<_>>();
553 std::iter::once(EDGE)
554 .chain(tracks)
555 .chain(std::iter::once(EDGE))
556 .collect()
557}
558
559/// One row's cells, in column order, on the ground.
560///
561/// The ground and not the stripe, since a row does not know where it falls.
562/// [`table`] lays the stripe over every second row; a caller assembling its
563/// own [`Table`] takes [`TableInk::stripe`] for those rows itself, or asks
564/// [`striped`].
565///
566/// Ordered by the columns and not by the cells, so a row cannot silently
567/// disagree with its table about what comes where. A column with no cell gets an
568/// empty cell, which keeps the tracks aligned; a cell naming no column is
569/// dropped, because there is nowhere to put it. That is the webview renderer's
570/// rule too, and it has to be the same rule or the two renderers disagree about
571/// a row they were handed identically.
572#[must_use]
573pub fn row<'a>(
574 columns: &[Head<'_>],
575 cells: &[Cell<'a>],
576 cutoff: Priority,
577 ink: &TableInk,
578) -> Row<'a> {
579 Row::new(edged(
580 columns
581 .iter()
582 .enumerate()
583 .filter(|(_, column)| column.kept_at(cutoff))
584 .map(|(at, column)| {
585 let found = cell_of(columns, at, cells);
586 let part = found.and_then(|cell| cell.part);
587 let content = found.map_or_else(Line::default, |cell| {
588 crate::text::sanitise(cell.content.clone())
589 });
590 TrackCell::from(aligned(column, content)).style(ink.for_part(part))
591 }),
592 ))
593 .style(ink.ground)
594}
595
596/// The heading row for the columns kept at `cutoff`.
597///
598/// Exposed beside [`table`] because a caller assembling its own [`Table`] still
599/// has to draw a header that agrees with the body about what just disappeared.
600#[must_use]
601pub fn header<'a>(columns: &[Head<'_>], cutoff: Priority, ink: &TableInk) -> Row<'a> {
602 Row::new(edged(
603 columns
604 .iter()
605 .filter(|column| column.kept_at(cutoff))
606 .map(|column| {
607 // Three states, three tones (wiki `three-tone-convention`): in
608 // force, offering, and not a control at all.
609 let tone = match (column.sorted, column.room.caret) {
610 (Some(_), _) => ink.sorted,
611 (None, true) => ink.sortable,
612 (None, false) => ink.header,
613 };
614 let head = crate::text::sanitise(heading(column, &ink.style));
615 TrackCell::from(aligned(column, head)).style(tone)
616 }),
617 ))
618 .style(ink.header)
619}
620
621/// A described table, sized and narrowed for `width`.
622///
623/// Hands back a [`Table`] rather than drawing one. Selection and scroll live in
624/// the app's [`TableState`](ratatui::widgets::TableState), and the row highlight
625/// is already set from [`TableInk::selected`], so a caller renders this with
626/// `render_stateful_widget` and gets the house selection without saying anything
627/// further.
628///
629/// `width` is the area the table will be drawn in, which is what narrowing is
630/// decided against. Pass the [`Rect`](ratatui::layout::Rect) width that
631/// [`frame`](crate::frame) handed back rather than the region's own, or the
632/// table budgets for the two cells the edge took.
633///
634/// Builds every row it is handed. A table longer than its area is cheaper
635/// through [`table_window`], which builds only the rows drawn.
636#[must_use]
637pub fn table<'a, R>(
638 columns: &[Head<'_>],
639 rows: &[R],
640 sizing: &Sizing<'_, u16>,
641 width: u16,
642 ink: &TableInk,
643) -> Table<'a>
644where
645 R: AsRef<[Cell<'a>]>,
646{
647 table_window(
648 columns,
649 rows,
650 Window::WHOLE,
651 |at| widest_cell(columns, at, rows),
652 sizing,
653 width,
654 ink,
655 )
656}
657
658/// Which stretch of a longer table a caller is drawing.
659///
660/// A table's columns are sized from every row and its stripe is counted from
661/// the first, so drawing a stretch of one is not drawing a shorter table: the
662/// stretch has to know where it starts, and the widths have to come from rows
663/// it was not handed.
664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
665pub struct Window {
666 /// The whole table's index of the first row handed over.
667 pub first: usize,
668 /// Whether the heading row is drawn above it.
669 pub header: bool,
670}
671
672impl Window {
673 /// The whole table, from its heading down.
674 pub const WHOLE: Self = Self {
675 first: 0,
676 header: true,
677 };
678}
679
680/// A stretch of a described table, sized for the whole of it.
681///
682/// [`table`] for a caller that knows which rows it will draw. `rows` is that
683/// stretch alone, starting at the whole table's row `window.first`; `widest`
684/// answers each [`Width::Content`] column's widest cell across the WHOLE table,
685/// by column index, as [`constraints_from`] asks it. So the columns sit where
686/// they would with every row built, and a reader scrolling through does not see
687/// them move.
688///
689/// The stripe is counted from the whole table's first row, so a stretch
690/// starting on an odd row starts striped.
691#[must_use]
692pub fn table_window<'a, R>(
693 columns: &[Head<'_>],
694 rows: &[R],
695 window: Window,
696 widest: impl FnMut(usize) -> u16,
697 sizing: &Sizing<'_, u16>,
698 width: u16,
699 ink: &TableInk,
700) -> Table<'a>
701where
702 R: AsRef<[Cell<'a>]>,
703{
704 let cutoff = cutoff_for(columns, width, &ink.style);
705 let widths = constraints_from(columns, widest, sizing, cutoff, &ink.style);
706 let striped = striped(columns, cutoff);
707 let body: Vec<Row<'a>> = rows
708 .iter()
709 .enumerate()
710 .map(|(index, cells)| {
711 let drawn = row(columns, cells.as_ref(), cutoff, ink);
712 if striped && (window.first + index) % 2 == 1 {
713 drawn.style(ink.stripe)
714 } else {
715 drawn
716 }
717 })
718 .collect();
719
720 let drawn = Table::new(body, widths)
721 .column_spacing(ink.style.column_spacing)
722 .row_highlight_style(ink.selected);
723 if window.header {
724 drawn.header(header(columns, cutoff, ink))
725 } else {
726 drawn
727 }
728}
729
730/// Whether the rows of a table with these columns take the stripe.
731///
732/// False for a table holding code at `cutoff`, which keeps its header and
733/// drops the record treatment, as the webview renderer's code table does.
734#[must_use]
735pub fn striped(columns: &[Head<'_>], cutoff: Priority) -> bool {
736 !columns
737 .iter()
738 .any(|column| column.kept_at(cutoff) && column.room.kind == ColumnKind::Code)
739}
740
741/// Whether a table drawn at `width` would leave anything overflowing.
742///
743/// True only when the essential columns alone do not fit, since that is the one
744/// case narrowing cannot answer. A caller that would rather show fewer rows than
745/// truncate a cell can ask this and draw something else.
746#[must_use]
747pub fn overflows(columns: &[Head<'_>], width: u16, style: &TableStyle) -> bool {
748 !fits(
749 ColumnRoom::budget(&rooms(columns), Priority::Essential),
750 style,
751 width,
752 )
753}
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 fn columns() -> Vec<Head<'static>> {
760 vec![
761 Head::new("name")
762 .width(Width::Fill)
763 .priority(Priority::Essential)
764 .kind(ColumnKind::Text)
765 .sortable(true)
766 .sorted(Sort::Ascending),
767 Head::new("size")
768 .width(Width::Fixed)
769 .priority(Priority::Secondary)
770 .kind(ColumnKind::Text)
771 .sortable(true),
772 Head::new("note")
773 .width(Width::Content)
774 .priority(Priority::Optional)
775 .kind(ColumnKind::Text)
776 .sortable(false),
777 ]
778 }
779
780 fn sizing() -> Sizing<'static, u16> {
781 Sizing::new(&[("name", 10), ("size", 6)], 4)
782 }
783
784 /// A table's tones on a palette with none: what a terminal with no colour
785 /// to spend draws.
786 fn ink_of(style: &TableStyle) -> TableInk {
787 let palette = crate::Palette::new(
788 Color::Reset,
789 Color::Reset,
790 Color::Reset,
791 Color::Reset,
792 Color::Reset,
793 crate::Fidelity::TrueColor,
794 );
795 TableInk::new(&palette, style)
796 }
797
798 /// A table's ink on a palette with these tones.
799 fn ink_with(tones: crate::Tones) -> TableInk {
800 let palette = crate::Palette::new(
801 Color::Reset,
802 Color::Reset,
803 Color::Reset,
804 Color::Reset,
805 Color::Reset,
806 crate::Fidelity::TrueColor,
807 )
808 .tones(tones);
809 TableInk::new(&palette, &TableStyle::default())
810 }
811
812 fn rows() -> Vec<Vec<Cell<'static>>> {
813 vec![
814 vec![
815 Cell::new("name", "alpha"),
816 Cell::new("size", "1kb"),
817 Cell::new("note", "a longer note"),
818 ],
819 vec![Cell::new("name", "beta"), Cell::new("size", "2kb")],
820 ]
821 }
822
823 fn cell_text(row: &Row<'_>) -> Vec<String> {
824 // Rendering is the only way to read a ratatui Row back, and reading it
825 // back is the point: these tests assert what a user sees.
826 use ratatui::layout::Rect;
827 use ratatui::widgets::Widget;
828 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
829 Table::new(vec![row.clone()], tracks())
830 .column_spacing(1)
831 .render(Rect::new(0, 0, 60, 1), &mut buf);
832 (0..3)
833 .map(|i| {
834 let start = 1 + i * 19;
835 (start..start + 18)
836 .map(|x| buf[(x as u16, 0)].symbol())
837 .collect::<String>()
838 .trim_end()
839 .to_owned()
840 })
841 .collect()
842 }
843
844 /// The foreground each of the three heading cells was drawn in.
845 ///
846 /// Read off a rendered buffer for [`cell_text`]'s reason: a ratatui `Row`
847 /// hands nothing back, and what is asserted is what a user sees.
848 fn cell_colors(row: &Row<'_>) -> Vec<Option<ratatui::style::Color>> {
849 use ratatui::layout::Rect;
850 use ratatui::widgets::Widget;
851 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
852 Table::new(vec![row.clone()], tracks())
853 .column_spacing(1)
854 .render(Rect::new(0, 0, 60, 1), &mut buf);
855 (0..3).map(|i| buf[(1 + i * 19, 0)].fg).map(Some).collect()
856 }
857
858 /// Three columns of 18 between the two edges, which puts column `i` at
859 /// `1 + i * 19`.
860 fn tracks() -> [Constraint; 5] {
861 [
862 EDGE,
863 Constraint::Length(18),
864 Constraint::Length(18),
865 Constraint::Length(18),
866 EDGE,
867 ]
868 }
869
870 #[test]
871 fn cells_are_ordered_by_the_columns_and_not_by_the_row() {
872 // The row hands them over backwards. The table decides the order, which
873 // is what stops a row silently disagreeing with its own header.
874 let cols = columns();
875 let out_of_order = vec![
876 Cell::new("note", "third"),
877 Cell::new("name", "first"),
878 Cell::new("size", "second"),
879 ];
880 let drawn = row(
881 &cols,
882 &out_of_order,
883 Priority::Optional,
884 &ink_of(&TableStyle::default()),
885 );
886 assert_eq!(cell_text(&drawn), vec!["first", "second", "third"]);
887 }
888
889 #[test]
890 fn a_cell_naming_no_column_is_dropped_and_a_column_with_no_cell_keeps_its_place() {
891 let cols = columns();
892 let cells = vec![Cell::new("note", "kept"), Cell::new("nonesuch", "lost")];
893 let drawn = row(
894 &cols,
895 &cells,
896 Priority::Optional,
897 &ink_of(&TableStyle::default()),
898 );
899 // Two empty tracks, then the note. The empties are what keeps the third
900 // column under the third heading.
901 assert_eq!(cell_text(&drawn), vec!["", "", "kept"]);
902 }
903
904 #[test]
905 fn a_content_column_is_measured_from_its_widest_cell() {
906 let style = TableStyle::default();
907 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
908 assert_eq!(widths[3], Constraint::Length("a longer note".len() as u16));
909 }
910
911 #[test]
912 fn a_content_column_never_truncates_its_own_heading() {
913 // The cells are two characters wide and the heading is eight. Sizing to
914 // the cells alone would draw the column as `du`.
915 let cols = vec![
916 Head::new("duration")
917 .width(Width::Content)
918 .priority(Priority::Essential)
919 .kind(ColumnKind::Text)
920 .sortable(false),
921 ];
922 let rows = vec![vec![Cell::new("duration", "3s")]];
923 let widths = constraints(
924 &cols,
925 &rows,
926 &sizing(),
927 Priority::Optional,
928 &TableStyle::default(),
929 );
930 assert_eq!(widths[1], Constraint::Length(8));
931 }
932
933 #[test]
934 fn a_caret_is_part_of_what_a_heading_costs() {
935 // Measured off `heading` and not off `name`, or the sorted column is
936 // exactly two cells too narrow and drops its own arrow.
937 let cols = vec![
938 Head::new("size")
939 .width(Width::Content)
940 .priority(Priority::Essential)
941 .kind(ColumnKind::Text)
942 .sortable(true)
943 .sorted(Sort::Descending),
944 ];
945 let rows: Vec<Vec<Cell<'_>>> = vec![];
946 let style = TableStyle::default();
947 let widths = constraints(&cols, &rows, &sizing(), Priority::Optional, &style);
948 assert_eq!(
949 widths[1],
950 Constraint::Length(6),
951 "size plus a space and a caret"
952 );
953 }
954
955 #[test]
956 fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
957 let style = TableStyle::default();
958 let cols = columns();
959 // Everything: floors of 16 (the name fills), 8 and 8, and a cell of
960 // spacing either side of each, which is 32 + 4.
961 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
962 assert_eq!(cutoff_for(&cols, 35, &style), Priority::Secondary);
963 // No room for the note: 24 + 3.
964 assert_eq!(cutoff_for(&cols, 27, &style), Priority::Secondary);
965 // No room for the size either: 16 + 2.
966 assert_eq!(cutoff_for(&cols, 26, &style), Priority::Essential);
967 assert_eq!(cutoff_for(&cols, 18, &style), Priority::Essential);
968 // No room for anything, and the essential column stays anyway.
969 assert_eq!(cutoff_for(&cols, 2, &style), Priority::Essential);
970 assert!(overflows(&cols, 2, &style));
971 assert!(!overflows(&cols, 18, &style));
972 }
973
974 #[test]
975 fn a_declared_minimum_moves_the_cut_and_a_measured_cell_does_not() {
976 // The floor is what the three hosts agree on, so a long value in a cell
977 // must not change where a column drops, and a declared minimum must.
978 let style = TableStyle::default();
979 let mut cols = columns();
980 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
981 cols[2] = cols[2].min(20);
982 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Secondary);
983 assert_eq!(cutoff_for(&cols, 48, &style), Priority::Optional);
984 }
985
986 #[test]
987 fn a_column_inserted_left_of_the_cut_does_not_change_what_drops() {
988 // The goingson bug, as a test. `nth-child(n+5)` against a seven-column
989 // table hides whatever lands at position five, so inserting a column
990 // anywhere left of the cut moves it onto a different column with nothing
991 // edited and nothing reported.
992 //
993 // Asserted at a fixed cutoff, because that is where the two ways of
994 // addressing a column disagree. A narrower budget SHOULD drop more
995 // columns, and does below; what must not change is which ones, in what
996 // order, for a given cutoff.
997 let dropped = |cols: &[Head<'_>], cutoff| -> Vec<String> {
998 cols.iter()
999 .filter(|c| !c.kept_at(cutoff))
1000 .map(|c| c.name().to_owned())
1001 .collect()
1002 };
1003 let before = columns();
1004 let mut after = vec![
1005 Head::new("mark")
1006 .width(Width::Fixed)
1007 .priority(Priority::Essential)
1008 .kind(ColumnKind::Text)
1009 .sortable(false),
1010 ];
1011 after.extend(columns());
1012
1013 for &cutoff in Priority::RAISING {
1014 assert_eq!(
1015 dropped(&before, cutoff),
1016 dropped(&after, cutoff),
1017 "inserting a column changed what {cutoff:?} drops"
1018 );
1019 }
1020 assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
1021 }
1022
1023 #[test]
1024 fn a_column_never_outlives_a_more_essential_one() {
1025 // The ordering claim narrowing rests on: whatever the budget, the set
1026 // kept is closed upward. A layout that dropped `size` while keeping
1027 // `note` would be counting something other than priority.
1028 let style = TableStyle::default();
1029 let cols = columns();
1030 for width in 0..48u16 {
1031 let cutoff = cutoff_for(&cols, width, &style);
1032 let kept: Vec<&str> = cols
1033 .iter()
1034 .filter(|c| c.kept_at(cutoff))
1035 .map(Head::name)
1036 .collect();
1037 assert!(
1038 kept.contains(&"name"),
1039 "the essential column left at {width}"
1040 );
1041 if kept.contains(&"note") {
1042 assert!(
1043 kept.contains(&"size"),
1044 "optional outlived secondary at {width}"
1045 );
1046 }
1047 }
1048 }
1049
1050 #[test]
1051 fn a_dropped_column_takes_its_track_with_it() {
1052 // A cell hidden with its track left behind is a column of empty space,
1053 // which is the half of the goingson bug that survives fixing the other.
1054 let style = TableStyle::default();
1055 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Secondary, &style);
1056 assert_eq!(widths.len(), 4, "two columns and the two edges");
1057 let drawn = row(&columns(), &rows()[0], Priority::Secondary, &ink_of(&style));
1058 assert_eq!(cell_text(&drawn), vec!["alpha", "1kb", ""]);
1059 }
1060
1061 #[test]
1062 fn a_fill_column_keeps_its_floor_while_taking_the_slack() {
1063 // `Min` and not `Fill`, which is `minmax(10, 1fr)` at the webview
1064 // renderer. A `Fill` track collapses under a fixed neighbour.
1065 let style = TableStyle::default();
1066 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
1067 assert_eq!(widths[1], Constraint::Min(10));
1068 assert_eq!(widths[2], Constraint::Length(6));
1069 }
1070
1071 #[test]
1072 fn a_column_with_no_length_of_its_own_takes_the_fallback() {
1073 let cols = vec![
1074 Head::new("unlisted")
1075 .width(Width::Fixed)
1076 .priority(Priority::Essential)
1077 .kind(ColumnKind::Text)
1078 .sortable(false),
1079 ];
1080 let rows: Vec<Vec<Cell<'_>>> = vec![];
1081 let widths = constraints(
1082 &cols,
1083 &rows,
1084 &sizing(),
1085 Priority::Optional,
1086 &TableStyle::default(),
1087 );
1088 assert_eq!(widths[1], Constraint::Length(4));
1089 }
1090
1091 #[test]
1092 fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
1093 let style = TableStyle::default();
1094 let head = header(&columns(), Priority::Optional, &ink_of(&style));
1095 assert_eq!(
1096 cell_text(&head),
1097 vec!["NAME \u{25B2}", "SIZE \u{25B2}", "NOTE"],
1098 "in force and offering both carry one; not a control carries none"
1099 );
1100 }
1101
1102 #[test]
1103 fn the_three_states_of_a_heading_are_three_tones() {
1104 // wiki `three-tone-convention`. The middle state is the one that had
1105 // nowhere to be said: a heading you can press looked exactly like one
1106 // you cannot, and the idle caret alone does not separate them, because
1107 // a sorted-but-unsortable column draws a caret too.
1108 let mut ink = ink_of(&TableStyle::default());
1109 ink.sorted = Style::new().fg(Color::Red);
1110 ink.sortable = Style::new().fg(Color::Green);
1111 ink.header = Style::new().fg(Color::Blue);
1112 let drawn = cell_colors(&header(&columns(), Priority::Optional, &ink));
1113 assert_eq!(
1114 drawn,
1115 vec![Some(Color::Red), Some(Color::Green), Some(Color::Blue)]
1116 );
1117
1118 // The colourless default separates them by the caret and nothing else,
1119 // and that is the honest limit rather than an oversight: a cell style
1120 // patches the row's, so a plain cell under a bold header row is drawn
1121 // bold whatever it holds. Three tones need three colours, which is what
1122 // a palette's tones are for.
1123 let house = TableStyle::default();
1124 let plain = cell_colors(&header(&columns(), Priority::Optional, &ink_of(&house)));
1125 assert_eq!(plain[0], plain[1], "no colour to spend, so none is claimed");
1126 }
1127
1128 #[test]
1129 fn pressing_a_heading_does_not_move_the_columns_after_it() {
1130 // The reflow the idle caret closes. `measure` sizes from `heading`, so
1131 // a caret that appeared with the press widened its own column by two
1132 // cells and shifted the rest of the row sideways.
1133 let style = TableStyle::default();
1134 let offering = Head::new("size")
1135 .width(Width::Content)
1136 .priority(Priority::Secondary)
1137 .kind(ColumnKind::Text)
1138 .sortable(true);
1139 let in_force = offering.sorted(Sort::Descending);
1140 assert_eq!(measure(&offering, 0, &style), measure(&in_force, 0, &style));
1141
1142 // And the column that is not a control at all is narrower, which is the
1143 // width that would be wrong to reserve: it has no caret to draw.
1144 let inert = offering.sortable(false);
1145 assert!(measure(&inert, 0, &style) < measure(&offering, 0, &style));
1146 }
1147
1148 #[test]
1149 fn a_column_sorted_without_being_sortable_still_draws_its_caret() {
1150 // A list ordered by a key the user cannot change is a real thing to
1151 // describe, which is why the description holds the two fields apart.
1152 // Drawing the caret only for a sortable column would collapse them.
1153 let cols = vec![
1154 Head::new("rank")
1155 .width(Width::Content)
1156 .priority(Priority::Essential)
1157 .kind(ColumnKind::Text)
1158 .sortable(false)
1159 .sorted(Sort::Descending),
1160 ];
1161 let head = header(&cols, Priority::Optional, &ink_of(&TableStyle::default()));
1162 assert_eq!(cell_text(&head), vec!["RANK \u{25BC}", "", ""]);
1163 }
1164
1165 #[test]
1166 fn a_cell_part_takes_the_ink_its_intent_names() {
1167 // makeover-layout's `CellPart::intent` is the rule every host reads, so
1168 // a link here draws as the webview's does: in the values' ink, with no
1169 // underline.
1170 let tones = crate::Tones {
1171 content: Some(Color::Indexed(1)),
1172 secondary: Some(Color::Indexed(2)),
1173 muted: Some(Color::Indexed(3)),
1174 action: Some(Color::Indexed(4)),
1175 ..crate::Tones::default()
1176 };
1177 let ink = ink_with(tones);
1178 for part in [
1179 CellPart::Value,
1180 CellPart::Tokens,
1181 CellPart::Actions,
1182 CellPart::Link,
1183 ] {
1184 let want = match part.intent() {
1185 "content" => tones.content,
1186 "content-secondary" => tones.secondary,
1187 "content-muted" => tones.muted,
1188 other => panic!("{part:?} names {other}, which this renderer has not learned"),
1189 };
1190 let got = ink.for_part(Some(part));
1191 assert_eq!(got.fg, want, "{part:?}");
1192 assert_eq!(got.add_modifier, Modifier::empty(), "{part:?}");
1193 }
1194 // A cell mixing parts says nothing, and takes the text style.
1195 assert_eq!(ink.for_part(None), ink.value);
1196 }
1197
1198 #[test]
1199 fn a_table_narrows_itself_from_the_width_it_is_given() {
1200 // The whole path in one call, which is what a consumer actually uses.
1201 let style = TableStyle::default();
1202 let wide = table(&columns(), &rows(), &sizing(), 40, &ink_of(&style));
1203 let narrow = table(&columns(), &rows(), &sizing(), 20, &ink_of(&style));
1204 use ratatui::layout::Rect;
1205 use ratatui::widgets::Widget;
1206
1207 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 40, 3));
1208 wide.render(Rect::new(0, 0, 40, 3), &mut buf);
1209 let head: String = (0..40).map(|x| buf[(x, 0)].symbol()).collect();
1210 assert!(head.contains("NOTE"));
1211
1212 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 20, 3));
1213 narrow.render(Rect::new(0, 0, 20, 3), &mut buf);
1214 let head: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
1215 assert!(!head.contains("NOTE"), "the optional column is gone");
1216 assert!(head.contains("NAME"), "the essential one is not");
1217 }
1218
1219 #[test]
1220 fn selection_is_carried_by_the_background_alone() {
1221 // A row can be red for a failure or green for a success, and a
1222 // foreground on the selection loses that on exactly the row being looked
1223 // at. Asserted with a selection colour and without one.
1224 assert!(ink_of(&TableStyle::default()).selected.fg.is_none());
1225 let coloured = ink_with(crate::Tones::NONE.selected(Color::Blue));
1226 assert_eq!(coloured.selected.bg, Some(Color::Blue));
1227 assert!(coloured.selected.fg.is_none());
1228 }
1229
1230 #[test]
1231 fn a_number_column_aligns_its_cells_and_heading_to_the_end() {
1232 let mut amount = Head::new("Amount");
1233 amount.room.kind = ColumnKind::Number;
1234 let prose = Head::new("Buyer");
1235 assert_eq!(
1236 aligned(&amount, Line::from("9.99")).alignment,
1237 Some(ratatui::layout::Alignment::Right)
1238 );
1239 assert_eq!(aligned(&prose, Line::from("ada")).alignment, None);
1240 }
1241
1242 #[test]
1243 fn a_row_keeps_a_cell_of_ground_at_either_end() {
1244 // The block padding, in cells. The first value does not touch the
1245 // table's left edge and an end-aligned last column does not touch its
1246 // right, whichever columns narrowing left first and last.
1247 use ratatui::layout::Rect;
1248 use ratatui::widgets::Widget;
1249 // Declared narrow, so both columns are kept in twelve cells: this is
1250 // about the ground at the ends, not about narrowing.
1251 let cols = vec![Head::new("a").min(2), {
1252 let mut n = Head::new("n").min(2);
1253 n.room.kind = ColumnKind::Number;
1254 n.room.width = Width::Fill;
1255 n
1256 }];
1257 let rows = vec![vec![Cell::new("a", "x"), Cell::new("n", "9")]];
1258 let drawn = table(&cols, &rows, &sizing(), 12, &ink_of(&TableStyle::default()));
1259 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 12, 2));
1260 drawn.render(Rect::new(0, 0, 12, 2), &mut buf);
1261 let body: String = (0..12).map(|x| buf[(x, 1)].symbol()).collect();
1262 assert!(body.starts_with(" x"), "{body:?}");
1263 assert!(body.ends_with("9 "), "{body:?}");
1264 }
1265
1266 #[test]
1267 fn every_second_row_takes_the_stripe_and_a_code_table_takes_none() {
1268 use ratatui::layout::Rect;
1269 use ratatui::widgets::Widget;
1270 let ink = ink_with(crate::Tones::NONE.ground(Color::Blue).stripe(Color::Green));
1271 let grounds = |cols: &[Head<'_>]| -> Vec<Color> {
1272 let rows: Vec<Vec<Cell<'_>>> = (0..3).map(|_| vec![Cell::new("a", "x")]).collect();
1273 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 8, 4));
1274 table(cols, &rows, &sizing(), 8, &ink).render(Rect::new(0, 0, 8, 4), &mut buf);
1275 (1..4).map(|y| buf[(0, y)].bg).collect()
1276 };
1277 let records = vec![Head::new("a").min(2)];
1278 assert_eq!(
1279 grounds(&records),
1280 vec![Color::Blue, Color::Green, Color::Blue]
1281 );
1282
1283 let mut code = Head::new("a").min(2);
1284 code.room.kind = ColumnKind::Code;
1285 assert_eq!(grounds(&[code]), vec![Color::Blue; 3]);
1286 }
1287
1288 /// Two columns sharing a name draw two cells, in order. Matched on the
1289 /// name alone both would draw the first, and the second never showed.
1290 #[test]
1291 fn same_named_columns_take_same_named_cells_in_order() {
1292 let cols = vec![
1293 Head::new("y").width(Width::Fixed),
1294 Head::new("x").width(Width::Fixed),
1295 Head::new("y").width(Width::Content),
1296 ];
1297 let cells = vec![
1298 Cell::new("y", "first"),
1299 Cell::new("x", "middle"),
1300 Cell::new("y", "second, longer"),
1301 ];
1302 let drawn = row(
1303 &cols,
1304 &cells,
1305 Priority::Optional,
1306 &ink_of(&TableStyle::default()),
1307 );
1308 assert_eq!(cell_text(&drawn), vec!["first", "middle", "second, longer"]);
1309 assert_eq!(widest_cell(&cols, 0, &[&cells[..]]), 5);
1310 assert_eq!(widest_cell(&cols, 2, &[&cells[..]]), 14);
1311 }
1312
1313 /// A stretch of a table draws exactly what the whole table draws on those
1314 /// lines: the same columns, the same stripe, the same cells. That is the
1315 /// contract a caller windowing a long table relies on, so it is asserted
1316 /// line by line against a render of every row.
1317 #[test]
1318 fn a_window_draws_what_the_whole_table_draws_on_its_lines() {
1319 use ratatui::layout::Rect;
1320 use ratatui::widgets::Widget;
1321
1322 let cols = columns();
1323 let long: Vec<Vec<Cell<'static>>> = (0..9)
1324 .map(|i| {
1325 vec![
1326 Cell::new("name", format!("row {i}")),
1327 Cell::new("size", "1kb"),
1328 Cell::new("note", "n".repeat(i * 3)),
1329 ]
1330 })
1331 .collect();
1332 let ink = ink_of(&TableStyle::default());
1333 let width = 60;
1334
1335 let mut whole = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 10));
1336 table(&cols, &long, &sizing(), width, &ink).render(whole.area, &mut whole);
1337
1338 // Rows 3 to 5, no heading, drawn three lines tall.
1339 let mut part = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 3));
1340 table_window(
1341 &cols,
1342 &long[3..6],
1343 Window {
1344 first: 3,
1345 header: false,
1346 },
1347 |at| widest_cell(&cols, at, &long),
1348 &sizing(),
1349 width,
1350 &ink,
1351 )
1352 .render(part.area, &mut part);
1353
1354 for line in 0..3u16 {
1355 for x in 0..width {
1356 // Line 0 of the whole render is the heading, so row 3 is on
1357 // line 4.
1358 assert_eq!(
1359 part[(x, line)],
1360 whole[(x, line + 4)],
1361 "line {line}, column {x}"
1362 );
1363 }
1364 }
1365 }
1366
1367 /// With the heading kept, a window starting at the top is the table.
1368 #[test]
1369 fn the_whole_window_is_the_table() {
1370 use ratatui::layout::Rect;
1371 use ratatui::widgets::Widget;
1372
1373 let ink = ink_of(&TableStyle::default());
1374 let area = Rect::new(0, 0, 40, 3);
1375 let mut a = ratatui::buffer::Buffer::empty(area);
1376 let mut b = ratatui::buffer::Buffer::empty(area);
1377 table(&columns(), &rows(), &sizing(), 40, &ink).render(area, &mut a);
1378 table_window(
1379 &columns(),
1380 &rows(),
1381 Window::WHOLE,
1382 |at| widest_cell(&columns(), at, &rows()),
1383 &sizing(),
1384 40,
1385 &ink,
1386 )
1387 .render(area, &mut b);
1388 assert_eq!(a, b);
1389 }
1390}