makeover-webview 0.84.1

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Column layout and row structure for lists and tables.
//!
//! The other half of phase B. [`form`](crate::form) renders a field; this
//! renders the frame a list of rows sits in: which columns exist, how wide they
//! are, which ones survive a narrow viewport, and the cell containers a row is
//! made of.
//!
//! # What this does not do
//!
//! It does not render a cell's contents. That is the crate's own limit, stated
//! in `makeover_layout`'s "Where the description stops": generate the boring
//! 80% so the bespoke 20% gets the attention. A goingson task row carries
//! delegated action hooks with argument substitution, four nested sub-renderers,
//! conditional state classes and aria labels built from data. A description
//! expressive enough to emit that is a templating language wearing a
//! description's name.
//!
//! So the split is the one [`Markup`] already draws for forms: this owns the
//! structure and the app owns what goes in it. What that removes from an app is
//! not small: cell order, cell classes, each column's floor, and above all the
//! narrowing, which is where addressing columns by position goes wrong.
//!
//! # Why positions are the bug
//!
//! goingson hides its mobile columns with `nth-child(n+5)` against a
//! seven-column table, plus a separate `nth-child(3)`, plus two class-based
//! rules — the same fact said three ways, two of them positional. Insert a
//! column anywhere left of the cut and the wrong one disappears, silently,
//! because nothing in the stylesheet knows what column five *is*.
//! [`Priority`] is the fix: a renderer narrows by what a column is worth, here as
//! a shrink factor on the column's own class, and never by counting.

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

/// The class a cell of this column carries.
///
/// Derived from the column's own name, which is what makes the narrowing rules
/// addressable. `data-column` would do as well; a class is what both webview
/// apps already key their cell styling on.
///
/// The name is reduced to identifier characters first. See [`push_column_name`].
#[must_use]
pub fn column_class(column: &Column<'_>, opts: &Emit) -> String {
    let mut out = String::new();
    push_column_class(&mut out, column, opts);
    out
}

/// The class a cell of this column carries, written into a buffer the caller
/// already has.
///
/// [`column_class`]'s streaming form. It is the one that runs per cell per row,
/// where the allocating form pays twice: once for `col-<name>` and once for the
/// prefix in front of it.
pub fn push_column_class(out: &mut String, column: &Column<'_>, opts: &Emit) {
    out.push_str(opts.class_prefix);
    out.push_str("col-");
    push_column_name(out, column.name);
}

/// A column's name as the identifier half of its class.
///
/// # Why this is not escaping
///
/// The name is the one app-supplied string this crate puts in a class attribute
/// rather than in text or an `aria-label`, so it may never go in raw. A column
/// named `a" onclick="steal()` emitted
///
/// ```html
/// <div class="cell col-a" onclick="steal() cell-fill cell-keeps">
/// ```
///
/// which is a live event handler on every cell of that column. HTML escaping is
/// the reflex and it is the wrong tool here, because a class is read twice: once
/// by the HTML parser, which would decode `&quot;` back to a quote, and once by
/// the CSS selector an app writes against it. An escaped name is safe in the
/// attribute and unmatchable from the stylesheet, so the two halves would stop
/// meeting -- silently, the way every other defect this module's comments
/// record did.
///
/// Reducing the name to identifier characters answers both. What comes out is a
/// valid CSS identifier, so the selector matches, and it holds none of the five
/// characters an attribute value can be ended with, so there is nothing to
/// escape.
///
/// # What it changes for a name that was already fine
///
/// Nothing. Alphanumerics, `_` and `-` pass through, and every column name in
/// the tree is made of those. A name that is *not* was already broken rather
/// than merely unsafe: `Due date` emitted `col-Due date`, which the HTML parser
/// reads as the two classes `col-Due` and `date`, and which a selector wrote as
/// a descendant selector that matched neither. Both now agree on
/// `col-Due-date`.
///
/// Alphanumeric in the Unicode sense, not the ASCII one. CSS identifiers admit
/// everything from U+00A0 up, so a column named `Größe` keeps its name; folding
/// it to `Gr--e` would collide with a neighbouring column for nothing.
pub fn push_column_name(out: &mut String, name: &str) {
    for ch in name.chars() {
        // Substituted rather than dropped. Two columns called `a b` and `ab`
        // are different columns, and dropping would give them one class and one
        // set of narrowing rules between them.
        if ch.is_alphanumeric() || ch == '_' || ch == '-' {
            out.push(ch);
        } else {
            out.push('-');
        }
    }
}

/// The class saying how wide a cell of this column asks to be.
///
/// A bounded vocabulary, unlike [`column_class`], which is why the stylesheet
/// can carry the rule. [`Width`] is `#[non_exhaustive]`, and a member added
/// upstream lands on the fill class: a column that takes the slack is the
/// behaviour that makes no claim.
fn width_class(width: Width) -> &'static str {
    match width {
        Width::Content => "cell-content",
        Width::Fixed => "cell-fixed",
        _ => "cell-fill",
    }
}

/// The class saying when a cell of this column drops.
///
/// [`Priority`] said as a class rather than as a cutoff, so the narrowing can
/// live in the stylesheet instead of being generated per table. The class is a
/// shrink factor: a table short of room takes the shortfall from the columns
/// worth least, and nothing counts positions or names a breakpoint.
fn drop_class(priority: Priority) -> &'static str {
    match priority {
        Priority::Optional => "cell-drops-first",
        Priority::Secondary => "cell-drops-next",
        // A priority added upstream keeps its column. `Priority` is
        // `#[non_exhaustive]`, and of the two ways to be wrong about one this
        // renderer has not learned, showing a column that should have dropped
        // is the one the user can see and work around.
        _ => "cell-keeps",
    }
}

/// The class saying what a column holds, or `None` for prose.
///
/// wiki `table-model`: the kind carries the look, so the class goes on every
/// cell and on the heading, and the sheet rules each kind once. Text is the
/// absence of a kind, as `cell-keeps` would be if a keep needed saying, so it
/// writes nothing. A kind added upstream reads as text: plain, never missing.
#[must_use]
pub fn kind_class(kind: ColumnKind) -> Option<&'static str> {
    match kind {
        ColumnKind::Identifier => Some("kind-identifier"),
        ColumnKind::Date => Some("kind-date"),
        ColumnKind::Number => Some("kind-number"),
        ColumnKind::Code => Some("kind-code"),
        ColumnKind::Status => Some("kind-status"),
        ColumnKind::Actions => Some("kind-actions"),
        _ => None,
    }
}

/// Every class [`kind_class`] can return.
pub const KIND_CLASSES: &[&str] = &[
    "kind-identifier",
    "kind-date",
    "kind-number",
    "kind-code",
    "kind-status",
    "kind-actions",
];

/// Every class a cell of this column carries.
///
/// The column's own name, how wide it asks to be, when it drops, what it holds
/// and its floor as a rung of the `min-N` ladder. A header cell has to carry the
/// same classes or the header and the body disagree about which column just
/// closed and how wide the rest are, and a renderer emitting its own header row
/// should call this rather than assemble the list a second time.
#[must_use]
pub fn column_classes(column: &Column<'_>, opts: &Emit) -> String {
    let mut out = String::new();
    push_column_classes(&mut out, column, opts);
    out
}

/// Every class a cell of this column carries, written into a buffer the caller
/// already has.
///
/// [`column_classes`]'s streaming form, and four allocations fewer per cell: the
/// three names and the string joining them.
pub fn push_column_classes(out: &mut String, column: &Column<'_>, opts: &Emit) {
    push_column_class(out, column, opts);
    out.push(' ');
    push_class(out, width_class(column.width), opts);
    out.push(' ');
    push_class(out, drop_class(column.priority), opts);
    if let Some(kind) = kind_class(column.kind) {
        out.push(' ');
        push_class(out, kind, opts);
    }
    out.push(' ');
    push_class(out, "min-", opts);
    let _ = write!(out, "{}", column.floor());
}

/// The wrapper every cell and heading holds its contents in.
///
/// The column is a flex item that may close to nothing, and padding cannot
/// shrink, so the padding lives on this and the column clips it. It is also
/// what a droppable column hides when it is under its floor, and where the
/// type goes, so a heading and the cells under it are the same box whatever
/// each holds.
pub const CELL_IN: &str = "cell-in";

/// One cell of a row.
///
/// The contents are [`Markup`] rather than text, and that is the whole shape of
/// this module: a cell holds whatever the app builds, and the app says so by
/// naming it. Escaping a cell here would be wrong as well as impossible — a
/// task row's description cell is five nested spans and a badge.
#[derive(Debug, Clone, Copy)]
pub struct Cell<'a> {
    /// Which column this fills, by name.
    pub column: &'a str,
    /// What the cell holds, when the whole cell is one thing.
    ///
    /// Carries the cell-part class the stylesheet half emits, so a cell that is
    /// nothing but controls says so in the description's own words rather than
    /// in the app's.
    ///
    /// `Option<CellPart>` and never `Option<RowPart>`: a table cell borrowing
    /// the list row's vocabulary is drift. A row's parts answer a different
    /// question (which of six emphases this run of text takes) from a
    /// cell's (whether this is text, tokens, controls or a link).
    ///
    /// `None` for a cell mixing parts. A cell holding a value *and* a strip of
    /// tokens *and* a control is three parts in one container, and each one
    /// wears its own class inside — this field is for the single-part case,
    /// where a wrapper span would say nothing the cell has not already said.
    pub part: Option<CellPart>,
    /// The contents. Trusted app markup.
    pub content: Markup<'a>,
}

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

/// The class for a row part.
///
/// [`RowPart`] is `#[non_exhaustive]`, so a member added upstream does not stop
/// this compiling.
///
/// The fallback is what that costs. A member added upstream lands here as a
/// bare `row-part`, which the sheet lets shrink like its siblings and otherwise
/// leaves plain: a thing rendering plainly rather than a build that stops. Grep
/// this function when adopting a new makeover-layout.
///
/// Public, because a row's parts are emitted by whoever builds the row element
/// and that is not always this crate: `cells_html` emits a table's cells, but a
/// list row carries the app's identity and hooks, so a screen renderer writes
/// it. A renderer that reimplements this list rather than calling it takes on
/// the obligation above without knowing it.
/// Every class [`part_class`] can return, including the fallback.
///
/// Beside the match rather than derived from it, because a `match` over a
/// `#[non_exhaustive]` enum cannot be enumerated from outside. It carries the
/// same obligation the match does and a test below holds the two together, so
/// a new arm added without a new entry fails rather than silently narrowing
/// what a checker believes this crate can emit.
pub const ROW_PART_CLASSES: &[&str] = &[
    "row-primary",
    "row-secondary",
    "row-meta",
    "row-actions",
    "row-tokens",
    "row-proportion",
    "row-part",
];

/// Every class [`flow_class`] can return.
///
/// `Flow::Tight` has no class: one line is what a run already does, so a rule
/// for it would restate the default on every part in every row. Only the tier
/// that departs from it is named, which is also why a renderer emitting nothing
/// for an unknown flow is correct rather than lossy.
pub const FLOW_CLASSES: &[&str] = &["row-relaxed"];

/// The classes a row inside a hierarchy carries.
///
/// Declared here because the generated sheet defines rules for them: the
/// vocabulary has to say so, or the check that every emitted name has a rule
/// cannot see them.
pub const NESTING_CLASSES: &[&str] = &["row-nested", "row-branch", "row-disclose"];

/// The class for a part's flow, if it needs one.
///
/// `None` for [`Flow::Tight`] and for any tier added upstream that this crate
/// has not been taught, which lands as one line: the same trade
/// [`part_class`]'s fallback makes, and the safe direction, since a part that
/// grows without bound breaks the rows around it while a part that stays on one
/// line only looks like the old rendering. Grep this when adopting a new
/// makeover-layout.
#[must_use]
pub fn flow_class(flow: Flow) -> Option<&'static str> {
    match flow {
        Flow::Relaxed => Some("row-relaxed"),
        _ => None,
    }
}

/// Every class [`width_class`](fn@width_class) can return, including the
/// fallback.
///
/// See [`ROW_PART_CLASSES`] for why it is written out. Only two of the three
/// carry a rule -- a fill is what a cell does when the sheet says nothing --
/// which is exactly why the list is here rather than being read off the
/// generated CSS: `cell-fill` reached every table in the tree and the
/// vocabulary named it nowhere.
pub const CELL_WIDTH_CLASSES: &[&str] = &["cell-content", "cell-fixed", "cell-fill"];

/// Every class [`drop_class`](fn@drop_class) can return, including the
/// fallback.
///
/// [`CELL_WIDTH_CLASSES`]' argument, one column property over: `cell-keeps` is
/// the tier the narrowing never hides, so the sheet writes no rule for it and
/// a scraped set cannot see it.
pub const CELL_DROP_CLASSES: &[&str] = &["cell-drops-first", "cell-drops-next", "cell-keeps"];

/// Every class [`cell_part_class`] can return, including the fallback.
///
/// See [`ROW_PART_CLASSES`] for why it is written out.
pub const CELL_PART_CLASSES: &[&str] = &[
    "cell-value",
    "cell-tokens",
    "cell-actions",
    "cell-link",
    "cell-part",
];

#[must_use]
pub fn part_class(part: RowPart) -> &'static str {
    match part {
        RowPart::Primary => "row-primary",
        RowPart::Secondary => "row-secondary",
        RowPart::Meta => "row-meta",
        RowPart::Actions => "row-actions",
        RowPart::Tokens => "row-tokens",
        RowPart::Proportion => "row-proportion",
        _ => "row-part",
    }
}

/// The class for a cell part.
///
/// [`part_class`]'s table half, for [`CellPart`]. The fallback is there for the
/// same reason and costs the same thing: a member added upstream lands as a
/// bare `cell-part` with no rule of its own, rather than as a build that stops.
/// Grep this function too when adopting a new makeover-layout. Public for the
/// reason [`part_class`] is.
#[must_use]
pub fn cell_part_class(part: CellPart) -> &'static str {
    match part {
        CellPart::Value => "cell-value",
        CellPart::Tokens => "cell-tokens",
        CellPart::Actions => "cell-actions",
        CellPart::Link => "cell-link",
        _ => "cell-part",
    }
}

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

/// A row's cells, written into a buffer the caller already has.
///
/// [`cells_html`]'s streaming form, byte-identical to it, and the one a host
/// rendering a table should call: a row is emitted once per row per render, so
/// this is where a `String` per cell class is paid for most often.
pub fn cells_html_into(columns: &[Column<'_>], cells: &[Cell<'_>], opts: &Emit, out: &mut String) {
    emit_cells(columns, cells, opts, out, None);
}

/// Where one column's markup went, and which of it the cell wrote.
///
/// Two ranges because two different things vary, and a caller compiling this
/// into a template needs to say which it means.
///
/// `block` is the whole `<div>`: the column emits one per column whether or not
/// a cell answers it, so a caller replacing a cell with a different one replaces
/// the block, class and all.
///
/// `content` is what the cell itself contributed. A cell that is absent leaves
/// the block standing and empty, so a caller compiling "this cell is there or
/// is not" must cover the content alone -- covering the block would delete a
/// `<div>` the row still draws, and the row would lose a column.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Placed {
    /// The whole column block, opening tag to closing tag.
    pub block: core::ops::Range<usize>,
    /// What the cell wrote inside it, empty range and all.
    pub content: core::ops::Range<usize>,
}

/// A row's cells, saying where each column's block landed.
///
/// Byte-identical to [`cells_html_into`], and it appends one entry to `placed`
/// per column, in column order: the offsets in `out` between which that
/// column's whole `<div>` was written.
///
/// # Who this is for
///
/// A caller compiling a described screen into a template, which has to know
/// which bytes of a row a particular cell produced. Finding that out by
/// searching the output for the content is the thing it exists to avoid: a
/// cell's markup may appear twice in a row, and a cell that renders to nothing
/// cannot be searched for at all. So the writer says where it wrote, which is
/// the only source that cannot be wrong.
///
/// Nothing about the markup changes, and a caller not compiling anything should
/// call [`cells_html_into`] and pay nothing for this.
pub fn cells_html_placed(
    columns: &[Column<'_>],
    cells: &[Cell<'_>],
    opts: &Emit,
    out: &mut String,
    placed: &mut Vec<Placed>,
) {
    emit_cells(columns, cells, opts, out, Some(placed));
}

fn emit_cells(
    columns: &[Column<'_>],
    cells: &[Cell<'_>],
    opts: &Emit,
    out: &mut String,
    mut placed: Option<&mut Vec<Placed>>,
) {
    for column in columns {
        let at = out.len();
        let found = cells.iter().find(|cell| cell.column == column.name);
        out.push_str("<div class=\"");
        push_class(out, "cell", opts);
        out.push(' ');
        push_column_classes(out, column, opts);
        if let Some(part) = found.and_then(|cell| cell.part) {
            out.push(' ');
            push_class(out, cell_part_class(part), opts);
        }
        out.push_str("\"><span class=\"");
        push_class(out, CELL_IN, opts);
        out.push_str("\">");
        let content = out.len();
        out.push_str(found.map_or("", |cell| cell.content.0));
        let wrote = content..out.len();
        out.push_str("</span></div>");
        if let Some(placed) = placed.as_deref_mut() {
            placed.push(Placed {
                block: at..out.len(),
                content: wrote,
            });
        }
    }
}

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

    /// The placed form writes the same bytes, and says where each one went.
    ///
    /// Both halves matter. If the two ever disagreed, a compiled screen would
    /// be built against markup nobody serves; if a range were off by a byte, it
    /// would cut a tag in half.
    #[test]
    fn saying_where_a_cell_landed_does_not_change_what_is_written() {
        let columns = [
            Column {
                name: "Name",
                ..Column::new("Name")
            },
            Column {
                name: "Price",
                ..Column::new("Price")
            },
        ];
        let cells = [
            Cell {
                column: "Name",
                part: Some(CellPart::Value),
                content: Markup("Kick"),
            },
            Cell {
                column: "Price",
                part: None,
                content: Markup("<b>Free</b>"),
            },
        ];
        let opts = Emit::default();

        let mut plain = String::new();
        cells_html_into(&columns, &cells, &opts, &mut plain);

        let mut said = String::from("before:");
        let mut placed = Vec::new();
        cells_html_placed(&columns, &cells, &opts, &mut said, &mut placed);

        assert_eq!(said.strip_prefix("before:").unwrap(), plain);
        assert_eq!(placed.len(), columns.len());
        assert_eq!(placed[0].block.start, "before:".len());
        assert_eq!(placed[1].block.end, said.len());
        for one in &placed {
            let block = &said[one.block.clone()];
            assert!(block.starts_with("<div class=\""), "{block}");
            assert!(block.ends_with("</div>"), "{block}");
        }

        // The content is what the cell wrote and nothing the column wrote, so
        // it is the half a caller covers when the cell may be absent: the
        // block stands either way.
        assert_eq!(&said[placed[0].content.clone()], "Kick");
        assert_eq!(&said[placed[1].content.clone()], "<b>Free</b>");
        for one in &placed {
            assert!(one.block.start < one.content.start);
            assert!(one.content.end < one.block.end);
        }

        // A column no cell answers still draws its block, and the content it
        // reports is the empty range inside it. That is the case the whole
        // split exists for.
        let mut none = String::new();
        let mut empty = Vec::new();
        cells_html_placed(&columns, &[], &opts, &mut none, &mut empty);
        assert_eq!(empty.len(), columns.len());
        for one in &empty {
            assert!(one.content.is_empty(), "{one:?}");
            assert!(!none[one.block.clone()].is_empty());
        }
    }

    #[test]
    fn every_width_and_drop_class_is_one_the_vocabulary_wrote_down() {
        // The obligation ROW_PART_CLASSES carries. Both matches have a wildcard
        // arm, so a member added upstream lands on a class that is already in
        // the list; what this catches is a new arm returning a new name, which
        // would otherwise narrow what a checker believes this crate emits
        // without narrowing what it writes.
        for width in [Width::Content, Width::Fixed, Width::Fill] {
            assert!(
                CELL_WIDTH_CLASSES.contains(&width_class(width)),
                "{width:?} is missing from CELL_WIDTH_CLASSES"
            );
        }
        for priority in [Priority::Optional, Priority::Secondary, Priority::Essential] {
            assert!(
                CELL_DROP_CLASSES.contains(&drop_class(priority)),
                "{priority:?} is missing from CELL_DROP_CLASSES"
            );
        }
        let names = crate::vocabulary::names(&Emit::default());
        for name in CELL_WIDTH_CLASSES.iter().chain(CELL_DROP_CLASSES) {
            assert!(names.contains(*name), "{name} is not in the vocabulary");
        }
    }

    #[test]
    fn a_column_name_cannot_break_out_of_the_class_attribute() {
        // Until 0.41.0 the name went in raw, so this emitted
        // `class="cell col-a" onclick="steal() cell-fill ...">` -- a live
        // handler on every cell of the column. The name is the one
        // app-supplied string this crate puts in a class rather than in text.
        let name = "a\" onclick=\"steal()";
        let columns = vec![Column::new(name)];
        let cells = vec![Cell {
            column: name,
            part: None,
            content: Markup("x"),
        }];
        let html = cells_html(&columns, &cells, &Emit::default());

        assert!(!html.contains("onclick=\"steal()"), "{html}");
        assert!(html.contains("col-a--onclick--steal--"), "{html}");
        // Four quotes in the whole cell, all this crate's: the ones opening and
        // closing the cell's class attribute and the wrapper's. A fifth would
        // be the name ending one of them.
        assert_eq!(html.matches('"').count(), 4, "{html}");
    }

    #[test]
    fn the_class_and_the_selector_that_names_it_agree_on_the_name() {
        // The reason the fix is a filter and not an escape. A class is read by
        // the HTML parser and again by a CSS selector an app writes against
        // `column_class`; an escaped name would be safe in the attribute and
        // unmatchable from the stylesheet.
        let columns = vec![Column {
            priority: Priority::Optional,
            kind: ColumnKind::Text,
            ..Column::new("Due date")
        }];
        let cells = vec![Cell {
            column: "Due date",
            part: None,
            content: Markup("x"),
        }];
        let opts = Emit::default();

        let html = cells_html(&columns, &cells, &opts);

        // One class, not the two `col-Due date` parsed as.
        assert!(html.contains("class=\"cell col-Due-date "), "{html}");
        assert_eq!(column_class(&columns[0], &opts), "col-Due-date");
    }

    #[test]
    fn a_name_already_made_of_identifier_characters_is_untouched() {
        // Every column name in the tree is one of these, which is what makes
        // 0.41.0 a fix rather than a rename.
        for name in ["description", "due", "progress", "Name", "col_2", "a-b"] {
            let mut out = String::new();
            push_column_name(&mut out, name);
            assert_eq!(out, name);
        }
    }

    #[test]
    fn a_name_outside_ascii_keeps_itself() {
        // CSS identifiers admit everything from U+00A0 up, so folding these to
        // dashes would collide two columns for nothing.
        let mut out = String::new();
        push_column_name(&mut out, "Größe");
        assert_eq!(out, "Größe");
    }

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

    /// The floor rides on the column's classes as a rung the stylesheet has a
    /// rule for, so a described table narrows at its declared width with no
    /// CSS travelling beside it.
    #[test]
    fn every_column_names_its_floor_as_a_rung_of_the_ladder() {
        let opts = Emit::default();
        let declared = Column::new("Buyer").min(15);
        assert!(column_classes(&declared, &opts).ends_with(" min-16"));
        let derived = Column::new("description");
        assert!(column_classes(&derived, &opts).ends_with(" min-16"));
        // Every floor a column can reach has a rule, prefix and all.
        let sheet = crate::stylesheet(&opts);
        for n in (2..=makeover_layout::MIN_CEILING).step_by(2) {
            assert!(sheet.contains(&format!(".min-{n} {{")), "no rung for {n}");
        }
    }

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

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

        // Three classes, not one: the column's own name, how wide it asks to
        // be, and when it drops. The last two are what lets the stylesheet
        // carry rules a described table cannot generate per table.
        assert!(
            html.contains(
                r#"<div class="cell col-description cell-fill cell-keeps min-16"><span class="cell-in">"#
            ),
            "{html}"
        );
        assert!(
            html.contains(
                r#"<div class="cell col-due cell-fixed cell-drops-next min-8 cell-value"><span class="cell-in">tomorrow</span></div>"#
            ),
            "{html}"
        );
        // progress had no cell, so it is present and empty rather than absent,
        // or every column after it would line up under the wrong heading.
        assert!(
            html.contains(
                r#"<div class="cell col-progress cell-fixed cell-drops-first min-10"><span class="cell-in"></span></div>"#
            ),
            "{html}"
        );
    }

    /// A row is emitted once per row per render, so the streaming form is the
    /// one a host should call and the two have to agree byte for byte.
    #[test]
    fn streamed_cells_are_the_cells_the_other_form_returns() {
        let opts = Emit {
            class_prefix: "mk-",
            ..Emit::default()
        };
        let cells = [
            Cell {
                column: "due",
                part: Some(CellPart::Value),
                content: Markup("tomorrow"),
            },
            Cell::new("description", Markup("<span>Ship it</span>")),
        ];
        for cells in [&cells[..], &[]] {
            let mut streamed = String::new();
            cells_html_into(&columns(), cells, &opts, &mut streamed);
            assert_eq!(streamed, cells_html(&columns(), cells, &opts));
        }
        for column in &columns() {
            let mut streamed = String::new();
            push_column_classes(&mut streamed, column, &opts);
            assert_eq!(streamed, column_classes(column, &opts));
        }
    }

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

    #[test]
    fn the_class_prefix_reaches_the_cells_the_rung_and_the_wrapper() {
        let opts = Emit {
            class_prefix: "mk-",
            ..Emit::default()
        };
        let cells = [Cell::new("due", Markup("x"))];
        let html = cells_html(&columns(), &cells, &opts);
        assert!(
            html.contains("mk-cell mk-col-due"),
            "prefix missing: {html}"
        );
        assert!(html.contains(" mk-min-8"), "prefix missing: {html}");
        assert!(
            html.contains("class=\"mk-cell-in\""),
            "prefix missing: {html}"
        );
    }
}