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