Skip to main content

makeover_immediate/
table.rs

1//! Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
2//!
3//! `makeover-webview`'s `list` module and `makeover-tui`'s `table` in the shape
4//! immediate mode allows. It owns the same four things: which columns exist, how
5//! wide they are, which ones survive a narrow viewport, and what each part of a
6//! cell is. It does not own what goes in a cell, which here is not a policy but
7//! a fact of the mode: a cell's contents are drawn by the app's own closure, the
8//! way [`group`](crate::group) already takes one per field.
9//!
10//! # Why `egui_extras` and not egui
11//!
12//! egui itself has no table. [`egui::Grid`] gives no per-column sizing, no
13//! sticky header and no scroll sync, which is why audiofiles reached for
14//! `egui_extras::TableBuilder` rather than building on `Grid`. Writing a third
15//! answer here would be reimplementing that crate worse, so this is a mapping
16//! layer over it.
17//!
18//! It moves in lockstep with egui's own version, which is the cost worth
19//! naming.
20//!
21//! # What immediate mode costs the narrowing
22//!
23//! The terminal renderer measures a [`Width::Content`] column from its cells,
24//! because it holds every cell before it draws any. Here the cells do not exist
25//! until the app's closure runs, so nothing can be measured before the layout is
26//! decided.
27//!
28//! That splits the answer in two, and both halves are honest:
29//!
30//! - **Sizing** hands a content column to
31//!   [`egui_extras::Column::auto`], which measures it and holds the result
32//!   between frames. This is better than the terminal gets, not worse.
33//! - **Narrowing** cannot wait for that, so it budgets every column at its
34//!   declared [`floor`](Column::floor), in `ch` of the body face. A column that
35//!   turns out wider than its floor is still drawn; it is the *decision to drop*
36//!   that uses the declared number, through `makeover_layout::cutoff_for` and
37//!   its one gap model, which is the number the terminal counts in cells.
38//!
39//! # The table model
40//!
41//! Wiki `table-model`, drawn the way `makeover-webview` draws it, since egui
42//! paints the same pixels a browser does: a raised ground inside a hairline
43//! frame, the header a sunken strip over a `bevel-dark` edge in secondary
44//! capitals, rows 45 points tall with a hairline between them, a stripe on
45//! every second row and a tone under the pointer. A table holding a
46//! [`ColumnKind::Code`] column keeps the frame and the header and drops the
47//! stripe, the hairlines and the tall row.
48//!
49//! The row fills are painted here rather than by egui_extras, for two reasons
50//! the crate cannot be configured past. Its stripe falls on the first row where
51//! the model's falls on the second, and its selection repaints the row's text
52//! in the selection stroke, which loses a failed row's red on exactly the row
53//! the user picked. A selected row takes `row-selected` behind its text and
54//! nothing else.
55//!
56//! # Why positions are the bug
57//!
58//! Carried from the other two renderers, because the mistake is not a CSS
59//! mistake and not a terminal one. goingson hides its mobile columns with
60//! `nth-child(n+5)` against a seven-column table; insert a column left of the
61//! cut and the wrong one disappears, silently. A renderer narrows by raising a
62//! cutoff and never by counting.
63
64use crate::Palette;
65use egui::{RichText, Sense, Ui};
66use egui_extras::{Column as Track, TableBuilder};
67use makeover_layout::{CellPart, Column, ColumnKind, Priority, Sort, Width};
68
69/// The lengths the description deferred, in points: the track for a
70/// [`Width::Fixed`] column, the floor for a [`Width::Fill`] one, and the
71/// narrowing budget for a [`Width::Content`] one. The suite's one sizing type,
72/// held here over points as the terminal holds it over cells.
73pub type Sizing<'a> = makeover_layout::Sizing<'a, f32>;
74
75/// The tones and metrics a table draws with.
76///
77/// Metrics only, and the tones come from [`Palette`]. That is the division this
78/// crate already draws: [`FieldStyle`](crate::FieldStyle) carries gaps and a
79/// marker while the colours stay in the palette, and a table's colours are the
80/// palette's `content`, `content_muted` and `action` rather than six new ones.
81/// `makeover-tui` splits it the other way round because its palette carries no
82/// text tones at all.
83#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct TableStyle {
85    /// The height of the heading row.
86    pub header_height: f32,
87    /// The height of a body row: the model's 45, `--row-block` at
88    /// `makeover-geometry`'s base.
89    pub row_height: f32,
90    /// The height of a row in a table holding code, which is one line of
91    /// source rather than a record.
92    pub code_row_height: f32,
93    /// The ground between the table's frame and the cells at either end of a
94    /// row: the webview's `gap-group`, which pads both ends of a row.
95    pub edge_padding: f32,
96    /// The caret drawn after the heading of an ascending column.
97    ///
98    /// Defaults to [`Sort::glyph`], which is where the spelling lives now:
99    /// three renderers holding the same literal agreed by coincidence. Bare,
100    /// with no leading space: the gap is [`heading`]'s, written once for all
101    /// three states rather than baked into two strings and forgotten in the
102    /// third.
103    pub ascending: &'static str,
104    /// Drawn after the heading of a descending column.
105    pub descending: &'static str,
106    /// Whether the user can drag the divider between two columns.
107    ///
108    /// The one knob that is not a metric. Not every setting egui_extras has
109    /// becomes a field here: a sticky heading is what `TableBuilder::header`
110    /// does and there is no version that does not, and the stripe is the table
111    /// model's at every host, so a knob for either would offer a choice this
112    /// renderer cannot make. Off by default: the description has no word for
113    /// resizing, so a default that turned it on would be this renderer adding a
114    /// claim the other two cannot make.
115    ///
116    /// It does not fight the narrowing. A drag moves a track for the frames it
117    /// is held; the narrowing still decides which columns exist, off each
118    /// column's declared [`floor`](Column::floor), so a resize can never drop a
119    /// column.
120    pub resizable: bool,
121}
122
123impl Default for TableStyle {
124    fn default() -> Self {
125        Self {
126            header_height: 32.0,
127            row_height: 45.0,
128            code_row_height: 20.0,
129            edge_padding: 12.0,
130            ascending: Sort::Ascending.glyph(),
131            descending: Sort::Descending.glyph(),
132            resizable: false,
133        }
134    }
135}
136
137/// The body's own facts for this frame: how many rows, which are selected, and
138/// which one to bring into view.
139///
140/// Held apart from [`TableStyle`] because none of it is style and none of it
141/// survives the frame: a row count changes when a folder does, a selection when
142/// the user clicks, and a scroll request exists for exactly one frame. Held
143/// apart from the [`Column`] slice because none of it is description either.
144/// The description says what a table *is*, and this says what it holds right
145/// now.
146///
147/// Both of the optional fields are here rather than left to the app because
148/// egui_extras answers them on a handle the app never sees: `set_selected` is a
149/// method on the row, and `scroll_to_row` a method on the builder, and this
150/// crate owns both. That is the same reason [`cell`] exists.
151#[derive(Default)]
152pub struct Body<'a> {
153    /// How many rows to draw.
154    pub rows: usize,
155    /// Whether a row is selected, by index.
156    ///
157    /// A predicate rather than a set, so an app whose selection is a range, a
158    /// bitmap or a single index does not have to build a collection to be asked.
159    /// `None` is a table no row of which is selected, which is not the same
160    /// claim as a predicate that always answers false and costs nothing to make.
161    pub selected: Option<&'a dyn Fn(usize) -> bool>,
162    /// A row to bring into view this frame.
163    ///
164    /// Set it from a request the app then clears, the way a keyboard cursor
165    /// moving off-screen raises one: held rather than taken, it would fight
166    /// every scroll the user makes with the mouse.
167    pub scroll_to: Option<usize>,
168}
169
170impl std::fmt::Debug for Body<'_> {
171    // Hand-written because `selected` is a closure and `#[derive(Debug)]` will
172    // not have it. What is worth printing is whether one was supplied.
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        f.debug_struct("Body")
175            .field("rows", &self.rows)
176            .field("selected", &self.selected.is_some())
177            .field("scroll_to", &self.scroll_to)
178            .finish()
179    }
180}
181
182/// The colour a cell of this part takes.
183///
184/// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
185/// `content`: a part this renderer has not learned draws as text, which is a
186/// cell rendering plainly rather than a build that stops. Grep this when
187/// adopting a new `makeover-layout`.
188#[must_use]
189pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
190    match part {
191        // A token paints its own background and carries its own tone. What is
192        // set here is what shows between them, not what paints them.
193        Some(CellPart::Tokens) => palette.content_muted,
194        // The drift `CellPart` exists to end: a control in a cell inheriting the
195        // cell's text colour. Both of these take the action intent instead.
196        Some(CellPart::Actions | CellPart::Link) => palette.action,
197        _ => palette.content,
198    }
199}
200
201/// Draw a cell's contents with the tone its part takes.
202///
203/// The app calls this inside its own cell closure, wrapping whatever it draws.
204/// A scoping function rather than a parameter on [`table`], for the reason
205/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
206/// does not exist until the closure runs, and immediate mode has no cascade to
207/// carry the answer down on its own. This is the cascade, for one scope.
208///
209/// ```no_run
210/// # use makeover_layout::CellPart;
211/// # let palette: makeover_immediate::Palette = unimplemented!();
212/// # let ui: &mut egui::Ui = unimplemented!();
213/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
214///     ui.label("opens the item");
215/// });
216/// ```
217pub fn cell<R>(
218    ui: &mut Ui,
219    part: Option<CellPart>,
220    palette: &Palette,
221    add_contents: impl FnOnce(&mut Ui) -> R,
222) -> R {
223    let restore = ui.visuals().override_text_color;
224    ui.visuals_mut().override_text_color = Some(part_color(part, palette));
225    let out = add_contents(ui);
226    ui.visuals_mut().override_text_color = restore;
227    out
228}
229
230/// The heading, in capitals, with the caret if the table is ordered by this
231/// column.
232///
233/// Capitals because the header strip's label is set that way at every host.
234/// A column [`sorted`](Column::sorted) but not [`sortable`](Column::sortable)
235/// still gets its caret. Both combinations mean something, which is why the
236/// description holds the two fields apart: a list ordered by a key the user
237/// cannot change is a real thing, and the caret is how it says so.
238#[must_use]
239pub fn heading(column: &Column<'_>, style: &TableStyle) -> String {
240    let caret = match column.sorted {
241        Some(Sort::Ascending) => style.ascending,
242        Some(Sort::Descending) => style.descending,
243        // A direction this renderer has not learnt keeps the column marked as
244        // the one in force.
245        Some(_) => style.ascending,
246        // Sortable and not sorted draws the idle mark, in the ascending
247        // spelling because that is the direction a first press takes. What
248        // separates it from the column in force is the tone, which is
249        // [`press`]'s to pick.
250        None if column.sortable => style.ascending,
251        None => return column.name.to_uppercase(),
252    };
253    format!("{} {caret}", column.name.to_uppercase())
254}
255
256/// The weakest cutoff whose columns fit in `width` points.
257///
258/// The suite's one budget: each kept column's declared floor at `ch` points a
259/// ch, and a gap of the edge padding either side of it, counted once between
260/// neighbours and once at each end. Nothing can be measured before the app's
261/// closure has drawn a cell and nothing needs to be: the floor is the number
262/// the terminal counts in cells, so the two drop a column at one declared
263/// width.
264fn cutoff(columns: &[Column<'_>], ch: f32, edge: f32, width: f32) -> Priority {
265    makeover_layout::cutoff_for(columns, |budget| budget.width(ch, 2.0 * edge) <= width)
266}
267
268/// The track for one column.
269fn track(column: &Column<'_>, sizing: &Sizing<'_>) -> Track {
270    match column.width {
271        // The one place immediate mode beats the terminal: egui_extras measures
272        // this and remembers it between frames, where `makeover-tui` has to walk
273        // the cells itself.
274        Width::Content => Track::auto(),
275        Width::Fixed => Track::exact(sizing.length_for(column.name)),
276        // Includes a width added to the description since this renderer was
277        // built. Taking the slack above a floor is the behaviour that makes no
278        // claim, which is the same fallback the webview renderer's `auto` track
279        // is chosen to be.
280        _ => Track::remainder().at_least(sizing.length_for(column.name)),
281    }
282}
283
284/// A described table, narrowed for the width available.
285///
286/// `draw` is called once per cell of each kept column, in column order, for each
287/// of [`Body::rows`] rows. Taking a closure rather than a slice of contents is
288/// what keeps the app's own data borrowed one cell at a time, which is
289/// [`group`](crate::group)'s reasoning and immediate mode's habit.
290///
291/// `body` is borrowed immutably and `draw` is `FnMut`, which is the split a
292/// caller has to plan for: a selection read by [`Body::selected`] cannot be the
293/// same value `draw` mutates. Snapshot it before the call. That is not this
294/// crate imposing anything. It is the borrow the app already takes when it
295/// clones its row list to hand egui a closure.
296///
297/// Returns the sortable column whose heading was pressed this frame, if any. The
298/// app owns the ordering, so this reports the press and changes nothing: what a
299/// press *calls* is an address, and the description names none. That is
300/// [`Column::sortable`]'s own documented split.
301///
302/// A heading is only pressable when its column says
303/// [`sortable`](Column::sortable). A column sorted by a key the user cannot
304/// change still draws its caret and does not answer.
305pub fn table<'a>(
306    ui: &mut Ui,
307    columns: &'a [Column<'a>],
308    body: &Body<'_>,
309    sizing: &Sizing<'_>,
310    palette: &Palette,
311    style: &TableStyle,
312    mut draw: impl FnMut(&mut Ui, &'a Column<'a>, usize),
313) -> Option<&'a Column<'a>> {
314    // One `ch` in the face the cells are drawn in, which is what a declared
315    // floor counts.
316    let ch = {
317        let font = egui::TextStyle::Body.resolve(ui.style());
318        ui.fonts_mut(|fonts| fonts.glyph_width(&font, '0'))
319    };
320    let cutoff = cutoff(columns, ch, style.edge_padding, ui.available_width());
321    let kept: Vec<&'a Column<'a>> = columns.iter().filter(|c| c.kept_at(cutoff)).collect();
322
323    // egui_extras panics on a table with no tracks, and a description whose
324    // every column dropped is reachable: `kept_at` keeps the essential ones, and
325    // a table described with none at all has nothing to keep.
326    if kept.is_empty() {
327        return None;
328    }
329
330    let code = kept.iter().any(|column| column.kind == ColumnKind::Code);
331    let row_height = if code {
332        style.code_row_height
333    } else {
334        style.row_height
335    };
336    // The whole width the table takes, which is the frame's: a cell only knows
337    // its own track. The fills stop a stroke's width inside it, so no row
338    // paints over the frame.
339    let outer = ui.available_rect_before_wrap();
340    let across = outer.x_range();
341    let fills = egui::Rangef::new(across.min + 1.0, across.max - 1.0);
342    let top = ui.cursor().top();
343    // Reserved before the table draws, so the ground lands under it once the
344    // table's height is known.
345    let ground = ui.painter().add(egui::Shape::Noop);
346    // How far down the header and the drawn rows reach, which is the frame's
347    // bottom. Not the scroll area's rect, which is the room the table was
348    // offered rather than the room it took.
349    let reach = std::cell::Cell::new(top);
350    let inner = outer.shrink2(egui::vec2(style.edge_padding, 0.0));
351    // Written through a Cell rather than returned, because egui_extras hands the
352    // header and the body their own closures and neither can return a value past
353    // the other.
354    let pressed = std::cell::Cell::new(None::<&'a Column<'a>>);
355
356    let viewport = ui
357        .scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| {
358            let mut builder = TableBuilder::new(ui)
359                .striped(false)
360                .resizable(style.resizable)
361                // Not a knob, because there is no second honest answer: a cell's
362                // contents sit on the row's centre line. CSS says `vertical-align:
363                // middle` and a terminal row is one line tall, so a field offering the
364                // choice would be offering one only this renderer could take. egui's own
365                // default is top-aligned, which is why it has to be said at all.
366                .cell_layout(egui::Layout::left_to_right(egui::Align::Center));
367            for column in &kept {
368                builder = builder.column(track(column, sizing));
369            }
370            if let Some(row) = body.scroll_to {
371                builder = builder.scroll_to_row(row, None);
372            }
373
374            builder
375                .header(style.header_height, |mut header| {
376                    for (at, column) in kept.iter().enumerate() {
377                        header.col(|ui| {
378                            if at == 0 {
379                                strip(ui, fills, &reach, palette);
380                            }
381                            placed(ui, column, |ui| {
382                                if press(ui, column, palette, style) {
383                                    pressed.set(Some(column));
384                                }
385                            });
386                        });
387                    }
388                })
389                .body(|table_body| {
390                    table_body.rows(row_height, body.rows, |mut row| {
391                        let index = row.index();
392                        let selected = body.selected.is_some_and(|selected| selected(index));
393                        for (at, column) in kept.iter().enumerate() {
394                            row.col(|ui| {
395                                // In the first cell and across the whole row, before
396                                // any cell's contents: a selection marks the row, and
397                                // a fill per cell would leave the gaps unpainted.
398                                if at == 0 {
399                                    let row = Row {
400                                        index,
401                                        selected,
402                                        code,
403                                    };
404                                    ground_row(ui, fills, row, &reach, palette);
405                                }
406                                placed(ui, column, |ui| draw(ui, column, index));
407                            });
408                        }
409                    });
410                })
411                .inner_rect
412        })
413        .inner;
414
415    let bottom = reach.get().min(viewport.bottom());
416    let frame = egui::Rect::from_x_y_ranges(across, top..=bottom);
417    ui.painter().set(
418        ground,
419        egui::epaint::RectShape::filled(frame, 0, palette.raised),
420    );
421    ui.painter().rect_stroke(
422        frame,
423        0,
424        egui::Stroke::new(1.0, palette.row_rule),
425        egui::StrokeKind::Inside,
426    );
427
428    pressed.get()
429}
430
431/// What decides one body row's fill.
432#[derive(Clone, Copy)]
433struct Row {
434    index: usize,
435    selected: bool,
436    code: bool,
437}
438
439/// The rect a row's fill covers: the whole table's width, and the cell's
440/// height with the half of the spacing either side that egui_extras leaves
441/// between rows.
442fn row_rect(ui: &Ui, across: egui::Rangef) -> egui::Rect {
443    let half = 0.5 * ui.spacing().item_spacing.y;
444    let cell = ui.max_rect();
445    egui::Rect::from_x_y_ranges(across, (cell.top() - half)..=(cell.bottom() + half))
446}
447
448/// The header strip: sunken, with the `bevel-dark` edge under it.
449fn strip(ui: &Ui, across: egui::Rangef, reach: &std::cell::Cell<f32>, palette: &Palette) {
450    let rect = row_rect(ui, across);
451    reach.set(reach.get().max(rect.bottom()));
452    ui.painter().rect_filled(rect, 0, palette.sunken);
453    ui.painter().hline(
454        across,
455        rect.bottom(),
456        egui::Stroke::new(1.0, palette.bevel_dark),
457    );
458}
459
460/// One body row's fill and the hairline above it.
461///
462/// Selected, then hovered, then the stripe on every second row, and the first
463/// of those that holds is the fill. A table holding code takes the selection
464/// and the hover and neither the stripe nor the hairline, which break the
465/// reading of source one line to a row.
466fn ground_row(
467    ui: &Ui,
468    across: egui::Rangef,
469    Row {
470        index,
471        selected,
472        code,
473    }: Row,
474    reach: &std::cell::Cell<f32>,
475    palette: &Palette,
476) {
477    let rect = row_rect(ui, across);
478    reach.set(reach.get().max(rect.bottom()));
479    let fill = if selected {
480        Some(palette.row_selected)
481    } else if ui.rect_contains_pointer(rect) {
482        Some(palette.row_hover)
483    } else if !code && index % 2 == 1 {
484        Some(palette.row_stripe)
485    } else {
486        None
487    };
488    if let Some(fill) = fill {
489        ui.painter().rect_filled(rect, 0, fill);
490    }
491    if !code && index > 0 {
492        ui.painter()
493            .hline(across, rect.top(), egui::Stroke::new(1.0, palette.row_rule));
494    }
495}
496
497/// A cell laid out the way its column's kind says, wiki `table-model`.
498///
499/// Alignment is the kind fact this renderer acts on. A number or actions
500/// column runs right to left, on the row's centre line like every cell, and
501/// its heading does the same so the label sits over its figures. The face and
502/// the figures a kind names are the caller's, who draws the cell's contents.
503fn placed(ui: &mut Ui, column: &Column<'_>, add: impl FnOnce(&mut Ui)) {
504    if column.kind.aligns_end() {
505        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), add);
506    } else {
507        add(ui);
508    }
509}
510
511/// What a heading's caret is drawn in.
512///
513/// Three states (wiki `three-tone-convention`), carried by the caret as the
514/// webview carries them: the column in force takes content, a column offering
515/// to reorder takes secondary, and a column that is not a control draws no
516/// caret. The label is the strip's own secondary ink in every state.
517///
518/// The offering state may not take `content_muted`, which is what
519/// [`State::Disabled`](makeover_layout::State::Disabled) resolves to: a heading
520/// the user can press would be claiming it will not answer.
521fn caret_color(column: &Column<'_>, palette: &Palette) -> egui::Color32 {
522    match column.sorted {
523        Some(_) => palette.content,
524        None => palette.content_secondary,
525    }
526}
527
528/// One heading, and whether it was pressed.
529fn press(ui: &mut Ui, column: &Column<'_>, palette: &Palette, style: &TableStyle) -> bool {
530    // The strip's type: small, strong and tracked, as the webview sets it, with
531    // the caret in its own run so it can take its own tone.
532    let size = egui::TextStyle::Small.resolve(ui.style()).size;
533    let heading = heading(column, style);
534    let label_len = column.name.to_uppercase().len();
535    let mut job = egui::text::LayoutJob::default();
536    RichText::new(&heading[..label_len])
537        .color(palette.content_secondary)
538        .small()
539        .strong()
540        .extra_letter_spacing(0.06 * size)
541        .append_to(
542            &mut job,
543            ui.style(),
544            egui::FontSelection::Default,
545            egui::Align::Center,
546        );
547    let caret = &heading[label_len..];
548    // The caret is text when the face can draw it and a painted triangle when
549    // it cannot. egui's bundled faces carry neither U+25B2 nor U+25BC, and an
550    // app's own face may or may not, so a glyph assumed present drew a box on
551    // every sorted column of an app on egui's defaults.
552    let font = egui::TextStyle::Small.resolve(ui.style());
553    let drawable = ui
554        .ctx()
555        .fonts_mut(|fonts| caret.trim().chars().all(|c| fonts.has_glyph(&font, c)));
556    let painted = !caret.is_empty() && !drawable;
557    if !caret.is_empty() && drawable {
558        RichText::new(caret)
559            .color(caret_color(column, palette))
560            .small()
561            .append_to(
562                &mut job,
563                ui.style(),
564                egui::FontSelection::Default,
565                egui::Align::Center,
566            );
567    }
568    let text = job;
569    let sense = if column.sortable {
570        Sense::click()
571    } else {
572        // Not sensed. A heading a user cannot press must not look like one they
573        // can, which is the affordance `Column::sortable` exists to carry, and
574        // the missing caret is half of saying so.
575        Sense::hover()
576    };
577    let response = ui
578        .horizontal(|ui| {
579            let label = ui.add(egui::Label::new(text).sense(sense));
580            if !painted {
581                return label;
582            }
583            let up = column.sorted != Some(Sort::Descending);
584            let (rect, mark) = ui.allocate_exact_size(egui::Vec2::splat(size), sense);
585            paint_caret(ui, rect, up, caret_color(column, palette));
586            label.union(mark)
587        })
588        .inner;
589    if !column.sortable {
590        return false;
591    }
592    let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
593    // Announced as the control it is, rather than as the `Label` it is drawn
594    // with. egui maps a `Label` to `Role::Label` whatever it senses, so left
595    // alone a screen reader is told this is static text, and a user who cannot
596    // see the pointer change has no way to know the table sorts.
597    // The same argument the comment above makes about affordance, made about
598    // the half of the interface that is not pixels.
599    //
600    // The name is the column's own, not `heading`'s: the caret is a rendering of
601    // `Column::sorted`, and reading a triangle aloud after every heading is
602    // noise. Which column is in force is a fact a client should get from the
603    // sort state, and egui has nowhere to put that yet, which is worth revisiting if it
604    // grows a sort field on `WidgetInfo`.
605    response.widget_info(|| {
606        egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), column.name)
607    });
608    response.clicked()
609}
610
611/// A filled triangle in `rect`, pointing up or down: the caret a face that
612/// cannot draw the glyph gets instead of a box.
613///
614/// Half the rect's height, centred on the text's midline, which is about the
615/// size a small-caps caret sits at beside the heading.
616fn paint_caret(ui: &Ui, rect: egui::Rect, up: bool, color: egui::Color32) {
617    let c = rect.center();
618    let half = rect.height() / 4.0;
619    let (tip, base) = if up {
620        (c.y - half, c.y + half)
621    } else {
622        (c.y + half, c.y - half)
623    };
624    ui.painter().add(egui::Shape::convex_polygon(
625        vec![
626            egui::Pos2::new(c.x, tip),
627            egui::Pos2::new(c.x + half * 1.15, base),
628            egui::Pos2::new(c.x - half * 1.15, base),
629        ],
630        color,
631        egui::Stroke::NONE,
632    ));
633}
634
635#[cfg(test)]
636mod tests {
637    use super::*;
638    use makeover_layout::ColumnKind;
639
640    /// What the accessibility tree says a heading row drew.
641    ///
642    /// egui builds it from the `WidgetInfo` each widget reports, so this is
643    /// what a screen reader would be handed rather than a second opinion.
644    fn announced(draw: impl FnMut(&mut Ui)) -> Vec<(egui::accesskit::Role, String)> {
645        let ctx = egui::Context::default();
646        ctx.enable_accesskit();
647        let mut draw = draw;
648        let input = || egui::RawInput {
649            screen_rect: Some(egui::Rect::from_min_size(
650                egui::Pos2::ZERO,
651                egui::vec2(800.0, 600.0),
652            )),
653            ..Default::default()
654        };
655        // A frame's texture changes are the host's to upload, and egui 0.36
656        // refuses to have them dropped unread. No host here, so they are
657        // cleared by hand.
658        ctx.run_ui(input(), &mut draw).textures_delta.clear();
659        let mut out = ctx.run_ui(input(), &mut draw);
660        out.textures_delta.clear();
661        out.platform_output
662            .accesskit_update
663            .expect("accesskit is on")
664            .nodes
665            .iter()
666            .map(|(_, node)| {
667                (
668                    node.role(),
669                    node.label()
670                        .or_else(|| node.value())
671                        .unwrap_or_default()
672                        .to_owned(),
673                )
674            })
675            .collect()
676    }
677
678    /// Every triangle a heading draws, as `(pointing up, tip y, base y)`.
679    fn triangles(column: &Column<'_>) -> Vec<bool> {
680        let ctx = egui::Context::default();
681        let p = palette();
682        let mut draw = |ui: &mut Ui| {
683            press(ui, column, &p, &TableStyle::default());
684        };
685        let input = || egui::RawInput {
686            screen_rect: Some(egui::Rect::from_min_size(
687                egui::Pos2::ZERO,
688                egui::vec2(800.0, 600.0),
689            )),
690            ..Default::default()
691        };
692        ctx.run_ui(input(), &mut draw).textures_delta.clear();
693        let mut out = ctx.run_ui(input(), &mut draw);
694        out.textures_delta.clear();
695        out.shapes
696            .iter()
697            .filter_map(|clipped| match &clipped.shape {
698                egui::Shape::Path(path) if path.points.len() == 3 => {
699                    Some(path.points[0].y < path.points[1].y)
700                }
701                _ => None,
702            })
703            .collect()
704    }
705
706    #[test]
707    fn a_caret_the_face_cannot_draw_is_painted_instead_of_boxed() {
708        // egui's bundled faces have no U+25B2 or U+25BC, measured with
709        // `has_glyph`, so on them the caret is a painted triangle pointing the
710        // way the column is sorted, and not a glyph drawn as a box.
711        let mut column = Column::new("Size")
712            .width(Width::Content)
713            .priority(Priority::Essential)
714            .kind(ColumnKind::Text)
715            .sortable(true)
716            .sorted(Sort::Ascending);
717        assert_eq!(triangles(&column), [true]);
718        column = column.sorted(Sort::Descending);
719        assert_eq!(triangles(&column), [false]);
720        column = Column::new("Size")
721            .width(Width::Content)
722            .priority(Priority::Essential)
723            .kind(ColumnKind::Text);
724        assert!(triangles(&column).is_empty());
725    }
726
727    #[test]
728    fn a_sortable_heading_is_announced_as_something_you_press() {
729        let column = Column::new("Name")
730            .width(Width::Fill)
731            .priority(Priority::Essential)
732            .kind(ColumnKind::Text)
733            .sortable(true)
734            .sorted(Sort::Ascending);
735        let p = palette();
736        let drawn = announced(|ui| {
737            press(ui, &column, &p, &TableStyle::default());
738        });
739
740        // The name is the column's, with no caret in it: the glyph renders
741        // `Column::sorted` and is not part of what the control is called.
742        assert!(
743            drawn
744                .iter()
745                .any(|(role, name)| *role == egui::accesskit::Role::Button && name == "Name"),
746            "{drawn:?}"
747        );
748    }
749
750    #[test]
751    fn a_heading_that_is_not_a_control_is_not_announced_as_one() {
752        let column = Column::new("Tags")
753            .width(Width::Fixed)
754            .priority(Priority::Optional)
755            .kind(ColumnKind::Text);
756        let p = palette();
757        let drawn = announced(|ui| {
758            press(ui, &column, &p, &TableStyle::default());
759        });
760
761        assert!(
762            !drawn
763                .iter()
764                .any(|(role, _)| *role == egui::accesskit::Role::Button),
765            "a heading with no sort answers nothing and must not claim to: {drawn:?}"
766        );
767    }
768    use egui::Color32;
769
770    fn palette() -> Palette {
771        Palette {
772            page: Color32::from_rgb(1, 1, 1),
773            raised: Color32::from_rgb(2, 2, 2),
774            overlay: Color32::from_rgb(3, 3, 3),
775            well: Color32::from_rgb(4, 4, 4),
776            sunken: Color32::from_rgb(5, 5, 5),
777            bevel_light: Color32::WHITE,
778            bevel_dark: Color32::BLACK,
779            elevation: Color32::from_black_alpha(46),
780            content: Color32::from_rgb(6, 6, 6),
781            content_secondary: Color32::from_rgb(56, 56, 56),
782            content_muted: Color32::from_rgb(7, 7, 7),
783            action: Color32::from_rgb(8, 8, 8),
784            content_on_action: Color32::from_rgb(250, 250, 250),
785            danger: Color32::from_rgb(9, 9, 9),
786            success: Color32::from_rgb(10, 10, 10),
787            warning: Color32::from_rgb(11, 11, 11),
788            info: Color32::from_rgb(12, 12, 12),
789            border: Color32::from_rgb(200, 200, 200),
790            info_surface: Color32::from_rgb(201, 201, 201),
791            success_surface: Color32::from_rgb(202, 202, 202),
792            warning_surface: Color32::from_rgb(203, 203, 203),
793            danger_surface: Color32::from_rgb(204, 204, 204),
794            row_stripe: Color32::from_rgb(205, 205, 205),
795            row_hover: Color32::from_rgb(206, 206, 206),
796            row_rule: Color32::from_rgb(207, 207, 207),
797            row_selected: Color32::from_rgb(208, 208, 208),
798        }
799    }
800
801    fn columns() -> Vec<Column<'static>> {
802        vec![
803            Column::new("name")
804                .width(Width::Fill)
805                .priority(Priority::Essential)
806                .kind(ColumnKind::Text)
807                .sortable(true)
808                .sorted(Sort::Ascending),
809            Column::new("size")
810                .width(Width::Fixed)
811                .priority(Priority::Secondary)
812                .kind(ColumnKind::Text)
813                .sortable(true),
814            Column::new("note")
815                .width(Width::Content)
816                .priority(Priority::Optional)
817                .kind(ColumnKind::Text),
818        ]
819    }
820
821    fn sizing() -> Sizing<'static> {
822        Sizing::new(&[("name", 120.0), ("size", 60.0), ("note", 80.0)], 40.0)
823    }
824
825    #[test]
826    fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
827        // Floors of 16ch (the name fills), 8 and 8, at 10 points a ch, and a
828        // gap of twice the 12-point edge between neighbours and at each end:
829        // 320 + 4 gaps, 240 + 3 gaps, 160 + 2 gaps.
830        let cols = columns();
831        assert_eq!(cutoff(&cols, 10.0, 12.0, 416.0), Priority::Optional);
832        assert_eq!(cutoff(&cols, 10.0, 12.0, 415.0), Priority::Secondary);
833        assert_eq!(cutoff(&cols, 10.0, 12.0, 312.0), Priority::Secondary);
834        assert_eq!(cutoff(&cols, 10.0, 12.0, 311.0), Priority::Essential);
835        // Narrower than the essential column, which stays anyway.
836        assert_eq!(cutoff(&cols, 10.0, 12.0, 10.0), Priority::Essential);
837    }
838
839    #[test]
840    fn the_same_floors_drop_at_the_same_ch_count_as_a_terminal() {
841        // A terminal counts one cell a ch. At one point a ch and no edge, the
842        // cut falls on the floors alone, which is the number both other hosts
843        // read, so a description narrows at one declared width everywhere.
844        let cols = columns();
845        assert_eq!(cutoff(&cols, 1.0, 0.0, 32.0), Priority::Optional);
846        assert_eq!(cutoff(&cols, 1.0, 0.0, 31.0), Priority::Secondary);
847        assert_eq!(cutoff(&cols, 1.0, 0.0, 24.0), Priority::Secondary);
848        assert_eq!(cutoff(&cols, 1.0, 0.0, 23.0), Priority::Essential);
849    }
850
851    #[test]
852    fn a_column_inserted_left_of_the_cut_does_not_change_what_drops() {
853        // The goingson bug, as a test. `nth-child(n+5)` against a seven-column
854        // table hides whatever lands at position five, so inserting a column
855        // moves the cut onto a different column with nothing edited.
856        //
857        // Asserted at a fixed cutoff, because that is where the two ways of
858        // addressing a column disagree. A narrower budget SHOULD drop more; what
859        // must not change is which ones, for a given cutoff.
860        let dropped = |cols: &[Column<'_>], cutoff| -> Vec<String> {
861            cols.iter()
862                .filter(|c| !c.kept_at(cutoff))
863                .map(|c| c.name.to_owned())
864                .collect()
865        };
866        let before = columns();
867        let mut after = vec![
868            Column::new("mark")
869                .width(Width::Fixed)
870                .priority(Priority::Essential)
871                .kind(ColumnKind::Text),
872        ];
873        after.extend(columns());
874
875        for &cutoff in Priority::RAISING {
876            assert_eq!(dropped(&before, cutoff), dropped(&after, cutoff));
877        }
878        assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
879    }
880
881    #[test]
882    fn a_content_column_is_measured_by_egui_and_budgeted_by_its_floor() {
883        // The split the module header names. The track defers to egui_extras,
884        // which can measure; the narrowing cannot wait for that and uses the
885        // declared floor. Both readings of the same column, and both honest.
886        let cols = columns();
887        let note = &cols[2];
888        assert!(matches!(note.width, Width::Content));
889        assert_eq!(note.floor(), 8, "undeclared, so the kind's floor");
890        // Floors of 16, 8 and 8ch at 10 points and four gaps of 24: 416 keeps
891        // every column and 415 does not, whatever the cells turn out to hold.
892        assert_eq!(cutoff(&cols, 10.0, 12.0, 416.0), Priority::Optional);
893        assert_eq!(cutoff(&cols, 10.0, 12.0, 415.0), Priority::Secondary);
894    }
895
896    #[test]
897    fn a_column_with_no_length_of_its_own_takes_the_fallback() {
898        let column = Column::new("unlisted")
899            .width(Width::Fixed)
900            .priority(Priority::Essential)
901            .kind(ColumnKind::Text);
902        // The fallback sizes a track and nothing else: which columns exist is
903        // the floor's to decide.
904        assert!((sizing().length_for(column.name) - 40.0).abs() < f32::EPSILON);
905    }
906
907    #[test]
908    fn the_parts_a_cell_can_be_are_coloured_apart() {
909        // The drift `CellPart` exists to end: one colour for a whole cell paints
910        // a control as though it were text.
911        let p = palette();
912        assert_eq!(part_color(Some(CellPart::Value), &p), p.content);
913        assert_eq!(part_color(Some(CellPart::Tokens), &p), p.content_muted);
914        assert_eq!(part_color(Some(CellPart::Actions), &p), p.action);
915        assert_eq!(part_color(Some(CellPart::Link), &p), p.action);
916        assert_ne!(part_color(Some(CellPart::Link), &p), p.content);
917        // A cell mixing parts says nothing, and takes the text colour.
918        assert_eq!(part_color(None, &p), p.content);
919    }
920
921    #[test]
922    fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
923        let style = TableStyle::default();
924        let cols = columns();
925        assert_eq!(heading(&cols[0], &style), "NAME \u{25B2}");
926        // Sortable and idle. It draws the mark a first press would give, which
927        // is what stops the press from widening the column and shifting the
928        // ones after it.
929        assert_eq!(heading(&cols[1], &style), "SIZE \u{25B2}");
930        // Not a control. Nothing to mark.
931        assert_eq!(heading(&cols[2], &style), "NOTE");
932    }
933
934    #[test]
935    fn the_three_states_of_a_heading_are_carried_by_its_caret() {
936        // wiki `three-tone-convention`, as the webview draws it: the caret in
937        // force takes content, the idle caret secondary, and a heading that is
938        // not a control has no caret. The offering state may not take
939        // content_muted, which is what `State::Disabled` resolves to.
940        let p = palette();
941        let cols = columns();
942        let style = TableStyle::default();
943        assert_eq!(caret_color(&cols[0], &p), p.content);
944        assert_eq!(caret_color(&cols[1], &p), p.content_secondary);
945        assert_ne!(caret_color(&cols[1], &p), p.content_muted);
946        assert!(
947            !heading(&cols[2], &style).contains(' '),
948            "an inert heading has no caret"
949        );
950    }
951
952    #[test]
953    fn a_column_sorted_without_being_sortable_still_draws_its_caret() {
954        // A list ordered by a key the user cannot change is a real thing to
955        // describe, which is why the description holds the two fields apart.
956        let column = Column::new("rank")
957            .width(Width::Content)
958            .priority(Priority::Essential)
959            .kind(ColumnKind::Text)
960            .sorted(Sort::Descending);
961        assert_eq!(heading(&column, &TableStyle::default()), "RANK \u{25BC}");
962    }
963
964    #[test]
965    fn the_carets_match_the_terminal_renderers() {
966        // Two crates, one glyph pair, and no dependency between them to enforce
967        // it. A description sorted ascending must not point up in a window and
968        // down in a terminal.
969        // Composition rather than agreement: both read `Sort::glyph`, so a
970        // fourth spelling cannot appear in one crate.
971        let style = TableStyle::default();
972        assert_eq!(style.ascending, Sort::Ascending.glyph());
973        assert_eq!(style.descending, Sort::Descending.glyph());
974        // Bare. The gap is `heading`'s, so a consumer swapping the glyph for an
975        // ASCII one does not have to remember to bring a space with it.
976        assert_eq!(style.ascending.trim(), style.ascending);
977    }
978
979    #[test]
980    fn resizing_is_off_because_the_description_has_no_word_for_it() {
981        // egui_extras offers it and the other two renderers cannot say it. A
982        // default that turned it on would be this renderer adding a claim.
983        assert!(!TableStyle::default().resizable);
984    }
985
986    #[test]
987    fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
988        let style = TableStyle::default();
989        assert!((style.row_height - 45.0).abs() < f32::EPSILON);
990        assert!(style.code_row_height < style.row_height);
991    }
992
993    #[test]
994    fn a_body_claims_nothing_until_it_is_asked_to() {
995        // The default is a table of no rows, no selection and no scroll
996        // request. All three absences are the honest reading of an app that has
997        // not said otherwise, which is why they are `Option` and not a
998        // predicate that always answers false.
999        let body = Body::default();
1000        assert_eq!(body.rows, 0);
1001        assert!(body.selected.is_none());
1002        assert!(body.scroll_to.is_none());
1003    }
1004
1005    #[test]
1006    fn a_selection_is_asked_per_row_and_not_collected() {
1007        // A predicate, so an app whose selection is a range or a single index
1008        // does not build a set to be asked. Exercised the way `table` asks it:
1009        // once per row index, in order.
1010        let selected = |index: usize| index.is_multiple_of(2);
1011        let body = Body {
1012            rows: 4,
1013            selected: Some(&selected),
1014            scroll_to: None,
1015        };
1016        let f = body.selected.expect("a predicate was supplied");
1017        assert_eq!(
1018            (0..body.rows).map(f).collect::<Vec<_>>(),
1019            vec![true, false, true, false]
1020        );
1021    }
1022
1023    #[test]
1024    fn narrowing_reads_the_declared_widths_and_not_a_dragged_track() {
1025        // `resizable` lets the user move a divider, and the narrowing must not
1026        // hear about it: a drag that could drop a column would make the
1027        // narrowing a thing the user does by accident rather than a property of
1028        // the description. That `cutoff` takes the columns and two numbers,
1029        // and no `TableStyle` or track state, is the structural half of the
1030        // guarantee; this is the behavioural half, and it is what would fail if a
1031        // measured width were ever threaded in beside the declared floor.
1032        let cols = columns();
1033        assert_eq!(cutoff(&cols, 10.0, 12.0, 416.0), Priority::Optional);
1034        assert_eq!(cutoff(&cols, 10.0, 12.0, 312.0), Priority::Secondary);
1035    }
1036}