Skip to main content

makeover_webview/
list.rs

1//! Column layout and row structure for lists and tables.
2//!
3//! The other half of phase B. [`form`](crate::form) renders a field; this
4//! renders the frame a list of rows sits in: which columns exist, how wide they
5//! are, which ones survive a narrow viewport, and the cell containers a row is
6//! made of.
7//!
8//! # What this does not do
9//!
10//! It does not render a cell's contents. That is the crate's own limit, stated
11//! in `makeover_layout`'s "Where the description stops": generate the boring
12//! 80% so the bespoke 20% gets the attention. A goingson task row carries
13//! delegated action hooks with argument substitution, four nested sub-renderers,
14//! conditional state classes and aria labels built from data. A description
15//! expressive enough to emit that is a templating language wearing a
16//! description's name.
17//!
18//! So the split is the one [`Markup`] already draws for forms: this owns the
19//! structure and the app owns what goes in it. What that removes from an app is
20//! not small — cell order, cell classes, the grid tracks, and above all the
21//! narrowing rules, which is where addressing columns by position goes wrong.
22//!
23//! # Why positions are the bug
24//!
25//! goingson hides its mobile columns with `nth-child(n+5)` against a
26//! seven-column table, plus a separate `nth-child(3)`, plus two class-based
27//! rules — the same fact said three ways, two of them positional. Insert a
28//! column anywhere left of the cut and the wrong one disappears, silently,
29//! because nothing in the stylesheet knows what column five *is*.
30//! [`Priority`] is the fix: a renderer narrows by raising a cutoff, and never
31//! by counting.
32
33use crate::form::Markup;
34use crate::{Emit, class};
35use makeover_layout::{Column, Priority, RowPart, Width};
36use std::fmt::Write as _;
37
38/// The lengths the description deferred.
39///
40/// [`Width`] says `Content`, `Fixed` or `Fill` and deliberately carries no
41/// magnitude, because a magnitude is a CSS answer and the description is read
42/// by renderers that have no pixels. So the numbers arrive here instead, the
43/// way a field's value arrives in [`Filling`](crate::form::Filling) rather than
44/// in `Field`.
45///
46/// Looked up by column name, because an app's columns are not all one size:
47/// goingson's task table has six distinct fixed widths.
48#[derive(Debug, Clone, Copy, Default)]
49pub struct Sizing<'a> {
50    /// `(column name, CSS length)`. The length is the track for a
51    /// [`Width::Fixed`] column and the floor for a [`Width::Fill`] one.
52    pub lengths: &'a [(&'a str, &'a str)],
53    /// Used for a column with no entry above. Empty means `auto`.
54    pub fallback: &'a str,
55}
56
57impl Sizing<'_> {
58    /// The length for a named column.
59    fn length_for(&self, name: &str) -> &str {
60        self.lengths
61            .iter()
62            .find(|(column, _)| *column == name)
63            .map_or_else(
64                || {
65                    if self.fallback.is_empty() {
66                        "auto"
67                    } else {
68                        self.fallback
69                    }
70                },
71                |(_, length)| *length,
72            )
73    }
74
75    /// The grid track for one column.
76    fn track(&self, column: &Column<'_>) -> String {
77        match column.width {
78            Width::Content => "max-content".to_owned(),
79            Width::Fixed => self.length_for(column.name).to_owned(),
80            Width::Fill => format!("minmax({}, 1fr)", self.length_for(column.name)),
81            // A width added to the description since this renderer was built.
82            // `auto` is the track that makes no claim, which is the honest
83            // answer to a claim this renderer cannot read.
84            _ => "auto".to_owned(),
85        }
86    }
87}
88
89/// The class a cell of this column carries.
90///
91/// Derived from the column's own name, which is what makes the narrowing rules
92/// addressable. `data-column` would do as well; a class is what both webview
93/// apps already key their cell styling on.
94#[must_use]
95pub fn column_class(column: &Column<'_>, opts: &Emit) -> String {
96    class(&format!("col-{}", column.name), opts)
97}
98
99/// The `grid-template-columns` value for the columns kept at `cutoff`.
100///
101/// Emitting only the surviving tracks is what keeps the track list and the
102/// hiding in agreement. An app that hides a cell with `display: none` but
103/// leaves its track in place gets a column of empty space, which is the other
104/// half of goingson's mobile bug: its narrow rule drops to four tracks by hand
105/// and has to be edited in step with the `nth-child` cut.
106#[must_use]
107pub fn grid_template_columns(
108    columns: &[Column<'_>],
109    sizing: &Sizing<'_>,
110    cutoff: Priority,
111) -> String {
112    columns
113        .iter()
114        .filter(|column| column.kept_at(cutoff))
115        .map(|column| sizing.track(column))
116        .collect::<Vec<_>>()
117        .join(" ")
118}
119
120/// The rules that narrow `selector` to the columns kept at `cutoff`.
121///
122/// Both halves together: the shortened track list, and `display: none` on each
123/// dropped column *by its own class*. Nothing counts positions, so inserting a
124/// column changes what is emitted rather than changing which column vanishes.
125///
126/// `selector` may be a selector list. A descendant is appended to each part
127/// rather than to the whole, because appending to the whole changes what the
128/// earlier parts match: `.head, .row > .col-x` reads as "`.head`, or a `.col-x`
129/// inside `.row`", so `.head` itself would be hidden.
130#[must_use]
131pub fn narrowing_css(
132    columns: &[Column<'_>],
133    selector: &str,
134    sizing: &Sizing<'_>,
135    cutoff: Priority,
136    opts: &Emit,
137) -> String {
138    let parts: Vec<&str> = selector.split(',').map(str::trim).collect();
139
140    let mut css = format!(
141        "{} {{\n    grid-template-columns: {};\n}}\n",
142        parts.join(", "),
143        grid_template_columns(columns, sizing, cutoff)
144    );
145
146    for column in columns.iter().filter(|c| !c.kept_at(cutoff)) {
147        let class = column_class(column, opts);
148        let targets: Vec<String> = parts
149            .iter()
150            .map(|part| format!("{part} > .{class}"))
151            .collect();
152        let _ = write!(css, "{} {{\n    display: none;\n}}\n", targets.join(",\n"));
153    }
154    css
155}
156
157/// One cell of a row.
158///
159/// The contents are [`Markup`] rather than text, and that is the whole shape of
160/// this module: a cell holds whatever the app builds, and the app says so by
161/// naming it. Escaping a cell here would be wrong as well as impossible — a
162/// task row's description cell is five nested spans and a badge.
163#[derive(Debug, Clone, Copy)]
164pub struct Cell<'a> {
165    /// Which column this fills, by name.
166    pub column: &'a str,
167    /// What kind of text it is, when it is text.
168    ///
169    /// Carries the row-part class the stylesheet half already emits, so a
170    /// secondary cell says it is secondary in the description's own words
171    /// rather than in the app's.
172    pub part: Option<RowPart>,
173    /// The contents. Trusted app markup.
174    pub content: Markup<'a>,
175}
176
177impl<'a> Cell<'a> {
178    /// A cell with no row part.
179    #[must_use]
180    pub const fn new(column: &'a str, content: Markup<'a>) -> Self {
181        Self {
182            column,
183            part: None,
184            content,
185        }
186    }
187}
188
189/// The class for a row part.
190///
191/// This comment used to say `RowPart` was the one closed enum left here, and
192/// that gaining a member would stop this compiling — "the same lockstep break
193/// `non_exhaustive` was added elsewhere to end". makeover-layout 0.9.0 ended
194/// it: the enum gained [`RowPart::Tokens`] and `#[non_exhaustive]` in the same
195/// release, so the prediction was paid off rather than waited for.
196///
197/// The fallback is what that costs. A member added upstream lands here as a
198/// bare `row-part` with no rule of its own, which is a thing rendering plainly
199/// rather than a build that stops. Grep this function when adopting a new
200/// makeover-layout.
201pub(crate) fn part_class(part: RowPart) -> &'static str {
202    match part {
203        RowPart::Primary => "row-primary",
204        RowPart::Secondary => "row-secondary",
205        RowPart::Meta => "row-meta",
206        RowPart::Actions => "row-actions",
207        RowPart::Tokens => "row-tokens",
208        RowPart::Proportion => "row-proportion",
209        _ => "row-part",
210    }
211}
212
213/// A row's cells, in column order.
214///
215/// Ordered by the columns and not by the cells, so a row cannot silently
216/// disagree with its table about what comes where. A column with no cell gets
217/// an empty container, which keeps the grid aligned; a cell naming no column is
218/// dropped, because there is nowhere to put it.
219///
220/// Emits the cells alone, not the row element. The row carries the app's
221/// identity and hooks — `data-id`, a context-menu binding, a tabindex, its
222/// state classes — and none of that is describable here.
223///
224/// # Not for a webview's scroll path
225///
226/// This has no consumer in either webview app, deliberately, and wiring one in
227/// would be a mistake worth naming. goingson renders rows through a virtual
228/// scroller whose `_render` calls its row builder **synchronously** while
229/// scrolling; the code's own comment says scroll events fire at 60Hz+ and that
230/// this is the hot path. Reaching Rust from there means an IPC round trip and
231/// an `await` in that loop, per visible range, during a drag.
232///
233/// So this is for the hosts where rendering already happens in Rust: an axum
234/// route, and the router when it lands. There the objection does not apply,
235/// because nothing crosses a process boundary to reach it. A webview app should
236/// take [`narrowing_css`] and [`column_class`] and keep building its own rows.
237#[must_use]
238pub fn cells_html(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit) -> String {
239    let cell_class = class("cell", opts);
240    let mut html = String::new();
241
242    for column in columns {
243        let found = cells.iter().find(|cell| cell.column == column.name);
244        let mut classes = format!("{cell_class} {}", column_class(column, opts));
245        if let Some(part) = found.and_then(|cell| cell.part) {
246            let _ = write!(classes, " {}", class(part_class(part), opts));
247        }
248        let _ = write!(
249            html,
250            "<div class=\"{classes}\">{}</div>",
251            found.map_or("", |cell| cell.content.0)
252        );
253    }
254    html
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn columns() -> Vec<Column<'static>> {
262        vec![
263            Column {
264                width: Width::Fill,
265                priority: Priority::Essential,
266                ..Column::new("description")
267            },
268            Column {
269                width: Width::Fixed,
270                priority: Priority::Secondary,
271                ..Column::new("due")
272            },
273            Column {
274                width: Width::Fixed,
275                priority: Priority::Optional,
276                ..Column::new("progress")
277            },
278        ]
279    }
280
281    fn sizing() -> Sizing<'static> {
282        Sizing {
283            lengths: &[
284                ("description", "200px"),
285                ("due", "110px"),
286                ("progress", "100px"),
287            ],
288            fallback: "",
289        }
290    }
291
292    #[test]
293    fn a_fill_column_gets_a_floor_and_the_slack() {
294        let tracks = grid_template_columns(&columns(), &sizing(), Priority::Optional);
295        assert_eq!(tracks, "minmax(200px, 1fr) 110px 100px");
296    }
297
298    #[test]
299    fn a_column_with_no_length_makes_no_claim() {
300        let sizing = Sizing::default();
301        let tracks = grid_template_columns(&columns(), &sizing, Priority::Optional);
302        assert_eq!(tracks, "minmax(auto, 1fr) auto auto");
303    }
304
305    /// The point of the module. Raising the cutoff drops columns by what they
306    /// are worth, and the track list shortens to match, so the two cannot
307    /// disagree the way a hand-written `nth-child` cut and a hand-written
308    /// track list can.
309    #[test]
310    fn raising_the_cutoff_drops_columns_and_their_tracks_together() {
311        let columns = columns();
312
313        let wide = grid_template_columns(&columns, &sizing(), Priority::Optional);
314        assert_eq!(wide.split(' ').count(), 4); // minmax(200px, + 1fr) + 2
315
316        let narrow = grid_template_columns(&columns, &sizing(), Priority::Secondary);
317        assert_eq!(narrow, "minmax(200px, 1fr) 110px");
318
319        let narrowest = grid_template_columns(&columns, &sizing(), Priority::Essential);
320        assert_eq!(narrowest, "minmax(200px, 1fr)");
321    }
322
323    #[test]
324    fn narrowing_hides_a_dropped_column_by_its_own_class_not_its_position() {
325        let css = narrowing_css(
326            &columns(),
327            ".ui-mode-mobile .task-row",
328            &sizing(),
329            Priority::Secondary,
330            &Emit::default(),
331        );
332        assert!(
333            css.contains("grid-template-columns: minmax(200px, 1fr) 110px;"),
334            "{css}"
335        );
336        assert!(
337            css.contains(".ui-mode-mobile .task-row > .col-progress {"),
338            "{css}"
339        );
340        assert!(!css.contains("nth-child"), "{css}");
341        // The kept columns are not mentioned as hidden.
342        assert!(!css.contains(".col-due {\n    display: none"), "{css}");
343    }
344
345    /// A selector list has to distribute, or the earlier parts of it get the
346    /// child combinator appended to the whole and start matching things they
347    /// never named. This hid an entire table header the first time it ran.
348    #[test]
349    fn a_selector_list_distributes_the_hidden_column() {
350        let css = narrowing_css(
351            &columns(),
352            ".task-header-row, .task-row",
353            &sizing(),
354            Priority::Secondary,
355            &Emit::default(),
356        );
357        assert!(
358            css.contains(".task-header-row > .col-progress,\n.task-row > .col-progress {"),
359            "{css}"
360        );
361        // The bare header selector must never appear as a hiding target.
362        assert!(
363            !css.contains(".task-header-row {\n    display: none"),
364            "{css}"
365        );
366        assert!(
367            css.contains(".task-header-row, .task-row {\n    grid-template-columns:"),
368            "{css}"
369        );
370    }
371
372    #[test]
373    fn cells_follow_the_columns_and_carry_their_column_class() {
374        let cells = [
375            Cell {
376                column: "due",
377                part: Some(RowPart::Meta),
378                content: Markup("tomorrow"),
379            },
380            Cell::new("description", Markup("<span>Ship it</span>")),
381        ];
382        let html = cells_html(&columns(), &cells, &Emit::default());
383
384        // Column order, not cell order: description was passed second.
385        let description = html.find("Ship it").expect("description cell");
386        let due = html.find("tomorrow").expect("due cell");
387        assert!(description < due, "{html}");
388
389        assert!(
390            html.contains(r#"<div class="cell col-description">"#),
391            "{html}"
392        );
393        assert!(
394            html.contains(r#"<div class="cell col-due row-meta">"#),
395            "{html}"
396        );
397        // progress had no cell, so it is present and empty rather than absent,
398        // or the grid would shift left by one.
399        assert!(
400            html.contains(r#"<div class="cell col-progress"></div>"#),
401            "{html}"
402        );
403    }
404
405    #[test]
406    fn a_cell_naming_no_column_is_dropped() {
407        let cells = [Cell::new("nonexistent", Markup("nowhere"))];
408        let html = cells_html(&columns(), &cells, &Emit::default());
409        assert!(!html.contains("nowhere"), "{html}");
410    }
411
412    #[test]
413    fn the_class_prefix_reaches_the_cells_and_the_narrowing() {
414        let opts = Emit {
415            class_prefix: "mk-",
416            ..Emit::default()
417        };
418        let cells = [Cell::new("due", Markup("x"))];
419        assert!(
420            cells_html(&columns(), &cells, &opts).contains("mk-cell mk-col-due"),
421            "prefix missing"
422        );
423        assert!(
424            narrowing_css(&columns(), ".t", &sizing(), Priority::Secondary, &opts)
425                .contains(".mk-col-progress"),
426            "prefix missing"
427        );
428    }
429}