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_layout::{CellPart, Sort};
27
28/// The lengths the description deferred, in points: the track for a
29/// [`Width::Fixed`](makeover_layout::Width::Fixed) column, the floor for a [`Width::Fill`](makeover_layout::Width::Fill) one, and the
30/// narrowing budget for a [`Width::Content`](makeover_layout::Width::Content) one. The suite's one sizing type,
31/// held here over points as the terminal holds it over cells.
32pub type Sizing<'a> = makeover_layout::Sizing<'a, f32>;
33
34/// The tones and metrics a table draws with.
35///
36/// Metrics only, and the tones come from [`Palette`]. That is the division this
37/// crate already draws: [`FieldStyle`](crate::FieldStyle) carries gaps and a
38/// marker while the colours stay in the palette, and a table's colours are the
39/// palette's `content`, `content_muted` and `action` rather than six new ones.
40/// `makeover-tui` splits it the other way round because its palette carries no
41/// text tones at all.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub struct TableStyle {
44 /// The height of the heading row.
45 pub header_height: f32,
46 /// The height of a body row: the model's 45, `--row-block` at
47 /// `makeover-geometry`'s base.
48 pub row_height: f32,
49 /// The height of a row in a table holding code, which is one line of
50 /// source rather than a record.
51 pub code_row_height: f32,
52 /// The ground between the table's frame and the cells at either end of a
53 /// row: the webview's `gap-group`, which pads both ends of a row.
54 pub edge_padding: f32,
55 /// The caret drawn after the heading of an ascending column.
56 ///
57 /// Defaults to [`Sort::glyph`], which is where the spelling lives now:
58 /// three renderers holding the same literal agreed by coincidence. Bare,
59 /// with no leading space: the gap is the heading's, written once for all
60 /// three states rather than baked into two strings and forgotten in the
61 /// third.
62 pub ascending: &'static str,
63 /// Drawn after the heading of a descending column.
64 pub descending: &'static str,
65 /// Whether the user can drag the divider between two columns.
66 ///
67 /// The one knob that is not a metric. Not every setting egui_extras has
68 /// becomes a field here: a sticky heading is what `TableBuilder::header`
69 /// does and there is no version that does not, and the table model draws no
70 /// stripe at any host with a hairline, so a knob for either would offer a
71 /// choice this renderer cannot make. Off by default: the description has no word for
72 /// resizing, so a default that turned it on would be this renderer adding a
73 /// claim the other two cannot make.
74 ///
75 /// It does not fight the narrowing. A drag moves a track for the frames it
76 /// is held; the narrowing still decides which columns exist, off each
77 /// column's declared floor, so a resize can never drop a
78 /// column.
79 pub resizable: bool,
80}
81
82impl Default for TableStyle {
83 fn default() -> Self {
84 Self {
85 header_height: 32.0,
86 row_height: 45.0,
87 code_row_height: 20.0,
88 edge_padding: 12.0,
89 ascending: Sort::Ascending.glyph(),
90 descending: Sort::Descending.glyph(),
91 resizable: false,
92 }
93 }
94}
95
96/// The body's own facts for this frame: how many rows, which are selected, and
97/// which one to bring into view.
98///
99/// Held apart from [`TableStyle`] because none of it is style and none of it
100/// survives the frame: a row count changes when a folder does, a selection when
101/// the user clicks, and a scroll request exists for exactly one frame. Held
102/// apart from the columns because none of it is description either.
103/// The description says what a table *is*, and this says what it holds right
104/// now.
105///
106/// Both of the optional fields are here rather than left to the app because
107/// egui_extras answers them on a handle the app never sees: `set_selected` is a
108/// method on the row, and `scroll_to_row` a method on the builder, and the
109/// table owns both. That is the same reason [`cell`] exists.
110#[derive(Default)]
111pub struct Body<'a> {
112 /// How many rows to draw.
113 pub rows: usize,
114 /// Whether a row is selected, by index.
115 ///
116 /// A predicate rather than a set, so an app whose selection is a range, a
117 /// bitmap or a single index does not have to build a collection to be asked.
118 /// `None` is a table no row of which is selected, which is not the same
119 /// claim as a predicate that always answers false and costs nothing to make.
120 pub selected: Option<&'a dyn Fn(usize) -> bool>,
121 /// A row to bring into view this frame.
122 ///
123 /// Set it from a request the app then clears, the way a keyboard cursor
124 /// moving off-screen raises one: held rather than taken, it would fight
125 /// every scroll the user makes with the mouse.
126 pub scroll_to: Option<usize>,
127}
128
129impl std::fmt::Debug for Body<'_> {
130 // Hand-written because `selected` is a closure and `#[derive(Debug)]` will
131 // not have it. What is worth printing is whether one was supplied.
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.debug_struct("Body")
134 .field("rows", &self.rows)
135 .field("selected", &self.selected.is_some())
136 .field("scroll_to", &self.scroll_to)
137 .finish()
138 }
139}
140
141/// The colour a cell of this part takes.
142///
143/// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
144/// `content`: a part this renderer has not learned draws as text, which is a
145/// cell rendering plainly rather than a build that stops. Grep this when
146/// adopting a new `makeover-layout`.
147#[must_use]
148pub const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
149 match part {
150 // A token paints its own background and carries its own tone. What is
151 // set here is what shows between them, not what paints them.
152 Some(CellPart::Tokens) => palette.content_muted,
153 // The drift `CellPart` exists to end: a control in a cell inheriting the
154 // cell's text colour. Both of these take the action intent instead.
155 Some(CellPart::Actions | CellPart::Link) => palette.action,
156 _ => palette.content,
157 }
158}
159
160/// Draw a cell's contents with the tone its part takes.
161///
162/// The app calls this inside its own cell closure, wrapping whatever it draws.
163/// A scoping function rather than a parameter on the table, for the reason
164/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
165/// does not exist until the closure runs, and immediate mode has no cascade to
166/// carry the answer down on its own. This is the cascade, for one scope.
167///
168/// ```no_run
169/// # use makeover_layout::CellPart;
170/// # let palette: makeover_immediate::Palette = unimplemented!();
171/// # let ui: &mut egui::Ui = unimplemented!();
172/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
173/// ui.label("opens the item");
174/// });
175/// ```
176pub fn cell<R>(
177 ui: &mut Ui,
178 part: Option<CellPart>,
179 palette: &Palette,
180 add_contents: impl FnOnce(&mut Ui) -> R,
181) -> R {
182 let restore = ui.visuals().override_text_color;
183 ui.visuals_mut().override_text_color = Some(part_color(part, palette));
184 let out = add_contents(ui);
185 ui.visuals_mut().override_text_color = restore;
186 out
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use egui::Color32;
193
194 fn palette() -> Palette {
195 Palette {
196 page: Color32::from_rgb(1, 1, 1),
197 raised: Color32::from_rgb(2, 2, 2),
198 overlay: Color32::from_rgb(3, 3, 3),
199 well: Color32::from_rgb(4, 4, 4),
200 sunken: Color32::from_rgb(5, 5, 5),
201 bevel_light: Color32::WHITE,
202 bevel_dark: Color32::BLACK,
203 elevation: Color32::from_black_alpha(46),
204 content: Color32::from_rgb(6, 6, 6),
205 content_secondary: Color32::from_rgb(56, 56, 56),
206 content_muted: Color32::from_rgb(7, 7, 7),
207 action: Color32::from_rgb(8, 8, 8),
208 content_on_action: Color32::from_rgb(250, 250, 250),
209 danger: Color32::from_rgb(9, 9, 9),
210 success: Color32::from_rgb(10, 10, 10),
211 warning: Color32::from_rgb(11, 11, 11),
212 info: Color32::from_rgb(12, 12, 12),
213 border: Color32::from_rgb(200, 200, 200),
214 info_surface: Color32::from_rgb(201, 201, 201),
215 success_surface: Color32::from_rgb(202, 202, 202),
216 warning_surface: Color32::from_rgb(203, 203, 203),
217 danger_surface: Color32::from_rgb(204, 204, 204),
218 row_hover: Color32::from_rgb(206, 206, 206),
219 row_rule: Color32::from_rgb(207, 207, 207),
220 row_selected: Color32::from_rgb(208, 208, 208),
221 }
222 }
223
224 #[test]
225 fn the_parts_a_cell_can_be_are_coloured_apart() {
226 // The drift `CellPart` exists to end: one colour for a whole cell paints
227 // a control as though it were text.
228 let p = palette();
229 assert_eq!(part_color(Some(CellPart::Value), &p), p.content);
230 assert_eq!(part_color(Some(CellPart::Tokens), &p), p.content_muted);
231 assert_eq!(part_color(Some(CellPart::Actions), &p), p.action);
232 assert_eq!(part_color(Some(CellPart::Link), &p), p.action);
233 assert_ne!(part_color(Some(CellPart::Link), &p), p.content);
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_body_claims_nothing_until_it_is_asked_to() {
269 // The default is a table of no rows, no selection and no scroll
270 // request. All three absences are the honest reading of an app that has
271 // not said otherwise, which is why they are `Option` and not a
272 // predicate that always answers false.
273 let body = Body::default();
274 assert_eq!(body.rows, 0);
275 assert!(body.selected.is_none());
276 assert!(body.scroll_to.is_none());
277 }
278
279 #[test]
280 fn a_selection_is_asked_per_row_and_not_collected() {
281 // A predicate, so an app whose selection is a range or a single index
282 // does not build a set to be asked. Exercised the way the table asks it:
283 // once per row index, in order.
284 let selected = |index: usize| index.is_multiple_of(2);
285 let body = Body {
286 rows: 4,
287 selected: Some(&selected),
288 scroll_to: None,
289 };
290 let f = body.selected.expect("a predicate was supplied");
291 assert_eq!(
292 (0..body.rows).map(f).collect::<Vec<_>>(),
293 vec![true, false, true, false]
294 );
295 }
296}