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::{Caret, 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 Line::from(caret(column).label(column.name(), style.ascending, style.descending))
399}
400
401/// The caret this column's heading draws, by the rule every host shares.
402fn caret(column: &Head<'_>) -> Caret {
403 Caret::of(column.sorted, column.room.caret)
404}
405
406/// The ground at either end of a row: a track of no width, which the table's
407/// column spacing then separates from the first and last columns.
408///
409/// A track rather than a space in the first and last cells, because which
410/// columns are first and last moves as the table narrows, and an end-aligned
411/// last column would have to know to leave its space behind.
412const EDGE: Constraint = Constraint::Length(0);
413
414/// A row's cells between its two edges.
415///
416/// `Cell::new("")` and never `Cell::default()`: ratatui derives the default
417/// with a column span of zero, and a cell spanning nothing takes no track, so
418/// every cell after it lands one column to the left.
419fn edged<'a>(cells: impl Iterator<Item = TrackCell<'a>>) -> Vec<TrackCell<'a>> {
420 std::iter::once(TrackCell::new(""))
421 .chain(cells)
422 .chain(std::iter::once(TrackCell::new("")))
423 .collect()
424}
425
426/// The cell column `at` draws from a row's cells.
427///
428/// By name, and by place among the columns sharing that name: the second
429/// column called `y` takes the second cell called `y`. Matching on the name
430/// alone would hand every same-named column the first such cell, and the
431/// second `y` would never be drawn.
432fn cell_of<'c, 'a>(columns: &[Head<'_>], at: usize, cells: &'c [Cell<'a>]) -> Option<&'c Cell<'a>> {
433 let name = columns.get(at)?.name();
434 let nth = columns[..at]
435 .iter()
436 .filter(|column| column.name() == name)
437 .count();
438 cells.iter().filter(|cell| cell.column == name).nth(nth)
439}
440
441/// The widest cell column `at` holds across `rows`, in cells, heading not
442/// included.
443///
444/// What [`table`] measures a [`Width::Content`] column with. A caller drawing
445/// a [`Window`] of a long table hands [`table_window`] its own answer to this
446/// question instead, worked out without building the rows it is not drawing.
447#[must_use]
448pub fn widest_cell<'a, R>(columns: &[Head<'_>], at: usize, rows: &[R]) -> u16
449where
450 R: AsRef<[Cell<'a>]>,
451{
452 let widest = rows
453 .iter()
454 .filter_map(|row| cell_of(columns, at, row.as_ref()).map(|cell| cell.content.width()))
455 .max()
456 .unwrap_or(0);
457 u16::try_from(widest).unwrap_or(u16::MAX)
458}
459
460/// The widest thing in a column: its widest cell or its heading.
461///
462/// The heading counts because it is drawn: a column sized to its cells alone
463/// truncates its own name, and a two-character column called `duration` reads as
464/// `du`. The caret counts for the same reason, which is why this measures
465/// [`heading`] rather than [`Head::name`].
466fn measure(column: &Head<'_>, widest: u16, style: &TableStyle) -> u16 {
467 widest.max(u16::try_from(heading(column, style).width()).unwrap_or(u16::MAX))
468}
469
470/// Whether a budget fits in `width` cells.
471///
472/// A floor is counted in `ch` and a cell is one `ch`, so the budget is
473/// [`Budget::width`](makeover_layout::Budget::width) at one cell per `ch`, with
474/// the column spacing as the gap between columns and at either end.
475fn fits(budget: makeover_layout::Budget, style: &TableStyle, width: u16) -> bool {
476 budget.width(1.0, f32::from(style.column_spacing)) <= f32::from(width)
477}
478
479/// The weakest cutoff whose columns fit in `width` cells.
480///
481/// [`ColumnRoom::cutoff_for`] with this renderer's unit filled in, which is
482/// the one thing it adds: the narrowing rule and the gap model are the
483/// description's, so all three renderers drop a column at one declared width.
484#[must_use]
485pub fn cutoff_for(columns: &[Head<'_>], width: u16, style: &TableStyle) -> Priority {
486 ColumnRoom::cutoff_for(&rooms(columns), |budget| fits(budget, style, width))
487}
488
489/// The tracks for the columns kept at `cutoff`.
490///
491/// Only the surviving tracks, which is what keeps the track list and the hiding
492/// in agreement. A caller that dropped a cell but left its track would get a
493/// column of empty space.
494///
495/// Bracketed by the two edge tracks, which [`row`] and [`header`] fill, so the
496/// list is two longer than the columns kept.
497#[must_use]
498pub fn constraints<'a, R>(
499 columns: &[Head<'_>],
500 rows: &[R],
501 sizing: &Sizing<'_, u16>,
502 cutoff: Priority,
503 style: &TableStyle,
504) -> Vec<Constraint>
505where
506 R: AsRef<[Cell<'a>]>,
507{
508 constraints_from(
509 columns,
510 |at| widest_cell(columns, at, rows),
511 sizing,
512 cutoff,
513 style,
514 )
515}
516
517/// [`constraints`], with each [`Width::Content`] column's widest cell answered
518/// by `widest`, which takes the column's index in `columns`.
519///
520/// Asked only of the content columns kept at `cutoff`. The heading is still
521/// measured here, so `widest` answers for the cells alone, as
522/// [`widest_cell`] does.
523#[must_use]
524pub fn constraints_from(
525 columns: &[Head<'_>],
526 mut widest: impl FnMut(usize) -> u16,
527 sizing: &Sizing<'_, u16>,
528 cutoff: Priority,
529 style: &TableStyle,
530) -> Vec<Constraint> {
531 let tracks = columns
532 .iter()
533 .enumerate()
534 .filter(|(_, column)| column.kept_at(cutoff))
535 .map(|(at, column)| match column.room.width {
536 // Takes what it needs and no more, which is a fixed track once the
537 // needing has been measured.
538 Width::Content => Constraint::Length(measure(column, widest(at), style)),
539 Width::Fixed => Constraint::Length(sizing.length_for(column.name())),
540 // `Min` and not `Fill`: a fill column absorbs the slack *and* keeps
541 // its floor. `Fill` would let it collapse below the floor when a
542 // fixed column takes the room.
543 _ => Constraint::Min(sizing.length_for(column.name())),
544 })
545 .collect::<Vec<_>>();
546 std::iter::once(EDGE)
547 .chain(tracks)
548 .chain(std::iter::once(EDGE))
549 .collect()
550}
551
552/// One row's cells, in column order, on the ground.
553///
554/// The ground and not the stripe, since a row does not know where it falls.
555/// [`table`] lays the stripe over every second row; a caller assembling its
556/// own [`Table`] takes [`TableInk::stripe`] for those rows itself, or asks
557/// [`striped`].
558///
559/// Ordered by the columns and not by the cells, so a row cannot silently
560/// disagree with its table about what comes where. A column with no cell gets an
561/// empty cell, which keeps the tracks aligned; a cell naming no column is
562/// dropped, because there is nowhere to put it. That is the webview renderer's
563/// rule too, and it has to be the same rule or the two renderers disagree about
564/// a row they were handed identically.
565#[must_use]
566pub fn row<'a>(
567 columns: &[Head<'_>],
568 cells: &[Cell<'a>],
569 cutoff: Priority,
570 ink: &TableInk,
571) -> Row<'a> {
572 Row::new(edged(
573 columns
574 .iter()
575 .enumerate()
576 .filter(|(_, column)| column.kept_at(cutoff))
577 .map(|(at, column)| {
578 let found = cell_of(columns, at, cells);
579 let part = found.and_then(|cell| cell.part);
580 let content = found.map_or_else(Line::default, |cell| {
581 crate::text::sanitise(cell.content.clone())
582 });
583 TrackCell::from(aligned(column, content)).style(ink.for_part(part))
584 }),
585 ))
586 .style(ink.ground)
587}
588
589/// The heading row for the columns kept at `cutoff`.
590///
591/// Exposed beside [`table`] because a caller assembling its own [`Table`] still
592/// has to draw a header that agrees with the body about what just disappeared.
593#[must_use]
594pub fn header<'a>(columns: &[Head<'_>], cutoff: Priority, ink: &TableInk) -> Row<'a> {
595 Row::new(edged(
596 columns
597 .iter()
598 .filter(|column| column.kept_at(cutoff))
599 .map(|column| {
600 // Three states, three tones (wiki `three-tone-convention`): in
601 // force, offering, and not a control at all.
602 let tone = match caret(column) {
603 Caret::Idle => ink.sortable,
604 Caret::None => ink.header,
605 // Sorted, and a mark this renderer has not learned, which
606 // reads as the column in force.
607 _ => ink.sorted,
608 };
609 let head = crate::text::sanitise(heading(column, &ink.style));
610 TrackCell::from(aligned(column, head)).style(tone)
611 }),
612 ))
613 .style(ink.header)
614}
615
616/// A described table, sized and narrowed for `width`.
617///
618/// Hands back a [`Table`] rather than drawing one. Selection and scroll live in
619/// the app's [`TableState`](ratatui::widgets::TableState), and the row highlight
620/// is already set from [`TableInk::selected`], so a caller renders this with
621/// `render_stateful_widget` and gets the house selection without saying anything
622/// further.
623///
624/// `width` is the area the table will be drawn in, which is what narrowing is
625/// decided against. Pass the [`Rect`](ratatui::layout::Rect) width that
626/// [`frame`](crate::frame) handed back rather than the region's own, or the
627/// table budgets for the two cells the edge took.
628///
629/// Builds every row it is handed. A table longer than its area is cheaper
630/// through [`table_window`], which builds only the rows drawn.
631#[must_use]
632pub fn table<'a, R>(
633 columns: &[Head<'_>],
634 rows: &[R],
635 sizing: &Sizing<'_, u16>,
636 width: u16,
637 ink: &TableInk,
638) -> Table<'a>
639where
640 R: AsRef<[Cell<'a>]>,
641{
642 table_window(
643 columns,
644 rows,
645 Window::WHOLE,
646 |at| widest_cell(columns, at, rows),
647 sizing,
648 width,
649 ink,
650 )
651}
652
653/// Which stretch of a longer table a caller is drawing.
654///
655/// A table's columns are sized from every row and its stripe is counted from
656/// the first, so drawing a stretch of one is not drawing a shorter table: the
657/// stretch has to know where it starts, and the widths have to come from rows
658/// it was not handed.
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660pub struct Window {
661 /// The whole table's index of the first row handed over.
662 pub first: usize,
663 /// Whether the heading row is drawn above it.
664 pub header: bool,
665}
666
667impl Window {
668 /// The whole table, from its heading down.
669 pub const WHOLE: Self = Self {
670 first: 0,
671 header: true,
672 };
673}
674
675/// A stretch of a described table, sized for the whole of it.
676///
677/// [`table`] for a caller that knows which rows it will draw. `rows` is that
678/// stretch alone, starting at the whole table's row `window.first`; `widest`
679/// answers each [`Width::Content`] column's widest cell across the WHOLE table,
680/// by column index, as [`constraints_from`] asks it. So the columns sit where
681/// they would with every row built, and a reader scrolling through does not see
682/// them move.
683///
684/// The stripe is counted from the whole table's first row, so a stretch
685/// starting on an odd row starts striped.
686#[must_use]
687pub fn table_window<'a, R>(
688 columns: &[Head<'_>],
689 rows: &[R],
690 window: Window,
691 widest: impl FnMut(usize) -> u16,
692 sizing: &Sizing<'_, u16>,
693 width: u16,
694 ink: &TableInk,
695) -> Table<'a>
696where
697 R: AsRef<[Cell<'a>]>,
698{
699 let cutoff = cutoff_for(columns, width, &ink.style);
700 let widths = constraints_from(columns, widest, sizing, cutoff, &ink.style);
701 let striped = striped(columns, cutoff);
702 let body: Vec<Row<'a>> = rows
703 .iter()
704 .enumerate()
705 .map(|(index, cells)| {
706 let drawn = row(columns, cells.as_ref(), cutoff, ink);
707 if striped && (window.first + index) % 2 == 1 {
708 drawn.style(ink.stripe)
709 } else {
710 drawn
711 }
712 })
713 .collect();
714
715 let drawn = Table::new(body, widths)
716 .column_spacing(ink.style.column_spacing)
717 .row_highlight_style(ink.selected);
718 if window.header {
719 drawn.header(header(columns, cutoff, ink))
720 } else {
721 drawn
722 }
723}
724
725/// Whether the rows of a table with these columns take the stripe.
726///
727/// False for a table holding code at `cutoff`, which keeps its header and
728/// drops the record treatment, as the webview renderer's code table does.
729#[must_use]
730pub fn striped(columns: &[Head<'_>], cutoff: Priority) -> bool {
731 !columns
732 .iter()
733 .any(|column| column.kept_at(cutoff) && column.room.kind == ColumnKind::Code)
734}
735
736/// Whether a table drawn at `width` would leave anything overflowing.
737///
738/// True only when the essential columns alone do not fit, since that is the one
739/// case narrowing cannot answer. A caller that would rather show fewer rows than
740/// truncate a cell can ask this and draw something else.
741#[must_use]
742pub fn overflows(columns: &[Head<'_>], width: u16, style: &TableStyle) -> bool {
743 !fits(
744 ColumnRoom::budget(&rooms(columns), Priority::Essential),
745 style,
746 width,
747 )
748}
749
750#[cfg(test)]
751mod tests {
752 use super::*;
753
754 fn columns() -> Vec<Head<'static>> {
755 vec![
756 Head::new("name")
757 .width(Width::Fill)
758 .priority(Priority::Essential)
759 .kind(ColumnKind::Text)
760 .sortable(true)
761 .sorted(Sort::Ascending),
762 Head::new("size")
763 .width(Width::Fixed)
764 .priority(Priority::Secondary)
765 .kind(ColumnKind::Text)
766 .sortable(true),
767 Head::new("note")
768 .width(Width::Content)
769 .priority(Priority::Optional)
770 .kind(ColumnKind::Text)
771 .sortable(false),
772 ]
773 }
774
775 fn sizing() -> Sizing<'static, u16> {
776 Sizing::new(&[("name", 10), ("size", 6)], 4)
777 }
778
779 /// A table's tones on a palette with none: what a terminal with no colour
780 /// to spend draws.
781 fn ink_of(style: &TableStyle) -> TableInk {
782 let palette = crate::Palette::new(
783 Color::Reset,
784 Color::Reset,
785 Color::Reset,
786 Color::Reset,
787 Color::Reset,
788 crate::Fidelity::TrueColor,
789 );
790 TableInk::new(&palette, style)
791 }
792
793 /// A table's ink on a palette with these tones.
794 fn ink_with(tones: crate::Tones) -> TableInk {
795 let palette = crate::Palette::new(
796 Color::Reset,
797 Color::Reset,
798 Color::Reset,
799 Color::Reset,
800 Color::Reset,
801 crate::Fidelity::TrueColor,
802 )
803 .tones(tones);
804 TableInk::new(&palette, &TableStyle::default())
805 }
806
807 fn rows() -> Vec<Vec<Cell<'static>>> {
808 vec![
809 vec![
810 Cell::new("name", "alpha"),
811 Cell::new("size", "1kb"),
812 Cell::new("note", "a longer note"),
813 ],
814 vec![Cell::new("name", "beta"), Cell::new("size", "2kb")],
815 ]
816 }
817
818 fn cell_text(row: &Row<'_>) -> Vec<String> {
819 // Rendering is the only way to read a ratatui Row back, and reading it
820 // back is the point: these tests assert what a user sees.
821 use ratatui::layout::Rect;
822 use ratatui::widgets::Widget;
823 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
824 Table::new(vec![row.clone()], tracks())
825 .column_spacing(1)
826 .render(Rect::new(0, 0, 60, 1), &mut buf);
827 (0..3)
828 .map(|i| {
829 let start = 1 + i * 19;
830 (start..start + 18)
831 .map(|x| buf[(x as u16, 0)].symbol())
832 .collect::<String>()
833 .trim_end()
834 .to_owned()
835 })
836 .collect()
837 }
838
839 /// The foreground each of the three heading cells was drawn in.
840 ///
841 /// Read off a rendered buffer for [`cell_text`]'s reason: a ratatui `Row`
842 /// hands nothing back, and what is asserted is what a user sees.
843 fn cell_colors(row: &Row<'_>) -> Vec<Option<ratatui::style::Color>> {
844 use ratatui::layout::Rect;
845 use ratatui::widgets::Widget;
846 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
847 Table::new(vec![row.clone()], tracks())
848 .column_spacing(1)
849 .render(Rect::new(0, 0, 60, 1), &mut buf);
850 (0..3).map(|i| buf[(1 + i * 19, 0)].fg).map(Some).collect()
851 }
852
853 /// Three columns of 18 between the two edges, which puts column `i` at
854 /// `1 + i * 19`.
855 fn tracks() -> [Constraint; 5] {
856 [
857 EDGE,
858 Constraint::Length(18),
859 Constraint::Length(18),
860 Constraint::Length(18),
861 EDGE,
862 ]
863 }
864
865 #[test]
866 fn cells_are_ordered_by_the_columns_and_not_by_the_row() {
867 // The row hands them over backwards. The table decides the order, which
868 // is what stops a row silently disagreeing with its own header.
869 let cols = columns();
870 let out_of_order = vec![
871 Cell::new("note", "third"),
872 Cell::new("name", "first"),
873 Cell::new("size", "second"),
874 ];
875 let drawn = row(
876 &cols,
877 &out_of_order,
878 Priority::Optional,
879 &ink_of(&TableStyle::default()),
880 );
881 assert_eq!(cell_text(&drawn), vec!["first", "second", "third"]);
882 }
883
884 #[test]
885 fn a_cell_naming_no_column_is_dropped_and_a_column_with_no_cell_keeps_its_place() {
886 let cols = columns();
887 let cells = vec![Cell::new("note", "kept"), Cell::new("nonesuch", "lost")];
888 let drawn = row(
889 &cols,
890 &cells,
891 Priority::Optional,
892 &ink_of(&TableStyle::default()),
893 );
894 // Two empty tracks, then the note. The empties are what keeps the third
895 // column under the third heading.
896 assert_eq!(cell_text(&drawn), vec!["", "", "kept"]);
897 }
898
899 #[test]
900 fn a_content_column_is_measured_from_its_widest_cell() {
901 let style = TableStyle::default();
902 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
903 assert_eq!(widths[3], Constraint::Length("a longer note".len() as u16));
904 }
905
906 #[test]
907 fn a_content_column_never_truncates_its_own_heading() {
908 // The cells are two characters wide and the heading is eight. Sizing to
909 // the cells alone would draw the column as `du`.
910 let cols = vec![
911 Head::new("duration")
912 .width(Width::Content)
913 .priority(Priority::Essential)
914 .kind(ColumnKind::Text)
915 .sortable(false),
916 ];
917 let rows = vec![vec![Cell::new("duration", "3s")]];
918 let widths = constraints(
919 &cols,
920 &rows,
921 &sizing(),
922 Priority::Optional,
923 &TableStyle::default(),
924 );
925 assert_eq!(widths[1], Constraint::Length(8));
926 }
927
928 #[test]
929 fn a_caret_is_part_of_what_a_heading_costs() {
930 // Measured off `heading` and not off `name`, or the sorted column is
931 // exactly two cells too narrow and drops its own arrow.
932 let cols = vec![
933 Head::new("size")
934 .width(Width::Content)
935 .priority(Priority::Essential)
936 .kind(ColumnKind::Text)
937 .sortable(true)
938 .sorted(Sort::Descending),
939 ];
940 let rows: Vec<Vec<Cell<'_>>> = vec![];
941 let style = TableStyle::default();
942 let widths = constraints(&cols, &rows, &sizing(), Priority::Optional, &style);
943 assert_eq!(
944 widths[1],
945 Constraint::Length(6),
946 "size plus a space and a caret"
947 );
948 }
949
950 #[test]
951 fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
952 let style = TableStyle::default();
953 let cols = columns();
954 // Everything: floors of 16 (the name fills), 8 and 8, and a cell of
955 // spacing either side of each, which is 32 + 4.
956 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
957 assert_eq!(cutoff_for(&cols, 35, &style), Priority::Secondary);
958 // No room for the note: 24 + 3.
959 assert_eq!(cutoff_for(&cols, 27, &style), Priority::Secondary);
960 // No room for the size either: 16 + 2.
961 assert_eq!(cutoff_for(&cols, 26, &style), Priority::Essential);
962 assert_eq!(cutoff_for(&cols, 18, &style), Priority::Essential);
963 // No room for anything, and the essential column stays anyway.
964 assert_eq!(cutoff_for(&cols, 2, &style), Priority::Essential);
965 assert!(overflows(&cols, 2, &style));
966 assert!(!overflows(&cols, 18, &style));
967 }
968
969 #[test]
970 fn a_declared_minimum_moves_the_cut_and_a_measured_cell_does_not() {
971 // The floor is what the three hosts agree on, so a long value in a cell
972 // must not change where a column drops, and a declared minimum must.
973 let style = TableStyle::default();
974 let mut cols = columns();
975 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
976 cols[2] = cols[2].min(20);
977 assert_eq!(cutoff_for(&cols, 36, &style), Priority::Secondary);
978 assert_eq!(cutoff_for(&cols, 48, &style), Priority::Optional);
979 }
980
981 #[test]
982 fn a_column_inserted_left_of_the_cut_does_not_change_what_drops() {
983 // The goingson bug, as a test. `nth-child(n+5)` against a seven-column
984 // table hides whatever lands at position five, so inserting a column
985 // anywhere left of the cut moves it onto a different column with nothing
986 // edited and nothing reported.
987 //
988 // Asserted at a fixed cutoff, because that is where the two ways of
989 // addressing a column disagree. A narrower budget SHOULD drop more
990 // columns, and does below; what must not change is which ones, in what
991 // order, for a given cutoff.
992 let dropped = |cols: &[Head<'_>], cutoff| -> Vec<String> {
993 cols.iter()
994 .filter(|c| !c.kept_at(cutoff))
995 .map(|c| c.name().to_owned())
996 .collect()
997 };
998 let before = columns();
999 let mut after = vec![
1000 Head::new("mark")
1001 .width(Width::Fixed)
1002 .priority(Priority::Essential)
1003 .kind(ColumnKind::Text)
1004 .sortable(false),
1005 ];
1006 after.extend(columns());
1007
1008 for &cutoff in Priority::RAISING {
1009 assert_eq!(
1010 dropped(&before, cutoff),
1011 dropped(&after, cutoff),
1012 "inserting a column changed what {cutoff:?} drops"
1013 );
1014 }
1015 assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
1016 }
1017
1018 #[test]
1019 fn a_column_never_outlives_a_more_essential_one() {
1020 // The ordering claim narrowing rests on: whatever the budget, the set
1021 // kept is closed upward. A layout that dropped `size` while keeping
1022 // `note` would be counting something other than priority.
1023 let style = TableStyle::default();
1024 let cols = columns();
1025 for width in 0..48u16 {
1026 let cutoff = cutoff_for(&cols, width, &style);
1027 let kept: Vec<&str> = cols
1028 .iter()
1029 .filter(|c| c.kept_at(cutoff))
1030 .map(Head::name)
1031 .collect();
1032 assert!(
1033 kept.contains(&"name"),
1034 "the essential column left at {width}"
1035 );
1036 if kept.contains(&"note") {
1037 assert!(
1038 kept.contains(&"size"),
1039 "optional outlived secondary at {width}"
1040 );
1041 }
1042 }
1043 }
1044
1045 #[test]
1046 fn a_dropped_column_takes_its_track_with_it() {
1047 // A cell hidden with its track left behind is a column of empty space,
1048 // which is the half of the goingson bug that survives fixing the other.
1049 let style = TableStyle::default();
1050 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Secondary, &style);
1051 assert_eq!(widths.len(), 4, "two columns and the two edges");
1052 let drawn = row(&columns(), &rows()[0], Priority::Secondary, &ink_of(&style));
1053 assert_eq!(cell_text(&drawn), vec!["alpha", "1kb", ""]);
1054 }
1055
1056 #[test]
1057 fn a_fill_column_keeps_its_floor_while_taking_the_slack() {
1058 // `Min` and not `Fill`, which is `minmax(10, 1fr)` at the webview
1059 // renderer. A `Fill` track collapses under a fixed neighbour.
1060 let style = TableStyle::default();
1061 let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
1062 assert_eq!(widths[1], Constraint::Min(10));
1063 assert_eq!(widths[2], Constraint::Length(6));
1064 }
1065
1066 #[test]
1067 fn a_column_with_no_length_of_its_own_takes_the_fallback() {
1068 let cols = vec![
1069 Head::new("unlisted")
1070 .width(Width::Fixed)
1071 .priority(Priority::Essential)
1072 .kind(ColumnKind::Text)
1073 .sortable(false),
1074 ];
1075 let rows: Vec<Vec<Cell<'_>>> = vec![];
1076 let widths = constraints(
1077 &cols,
1078 &rows,
1079 &sizing(),
1080 Priority::Optional,
1081 &TableStyle::default(),
1082 );
1083 assert_eq!(widths[1], Constraint::Length(4));
1084 }
1085
1086 #[test]
1087 fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
1088 let style = TableStyle::default();
1089 let head = header(&columns(), Priority::Optional, &ink_of(&style));
1090 assert_eq!(
1091 cell_text(&head),
1092 vec!["NAME \u{25B2}", "SIZE \u{25B2}", "NOTE"],
1093 "in force and offering both carry one; not a control carries none"
1094 );
1095 }
1096
1097 #[test]
1098 fn the_three_states_of_a_heading_are_three_tones() {
1099 // wiki `three-tone-convention`. The middle state is the one that had
1100 // nowhere to be said: a heading you can press looked exactly like one
1101 // you cannot, and the idle caret alone does not separate them, because
1102 // a sorted-but-unsortable column draws a caret too.
1103 let mut ink = ink_of(&TableStyle::default());
1104 ink.sorted = Style::new().fg(Color::Red);
1105 ink.sortable = Style::new().fg(Color::Green);
1106 ink.header = Style::new().fg(Color::Blue);
1107 let drawn = cell_colors(&header(&columns(), Priority::Optional, &ink));
1108 assert_eq!(
1109 drawn,
1110 vec![Some(Color::Red), Some(Color::Green), Some(Color::Blue)]
1111 );
1112
1113 // The colourless default separates them by the caret and nothing else,
1114 // and that is the honest limit rather than an oversight: a cell style
1115 // patches the row's, so a plain cell under a bold header row is drawn
1116 // bold whatever it holds. Three tones need three colours, which is what
1117 // a palette's tones are for.
1118 let house = TableStyle::default();
1119 let plain = cell_colors(&header(&columns(), Priority::Optional, &ink_of(&house)));
1120 assert_eq!(plain[0], plain[1], "no colour to spend, so none is claimed");
1121 }
1122
1123 #[test]
1124 fn pressing_a_heading_does_not_move_the_columns_after_it() {
1125 // The reflow the idle caret closes. `measure` sizes from `heading`, so
1126 // a caret that appeared with the press widened its own column by two
1127 // cells and shifted the rest of the row sideways.
1128 let style = TableStyle::default();
1129 let offering = Head::new("size")
1130 .width(Width::Content)
1131 .priority(Priority::Secondary)
1132 .kind(ColumnKind::Text)
1133 .sortable(true);
1134 let in_force = offering.sorted(Sort::Descending);
1135 assert_eq!(measure(&offering, 0, &style), measure(&in_force, 0, &style));
1136
1137 // And the column that is not a control at all is narrower, which is the
1138 // width that would be wrong to reserve: it has no caret to draw.
1139 let inert = offering.sortable(false);
1140 assert!(measure(&inert, 0, &style) < measure(&offering, 0, &style));
1141 }
1142
1143 #[test]
1144 fn a_column_sorted_without_being_sortable_still_draws_its_caret() {
1145 // A list ordered by a key the user cannot change is a real thing to
1146 // describe, which is why the description holds the two fields apart.
1147 // Drawing the caret only for a sortable column would collapse them.
1148 let cols = vec![
1149 Head::new("rank")
1150 .width(Width::Content)
1151 .priority(Priority::Essential)
1152 .kind(ColumnKind::Text)
1153 .sortable(false)
1154 .sorted(Sort::Descending),
1155 ];
1156 let head = header(&cols, Priority::Optional, &ink_of(&TableStyle::default()));
1157 assert_eq!(cell_text(&head), vec!["RANK \u{25BC}", "", ""]);
1158 }
1159
1160 #[test]
1161 fn a_cell_part_takes_the_ink_its_intent_names() {
1162 // makeover-layout's `CellPart::intent` is the rule every host reads, so
1163 // a link here draws as the webview's does: in the values' ink, with no
1164 // underline.
1165 let tones = crate::Tones {
1166 content: Some(Color::Indexed(1)),
1167 secondary: Some(Color::Indexed(2)),
1168 muted: Some(Color::Indexed(3)),
1169 action: Some(Color::Indexed(4)),
1170 ..crate::Tones::default()
1171 };
1172 let ink = ink_with(tones);
1173 for part in [
1174 CellPart::Value,
1175 CellPart::Tokens,
1176 CellPart::Actions,
1177 CellPart::Link,
1178 ] {
1179 let want = match part.intent() {
1180 "content" => tones.content,
1181 "content-secondary" => tones.secondary,
1182 "content-muted" => tones.muted,
1183 other => panic!("{part:?} names {other}, which this renderer has not learned"),
1184 };
1185 let got = ink.for_part(Some(part));
1186 assert_eq!(got.fg, want, "{part:?}");
1187 assert_eq!(got.add_modifier, Modifier::empty(), "{part:?}");
1188 }
1189 // A cell mixing parts says nothing, and takes the text style.
1190 assert_eq!(ink.for_part(None), ink.value);
1191 }
1192
1193 #[test]
1194 fn a_table_narrows_itself_from_the_width_it_is_given() {
1195 // The whole path in one call, which is what a consumer actually uses.
1196 let style = TableStyle::default();
1197 let wide = table(&columns(), &rows(), &sizing(), 40, &ink_of(&style));
1198 let narrow = table(&columns(), &rows(), &sizing(), 20, &ink_of(&style));
1199 use ratatui::layout::Rect;
1200 use ratatui::widgets::Widget;
1201
1202 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 40, 3));
1203 wide.render(Rect::new(0, 0, 40, 3), &mut buf);
1204 let head: String = (0..40).map(|x| buf[(x, 0)].symbol()).collect();
1205 assert!(head.contains("NOTE"));
1206
1207 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 20, 3));
1208 narrow.render(Rect::new(0, 0, 20, 3), &mut buf);
1209 let head: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
1210 assert!(!head.contains("NOTE"), "the optional column is gone");
1211 assert!(head.contains("NAME"), "the essential one is not");
1212 }
1213
1214 #[test]
1215 fn selection_is_carried_by_the_background_alone() {
1216 // A row can be red for a failure or green for a success, and a
1217 // foreground on the selection loses that on exactly the row being looked
1218 // at. Asserted with a selection colour and without one.
1219 assert!(ink_of(&TableStyle::default()).selected.fg.is_none());
1220 let coloured = ink_with(crate::Tones::NONE.selected(Color::Blue));
1221 assert_eq!(coloured.selected.bg, Some(Color::Blue));
1222 assert!(coloured.selected.fg.is_none());
1223 }
1224
1225 #[test]
1226 fn a_number_column_aligns_its_cells_and_heading_to_the_end() {
1227 let mut amount = Head::new("Amount");
1228 amount.room.kind = ColumnKind::Number;
1229 let prose = Head::new("Buyer");
1230 assert_eq!(
1231 aligned(&amount, Line::from("9.99")).alignment,
1232 Some(ratatui::layout::Alignment::Right)
1233 );
1234 assert_eq!(aligned(&prose, Line::from("ada")).alignment, None);
1235 }
1236
1237 #[test]
1238 fn a_row_keeps_a_cell_of_ground_at_either_end() {
1239 // The block padding, in cells. The first value does not touch the
1240 // table's left edge and an end-aligned last column does not touch its
1241 // right, whichever columns narrowing left first and last.
1242 use ratatui::layout::Rect;
1243 use ratatui::widgets::Widget;
1244 // Declared narrow, so both columns are kept in twelve cells: this is
1245 // about the ground at the ends, not about narrowing.
1246 let cols = vec![Head::new("a").min(2), {
1247 let mut n = Head::new("n").min(2);
1248 n.room.kind = ColumnKind::Number;
1249 n.room.width = Width::Fill;
1250 n
1251 }];
1252 let rows = vec![vec![Cell::new("a", "x"), Cell::new("n", "9")]];
1253 let drawn = table(&cols, &rows, &sizing(), 12, &ink_of(&TableStyle::default()));
1254 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 12, 2));
1255 drawn.render(Rect::new(0, 0, 12, 2), &mut buf);
1256 let body: String = (0..12).map(|x| buf[(x, 1)].symbol()).collect();
1257 assert!(body.starts_with(" x"), "{body:?}");
1258 assert!(body.ends_with("9 "), "{body:?}");
1259 }
1260
1261 #[test]
1262 fn every_second_row_takes_the_stripe_and_a_code_table_takes_none() {
1263 use ratatui::layout::Rect;
1264 use ratatui::widgets::Widget;
1265 let ink = ink_with(crate::Tones::NONE.ground(Color::Blue).stripe(Color::Green));
1266 let grounds = |cols: &[Head<'_>]| -> Vec<Color> {
1267 let rows: Vec<Vec<Cell<'_>>> = (0..3).map(|_| vec![Cell::new("a", "x")]).collect();
1268 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 8, 4));
1269 table(cols, &rows, &sizing(), 8, &ink).render(Rect::new(0, 0, 8, 4), &mut buf);
1270 (1..4).map(|y| buf[(0, y)].bg).collect()
1271 };
1272 let records = vec![Head::new("a").min(2)];
1273 assert_eq!(
1274 grounds(&records),
1275 vec![Color::Blue, Color::Green, Color::Blue]
1276 );
1277
1278 let mut code = Head::new("a").min(2);
1279 code.room.kind = ColumnKind::Code;
1280 assert_eq!(grounds(&[code]), vec![Color::Blue; 3]);
1281 }
1282
1283 /// Two columns sharing a name draw two cells, in order. Matched on the
1284 /// name alone both would draw the first, and the second never showed.
1285 #[test]
1286 fn same_named_columns_take_same_named_cells_in_order() {
1287 let cols = vec![
1288 Head::new("y").width(Width::Fixed),
1289 Head::new("x").width(Width::Fixed),
1290 Head::new("y").width(Width::Content),
1291 ];
1292 let cells = vec![
1293 Cell::new("y", "first"),
1294 Cell::new("x", "middle"),
1295 Cell::new("y", "second, longer"),
1296 ];
1297 let drawn = row(
1298 &cols,
1299 &cells,
1300 Priority::Optional,
1301 &ink_of(&TableStyle::default()),
1302 );
1303 assert_eq!(cell_text(&drawn), vec!["first", "middle", "second, longer"]);
1304 assert_eq!(widest_cell(&cols, 0, &[&cells[..]]), 5);
1305 assert_eq!(widest_cell(&cols, 2, &[&cells[..]]), 14);
1306 }
1307
1308 /// A stretch of a table draws exactly what the whole table draws on those
1309 /// lines: the same columns, the same stripe, the same cells. That is the
1310 /// contract a caller windowing a long table relies on, so it is asserted
1311 /// line by line against a render of every row.
1312 #[test]
1313 fn a_window_draws_what_the_whole_table_draws_on_its_lines() {
1314 use ratatui::layout::Rect;
1315 use ratatui::widgets::Widget;
1316
1317 let cols = columns();
1318 let long: Vec<Vec<Cell<'static>>> = (0..9)
1319 .map(|i| {
1320 vec![
1321 Cell::new("name", format!("row {i}")),
1322 Cell::new("size", "1kb"),
1323 Cell::new("note", "n".repeat(i * 3)),
1324 ]
1325 })
1326 .collect();
1327 let ink = ink_of(&TableStyle::default());
1328 let width = 60;
1329
1330 let mut whole = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 10));
1331 table(&cols, &long, &sizing(), width, &ink).render(whole.area, &mut whole);
1332
1333 // Rows 3 to 5, no heading, drawn three lines tall.
1334 let mut part = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 3));
1335 table_window(
1336 &cols,
1337 &long[3..6],
1338 Window {
1339 first: 3,
1340 header: false,
1341 },
1342 |at| widest_cell(&cols, at, &long),
1343 &sizing(),
1344 width,
1345 &ink,
1346 )
1347 .render(part.area, &mut part);
1348
1349 for line in 0..3u16 {
1350 for x in 0..width {
1351 // Line 0 of the whole render is the heading, so row 3 is on
1352 // line 4.
1353 assert_eq!(
1354 part[(x, line)],
1355 whole[(x, line + 4)],
1356 "line {line}, column {x}"
1357 );
1358 }
1359 }
1360 }
1361
1362 /// With the heading kept, a window starting at the top is the table.
1363 #[test]
1364 fn the_whole_window_is_the_table() {
1365 use ratatui::layout::Rect;
1366 use ratatui::widgets::Widget;
1367
1368 let ink = ink_of(&TableStyle::default());
1369 let area = Rect::new(0, 0, 40, 3);
1370 let mut a = ratatui::buffer::Buffer::empty(area);
1371 let mut b = ratatui::buffer::Buffer::empty(area);
1372 table(&columns(), &rows(), &sizing(), 40, &ink).render(area, &mut a);
1373 table_window(
1374 &columns(),
1375 &rows(),
1376 Window::WHOLE,
1377 |at| widest_cell(&columns(), at, &rows()),
1378 &sizing(),
1379 40,
1380 &ink,
1381 )
1382 .render(area, &mut b);
1383 assert_eq!(a, b);
1384 }
1385}