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