Skip to main content

makeover_immediate/
table.rs

1//! A table's style, its per-frame facts, and the tone each part of a cell
2//! takes.
3//!
4//! The table itself, which takes the description's columns, narrows them for
5//! the width on offer and draws the heading row over `egui_extras`, is
6//! `quasi-immediate`'s, because a column is a vocabulary member and the quasi
7//! hosts own the vocabulary. What carries no column stays here and is what
8//! that table is drawn with: [`TableStyle`] for the metrics, [`Body`] for the
9//! rows, selection and scroll request of one frame, [`Sizing`] for the lengths
10//! the description deferred, and [`cell`] with [`part_color`] for the tone a
11//! cell's contents take.
12//!
13//! # The table model
14//!
15//! Wiki `table-model`, drawn the way `makeover-webview` draws it, since egui
16//! paints the same pixels a browser does: a raised ground inside a hairline
17//! frame, the header a sunken strip over a `bevel-dark` edge in secondary
18//! capitals, rows 45 points tall with a hairline between them and a tone under
19//! the pointer. No stripe: the hairline separates the rows, and makeover 5 has
20//! no stripe tone. A table holding code keeps the frame and the header and
21//! drops the hairlines and the tall row, which is what
22//! [`TableStyle::code_row_height`] is for.
23
24use crate::Palette;
25use egui::Ui;
26use makeover_geometry::{Compactness, Step, Surface};
27use makeover_layout::{CellPart, Sort};
28
29/// The lengths the description deferred, in points: the track for a
30/// [`Width::Fixed`](makeover_layout::Width::Fixed) column, the floor for a [`Width::Fill`](makeover_layout::Width::Fill) one, and the
31/// narrowing budget for a [`Width::Content`](makeover_layout::Width::Content) one. The suite's one sizing type,
32/// held here over points as the terminal holds it over cells.
33pub type Sizing<'a> = makeover_layout::Sizing<'a, f32>;
34
35/// The tones and metrics a table draws with.
36///
37/// Metrics only, and the tones come from [`Palette`]. That is the division this
38/// crate already draws: [`FieldStyle`](crate::FieldStyle) carries gaps and a
39/// marker while the colours stay in the palette, and a table's colours are the
40/// palette's content tones rather than six new ones.
41/// `makeover-tui` splits it the other way round because its palette carries no
42/// text tones at all.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct TableStyle {
45    /// How densely the rows are packed: [`Compactness::Comfortable`] is the
46    /// model's [`ROW_BLOCK`](makeover_geometry::ROW_BLOCK), [`Compactness::Compact`] a denser row. The
47    /// reader's choice, not the description's: packing is a fact about eyes
48    /// and screen, not about what the table says.
49    pub compactness: Compactness,
50    /// The height of the heading row.
51    pub header_height: f32,
52    /// The height of a body row: [`Compactness::row_block`] at
53    /// `makeover-geometry`'s base.
54    pub row_height: f32,
55    /// The height of a row in a table holding code, which is one line of
56    /// source rather than a record.
57    pub code_row_height: f32,
58    /// The ground between the table's frame and the cells at either end of a
59    /// row: the webview's `gap-group`, which pads both ends of a row.
60    pub edge_padding: f32,
61    /// The caret drawn after the heading of an ascending column.
62    ///
63    /// Defaults to [`Sort::glyph`], which is where the spelling lives now:
64    /// three renderers holding the same literal agreed by coincidence. Bare,
65    /// with no leading space: the gap is the heading's, written once for all
66    /// three states rather than baked into two strings and forgotten in the
67    /// third.
68    pub ascending: &'static str,
69    /// Drawn after the heading of a descending column.
70    pub descending: &'static str,
71    /// Whether the user can drag the divider between two columns.
72    ///
73    /// The one knob that is not a metric. Not every setting egui_extras has
74    /// becomes a field here: a sticky heading is what `TableBuilder::header`
75    /// does and there is no version that does not, and the table model draws no
76    /// stripe at any host with a hairline, so a knob for either would offer a
77    /// choice this renderer cannot make. Off by default: the description has no word for
78    /// resizing, so a default that turned it on would be this renderer adding a
79    /// claim the other two cannot make.
80    ///
81    /// It does not fight the narrowing. A drag moves a track for the frames it
82    /// is held; the narrowing still decides which columns exist, off each
83    /// column's declared floor, so a resize can never drop a
84    /// column.
85    pub resizable: bool,
86}
87
88impl Default for TableStyle {
89    fn default() -> Self {
90        Self::for_compactness(Surface::web(), Compactness::Comfortable)
91    }
92}
93
94impl TableStyle {
95    /// The default metrics on `surface`, at `compactness`.
96    ///
97    /// Resolved from the geometry scale rather than written as literals, so a
98    /// changed base moves egui tables with the webview's `--row-block` and
99    /// with the heading the other hosts draw. The web surface is the egui one:
100    /// points at the default base, one point to the quantum.
101    #[must_use]
102    pub fn for_compactness(surface: Surface, compactness: Compactness) -> Self {
103        Self {
104            compactness,
105            header_height: surface.resolve(Step::Vast.ratio()),
106            row_height: surface.resolve(compactness.row_block()),
107            code_row_height: 20.0,
108            edge_padding: 12.0,
109            ascending: Sort::Ascending.glyph(),
110            descending: Sort::Descending.glyph(),
111            resizable: false,
112        }
113    }
114}
115
116/// The body's own facts for this frame: how many rows, which are selected, and
117/// which one to bring into view.
118///
119/// Held apart from [`TableStyle`] because none of it is style and none of it
120/// survives the frame: a row count changes when a folder does, a selection when
121/// the user clicks, and a scroll request exists for exactly one frame. Held
122/// apart from the columns because none of it is description either.
123/// The description says what a table *is*, and this says what it holds right
124/// now.
125///
126/// Both of the optional fields are here rather than left to the app because
127/// egui_extras answers them on a handle the app never sees: `set_selected` is a
128/// method on the row, and `scroll_to_row` a method on the builder, and the
129/// table owns both. That is the same reason [`cell`] exists.
130#[derive(Default)]
131pub struct Body<'a> {
132    /// How many rows to draw.
133    pub rows: usize,
134    /// Whether a row is selected, by index.
135    ///
136    /// A predicate rather than a set, so an app whose selection is a range, a
137    /// bitmap or a single index does not have to build a collection to be asked.
138    /// `None` is a table no row of which is selected, which is not the same
139    /// claim as a predicate that always answers false and costs nothing to make.
140    pub selected: Option<&'a dyn Fn(usize) -> bool>,
141    /// A row to bring into view this frame.
142    ///
143    /// Set it from a request the app then clears, the way a keyboard cursor
144    /// moving off-screen raises one: held rather than taken, it would fight
145    /// every scroll the user makes with the mouse.
146    pub scroll_to: Option<usize>,
147}
148
149impl std::fmt::Debug for Body<'_> {
150    // Hand-written because `selected` is a closure and `#[derive(Debug)]` will
151    // not have it. What is worth printing is whether one was supplied.
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("Body")
154            .field("rows", &self.rows)
155            .field("selected", &self.selected.is_some())
156            .field("scroll_to", &self.scroll_to)
157            .finish()
158    }
159}
160
161/// The colour a cell of this part takes: the content intent
162/// [`CellPart::intent`] names.
163///
164/// A cell that says no part, and an intent outside makeover-layout's
165/// `content*` set, take `content`, so a part or an intent this renderer has
166/// not learned draws as text rather than as nothing.
167#[must_use]
168pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
169    let Some(part) = part else {
170        return palette.content;
171    };
172    match part.intent().as_bytes() {
173        b"content-secondary" => palette.content_secondary,
174        b"content-muted" => palette.content_muted,
175        b"content-disabled" => palette.content_disabled,
176        _ => palette.content,
177    }
178}
179
180/// Draw a cell's contents with the tone its part takes.
181///
182/// The app calls this inside its own cell closure, wrapping whatever it draws.
183/// A scoping function rather than a parameter on the table, for the reason
184/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
185/// does not exist until the closure runs, and immediate mode has no cascade to
186/// carry the answer down on its own. This is the cascade, for one scope.
187///
188/// ```no_run
189/// # use makeover_layout::CellPart;
190/// # let palette: makeover_immediate::Palette = unimplemented!();
191/// # let ui: &mut egui::Ui = unimplemented!();
192/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
193///     ui.label("opens the item");
194/// });
195/// ```
196pub fn cell<R>(
197    ui: &mut Ui,
198    part: Option<CellPart>,
199    palette: &Palette,
200    add_contents: impl FnOnce(&mut Ui) -> R,
201) -> R {
202    let restore = ui.visuals().override_text_color;
203    ui.visuals_mut().override_text_color = Some(part_color(part, palette));
204    let out = add_contents(ui);
205    ui.visuals_mut().override_text_color = restore;
206    out
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::tests::palette;
213
214    #[test]
215    fn a_cell_part_takes_the_colour_its_intent_names() {
216        // makeover-layout's `CellPart::intent` is the rule every host reads, so
217        // a link here draws as the webview's does, in the values' ink.
218        let p = palette();
219        for part in [
220            CellPart::Value,
221            CellPart::Tokens,
222            CellPart::Actions,
223            CellPart::Link,
224        ] {
225            let want = match part.intent() {
226                "content" => p.content,
227                "content-secondary" => p.content_secondary,
228                "content-muted" => p.content_muted,
229                "content-disabled" => p.content_disabled,
230                other => panic!("{part:?} names {other}, which this renderer has not learned"),
231            };
232            assert_eq!(part_color(Some(part), &p), want, "{part:?}");
233        }
234        // A cell mixing parts says nothing, and takes the text colour.
235        assert_eq!(part_color(None, &p), p.content);
236    }
237
238    #[test]
239    fn the_carets_match_the_terminal_renderers() {
240        // Two crates, one glyph pair, and no dependency between them to enforce
241        // it. A description sorted ascending must not point up in a window and
242        // down in a terminal.
243        // Composition rather than agreement: both read `Sort::glyph`, so a
244        // fourth spelling cannot appear in one crate.
245        let style = TableStyle::default();
246        assert_eq!(style.ascending, Sort::Ascending.glyph());
247        assert_eq!(style.descending, Sort::Descending.glyph());
248        // Bare. The gap is the heading's, so a consumer swapping the glyph for an
249        // ASCII one does not have to remember to bring a space with it.
250        assert_eq!(style.ascending.trim(), style.ascending);
251    }
252
253    #[test]
254    fn resizing_is_off_because_the_description_has_no_word_for_it() {
255        // egui_extras offers it and the other two renderers cannot say it. A
256        // default that turned it on would be this renderer adding a claim.
257        assert!(!TableStyle::default().resizable);
258    }
259
260    #[test]
261    fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
262        let style = TableStyle::default();
263        assert!((style.row_height - 45.0).abs() < f32::EPSILON);
264        assert!(style.code_row_height < style.row_height);
265    }
266
267    #[test]
268    fn a_compact_table_packs_rows_at_the_dense_step() {
269        // Compact is the reader's denser row, not a description claim. It is
270        // Step::Broad of the base (24pt), audiofiles' historical default.
271        let style = TableStyle::for_compactness(Surface::web(), Compactness::Compact);
272        assert_eq!(style.compactness, Compactness::Compact);
273        assert!((style.row_height - 24.0).abs() < f32::EPSILON);
274    }
275
276    #[test]
277    fn a_body_claims_nothing_until_it_is_asked_to() {
278        // The default is a table of no rows, no selection and no scroll
279        // request. All three absences are the honest reading of an app that has
280        // not said otherwise, which is why they are `Option` and not a
281        // predicate that always answers false.
282        let body = Body::default();
283        assert_eq!(body.rows, 0);
284        assert!(body.selected.is_none());
285        assert!(body.scroll_to.is_none());
286    }
287
288    #[test]
289    fn a_selection_is_asked_per_row_and_not_collected() {
290        // A predicate, so an app whose selection is a range or a single index
291        // does not build a set to be asked. Exercised the way the table asks it:
292        // once per row index, in order.
293        let selected = |index: usize| index.is_multiple_of(2);
294        let body = Body {
295            rows: 4,
296            selected: Some(&selected),
297            scroll_to: None,
298        };
299        let f = body.selected.expect("a predicate was supplied");
300        assert_eq!(
301            (0..body.rows).map(f).collect::<Vec<_>>(),
302            vec![true, false, true, false]
303        );
304    }
305}