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, push_class};
35use makeover_layout::{CellPart, Column, Flow, 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///
95/// The name is reduced to identifier characters first. See [`push_column_name`].
96#[must_use]
97pub fn column_class(column: &Column<'_>, opts: &Emit) -> String {
98    let mut out = String::new();
99    push_column_class(&mut out, column, opts);
100    out
101}
102
103/// The class a cell of this column carries, written into a buffer the caller
104/// already has.
105///
106/// [`column_class`]'s streaming form. It is the one that runs per cell per row,
107/// where the allocating form pays twice: once for `col-<name>` and once for the
108/// prefix in front of it.
109pub fn push_column_class(out: &mut String, column: &Column<'_>, opts: &Emit) {
110    out.push_str(opts.class_prefix);
111    out.push_str("col-");
112    push_column_name(out, column.name);
113}
114
115/// A column's name as the identifier half of its class.
116///
117/// # Why this is not escaping
118///
119/// The name is the one app-supplied string this crate puts in a class attribute
120/// rather than in text or an `aria-label`, so it may never go in raw. A column
121/// named `a" onclick="steal()` emitted
122///
123/// ```html
124/// <div class="cell col-a" onclick="steal() cell-fill cell-keeps">
125/// ```
126///
127/// which is a live event handler on every cell of that column. HTML escaping is
128/// the reflex and it is the wrong tool here, because a class is read twice: once
129/// by the HTML parser, which would decode `&quot;` back to a quote, and once by
130/// a CSS selector, which [`narrowing_css`] writes from this same function. An
131/// escaped name is safe in the attribute and unmatchable from the stylesheet,
132/// so the two halves of the narrowing would stop meeting -- silently, the way
133/// every other defect this module's comments record did.
134///
135/// Reducing the name to identifier characters answers both. What comes out is a
136/// valid CSS identifier, so the selector matches, and it holds none of the five
137/// characters an attribute value can be ended with, so there is nothing to
138/// escape.
139///
140/// # What it changes for a name that was already fine
141///
142/// Nothing. Alphanumerics, `_` and `-` pass through, and every column name in
143/// the tree is made of those. A name that is *not* was already broken rather
144/// than merely unsafe: `Due date` emitted `col-Due date`, which the HTML parser
145/// reads as the two classes `col-Due` and `date`, and which `narrowing_css`
146/// wrote as a descendant selector that matched neither. Both now agree on
147/// `col-Due-date`.
148///
149/// Alphanumeric in the Unicode sense, not the ASCII one. CSS identifiers admit
150/// everything from U+00A0 up, so a column named `Größe` keeps its name; folding
151/// it to `Gr--e` would collide with a neighbouring column for nothing.
152pub fn push_column_name(out: &mut String, name: &str) {
153    for ch in name.chars() {
154        // Substituted rather than dropped. Two columns called `a b` and `ab`
155        // are different columns, and dropping would give them one class and one
156        // set of narrowing rules between them.
157        if ch.is_alphanumeric() || ch == '_' || ch == '-' {
158            out.push(ch);
159        } else {
160            out.push('-');
161        }
162    }
163}
164
165/// The class saying how wide a cell of this column asks to be.
166///
167/// A bounded vocabulary, unlike [`column_class`], which is why the stylesheet
168/// can carry the rule. [`Width`] is `#[non_exhaustive]`, and a member added
169/// upstream lands on the fill class: a column that takes the slack is the
170/// behaviour that makes no claim, matching the `auto` track
171/// [`Sizing::track`] falls back to for the same reason.
172fn width_class(width: Width) -> &'static str {
173    match width {
174        Width::Content => "cell-content",
175        Width::Fixed => "cell-fixed",
176        _ => "cell-fill",
177    }
178}
179
180/// The class saying when a cell of this column drops.
181///
182/// [`Priority`] said as a class rather than as a cutoff, so the hiding can live
183/// in the stylesheet instead of being generated per table. That is what a
184/// [`display: table`](crate::table_rules) frame needs and a grid one cannot use:
185/// a grid also has to shorten its track list, which only the columns themselves
186/// can say.
187fn drop_class(priority: Priority) -> &'static str {
188    match priority {
189        Priority::Optional => "cell-drops-first",
190        Priority::Secondary => "cell-drops-next",
191        // A priority added upstream keeps its column. `Priority` is
192        // `#[non_exhaustive]`, and of the two ways to be wrong about one this
193        // renderer has not learned, showing a column that should have dropped
194        // is the one the user can see and work around.
195        _ => "cell-keeps",
196    }
197}
198
199/// Every class a cell of this column carries.
200///
201/// The column's own name, how wide it asks to be, and when it drops. A header
202/// cell has to carry the same three or the header and the body disagree about
203/// which column just disappeared, and a renderer emitting its own header row
204/// should call this rather than assemble the list a second time.
205#[must_use]
206pub fn column_classes(column: &Column<'_>, opts: &Emit) -> String {
207    let mut out = String::new();
208    push_column_classes(&mut out, column, opts);
209    out
210}
211
212/// Every class a cell of this column carries, written into a buffer the caller
213/// already has.
214///
215/// [`column_classes`]'s streaming form, and four allocations fewer per cell: the
216/// three names and the string joining them.
217pub fn push_column_classes(out: &mut String, column: &Column<'_>, opts: &Emit) {
218    push_column_class(out, column, opts);
219    out.push(' ');
220    push_class(out, width_class(column.width), opts);
221    out.push(' ');
222    push_class(out, drop_class(column.priority), opts);
223}
224
225/// The `grid-template-columns` value for the columns kept at `cutoff`.
226///
227/// Emitting only the surviving tracks is what keeps the track list and the
228/// hiding in agreement. An app that hides a cell with `display: none` but
229/// leaves its track in place gets a column of empty space, which is the other
230/// half of goingson's mobile bug: its narrow rule drops to four tracks by hand
231/// and has to be edited in step with the `nth-child` cut.
232#[must_use]
233pub fn grid_template_columns(
234    columns: &[Column<'_>],
235    sizing: &Sizing<'_>,
236    cutoff: Priority,
237) -> String {
238    columns
239        .iter()
240        .filter(|column| column.kept_at(cutoff))
241        .map(|column| sizing.track(column))
242        .collect::<Vec<_>>()
243        .join(" ")
244}
245
246/// The rules that narrow `selector` to the columns kept at `cutoff`.
247///
248/// Both halves together: the shortened track list, and `display: none` on each
249/// dropped column *by its own class*. Nothing counts positions, so inserting a
250/// column changes what is emitted rather than changing which column vanishes.
251///
252/// `selector` may be a selector list. A descendant is appended to each part
253/// rather than to the whole, because appending to the whole changes what the
254/// earlier parts match: `.head, .row > .col-x` reads as "`.head`, or a `.col-x`
255/// inside `.row`", so `.head` itself would be hidden.
256#[must_use]
257pub fn narrowing_css(
258    columns: &[Column<'_>],
259    selector: &str,
260    sizing: &Sizing<'_>,
261    cutoff: Priority,
262    opts: &Emit,
263) -> String {
264    let parts: Vec<&str> = selector.split(',').map(str::trim).collect();
265
266    let mut css = format!(
267        "{} {{\n    grid-template-columns: {};\n}}\n",
268        parts.join(", "),
269        grid_template_columns(columns, sizing, cutoff)
270    );
271
272    for column in columns.iter().filter(|c| !c.kept_at(cutoff)) {
273        let class = column_class(column, opts);
274        let targets: Vec<String> = parts
275            .iter()
276            .map(|part| format!("{part} > .{class}"))
277            .collect();
278        let _ = write!(css, "{} {{\n    display: none;\n}}\n", targets.join(",\n"));
279    }
280    css
281}
282
283/// One cell of a row.
284///
285/// The contents are [`Markup`] rather than text, and that is the whole shape of
286/// this module: a cell holds whatever the app builds, and the app says so by
287/// naming it. Escaping a cell here would be wrong as well as impossible — a
288/// task row's description cell is five nested spans and a badge.
289#[derive(Debug, Clone, Copy)]
290pub struct Cell<'a> {
291    /// Which column this fills, by name.
292    pub column: &'a str,
293    /// What the cell holds, when the whole cell is one thing.
294    ///
295    /// Carries the cell-part class the stylesheet half emits, so a cell that is
296    /// nothing but controls says so in the description's own words rather than
297    /// in the app's.
298    ///
299    /// `Option<CellPart>` and never `Option<RowPart>`: a table cell borrowing
300    /// the list row's vocabulary is drift. A row's parts answer a different
301    /// question (which of six emphases this run of text takes) from a
302    /// cell's (whether this is text, tokens, controls or a link).
303    ///
304    /// `None` for a cell mixing parts. A cell holding a value *and* a strip of
305    /// tokens *and* a control is three parts in one container, and each one
306    /// wears its own class inside — this field is for the single-part case,
307    /// where a wrapper span would say nothing the cell has not already said.
308    pub part: Option<CellPart>,
309    /// The contents. Trusted app markup.
310    pub content: Markup<'a>,
311}
312
313impl<'a> Cell<'a> {
314    /// A cell with no cell part.
315    #[must_use]
316    pub const fn new(column: &'a str, content: Markup<'a>) -> Self {
317        Self {
318            column,
319            part: None,
320            content,
321        }
322    }
323}
324
325/// The class for a row part.
326///
327/// [`RowPart`] is `#[non_exhaustive]`, so a member added upstream does not stop
328/// this compiling.
329///
330/// The fallback is what that costs. A member added upstream lands here as a
331/// bare `row-part` with no rule of its own, which is a thing rendering plainly
332/// rather than a build that stops. Grep this function when adopting a new
333/// makeover-layout.
334///
335/// Public, because a row's parts are emitted by whoever builds the row element
336/// and that is not always this crate: `cells_html` emits a table's cells, but a
337/// list row carries the app's identity and hooks, so a screen renderer writes
338/// it. A renderer that reimplements this list rather than calling it takes on
339/// the obligation above without knowing it.
340/// Every class [`part_class`] can return, including the fallback.
341///
342/// Beside the match rather than derived from it, because a `match` over a
343/// `#[non_exhaustive]` enum cannot be enumerated from outside. It carries the
344/// same obligation the match does and a test below holds the two together, so
345/// a new arm added without a new entry fails rather than silently narrowing
346/// what a checker believes this crate can emit.
347pub const ROW_PART_CLASSES: &[&str] = &[
348    "row-primary",
349    "row-secondary",
350    "row-meta",
351    "row-actions",
352    "row-tokens",
353    "row-proportion",
354    "row-part",
355];
356
357/// Every class [`flow_class`] can return.
358///
359/// `Flow::Tight` has no class: one line is what a run already does, so a rule
360/// for it would restate the default on every part in every row. Only the tier
361/// that departs from it is named, which is also why a renderer emitting nothing
362/// for an unknown flow is correct rather than lossy.
363pub const FLOW_CLASSES: &[&str] = &["row-relaxed"];
364
365/// The classes a row inside a hierarchy carries.
366///
367/// Declared here because the generated sheet defines rules for them: the
368/// vocabulary has to say so, or the check that every emitted name has a rule
369/// cannot see them.
370pub const NESTING_CLASSES: &[&str] = &["row-nested", "row-branch", "row-disclose"];
371
372/// The class for a part's flow, if it needs one.
373///
374/// `None` for [`Flow::Tight`] and for any tier added upstream that this crate
375/// has not been taught, which lands as one line: the same trade
376/// [`part_class`]'s fallback makes, and the safe direction, since a part that
377/// grows without bound breaks the rows around it while a part that stays on one
378/// line only looks like the old rendering. Grep this when adopting a new
379/// makeover-layout.
380#[must_use]
381pub fn flow_class(flow: Flow) -> Option<&'static str> {
382    match flow {
383        Flow::Relaxed => Some("row-relaxed"),
384        _ => None,
385    }
386}
387
388/// Every class [`width_class`](fn@width_class) can return, including the
389/// fallback.
390///
391/// See [`ROW_PART_CLASSES`] for why it is written out. Only two of the three
392/// carry a rule -- a fill is what a cell does when the sheet says nothing --
393/// which is exactly why the list is here rather than being read off the
394/// generated CSS: `cell-fill` reached every table in the tree and the
395/// vocabulary named it nowhere.
396pub const CELL_WIDTH_CLASSES: &[&str] = &["cell-content", "cell-fixed", "cell-fill"];
397
398/// Every class [`drop_class`](fn@drop_class) can return, including the
399/// fallback.
400///
401/// [`CELL_WIDTH_CLASSES`]' argument, one column property over: `cell-keeps` is
402/// the tier the narrowing never hides, so the sheet writes no rule for it and
403/// a scraped set cannot see it.
404pub const CELL_DROP_CLASSES: &[&str] = &["cell-drops-first", "cell-drops-next", "cell-keeps"];
405
406/// Every class [`cell_part_class`] can return, including the fallback.
407///
408/// See [`ROW_PART_CLASSES`] for why it is written out.
409pub const CELL_PART_CLASSES: &[&str] = &[
410    "cell-value",
411    "cell-tokens",
412    "cell-actions",
413    "cell-link",
414    "cell-part",
415];
416
417#[must_use]
418pub fn part_class(part: RowPart) -> &'static str {
419    match part {
420        RowPart::Primary => "row-primary",
421        RowPart::Secondary => "row-secondary",
422        RowPart::Meta => "row-meta",
423        RowPart::Actions => "row-actions",
424        RowPart::Tokens => "row-tokens",
425        RowPart::Proportion => "row-proportion",
426        _ => "row-part",
427    }
428}
429
430/// The class for a cell part.
431///
432/// [`part_class`]'s table half, for [`CellPart`]. The fallback is there for the
433/// same reason and costs the same thing: a member added upstream lands as a
434/// bare `cell-part` with no rule of its own, rather than as a build that stops.
435/// Grep this function too when adopting a new makeover-layout. Public for the
436/// reason [`part_class`] is.
437#[must_use]
438pub fn cell_part_class(part: CellPart) -> &'static str {
439    match part {
440        CellPart::Value => "cell-value",
441        CellPart::Tokens => "cell-tokens",
442        CellPart::Actions => "cell-actions",
443        CellPart::Link => "cell-link",
444        _ => "cell-part",
445    }
446}
447
448/// A row's cells, in column order.
449///
450/// Ordered by the columns and not by the cells, so a row cannot silently
451/// disagree with its table about what comes where. A column with no cell gets
452/// an empty container, which keeps the grid aligned; a cell naming no column is
453/// dropped, because there is nowhere to put it.
454///
455/// Emits the cells alone, not the row element. The row carries the app's
456/// identity and hooks — `data-id`, a context-menu binding, a tabindex, its
457/// state classes — and none of that is describable here.
458///
459/// # Not for a webview's scroll path
460///
461/// This has no consumer in either webview app, deliberately, and wiring one in
462/// would be a mistake worth naming. goingson renders rows through a virtual
463/// scroller whose `_render` calls its row builder **synchronously** while
464/// scrolling; the code's own comment says scroll events fire at 60Hz+ and that
465/// this is the hot path. Reaching Rust from there means an IPC round trip and
466/// an `await` in that loop, per visible range, during a drag.
467///
468/// So this is for the hosts where rendering already happens in Rust: an axum
469/// route, and the router when it lands. There the objection does not apply,
470/// because nothing crosses a process boundary to reach it. A webview app should
471/// take [`narrowing_css`] and [`column_class`] and keep building its own rows.
472#[must_use]
473pub fn cells_html(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit) -> String {
474    let mut html = String::new();
475    cells_html_into(columns, cells, opts, &mut html);
476    html
477}
478
479/// A row's cells, written into a buffer the caller already has.
480///
481/// [`cells_html`]'s streaming form, byte-identical to it, and the one a host
482/// rendering a table should call: a row is emitted once per row per render, so
483/// this is where a `String` per cell class is paid for most often.
484pub fn cells_html_into(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit, out: &mut String) {
485    emit_cells(columns, cells, opts, out, None);
486}
487
488/// Where one column's markup went, and which of it the cell wrote.
489///
490/// Two ranges because two different things vary, and a caller compiling this
491/// into a template needs to say which it means.
492///
493/// `block` is the whole `<div>`: the column emits one per column whether or not
494/// a cell answers it, so a caller replacing a cell with a different one replaces
495/// the block, class and all.
496///
497/// `content` is what the cell itself contributed. A cell that is absent leaves
498/// the block standing and empty, so a caller compiling "this cell is there or
499/// is not" must cover the content alone -- covering the block would delete a
500/// `<div>` the row still draws, and the row would lose a column.
501#[derive(Clone, Debug, PartialEq, Eq)]
502pub struct Placed {
503    /// The whole column block, opening tag to closing tag.
504    pub block: core::ops::Range<usize>,
505    /// What the cell wrote inside it, empty range and all.
506    pub content: core::ops::Range<usize>,
507}
508
509/// A row's cells, saying where each column's block landed.
510///
511/// Byte-identical to [`cells_html_into`], and it appends one entry to `placed`
512/// per column, in column order: the offsets in `out` between which that
513/// column's whole `<div>` was written.
514///
515/// # Who this is for
516///
517/// A caller compiling a described screen into a template, which has to know
518/// which bytes of a row a particular cell produced. Finding that out by
519/// searching the output for the content is the thing it exists to avoid: a
520/// cell's markup may appear twice in a row, and a cell that renders to nothing
521/// cannot be searched for at all. So the writer says where it wrote, which is
522/// the only source that cannot be wrong.
523///
524/// Nothing about the markup changes, and a caller not compiling anything should
525/// call [`cells_html_into`] and pay nothing for this.
526pub fn cells_html_placed(
527    columns: &[Column<'_>],
528    cells: &[Cell<'_>],
529    opts: &Emit,
530    out: &mut String,
531    placed: &mut Vec<Placed>,
532) {
533    emit_cells(columns, cells, opts, out, Some(placed));
534}
535
536fn emit_cells(
537    columns: &[Column<'_>],
538    cells: &[Cell<'_>],
539    opts: &Emit,
540    out: &mut String,
541    mut placed: Option<&mut Vec<Placed>>,
542) {
543    for column in columns {
544        let at = out.len();
545        let found = cells.iter().find(|cell| cell.column == column.name);
546        out.push_str("<div class=\"");
547        push_class(out, "cell", opts);
548        out.push(' ');
549        push_column_classes(out, column, opts);
550        if let Some(part) = found.and_then(|cell| cell.part) {
551            out.push(' ');
552            push_class(out, cell_part_class(part), opts);
553        }
554        out.push_str("\">");
555        let content = out.len();
556        out.push_str(found.map_or("", |cell| cell.content.0));
557        let wrote = content..out.len();
558        out.push_str("</div>");
559        if let Some(placed) = placed.as_deref_mut() {
560            placed.push(Placed {
561                block: at..out.len(),
562                content: wrote,
563            });
564        }
565    }
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571
572    /// The placed form writes the same bytes, and says where each one went.
573    ///
574    /// Both halves matter. If the two ever disagreed, a compiled screen would
575    /// be built against markup nobody serves; if a range were off by a byte, it
576    /// would cut a tag in half.
577    #[test]
578    fn saying_where_a_cell_landed_does_not_change_what_is_written() {
579        let columns = [
580            Column {
581                name: "Name",
582                ..Column::new("Name")
583            },
584            Column {
585                name: "Price",
586                ..Column::new("Price")
587            },
588        ];
589        let cells = [
590            Cell {
591                column: "Name",
592                part: Some(CellPart::Value),
593                content: Markup("Kick"),
594            },
595            Cell {
596                column: "Price",
597                part: None,
598                content: Markup("<b>Free</b>"),
599            },
600        ];
601        let opts = Emit::default();
602
603        let mut plain = String::new();
604        cells_html_into(&columns, &cells, &opts, &mut plain);
605
606        let mut said = String::from("before:");
607        let mut placed = Vec::new();
608        cells_html_placed(&columns, &cells, &opts, &mut said, &mut placed);
609
610        assert_eq!(said.strip_prefix("before:").unwrap(), plain);
611        assert_eq!(placed.len(), columns.len());
612        assert_eq!(placed[0].block.start, "before:".len());
613        assert_eq!(placed[1].block.end, said.len());
614        for one in &placed {
615            let block = &said[one.block.clone()];
616            assert!(block.starts_with("<div class=\""), "{block}");
617            assert!(block.ends_with("</div>"), "{block}");
618        }
619
620        // The content is what the cell wrote and nothing the column wrote, so
621        // it is the half a caller covers when the cell may be absent: the
622        // block stands either way.
623        assert_eq!(&said[placed[0].content.clone()], "Kick");
624        assert_eq!(&said[placed[1].content.clone()], "<b>Free</b>");
625        for one in &placed {
626            assert!(one.block.start < one.content.start);
627            assert!(one.content.end < one.block.end);
628        }
629
630        // A column no cell answers still draws its block, and the content it
631        // reports is the empty range inside it. That is the case the whole
632        // split exists for.
633        let mut none = String::new();
634        let mut empty = Vec::new();
635        cells_html_placed(&columns, &[], &opts, &mut none, &mut empty);
636        assert_eq!(empty.len(), columns.len());
637        for one in &empty {
638            assert!(one.content.is_empty(), "{one:?}");
639            assert!(!none[one.block.clone()].is_empty());
640        }
641    }
642
643    #[test]
644    fn every_width_and_drop_class_is_one_the_vocabulary_wrote_down() {
645        // The obligation ROW_PART_CLASSES carries. Both matches have a wildcard
646        // arm, so a member added upstream lands on a class that is already in
647        // the list; what this catches is a new arm returning a new name, which
648        // would otherwise narrow what a checker believes this crate emits
649        // without narrowing what it writes.
650        for width in [Width::Content, Width::Fixed, Width::Fill] {
651            assert!(
652                CELL_WIDTH_CLASSES.contains(&width_class(width)),
653                "{width:?} is missing from CELL_WIDTH_CLASSES"
654            );
655        }
656        for priority in [Priority::Optional, Priority::Secondary, Priority::Essential] {
657            assert!(
658                CELL_DROP_CLASSES.contains(&drop_class(priority)),
659                "{priority:?} is missing from CELL_DROP_CLASSES"
660            );
661        }
662        let names = crate::vocabulary::names(&Emit::default());
663        for name in CELL_WIDTH_CLASSES.iter().chain(CELL_DROP_CLASSES) {
664            assert!(names.contains(*name), "{name} is not in the vocabulary");
665        }
666    }
667
668    #[test]
669    fn a_column_name_cannot_break_out_of_the_class_attribute() {
670        // Until 0.41.0 the name went in raw, so this emitted
671        // `class="cell col-a" onclick="steal() cell-fill ...">` -- a live
672        // handler on every cell of the column. The name is the one
673        // app-supplied string this crate puts in a class rather than in text.
674        let name = "a\" onclick=\"steal()";
675        let columns = vec![Column::new(name)];
676        let cells = vec![Cell {
677            column: name,
678            part: None,
679            content: Markup("x"),
680        }];
681        let html = cells_html(&columns, &cells, &Emit::default());
682
683        assert!(!html.contains("onclick=\"steal()"), "{html}");
684        assert!(html.contains("col-a--onclick--steal--"), "{html}");
685        // Two quotes in the whole cell, both this crate's: the ones opening and
686        // closing the class attribute. A third would be the name ending it.
687        assert_eq!(html.matches('"').count(), 2, "{html}");
688    }
689
690    #[test]
691    fn the_class_and_the_selector_that_hides_it_agree_on_the_name() {
692        // The reason the fix is a filter and not an escape. A class is read by
693        // the HTML parser and again by a CSS selector; an escaped name would be
694        // safe in the attribute and unmatchable from the stylesheet, so the
695        // narrowing would stop hiding the column it names.
696        let columns = vec![Column {
697            priority: Priority::Optional,
698            ..Column::new("Due date")
699        }];
700        let cells = vec![Cell {
701            column: "Due date",
702            part: None,
703            content: Markup("x"),
704        }];
705        let opts = Emit::default();
706
707        let html = cells_html(&columns, &cells, &opts);
708        let css = narrowing_css(&columns, ".row", &sizing(), Priority::Essential, &opts);
709
710        // One class, not the two `col-Due date` parsed as.
711        assert!(html.contains("class=\"cell col-Due-date "), "{html}");
712        assert!(css.contains(".row > .col-Due-date {"), "{css}");
713    }
714
715    #[test]
716    fn a_name_already_made_of_identifier_characters_is_untouched() {
717        // Every column name in the tree is one of these, which is what makes
718        // 0.41.0 a fix rather than a rename.
719        for name in ["description", "due", "progress", "Name", "col_2", "a-b"] {
720            let mut out = String::new();
721            push_column_name(&mut out, name);
722            assert_eq!(out, name);
723        }
724    }
725
726    #[test]
727    fn a_name_outside_ascii_keeps_itself() {
728        // CSS identifiers admit everything from U+00A0 up, so folding these to
729        // dashes would collide two columns for nothing.
730        let mut out = String::new();
731        push_column_name(&mut out, "Größe");
732        assert_eq!(out, "Größe");
733    }
734
735    fn columns() -> Vec<Column<'static>> {
736        vec![
737            Column {
738                width: Width::Fill,
739                priority: Priority::Essential,
740                ..Column::new("description")
741            },
742            Column {
743                width: Width::Fixed,
744                priority: Priority::Secondary,
745                ..Column::new("due")
746            },
747            Column {
748                width: Width::Fixed,
749                priority: Priority::Optional,
750                ..Column::new("progress")
751            },
752        ]
753    }
754
755    fn sizing() -> Sizing<'static> {
756        Sizing {
757            lengths: &[
758                ("description", "200px"),
759                ("due", "110px"),
760                ("progress", "100px"),
761            ],
762            fallback: "",
763        }
764    }
765
766    #[test]
767    fn a_fill_column_gets_a_floor_and_the_slack() {
768        let tracks = grid_template_columns(&columns(), &sizing(), Priority::Optional);
769        assert_eq!(tracks, "minmax(200px, 1fr) 110px 100px");
770    }
771
772    #[test]
773    fn a_column_with_no_length_makes_no_claim() {
774        let sizing = Sizing::default();
775        let tracks = grid_template_columns(&columns(), &sizing, Priority::Optional);
776        assert_eq!(tracks, "minmax(auto, 1fr) auto auto");
777    }
778
779    /// The point of the module. Raising the cutoff drops columns by what they
780    /// are worth, and the track list shortens to match, so the two cannot
781    /// disagree the way a hand-written `nth-child` cut and a hand-written
782    /// track list can.
783    #[test]
784    fn raising_the_cutoff_drops_columns_and_their_tracks_together() {
785        let columns = columns();
786
787        let wide = grid_template_columns(&columns, &sizing(), Priority::Optional);
788        assert_eq!(wide.split(' ').count(), 4); // minmax(200px, + 1fr) + 2
789
790        let narrow = grid_template_columns(&columns, &sizing(), Priority::Secondary);
791        assert_eq!(narrow, "minmax(200px, 1fr) 110px");
792
793        let narrowest = grid_template_columns(&columns, &sizing(), Priority::Essential);
794        assert_eq!(narrowest, "minmax(200px, 1fr)");
795    }
796
797    #[test]
798    fn narrowing_hides_a_dropped_column_by_its_own_class_not_its_position() {
799        let css = narrowing_css(
800            &columns(),
801            ".ui-mode-mobile .task-row",
802            &sizing(),
803            Priority::Secondary,
804            &Emit::default(),
805        );
806        assert!(
807            css.contains("grid-template-columns: minmax(200px, 1fr) 110px;"),
808            "{css}"
809        );
810        assert!(
811            css.contains(".ui-mode-mobile .task-row > .col-progress {"),
812            "{css}"
813        );
814        assert!(!css.contains("nth-child"), "{css}");
815        // The kept columns are not mentioned as hidden.
816        assert!(!css.contains(".col-due {\n    display: none"), "{css}");
817    }
818
819    /// A selector list has to distribute, or the earlier parts of it get the
820    /// child combinator appended to the whole and start matching things they
821    /// never named. This hid an entire table header the first time it ran.
822    #[test]
823    fn a_selector_list_distributes_the_hidden_column() {
824        let css = narrowing_css(
825            &columns(),
826            ".task-header-row, .task-row",
827            &sizing(),
828            Priority::Secondary,
829            &Emit::default(),
830        );
831        assert!(
832            css.contains(".task-header-row > .col-progress,\n.task-row > .col-progress {"),
833            "{css}"
834        );
835        // The bare header selector must never appear as a hiding target.
836        assert!(
837            !css.contains(".task-header-row {\n    display: none"),
838            "{css}"
839        );
840        assert!(
841            css.contains(".task-header-row, .task-row {\n    grid-template-columns:"),
842            "{css}"
843        );
844    }
845
846    #[test]
847    fn cells_follow_the_columns_and_carry_their_column_class() {
848        let cells = [
849            Cell {
850                column: "due",
851                part: Some(CellPart::Value),
852                content: Markup("tomorrow"),
853            },
854            Cell::new("description", Markup("<span>Ship it</span>")),
855        ];
856        let html = cells_html(&columns(), &cells, &Emit::default());
857
858        // Column order, not cell order: description was passed second.
859        let description = html.find("Ship it").expect("description cell");
860        let due = html.find("tomorrow").expect("due cell");
861        assert!(description < due, "{html}");
862
863        // Three classes, not one: the column's own name, how wide it asks to
864        // be, and when it drops. The last two are what lets the stylesheet
865        // carry rules a described table cannot generate per table.
866        assert!(
867            html.contains(r#"<div class="cell col-description cell-fill cell-keeps">"#),
868            "{html}"
869        );
870        assert!(
871            html.contains(r#"<div class="cell col-due cell-fixed cell-drops-next cell-value">"#),
872            "{html}"
873        );
874        // progress had no cell, so it is present and empty rather than absent,
875        // or the grid would shift left by one.
876        assert!(
877            html.contains(r#"<div class="cell col-progress cell-fixed cell-drops-first"></div>"#),
878            "{html}"
879        );
880    }
881
882    /// A row is emitted once per row per render, so the streaming form is the
883    /// one a host should call and the two have to agree byte for byte.
884    #[test]
885    fn streamed_cells_are_the_cells_the_other_form_returns() {
886        let opts = Emit {
887            class_prefix: "mk-",
888            ..Emit::default()
889        };
890        let cells = [
891            Cell {
892                column: "due",
893                part: Some(CellPart::Value),
894                content: Markup("tomorrow"),
895            },
896            Cell::new("description", Markup("<span>Ship it</span>")),
897        ];
898        for cells in [&cells[..], &[]] {
899            let mut streamed = String::new();
900            cells_html_into(&columns(), cells, &opts, &mut streamed);
901            assert_eq!(streamed, cells_html(&columns(), cells, &opts));
902        }
903        for column in &columns() {
904            let mut streamed = String::new();
905            push_column_classes(&mut streamed, column, &opts);
906            assert_eq!(streamed, column_classes(column, &opts));
907        }
908    }
909
910    #[test]
911    fn a_cell_naming_no_column_is_dropped() {
912        let cells = [Cell::new("nonexistent", Markup("nowhere"))];
913        let html = cells_html(&columns(), &cells, &Emit::default());
914        assert!(!html.contains("nowhere"), "{html}");
915    }
916
917    #[test]
918    fn the_class_prefix_reaches_the_cells_and_the_narrowing() {
919        let opts = Emit {
920            class_prefix: "mk-",
921            ..Emit::default()
922        };
923        let cells = [Cell::new("due", Markup("x"))];
924        assert!(
925            cells_html(&columns(), &cells, &opts).contains("mk-cell mk-col-due"),
926            "prefix missing"
927        );
928        assert!(
929            narrowing_css(&columns(), ".t", &sizing(), Priority::Secondary, &opts)
930                .contains(".mk-col-progress"),
931            "prefix missing"
932        );
933    }
934}