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