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`, `content_muted` and `action` 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`], [`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.
162///
163/// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
164/// `content`: a part this renderer has not learned draws as text, which is a
165/// cell rendering plainly rather than a build that stops. Grep this when
166/// adopting a new `makeover-layout`.
167#[must_use]
168pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
169    match part {
170        // A token paints its own background and carries its own tone. What is
171        // set here is what shows between them, not what paints them.
172        Some(CellPart::Tokens) => palette.content_muted,
173        // The drift `CellPart` exists to end: a control in a cell inheriting the
174        // cell's text colour. Both of these take the action intent instead.
175        Some(CellPart::Actions | CellPart::Link) => palette.action,
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 egui::Color32;
213
214    fn palette() -> Palette {
215        Palette {
216            page: Color32::from_rgb(1, 1, 1),
217            raised: Color32::from_rgb(2, 2, 2),
218            overlay: Color32::from_rgb(3, 3, 3),
219            well: Color32::from_rgb(4, 4, 4),
220            sunken: Color32::from_rgb(5, 5, 5),
221            bevel_light: Color32::WHITE,
222            bevel_dark: Color32::BLACK,
223            elevation: Color32::from_black_alpha(46),
224            content: Color32::from_rgb(6, 6, 6),
225            content_secondary: Color32::from_rgb(56, 56, 56),
226            content_muted: Color32::from_rgb(7, 7, 7),
227            action: Color32::from_rgb(8, 8, 8),
228            content_on_action: Color32::from_rgb(250, 250, 250),
229            danger: Color32::from_rgb(9, 9, 9),
230            success: Color32::from_rgb(10, 10, 10),
231            warning: Color32::from_rgb(11, 11, 11),
232            info: Color32::from_rgb(12, 12, 12),
233            border: Color32::from_rgb(200, 200, 200),
234            info_surface: Color32::from_rgb(201, 201, 201),
235            success_surface: Color32::from_rgb(202, 202, 202),
236            warning_surface: Color32::from_rgb(203, 203, 203),
237            danger_surface: Color32::from_rgb(204, 204, 204),
238            row_hover: Color32::from_rgb(206, 206, 206),
239            row_rule: Color32::from_rgb(207, 207, 207),
240            row_selected: Color32::from_rgb(208, 208, 208),
241        }
242    }
243
244    #[test]
245    fn the_parts_a_cell_can_be_are_coloured_apart() {
246        // The drift `CellPart` exists to end: one colour for a whole cell paints
247        // a control as though it were text.
248        let p = palette();
249        assert_eq!(part_color(Some(CellPart::Value), &p), p.content);
250        assert_eq!(part_color(Some(CellPart::Tokens), &p), p.content_muted);
251        assert_eq!(part_color(Some(CellPart::Actions), &p), p.action);
252        assert_eq!(part_color(Some(CellPart::Link), &p), p.action);
253        assert_ne!(part_color(Some(CellPart::Link), &p), p.content);
254        // A cell mixing parts says nothing, and takes the text colour.
255        assert_eq!(part_color(None, &p), p.content);
256    }
257
258    #[test]
259    fn the_carets_match_the_terminal_renderers() {
260        // Two crates, one glyph pair, and no dependency between them to enforce
261        // it. A description sorted ascending must not point up in a window and
262        // down in a terminal.
263        // Composition rather than agreement: both read `Sort::glyph`, so a
264        // fourth spelling cannot appear in one crate.
265        let style = TableStyle::default();
266        assert_eq!(style.ascending, Sort::Ascending.glyph());
267        assert_eq!(style.descending, Sort::Descending.glyph());
268        // Bare. The gap is the heading's, so a consumer swapping the glyph for an
269        // ASCII one does not have to remember to bring a space with it.
270        assert_eq!(style.ascending.trim(), style.ascending);
271    }
272
273    #[test]
274    fn resizing_is_off_because_the_description_has_no_word_for_it() {
275        // egui_extras offers it and the other two renderers cannot say it. A
276        // default that turned it on would be this renderer adding a claim.
277        assert!(!TableStyle::default().resizable);
278    }
279
280    #[test]
281    fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
282        let style = TableStyle::default();
283        assert!((style.row_height - 45.0).abs() < f32::EPSILON);
284        assert!(style.code_row_height < style.row_height);
285    }
286
287    #[test]
288    fn a_compact_table_packs_rows_at_the_dense_step() {
289        // Compact is the reader's denser row, not a description claim. It is
290        // Step::Broad of the base (24pt), audiofiles' historical default.
291        let style = TableStyle::for_compactness(Surface::web(), Compactness::Compact);
292        assert_eq!(style.compactness, Compactness::Compact);
293        assert!((style.row_height - 24.0).abs() < f32::EPSILON);
294    }
295
296    #[test]
297    fn a_body_claims_nothing_until_it_is_asked_to() {
298        // The default is a table of no rows, no selection and no scroll
299        // request. All three absences are the honest reading of an app that has
300        // not said otherwise, which is why they are `Option` and not a
301        // predicate that always answers false.
302        let body = Body::default();
303        assert_eq!(body.rows, 0);
304        assert!(body.selected.is_none());
305        assert!(body.scroll_to.is_none());
306    }
307
308    #[test]
309    fn a_selection_is_asked_per_row_and_not_collected() {
310        // A predicate, so an app whose selection is a range or a single index
311        // does not build a set to be asked. Exercised the way the table asks it:
312        // once per row index, in order.
313        let selected = |index: usize| index.is_multiple_of(2);
314        let body = Body {
315            rows: 4,
316            selected: Some(&selected),
317            scroll_to: None,
318        };
319        let f = body.selected.expect("a predicate was supplied");
320        assert_eq!(
321            (0..body.rows).map(f).collect::<Vec<_>>(),
322            vec![true, false, true, false]
323        );
324    }
325}