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 `"` 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.
248pub fn push_sizer(out: &mut String, copies: &str, opts: &Emit) {
249 if copies.is_empty() {
250 return;
251 }
252 out.push_str("<span class=\"");
253 push_class(out, CELL_SIZER, opts);
254 out.push_str("\" aria-hidden=\"true\">");
255 out.push_str(copies);
256 out.push_str("</span>");
257}
258
259/// One cell of a row.
260///
261/// The contents are [`Markup`] rather than text, and that is the whole shape of
262/// this module: a cell holds whatever the app builds, and the app says so by
263/// naming it. Escaping a cell here would be wrong as well as impossible — a
264/// task row's description cell is five nested spans and a badge.
265#[derive(Debug, Clone, Copy)]
266pub struct Cell<'a> {
267 /// Which column this fills, by name.
268 pub column: &'a str,
269 /// What the cell holds, when the whole cell is one thing.
270 ///
271 /// Carries the cell-part class the stylesheet half emits, so a cell that is
272 /// nothing but controls says so in the description's own words rather than
273 /// in the app's.
274 ///
275 /// `Option<CellPart>` and never `Option<RowPart>`: a table cell borrowing
276 /// the list row's vocabulary is drift. A row's parts answer a different
277 /// question (which of six emphases this run of text takes) from a
278 /// cell's (whether this is text, tokens, controls or a link).
279 ///
280 /// `None` for a cell mixing parts. A cell holding a value *and* a strip of
281 /// tokens *and* a control is three parts in one container, and each one
282 /// wears its own class inside — this field is for the single-part case,
283 /// where a wrapper span would say nothing the cell has not already said.
284 pub part: Option<CellPart>,
285 /// The contents. Trusted app markup.
286 pub content: Markup<'a>,
287}
288
289impl<'a> Cell<'a> {
290 /// A cell with no cell part.
291 #[must_use]
292 pub const fn new(column: &'a str, content: Markup<'a>) -> Self {
293 Self {
294 column,
295 part: None,
296 content,
297 }
298 }
299}
300
301/// The class for a row part.
302///
303/// [`RowPart`] is `#[non_exhaustive]`, so a member added upstream does not stop
304/// this compiling.
305///
306/// The fallback is what that costs. A member added upstream lands here as a
307/// bare `row-part`, which the sheet lets shrink like its siblings and otherwise
308/// leaves plain: a thing rendering plainly rather than a build that stops. Grep
309/// this function when adopting a new makeover-layout.
310///
311/// Public, because a row's parts are emitted by whoever builds the row element
312/// and that is not always this crate: `cells_html` emits a table's cells, but a
313/// list row carries the app's identity and hooks, so a screen renderer writes
314/// it. A renderer that reimplements this list rather than calling it takes on
315/// the obligation above without knowing it.
316/// Every class [`part_class`] can return, including the fallback.
317///
318/// Beside the match rather than derived from it, because a `match` over a
319/// `#[non_exhaustive]` enum cannot be enumerated from outside. It carries the
320/// same obligation the match does and a test below holds the two together, so
321/// a new arm added without a new entry fails rather than silently narrowing
322/// what a checker believes this crate can emit.
323pub const ROW_PART_CLASSES: &[&str] = &[
324 "row-primary",
325 "row-secondary",
326 "row-meta",
327 "row-actions",
328 "row-tokens",
329 "row-proportion",
330 "row-part",
331];
332
333/// Every class [`flow_class`] can return.
334///
335/// `Flow::Tight` has no class: one line is what a run already does, so a rule
336/// for it would restate the default on every part in every row. Only the tier
337/// that departs from it is named, which is also why a renderer emitting nothing
338/// for an unknown flow is correct rather than lossy.
339pub const FLOW_CLASSES: &[&str] = &["row-relaxed"];
340
341/// The classes a row inside a hierarchy carries.
342///
343/// Declared here because the generated sheet defines rules for them: the
344/// vocabulary has to say so, or the check that every emitted name has a rule
345/// cannot see them.
346pub const NESTING_CLASSES: &[&str] = &["row-nested", "row-branch", "row-disclose"];
347
348/// The class for a part's flow, if it needs one.
349///
350/// `None` for [`Flow::Tight`] and for any tier added upstream that this crate
351/// has not been taught, which lands as one line: the same trade
352/// [`part_class`]'s fallback makes, and the safe direction, since a part that
353/// grows without bound breaks the rows around it while a part that stays on one
354/// line only looks like the old rendering. Grep this when adopting a new
355/// makeover-layout.
356#[must_use]
357pub fn flow_class(flow: Flow) -> Option<&'static str> {
358 match flow {
359 Flow::Relaxed => Some("row-relaxed"),
360 _ => None,
361 }
362}
363
364/// Every class [`width_class`](fn@width_class) can return, including the
365/// fallback.
366///
367/// See [`ROW_PART_CLASSES`] for why it is written out. Only two of the three
368/// carry a rule -- a fill is what a cell does when the sheet says nothing --
369/// which is exactly why the list is here rather than being read off the
370/// generated CSS: `cell-fill` reached every table in the tree and the
371/// vocabulary named it nowhere.
372pub const CELL_WIDTH_CLASSES: &[&str] = &["cell-content", "cell-fixed", "cell-fill"];
373
374/// Every class [`drop_class`](fn@drop_class) can return, including the
375/// fallback.
376///
377/// [`CELL_WIDTH_CLASSES`]' argument, one column property over: `cell-keeps` is
378/// the tier the narrowing never hides, so the sheet writes no rule for it and
379/// a scraped set cannot see it.
380pub const CELL_DROP_CLASSES: &[&str] = &["cell-drops-first", "cell-drops-next", "cell-keeps"];
381
382/// Every class [`cell_part_class`] can return, including the fallback.
383///
384/// See [`ROW_PART_CLASSES`] for why it is written out.
385pub const CELL_PART_CLASSES: &[&str] = &[
386 "cell-value",
387 "cell-tokens",
388 "cell-actions",
389 "cell-link",
390 "cell-part",
391];
392
393#[must_use]
394pub fn part_class(part: RowPart) -> &'static str {
395 match part {
396 RowPart::Primary => "row-primary",
397 RowPart::Secondary => "row-secondary",
398 RowPart::Meta => "row-meta",
399 RowPart::Actions => "row-actions",
400 RowPart::Tokens => "row-tokens",
401 RowPart::Proportion => "row-proportion",
402 _ => "row-part",
403 }
404}
405
406/// The class for a cell part.
407///
408/// [`part_class`]'s table half, for [`CellPart`]. The fallback is there for the
409/// same reason and costs the same thing: a member added upstream lands as a
410/// bare `cell-part` with no rule of its own, rather than as a build that stops.
411/// Grep this function too when adopting a new makeover-layout. Public for the
412/// reason [`part_class`] is.
413#[must_use]
414pub fn cell_part_class(part: CellPart) -> &'static str {
415 match part {
416 CellPart::Value => "cell-value",
417 CellPart::Tokens => "cell-tokens",
418 CellPart::Actions => "cell-actions",
419 CellPart::Link => "cell-link",
420 _ => "cell-part",
421 }
422}
423
424/// A row's cells, in column order.
425///
426/// Ordered by the columns and not by the cells, so a row cannot silently
427/// disagree with its table about what comes where. A column with no cell gets
428/// an empty container, which keeps the grid aligned; a cell naming no column is
429/// dropped, because there is nowhere to put it.
430///
431/// Emits the cells alone, not the row element. The row carries the app's
432/// identity and hooks — `data-id`, a context-menu binding, a tabindex, its
433/// state classes — and none of that is describable here.
434///
435/// # Not for a webview's scroll path
436///
437/// This has no consumer in either webview app, deliberately, and wiring one in
438/// would be a mistake worth naming. goingson renders rows through a virtual
439/// scroller whose `_render` calls its row builder **synchronously** while
440/// scrolling; the code's own comment says scroll events fire at 60Hz+ and that
441/// this is the hot path. Reaching Rust from there means an IPC round trip and
442/// an `await` in that loop, per visible range, during a drag.
443///
444/// So this is for the hosts where rendering already happens in Rust: an axum
445/// route, and the router when it lands. There the objection does not apply,
446/// because nothing crosses a process boundary to reach it. A webview app should
447/// take [`column_classes`] and [`CELL_IN`] and keep building its own rows.
448#[must_use]
449pub fn cells_html(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit) -> String {
450 let mut html = String::new();
451 cells_html_into(columns, cells, opts, &mut html);
452 html
453}
454
455/// A row's cells, written into a buffer the caller already has.
456///
457/// [`cells_html`]'s streaming form, byte-identical to it, and the one a host
458/// rendering a table should call: a row is emitted once per row per render, so
459/// this is where a `String` per cell class is paid for most often.
460pub fn cells_html_into(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit, out: &mut String) {
461 emit_cells(columns, &[], cells, opts, out, None);
462}
463
464/// A row's cells with a [`CELL_SIZER`] in the columns that have one.
465///
466/// `sizers` runs parallel to `columns`: the copies for the column at the same
467/// position, empty or missing for a column that has none. The copies are the
468/// same in every row, so they are the column's to pass and not a cell's, and a
469/// column no cell answers still gets them: an empty cell holding no copy would
470/// be the one row narrower than the rest.
471///
472/// Written after the cell's content and inside its block, so a caller passing
473/// `placed` finds them in the block's range and not in the content's: they do
474/// not vary with the cell. Byte-identical to [`cells_html_into`] or
475/// [`cells_html_placed`] when `sizers` is empty.
476pub fn sized_cells_html_into(
477 columns: &[Column<'_>],
478 sizers: &[Markup<'_>],
479 cells: &[Cell<'_>],
480 opts: &Emit,
481 out: &mut String,
482 placed: Option<&mut Vec<Placed>>,
483) {
484 emit_cells(columns, sizers, cells, opts, out, placed);
485}
486
487/// Where one column's markup went, and which of it the cell wrote.
488///
489/// Two ranges because two different things vary, and a caller compiling this
490/// into a template needs to say which it means.
491///
492/// `block` is the whole `<div>`: the column emits one per column whether or not
493/// a cell answers it, so a caller replacing a cell with a different one replaces
494/// the block, class and all.
495///
496/// `content` is what the cell itself contributed. A cell that is absent leaves
497/// the block standing and empty, so a caller compiling "this cell is there or
498/// is not" must cover the content alone -- covering the block would delete a
499/// `<div>` the row still draws, and the row would lose a column.
500#[derive(Clone, Debug, PartialEq, Eq)]
501pub struct Placed {
502 /// The whole column block, opening tag to closing tag.
503 pub block: core::ops::Range<usize>,
504 /// What the cell wrote inside it, empty range and all.
505 pub content: core::ops::Range<usize>,
506}
507
508/// A row's cells, saying where each column's block landed.
509///
510/// Byte-identical to [`cells_html_into`], and it appends one entry to `placed`
511/// per column, in column order: the offsets in `out` between which that
512/// column's whole `<div>` was written.
513///
514/// # Who this is for
515///
516/// A caller compiling a described screen into a template, which has to know
517/// which bytes of a row a particular cell produced. Finding that out by
518/// searching the output for the content is the thing it exists to avoid: a
519/// cell's markup may appear twice in a row, and a cell that renders to nothing
520/// cannot be searched for at all. So the writer says where it wrote, which is
521/// the only source that cannot be wrong.
522///
523/// Nothing about the markup changes, and a caller not compiling anything should
524/// call [`cells_html_into`] and pay nothing for this.
525pub fn cells_html_placed(
526 columns: &[Column<'_>],
527 cells: &[Cell<'_>],
528 opts: &Emit,
529 out: &mut String,
530 placed: &mut Vec<Placed>,
531) {
532 emit_cells(columns, &[], cells, opts, out, Some(placed));
533}
534
535fn emit_cells(
536 columns: &[Column<'_>],
537 sizers: &[Markup<'_>],
538 cells: &[Cell<'_>],
539 opts: &Emit,
540 out: &mut String,
541 mut placed: Option<&mut Vec<Placed>>,
542) {
543 for (at_column, column) in columns.iter().enumerate() {
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("\"><span class=\"");
555 push_class(out, CELL_IN, opts);
556 out.push_str("\">");
557 let content = out.len();
558 out.push_str(found.map_or("", |cell| cell.content.0));
559 let wrote = content..out.len();
560 if let Some(copies) = sizers.get(at_column) {
561 push_sizer(out, copies.0, opts);
562 }
563 out.push_str("</span></div>");
564 if let Some(placed) = placed.as_deref_mut() {
565 placed.push(Placed {
566 block: at..out.len(),
567 content: wrote,
568 });
569 }
570 }
571}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576
577 /// A column's copies go in every cell of it, a cell no row answers
578 /// included, after the content and inside the block; no sizers writes what
579 /// was always written.
580 #[test]
581 fn a_sizer_is_the_columns_and_sits_outside_what_the_cell_wrote() {
582 let columns = [
583 Column::new("Name"),
584 Column {
585 kind: ColumnKind::Actions,
586 ..Column::new("")
587 },
588 ];
589 let cells = [Cell {
590 column: "Name",
591 part: Some(CellPart::Value),
592 content: Markup("Kick"),
593 }];
594 let opts = Emit::default();
595
596 let mut plain = String::new();
597 cells_html_into(&columns, &cells, &opts, &mut plain);
598 let mut bare = String::new();
599 sized_cells_html_into(&columns, &[], &cells, &opts, &mut bare, None);
600 assert_eq!(bare, plain);
601
602 let sizers = [Markup(""), Markup("<span>Delete</span>")];
603 let mut html = String::new();
604 let mut placed = Vec::new();
605 sized_cells_html_into(
606 &columns,
607 &sizers,
608 &cells,
609 &opts,
610 &mut html,
611 Some(&mut placed),
612 );
613 assert_eq!(html.matches(CELL_SIZER).count(), 1, "{html}");
614 assert!(
615 html.contains(
616 r#"<span class="cell-in"><span class="cell-sizer" aria-hidden="true"><span>Delete</span></span></span></div>"#
617 ),
618 "{html}"
619 );
620 assert!(
621 !html[placed[0].block.clone()].contains(CELL_SIZER),
622 "{html}"
623 );
624 assert!(html[placed[1].block.clone()].contains(CELL_SIZER), "{html}");
625 assert!(placed[1].content.is_empty(), "{html}");
626 }
627
628 /// The placed form writes the same bytes, and says where each one went.
629 ///
630 /// Both halves matter. If the two ever disagreed, a compiled screen would
631 /// be built against markup nobody serves; if a range were off by a byte, it
632 /// would cut a tag in half.
633 #[test]
634 fn saying_where_a_cell_landed_does_not_change_what_is_written() {
635 let columns = [
636 Column {
637 name: "Name",
638 ..Column::new("Name")
639 },
640 Column {
641 name: "Price",
642 ..Column::new("Price")
643 },
644 ];
645 let cells = [
646 Cell {
647 column: "Name",
648 part: Some(CellPart::Value),
649 content: Markup("Kick"),
650 },
651 Cell {
652 column: "Price",
653 part: None,
654 content: Markup("<b>Free</b>"),
655 },
656 ];
657 let opts = Emit::default();
658
659 let mut plain = String::new();
660 cells_html_into(&columns, &cells, &opts, &mut plain);
661
662 let mut said = String::from("before:");
663 let mut placed = Vec::new();
664 cells_html_placed(&columns, &cells, &opts, &mut said, &mut placed);
665
666 assert_eq!(said.strip_prefix("before:").unwrap(), plain);
667 assert_eq!(placed.len(), columns.len());
668 assert_eq!(placed[0].block.start, "before:".len());
669 assert_eq!(placed[1].block.end, said.len());
670 for one in &placed {
671 let block = &said[one.block.clone()];
672 assert!(block.starts_with("<div class=\""), "{block}");
673 assert!(block.ends_with("</div>"), "{block}");
674 }
675
676 // The content is what the cell wrote and nothing the column wrote, so
677 // it is the half a caller covers when the cell may be absent: the
678 // block stands either way.
679 assert_eq!(&said[placed[0].content.clone()], "Kick");
680 assert_eq!(&said[placed[1].content.clone()], "<b>Free</b>");
681 for one in &placed {
682 assert!(one.block.start < one.content.start);
683 assert!(one.content.end < one.block.end);
684 }
685
686 // A column no cell answers still draws its block, and the content it
687 // reports is the empty range inside it. That is the case the whole
688 // split exists for.
689 let mut none = String::new();
690 let mut empty = Vec::new();
691 cells_html_placed(&columns, &[], &opts, &mut none, &mut empty);
692 assert_eq!(empty.len(), columns.len());
693 for one in &empty {
694 assert!(one.content.is_empty(), "{one:?}");
695 assert!(!none[one.block.clone()].is_empty());
696 }
697 }
698
699 #[test]
700 fn every_width_and_drop_class_is_one_the_vocabulary_wrote_down() {
701 // The obligation ROW_PART_CLASSES carries. Both matches have a wildcard
702 // arm, so a member added upstream lands on a class that is already in
703 // the list; what this catches is a new arm returning a new name, which
704 // would otherwise narrow what a checker believes this crate emits
705 // without narrowing what it writes.
706 for width in [Width::Content, Width::Fixed, Width::Fill] {
707 assert!(
708 CELL_WIDTH_CLASSES.contains(&width_class(width)),
709 "{width:?} is missing from CELL_WIDTH_CLASSES"
710 );
711 }
712 for priority in [Priority::Optional, Priority::Secondary, Priority::Essential] {
713 assert!(
714 CELL_DROP_CLASSES.contains(&drop_class(priority)),
715 "{priority:?} is missing from CELL_DROP_CLASSES"
716 );
717 }
718 let names = crate::vocabulary::names(&Emit::default());
719 for name in CELL_WIDTH_CLASSES.iter().chain(CELL_DROP_CLASSES) {
720 assert!(names.contains(*name), "{name} is not in the vocabulary");
721 }
722 }
723
724 #[test]
725 fn a_column_name_cannot_break_out_of_the_class_attribute() {
726 // Until 0.41.0 the name went in raw, so this emitted
727 // `class="cell col-a" onclick="steal() cell-fill ...">` -- a live
728 // handler on every cell of the column. The name is the one
729 // app-supplied string this crate puts in a class rather than in text.
730 let name = "a\" onclick=\"steal()";
731 let columns = vec![Column::new(name)];
732 let cells = vec![Cell {
733 column: name,
734 part: None,
735 content: Markup("x"),
736 }];
737 let html = cells_html(&columns, &cells, &Emit::default());
738
739 assert!(!html.contains("onclick=\"steal()"), "{html}");
740 assert!(html.contains("col-a--onclick--steal--"), "{html}");
741 // Four quotes in the whole cell, all this crate's: the ones opening and
742 // closing the cell's class attribute and the wrapper's. A fifth would
743 // be the name ending one of them.
744 assert_eq!(html.matches('"').count(), 4, "{html}");
745 }
746
747 #[test]
748 fn the_class_and_the_selector_that_names_it_agree_on_the_name() {
749 // The reason the fix is a filter and not an escape. A class is read by
750 // the HTML parser and again by a CSS selector an app writes against
751 // `column_class`; an escaped name would be safe in the attribute and
752 // unmatchable from the stylesheet.
753 let columns = vec![Column {
754 priority: Priority::Optional,
755 kind: ColumnKind::Text,
756 ..Column::new("Due date")
757 }];
758 let cells = vec![Cell {
759 column: "Due date",
760 part: None,
761 content: Markup("x"),
762 }];
763 let opts = Emit::default();
764
765 let html = cells_html(&columns, &cells, &opts);
766
767 // One class, not the two `col-Due date` parsed as.
768 assert!(html.contains("class=\"cell col-Due-date "), "{html}");
769 assert_eq!(column_class(&columns[0], &opts), "col-Due-date");
770 }
771
772 #[test]
773 fn a_name_already_made_of_identifier_characters_is_untouched() {
774 // Every column name in the tree is one of these, which is what makes
775 // 0.41.0 a fix rather than a rename.
776 for name in ["description", "due", "progress", "Name", "col_2", "a-b"] {
777 let mut out = String::new();
778 push_column_name(&mut out, name);
779 assert_eq!(out, name);
780 }
781 }
782
783 #[test]
784 fn a_name_outside_ascii_keeps_itself() {
785 // CSS identifiers admit everything from U+00A0 up, so folding these to
786 // dashes would collide two columns for nothing.
787 let mut out = String::new();
788 push_column_name(&mut out, "Größe");
789 assert_eq!(out, "Größe");
790 }
791
792 fn columns() -> Vec<Column<'static>> {
793 vec![
794 Column {
795 width: Width::Fill,
796 priority: Priority::Essential,
797 kind: ColumnKind::Text,
798 ..Column::new("description")
799 },
800 Column {
801 width: Width::Fixed,
802 priority: Priority::Secondary,
803 kind: ColumnKind::Text,
804 ..Column::new("due")
805 },
806 Column {
807 width: Width::Fixed,
808 priority: Priority::Optional,
809 kind: ColumnKind::Text,
810 ..Column::new("progress")
811 },
812 ]
813 }
814
815 /// The floor rides on the column's classes as a rung the stylesheet has a
816 /// rule for, so a described table narrows at its declared width with no
817 /// CSS travelling beside it.
818 #[test]
819 fn every_column_names_its_floor_as_a_rung_of_the_ladder() {
820 let opts = Emit::default();
821 let declared = Column::new("Buyer").min(15);
822 assert!(column_classes(&declared, &opts).ends_with(" min-16"));
823 let derived = Column::new("description");
824 assert!(column_classes(&derived, &opts).ends_with(" min-16"));
825 // Every floor a column can reach has a rule, prefix and all.
826 let sheet = crate::stylesheet(&opts);
827 for n in (2..=makeover_layout::MIN_CEILING).step_by(2) {
828 assert!(sheet.contains(&format!(".min-{n} {{")), "no rung for {n}");
829 }
830 }
831
832 #[test]
833 fn cells_follow_the_columns_and_carry_their_column_class() {
834 let cells = [
835 Cell {
836 column: "due",
837 part: Some(CellPart::Value),
838 content: Markup("tomorrow"),
839 },
840 Cell::new("description", Markup("<span>Ship it</span>")),
841 ];
842 let html = cells_html(&columns(), &cells, &Emit::default());
843
844 // Column order, not cell order: description was passed second.
845 let description = html.find("Ship it").expect("description cell");
846 let due = html.find("tomorrow").expect("due cell");
847 assert!(description < due, "{html}");
848
849 // Three classes, not one: the column's own name, how wide it asks to
850 // be, and when it drops. The last two are what lets the stylesheet
851 // carry rules a described table cannot generate per table.
852 assert!(
853 html.contains(
854 r#"<div class="cell col-description cell-fill cell-keeps min-16"><span class="cell-in">"#
855 ),
856 "{html}"
857 );
858 assert!(
859 html.contains(
860 r#"<div class="cell col-due cell-fixed cell-drops-next min-8 cell-value"><span class="cell-in">tomorrow</span></div>"#
861 ),
862 "{html}"
863 );
864 // progress had no cell, so it is present and empty rather than absent,
865 // or every column after it would line up under the wrong heading.
866 assert!(
867 html.contains(
868 r#"<div class="cell col-progress cell-fixed cell-drops-first min-10"><span class="cell-in"></span></div>"#
869 ),
870 "{html}"
871 );
872 }
873
874 /// A row is emitted once per row per render, so the streaming form is the
875 /// one a host should call and the two have to agree byte for byte.
876 #[test]
877 fn streamed_cells_are_the_cells_the_other_form_returns() {
878 let opts = Emit {
879 class_prefix: "mk-",
880 ..Emit::default()
881 };
882 let cells = [
883 Cell {
884 column: "due",
885 part: Some(CellPart::Value),
886 content: Markup("tomorrow"),
887 },
888 Cell::new("description", Markup("<span>Ship it</span>")),
889 ];
890 for cells in [&cells[..], &[]] {
891 let mut streamed = String::new();
892 cells_html_into(&columns(), cells, &opts, &mut streamed);
893 assert_eq!(streamed, cells_html(&columns(), cells, &opts));
894 }
895 for column in &columns() {
896 let mut streamed = String::new();
897 push_column_classes(&mut streamed, column, &opts);
898 assert_eq!(streamed, column_classes(column, &opts));
899 }
900 }
901
902 #[test]
903 fn a_cell_naming_no_column_is_dropped() {
904 let cells = [Cell::new("nonexistent", Markup("nowhere"))];
905 let html = cells_html(&columns(), &cells, &Emit::default());
906 assert!(!html.contains("nowhere"), "{html}");
907 }
908
909 #[test]
910 fn the_class_prefix_reaches_the_cells_the_rung_and_the_wrapper() {
911 let opts = Emit {
912 class_prefix: "mk-",
913 ..Emit::default()
914 };
915 let cells = [Cell::new("due", Markup("x"))];
916 let html = cells_html(&columns(), &cells, &opts);
917 assert!(
918 html.contains("mk-cell mk-col-due"),
919 "prefix missing: {html}"
920 );
921 assert!(html.contains(" mk-min-8"), "prefix missing: {html}");
922 assert!(
923 html.contains("class=\"mk-cell-in\""),
924 "prefix missing: {html}"
925 );
926 }
927}