makeover-webview 0.9.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Column layout and row structure for lists and tables.
//!
//! The other half of phase B. [`form`](crate::form) renders a field; this
//! renders the frame a list of rows sits in: which columns exist, how wide they
//! are, which ones survive a narrow viewport, and the cell containers a row is
//! made of.
//!
//! # What this does not do
//!
//! It does not render a cell's contents. That is the crate's own limit, stated
//! in `makeover_layout`'s "Where the description stops": generate the boring
//! 80% so the bespoke 20% gets the attention. A goingson task row carries
//! delegated action hooks with argument substitution, four nested sub-renderers,
//! conditional state classes and aria labels built from data. A description
//! expressive enough to emit that is a templating language wearing a
//! description's name.
//!
//! So the split is the one [`Markup`] already draws for forms: this owns the
//! structure and the app owns what goes in it. What that removes from an app is
//! not small — cell order, cell classes, the grid tracks, and above all the
//! narrowing rules, which is where addressing columns by position goes wrong.
//!
//! # Why positions are the bug
//!
//! goingson hides its mobile columns with `nth-child(n+5)` against a
//! seven-column table, plus a separate `nth-child(3)`, plus two class-based
//! rules — the same fact said three ways, two of them positional. Insert a
//! column anywhere left of the cut and the wrong one disappears, silently,
//! because nothing in the stylesheet knows what column five *is*.
//! [`Priority`] is the fix: a renderer narrows by raising a cutoff, and never
//! by counting.

use crate::form::Markup;
use crate::{Emit, class};
use makeover_layout::{Column, Priority, RowPart, Width};
use std::fmt::Write as _;

/// The lengths the description deferred.
///
/// [`Width`] says `Content`, `Fixed` or `Fill` and deliberately carries no
/// magnitude, because a magnitude is a CSS answer and the description is read
/// by renderers that have no pixels. So the numbers arrive here instead, the
/// way a field's value arrives in [`Filling`](crate::form::Filling) rather than
/// in `Field`.
///
/// Looked up by column name, because an app's columns are not all one size:
/// goingson's task table has six distinct fixed widths.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sizing<'a> {
    /// `(column name, CSS length)`. The length is the track for a
    /// [`Width::Fixed`] column and the floor for a [`Width::Fill`] one.
    pub lengths: &'a [(&'a str, &'a str)],
    /// Used for a column with no entry above. Empty means `auto`.
    pub fallback: &'a str,
}

impl Sizing<'_> {
    /// The length for a named column.
    fn length_for(&self, name: &str) -> &str {
        self.lengths
            .iter()
            .find(|(column, _)| *column == name)
            .map_or_else(
                || {
                    if self.fallback.is_empty() {
                        "auto"
                    } else {
                        self.fallback
                    }
                },
                |(_, length)| *length,
            )
    }

    /// The grid track for one column.
    fn track(&self, column: &Column<'_>) -> String {
        match column.width {
            Width::Content => "max-content".to_owned(),
            Width::Fixed => self.length_for(column.name).to_owned(),
            Width::Fill => format!("minmax({}, 1fr)", self.length_for(column.name)),
            // A width added to the description since this renderer was built.
            // `auto` is the track that makes no claim, which is the honest
            // answer to a claim this renderer cannot read.
            _ => "auto".to_owned(),
        }
    }
}

/// The class a cell of this column carries.
///
/// Derived from the column's own name, which is what makes the narrowing rules
/// addressable. `data-column` would do as well; a class is what both webview
/// apps already key their cell styling on.
#[must_use]
pub fn column_class(column: &Column<'_>, opts: &Emit) -> String {
    class(&format!("col-{}", column.name), opts)
}

/// The `grid-template-columns` value for the columns kept at `cutoff`.
///
/// Emitting only the surviving tracks is what keeps the track list and the
/// hiding in agreement. An app that hides a cell with `display: none` but
/// leaves its track in place gets a column of empty space, which is the other
/// half of goingson's mobile bug: its narrow rule drops to four tracks by hand
/// and has to be edited in step with the `nth-child` cut.
#[must_use]
pub fn grid_template_columns(
    columns: &[Column<'_>],
    sizing: &Sizing<'_>,
    cutoff: Priority,
) -> String {
    columns
        .iter()
        .filter(|column| column.kept_at(cutoff))
        .map(|column| sizing.track(column))
        .collect::<Vec<_>>()
        .join(" ")
}

/// The rules that narrow `selector` to the columns kept at `cutoff`.
///
/// Both halves together: the shortened track list, and `display: none` on each
/// dropped column *by its own class*. Nothing counts positions, so inserting a
/// column changes what is emitted rather than changing which column vanishes.
///
/// `selector` may be a selector list. A descendant is appended to each part
/// rather than to the whole, because appending to the whole changes what the
/// earlier parts match: `.head, .row > .col-x` reads as "`.head`, or a `.col-x`
/// inside `.row`", so `.head` itself would be hidden.
#[must_use]
pub fn narrowing_css(
    columns: &[Column<'_>],
    selector: &str,
    sizing: &Sizing<'_>,
    cutoff: Priority,
    opts: &Emit,
) -> String {
    let parts: Vec<&str> = selector.split(',').map(str::trim).collect();

    let mut css = format!(
        "{} {{\n    grid-template-columns: {};\n}}\n",
        parts.join(", "),
        grid_template_columns(columns, sizing, cutoff)
    );

    for column in columns.iter().filter(|c| !c.kept_at(cutoff)) {
        let class = column_class(column, opts);
        let targets: Vec<String> = parts
            .iter()
            .map(|part| format!("{part} > .{class}"))
            .collect();
        let _ = write!(
            css,
            "{} {{\n    display: none;\n}}\n",
            targets.join(",\n")
        );
    }
    css
}

/// One cell of a row.
///
/// The contents are [`Markup`] rather than text, and that is the whole shape of
/// this module: a cell holds whatever the app builds, and the app says so by
/// naming it. Escaping a cell here would be wrong as well as impossible — a
/// task row's description cell is five nested spans and a badge.
#[derive(Debug, Clone, Copy)]
pub struct Cell<'a> {
    /// Which column this fills, by name.
    pub column: &'a str,
    /// What kind of text it is, when it is text.
    ///
    /// Carries the row-part class the stylesheet half already emits, so a
    /// secondary cell says it is secondary in the description's own words
    /// rather than in the app's.
    pub part: Option<RowPart>,
    /// The contents. Trusted app markup.
    pub content: Markup<'a>,
}

impl<'a> Cell<'a> {
    /// A cell with no row part.
    #[must_use]
    pub const fn new(column: &'a str, content: Markup<'a>) -> Self {
        Self {
            column,
            part: None,
            content,
        }
    }
}

/// The class for a row part.
///
/// Exhaustive, unlike the matches on [`Width`] and [`Priority`] above:
/// `RowPart` is the one vocabulary in this module that is still a closed enum.
/// If it ever gains a member this stops compiling, which is the same lockstep
/// break `non_exhaustive` was added elsewhere to end.
fn part_class(part: RowPart) -> &'static str {
    match part {
        RowPart::Primary => "row-primary",
        RowPart::Secondary => "row-secondary",
        RowPart::Meta => "row-meta",
        RowPart::Actions => "row-actions",
    }
}

/// A row's cells, in column order.
///
/// Ordered by the columns and not by the cells, so a row cannot silently
/// disagree with its table about what comes where. A column with no cell gets
/// an empty container, which keeps the grid aligned; a cell naming no column is
/// dropped, because there is nowhere to put it.
///
/// Emits the cells alone, not the row element. The row carries the app's
/// identity and hooks — `data-id`, a context-menu binding, a tabindex, its
/// state classes — and none of that is describable here.
///
/// # Not for a webview's scroll path
///
/// This has no consumer in either webview app, deliberately, and wiring one in
/// would be a mistake worth naming. goingson renders rows through a virtual
/// scroller whose `_render` calls its row builder **synchronously** while
/// scrolling; the code's own comment says scroll events fire at 60Hz+ and that
/// this is the hot path. Reaching Rust from there means an IPC round trip and
/// an `await` in that loop, per visible range, during a drag.
///
/// So this is for the hosts where rendering already happens in Rust: an axum
/// route, and the router when it lands. There the objection does not apply,
/// because nothing crosses a process boundary to reach it. A webview app should
/// take [`narrowing_css`] and [`column_class`] and keep building its own rows.
#[must_use]
pub fn cells_html(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit) -> String {
    let cell_class = class("cell", opts);
    let mut html = String::new();

    for column in columns {
        let found = cells.iter().find(|cell| cell.column == column.name);
        let mut classes = format!("{cell_class} {}", column_class(column, opts));
        if let Some(part) = found.and_then(|cell| cell.part) {
            let _ = write!(classes, " {}", class(part_class(part), opts));
        }
        let _ = write!(
            html,
            "<div class=\"{classes}\">{}</div>",
            found.map_or("", |cell| cell.content.0)
        );
    }
    html
}

#[cfg(test)]
mod tests {
    use super::*;

    fn columns() -> Vec<Column<'static>> {
        vec![
            Column {
                name: "description",
                width: Width::Fill,
                priority: Priority::Essential,
            },
            Column {
                name: "due",
                width: Width::Fixed,
                priority: Priority::Secondary,
            },
            Column {
                name: "progress",
                width: Width::Fixed,
                priority: Priority::Optional,
            },
        ]
    }

    fn sizing() -> Sizing<'static> {
        Sizing {
            lengths: &[
                ("description", "200px"),
                ("due", "110px"),
                ("progress", "100px"),
            ],
            fallback: "",
        }
    }

    #[test]
    fn a_fill_column_gets_a_floor_and_the_slack() {
        let tracks = grid_template_columns(&columns(), &sizing(), Priority::Optional);
        assert_eq!(tracks, "minmax(200px, 1fr) 110px 100px");
    }

    #[test]
    fn a_column_with_no_length_makes_no_claim() {
        let sizing = Sizing::default();
        let tracks = grid_template_columns(&columns(), &sizing, Priority::Optional);
        assert_eq!(tracks, "minmax(auto, 1fr) auto auto");
    }

    /// The point of the module. Raising the cutoff drops columns by what they
    /// are worth, and the track list shortens to match, so the two cannot
    /// disagree the way a hand-written `nth-child` cut and a hand-written
    /// track list can.
    #[test]
    fn raising_the_cutoff_drops_columns_and_their_tracks_together() {
        let columns = columns();

        let wide = grid_template_columns(&columns, &sizing(), Priority::Optional);
        assert_eq!(wide.split(' ').count(), 4); // minmax(200px, + 1fr) + 2

        let narrow = grid_template_columns(&columns, &sizing(), Priority::Secondary);
        assert_eq!(narrow, "minmax(200px, 1fr) 110px");

        let narrowest = grid_template_columns(&columns, &sizing(), Priority::Essential);
        assert_eq!(narrowest, "minmax(200px, 1fr)");
    }

    #[test]
    fn narrowing_hides_a_dropped_column_by_its_own_class_not_its_position() {
        let css = narrowing_css(
            &columns(),
            ".ui-mode-mobile .task-row",
            &sizing(),
            Priority::Secondary,
            &Emit::default(),
        );
        assert!(
            css.contains("grid-template-columns: minmax(200px, 1fr) 110px;"),
            "{css}"
        );
        assert!(
            css.contains(".ui-mode-mobile .task-row > .col-progress {"),
            "{css}"
        );
        assert!(!css.contains("nth-child"), "{css}");
        // The kept columns are not mentioned as hidden.
        assert!(!css.contains(".col-due {\n    display: none"), "{css}");
    }

    /// A selector list has to distribute, or the earlier parts of it get the
    /// child combinator appended to the whole and start matching things they
    /// never named. This hid an entire table header the first time it ran.
    #[test]
    fn a_selector_list_distributes_the_hidden_column() {
        let css = narrowing_css(
            &columns(),
            ".task-header-row, .task-row",
            &sizing(),
            Priority::Secondary,
            &Emit::default(),
        );
        assert!(css.contains(".task-header-row > .col-progress,\n.task-row > .col-progress {"), "{css}");
        // The bare header selector must never appear as a hiding target.
        assert!(!css.contains(".task-header-row {\n    display: none"), "{css}");
        assert!(css.contains(".task-header-row, .task-row {\n    grid-template-columns:"), "{css}");
    }

    #[test]
    fn cells_follow_the_columns_and_carry_their_column_class() {
        let cells = [
            Cell {
                column: "due",
                part: Some(RowPart::Meta),
                content: Markup("tomorrow"),
            },
            Cell::new("description", Markup("<span>Ship it</span>")),
        ];
        let html = cells_html(&columns(), &cells, &Emit::default());

        // Column order, not cell order: description was passed second.
        let description = html.find("Ship it").expect("description cell");
        let due = html.find("tomorrow").expect("due cell");
        assert!(description < due, "{html}");

        assert!(
            html.contains(r#"<div class="cell col-description">"#),
            "{html}"
        );
        assert!(
            html.contains(r#"<div class="cell col-due row-meta">"#),
            "{html}"
        );
        // progress had no cell, so it is present and empty rather than absent,
        // or the grid would shift left by one.
        assert!(
            html.contains(r#"<div class="cell col-progress"></div>"#),
            "{html}"
        );
    }

    #[test]
    fn a_cell_naming_no_column_is_dropped() {
        let cells = [Cell::new("nonexistent", Markup("nowhere"))];
        let html = cells_html(&columns(), &cells, &Emit::default());
        assert!(!html.contains("nowhere"), "{html}");
    }

    #[test]
    fn the_class_prefix_reaches_the_cells_and_the_narrowing() {
        let opts = Emit {
            class_prefix: "mk-",
            ..Emit::default()
        };
        let cells = [Cell::new("due", Markup("x"))];
        assert!(
            cells_html(&columns(), &cells, &opts).contains("mk-cell mk-col-due"),
            "prefix missing"
        );
        assert!(
            narrowing_css(&columns(), ".t", &sizing(), Priority::Secondary, &opts)
                .contains(".mk-col-progress"),
            "prefix missing"
        );
    }
}