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 _ => palette.content,
176 }
177}
178
179/// Draw a cell's contents with the tone its part takes.
180///
181/// The app calls this inside its own cell closure, wrapping whatever it draws.
182/// A scoping function rather than a parameter on the table, for the reason
183/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
184/// does not exist until the closure runs, and immediate mode has no cascade to
185/// carry the answer down on its own. This is the cascade, for one scope.
186///
187/// ```no_run
188/// # use makeover_layout::CellPart;
189/// # let palette: makeover_immediate::Palette = unimplemented!();
190/// # let ui: &mut egui::Ui = unimplemented!();
191/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
192/// ui.label("opens the item");
193/// });
194/// ```
195pub fn cell<R>(
196 ui: &mut Ui,
197 part: Option<CellPart>,
198 palette: &Palette,
199 add_contents: impl FnOnce(&mut Ui) -> R,
200) -> R {
201 let restore = ui.visuals().override_text_color;
202 ui.visuals_mut().override_text_color = Some(part_color(part, palette));
203 let out = add_contents(ui);
204 ui.visuals_mut().override_text_color = restore;
205 out
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use crate::tests::palette;
212
213 #[test]
214 fn a_cell_part_takes_the_colour_its_intent_names() {
215 // makeover-layout's `CellPart::intent` is the rule every host reads, so
216 // a link here draws as the webview's does, in the values' ink.
217 let p = palette();
218 for part in [
219 CellPart::Value,
220 CellPart::Tokens,
221 CellPart::Actions,
222 CellPart::Link,
223 ] {
224 let want = match part.intent() {
225 "content" => p.content,
226 "content-secondary" => p.content_secondary,
227 "content-muted" => p.content_muted,
228 other => panic!("{part:?} names {other}, which this renderer has not learned"),
229 };
230 assert_eq!(part_color(Some(part), &p), want, "{part:?}");
231 }
232 // A cell mixing parts says nothing, and takes the text colour.
233 assert_eq!(part_color(None, &p), p.content);
234 }
235
236 #[test]
237 fn the_carets_match_the_terminal_renderers() {
238 // Two crates, one glyph pair, and no dependency between them to enforce
239 // it. A description sorted ascending must not point up in a window and
240 // down in a terminal.
241 // Composition rather than agreement: both read `Sort::glyph`, so a
242 // fourth spelling cannot appear in one crate.
243 let style = TableStyle::default();
244 assert_eq!(style.ascending, Sort::Ascending.glyph());
245 assert_eq!(style.descending, Sort::Descending.glyph());
246 // Bare. The gap is the heading's, so a consumer swapping the glyph for an
247 // ASCII one does not have to remember to bring a space with it.
248 assert_eq!(style.ascending.trim(), style.ascending);
249 }
250
251 #[test]
252 fn resizing_is_off_because_the_description_has_no_word_for_it() {
253 // egui_extras offers it and the other two renderers cannot say it. A
254 // default that turned it on would be this renderer adding a claim.
255 assert!(!TableStyle::default().resizable);
256 }
257
258 #[test]
259 fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
260 let style = TableStyle::default();
261 assert!((style.row_height - 45.0).abs() < f32::EPSILON);
262 assert!(style.code_row_height < style.row_height);
263 }
264
265 #[test]
266 fn a_compact_table_packs_rows_at_the_dense_step() {
267 // Compact is the reader's denser row, not a description claim. It is
268 // Step::Broad of the base (24pt), audiofiles' historical default.
269 let style = TableStyle::for_compactness(Surface::web(), Compactness::Compact);
270 assert_eq!(style.compactness, Compactness::Compact);
271 assert!((style.row_height - 24.0).abs() < f32::EPSILON);
272 }
273
274 #[test]
275 fn a_body_claims_nothing_until_it_is_asked_to() {
276 // The default is a table of no rows, no selection and no scroll
277 // request. All three absences are the honest reading of an app that has
278 // not said otherwise, which is why they are `Option` and not a
279 // predicate that always answers false.
280 let body = Body::default();
281 assert_eq!(body.rows, 0);
282 assert!(body.selected.is_none());
283 assert!(body.scroll_to.is_none());
284 }
285
286 #[test]
287 fn a_selection_is_asked_per_row_and_not_collected() {
288 // A predicate, so an app whose selection is a range or a single index
289 // does not build a set to be asked. Exercised the way the table asks it:
290 // once per row index, in order.
291 let selected = |index: usize| index.is_multiple_of(2);
292 let body = Body {
293 rows: 4,
294 selected: Some(&selected),
295 scroll_to: None,
296 };
297 let f = body.selected.expect("a predicate was supplied");
298 assert_eq!(
299 (0..body.rows).map(f).collect::<Vec<_>>(),
300 vec![true, false, true, false]
301 );
302 }
303}