makeover-webview 0.22.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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! Phase B, the forms half: [`makeover_layout::Field`] rendered to HTML.
//!
//! # Why this emits strings
//!
//! Both webview apps build their markup as strings and hand it to `innerHTML`:
//! goingson's `renderFormField` returns a template literal that fifteen call
//! sites interpolate into larger literals, and Balanced Breakfast's builds
//! nodes but appends them into the same string-built forms. Returning nodes
//! would rewrite the surrounding templates as well, which makes it a migration
//! rather than an adoption. So: strings, and the escaping comes with them.
//!
//! # Why one escaper is enough here
//!
//! goingson carries four escapers and 543 call sites that must pick between
//! them, because `escapeHtml` is built on `textContent` serialization and
//! **`textContent` refuses to encode `"`**. That is what makes it unsound in an
//! attribute, and it is the whole reason the choice exists. Its `escape.js`
//! records the finding as the CHRONIC-XSS seal, and its test suite has a gate
//! keeping the unsafe one off the namespace.
//!
//! [`escape`] here is not built on that, so it encodes the quote along with
//! everything else, which makes one function sound in both sinks. The four-way
//! choice does not move into Rust: it disappears. Nothing in this module hands
//! an unescaped value to the output except through [`Markup`], which a caller
//! has to name.
//!
//! # What the description does not carry
//!
//! One thing: the **current value**, which arrives in [`Filling`].
//!
//! It used to be three. Writing this emitter is what found them, and the other
//! two turned out not to be renderer state at all — the placeholder is
//! user-facing text that sits with `label` and `hint`, and a select's options
//! are needed by every renderer, which is how each of them ends up inventing a
//! near-miss of the same struct. Both moved down into `makeover-layout` 0.8.0,
//! `Choice` included, and this crate reads them off [`Field`] now.
//!
//! The value stays, and it is not a leftover. A webview reads it back out of
//! the DOM, an immediate-mode renderer writes through a `&mut`, and a terminal
//! keeps an edit buffer; a description carrying it would have to carry a way to
//! write it back, at which point it is a form model.

use crate::{Emit, class};
use makeover_layout::{Choice, Field, FieldKind};
use std::fmt::Write as _;

/// A string that is already markup, and is emitted without escaping.
///
/// The one hole in the escaping, and it has to be named to be used. goingson
/// has two live callers that need it, both passing a recurrence-config block
/// built elsewhere, and both would otherwise have their markup rendered as
/// visible angle brackets. A caller constructing this is stating that the
/// contents are trusted; nothing here can check that for them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Markup<'a>(pub &'a str);

/// What the field currently holds.
///
/// An enum rather than a bag of optional fields, on the same reasoning
/// [`makeover_layout::Depth`] is one: a checkbox holding a string is unsayable
/// here, where a struct would let it be said and then have to cope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Value<'a> {
    /// Nothing yet.
    #[default]
    Absent,
    /// The value of anything that takes typed text, a select included: what a
    /// select holds is the `value` of one of [`Field::options`]'s
    /// [`Choice`]s.
    ///
    /// It carried the options too until makeover-layout 0.8.0 moved them onto
    /// the field, which collapsed a `Chosen { options, value }` variant into
    /// this one. `makeover-immediate` arrived at the same single-variant shape
    /// on its own, from the other direction.
    Text(&'a str),
    /// A checkbox, on or off.
    On(bool),
}

impl<'a> Value<'a> {
    /// The value as text, for the kinds that submit one.
    const fn as_text(&self) -> &'a str {
        match self {
            Self::Text(text) => text,
            Self::Absent | Self::On(_) => "",
        }
    }
}

/// Everything about the field that the description does not carry.
#[derive(Debug, Clone, Copy, Default)]
pub struct Filling<'a> {
    /// What the field holds now.
    pub value: Value<'a>,
    /// Markup appended inside the group, after the hint. Not escaped.
    pub trailing: Option<Markup<'a>>,
    /// Scopes the `id` attributes to one instance of the form.
    ///
    /// The field's `name` is what the value submits under and is the same
    /// wherever the form appears; its `id` has to be unique in the document,
    /// and those two facts stop agreeing the moment a form appears twice.
    /// goingson hits this directly: its new-task and edit-task modals are the
    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
    /// `label for` and `aria-describedby` pointing at the right control.
    ///
    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
    /// `name`, which would change what the form submits.
    pub id_prefix: Option<&'a str>,
}

impl<'a> Filling<'a> {
    /// A filling that carries a value and nothing else.
    #[must_use]
    pub const fn of(value: Value<'a>) -> Self {
        Self {
            value,
            trailing: None,
            id_prefix: None,
        }
    }

    /// The document-unique id for a field of this name.
    fn id_for(&self, name: &str) -> String {
        match self.id_prefix {
            Some(prefix) => format!("{}-{}", escape(prefix), escape(name)),
            None => escape(name),
        }
    }
}

/// Encode the five characters that let a value stop being a value.
///
/// Sound in element text and in a double-quoted attribute alike, which is the
/// property `textContent`-based escaping cannot have. Both sinks are covered by
/// one function so that no call site has to choose, here or downstream.
#[must_use]
pub fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            other => out.push(other),
        }
    }
    out
}

/// The `type` an input takes for a kind.
///
/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
const fn input_type(kind: FieldKind) -> &'static str {
    match kind {
        FieldKind::Secret => "password",
        FieldKind::Number => "number",
        FieldKind::Checkbox => "checkbox",
        FieldKind::File => "file",
        FieldKind::Hidden => "hidden",
        // Not decoration. Each of these changes the keyboard a touch device
        // offers and turns on the platform's own validation, which is why the
        // description names them apart from text rather than letting the app
        // pass an HTML type through.
        FieldKind::Email => "email",
        FieldKind::Url => "url",
        FieldKind::Tel => "tel",
        FieldKind::Radio => "radio",
        // Select and Textarea are not inputs at all; they never reach here.
        // Radio is one, but it is emitted once per option by `radio_html` and
        // so does not reach here either.
        FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
        // A kind added to the description since this renderer was built. Text
        // accepts any value the others would, so it degrades rather than
        // dropping the field.
        _ => "text",
    }
}

/// The attributes every visible control carries, error state included.
///
/// `aria-invalid` is the whole reason the error state is readable at all: the
/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
/// than on a class, so a control rendered already-invalid without it is styled
/// as if nothing were wrong. goingson's runtime validation path sets the
/// attribute and its initial render does not, which is exactly the drift one
/// emitter removes.
/// `id` and `name` arrive separately because they are not the same fact. The
/// name is what submits and is fixed by the description; the id has to be
/// unique in the document and so carries [`Filling::id_prefix`] when a form
/// appears more than once.
fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
    let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
    if field.required {
        attrs.push_str(" required");
    }
    // makeover-layout 0.11.0's constraints. The description carries the rule and
    // this emits the browser's idiom for it, which is the model `required` has
    // been using since before the crate wrote down that it carried none.
    // Enforcement is still whoever validated's, and arrives back as `error`.
    if let Some(limit) = field.max_length {
        let _ = write!(attrs, " maxlength=\"{limit}\"");
    }
    if let Some(min) = field.min {
        let _ = write!(attrs, " min=\"{}\"", escape(min));
    }
    if let Some(max) = field.max {
        let _ = write!(attrs, " max=\"{}\"", escape(max));
    }
    if field.invalid() {
        attrs.push_str(" aria-invalid=\"true\"");
    }

    attrs.push_str(&described_by(field, id));
    attrs
}

/// The `aria-describedby` naming whatever of the hint and the error exist.
///
/// Both associations, in the order they are useful: the standing help, then
/// what is currently wrong. goingson's runtime path points describedby at the
/// error alone and drops the hint association it never made in the first place;
/// naming both here means the hint survives an error appearing.
///
/// Its own function because a radio group carries it on the group rather than
/// on a control, and one reading of "what describes this field" is the point.
fn described_by(field: &Field<'_>, id: &str) -> String {
    let mut described = Vec::new();
    if field.hint.is_some() {
        described.push(format!("{id}-hint"));
    }
    if field.error.is_some() {
        described.push(format!("{id}-error"));
    }
    if described.is_empty() {
        return String::new();
    }
    format!(" aria-describedby=\"{}\"", described.join(" "))
}

/// Whether the field's control is a set of elements rather than one.
///
/// A DOM concern rather than a description one, which is why it is decided here
/// and not in `makeover-layout`: `for` and `id` are an HTML association and
/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
/// points at nothing, because no single element carries the group's id, so the
/// association has to invert — the label takes an id and the group names itself
/// with `aria-labelledby`.
const fn is_group_control(kind: FieldKind) -> bool {
    matches!(kind, FieldKind::Radio)
}

/// A radio group: the options as sibling inputs sharing one `name`.
///
/// The group carries the error state and the descriptions, and the inputs carry
/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
/// down: marking a single input invalid would say the wrong thing, since what
/// is wrong is the answer to the question and not one of the alternatives.
///
/// Ids are numbered rather than built from the option values, which can hold
/// anything a `&str` can — spaces and quotes included — and would otherwise
/// have to be slugged into something unique by a rule this crate would then own.
///
/// `required` lands on every input, which is how HTML says a group is
/// compulsory: the constraint is satisfied when any one of them is checked.
fn radio_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
    let id = filling.id_for(field.name);
    let value = filling.value.as_text();
    let name = escape(field.name);

    let mut html = format!(
        "<div class=\"{}\" role=\"radiogroup\"",
        class("form-radio-group", opts)
    );
    let _ = write!(html, " aria-labelledby=\"{id}-label\"");
    if field.invalid() {
        html.push_str(" aria-invalid=\"true\"");
    }
    html.push_str(&described_by(field, &id));
    html.push('>');

    // A group described with no options emits an empty group, for the reason
    // `Field::options` gives: an app whose option list has not loaded has
    // exactly that, and an empty group says so on screen rather than in a log.
    for (index, opt) in field.options.iter().enumerate() {
        let checked = if opt.value == value { " checked" } else { "" };
        let required = if field.required { " required" } else { "" };
        let _ = write!(
            html,
            "<label class=\"{}\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" \
             value=\"{}\"{checked}{required}><span>{}</span></label>",
            class("form-radio-label", opts),
            escape(opt.value),
            escape(opt.label)
        );
    }

    html.push_str("</div>");
    html
}

/// The options of a select, with an unmatched current value carried as its own.
///
/// A select handed a value no option carries renders with nothing selected, the
/// browser falls back to the first option, and the next save writes a value
/// nobody chose. goingson hit exactly that with a backup-retention default of
/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
/// here so the second app gets it without hitting the bug first.
fn options_html(options: &[Choice<'_>], value: &str) -> String {
    let mut html = String::new();
    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
        let escaped = escape(value);
        let _ = write!(
            html,
            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
        );
    }
    for opt in options {
        let selected = if opt.value == value { " selected" } else { "" };
        let _ = write!(
            html,
            "<option value=\"{}\"{selected}>{}</option>",
            escape(opt.value),
            escape(opt.label)
        );
    }
    html
}

/// The control itself, without its label, hint or error.
fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
    let id = filling.id_for(field.name);
    let attrs = control_attributes(field, &id, field.name);
    let field_class = class("field", opts);
    let placeholder = field.placeholder.map_or_else(String::new, |text| {
        format!(" placeholder=\"{}\"", escape(text))
    });

    match field.kind {
        FieldKind::Radio => radio_html(field, filling, opts),
        FieldKind::Textarea => format!(
            "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
            escape(filling.value.as_text())
        ),
        FieldKind::Select => {
            // A select described with no options emits an empty select, which
            // says so on screen rather than in a log. That is the description's
            // own position on `Field::options`, not a fallback invented here.
            let options = options_html(field.options, filling.value.as_text());
            format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
        }
        FieldKind::Checkbox => {
            let checked = if matches!(filling.value, Value::On(true)) {
                " checked"
            } else {
                ""
            };
            format!(
                "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
                class("form-checkbox-label", opts),
                escape(field.label)
            )
        }
        // A secret never carries its value into the markup. `FieldKind::secret`
        // is documented as a value that must not be round-tripped through
        // anything that might persist it, and the DOM is such a thing: it is
        // read by every extension on the page and is the first thing a crash
        // reporter serialises. Neither app pre-fills one today, so this costs
        // nothing and closes the door before something does.
        FieldKind::Secret => {
            format!("<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>")
        }
        // A file input carries no value, and this is the browser's rule rather
        // than a preference: setting one from markup is refused, because a page
        // that could preselect a path could read a file the user never offered.
        // Nothing upstream needs to know, which is why the exception is here.
        FieldKind::File => {
            format!("<input type=\"file\" class=\"{field_class}\"{attrs}>")
        }
        kind => format!(
            "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
            input_type(kind),
            escape(filling.value.as_text())
        ),
    }
}

/// One field, as the group the app drops into its form.
///
/// The shape is goingson's, down to the class names, so adoption there deletes
/// `renderFormField` rather than restyling anything. That is also why the class
/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
/// emits only what it can generate from the description. Whether they should
/// move into the description is the next question this raises, not one it
/// answers.
///
/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
/// nothing drawn, which is what [`FieldKind::visible`] means.
///
/// The error marks the group as well as the control. That is
/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
/// cannot find the group from the message, so the group has to be told.
///
/// ```
/// use makeover_layout::{Field, FieldKind};
/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
///
/// let field = Field::new(FieldKind::Text, "title", "Title");
/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
///
/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
/// assert!(html.contains(r#"value="Ship it""#));
/// ```
#[must_use]
pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
    let id = filling.id_for(field.name);

    if !field.kind.visible() {
        // Name only, no id: a hidden field is never pointed at by a label or a
        // description, so the one attribute it needs is the one that submits.
        return format!(
            "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
            escape(field.name),
            escape(filling.value.as_text())
        );
    }

    let mut html = format!("<div class=\"{}", class("form-group", opts));
    if field.invalid() {
        html.push_str(" has-error");
    }
    if field.extended {
        // The disclosure that hides these is a property of the form, not of the
        // field, so the field is marked and the app opens or closes the group.
        html.push_str("\" data-extended=\"true");
    }
    html.push_str("\">");

    // A checkbox labels itself, on the right of the box. Both apps special-case
    // this inline today, which is the tell that it belongs in the description;
    // `FieldKind::labels_itself` is where it went.
    if !field.kind.labels_itself() {
        // A group control is named *by* its label rather than pointing at it,
        // so the two carry opposite halves of the association. See
        // `is_group_control`.
        let association = if is_group_control(field.kind) {
            format!(" id=\"{id}-label\"")
        } else {
            format!(" for=\"{id}\"")
        };
        let _ = write!(
            html,
            "<label class=\"{}\"{association}>{}</label>",
            class("form-label", opts),
            escape(field.label)
        );
    }

    html.push_str(&control_html(field, filling, opts));

    if let Some(hint) = field.hint {
        let _ = write!(
            html,
            "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
            class("form-hint", opts),
            escape(hint)
        );
    }
    if let Some(Markup(markup)) = filling.trailing {
        html.push_str(markup);
    }
    if let Some(error) = field.error {
        let _ = write!(
            html,
            "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
            class("form-error", opts),
            escape(error)
        );
    }

    html.push_str("</div>");
    html
}

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

    fn field(kind: FieldKind) -> Field<'static> {
        Field::new(kind, "title", "Title")
    }

    #[test]
    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
        // The payload from goingson's own CHRONIC-XSS regression test.
        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
        // The payload survives as text, which is the point: it is inert
        // because the quote that would have closed the attribute is encoded,
        // not because the words were filtered.
        assert!(!html.contains("\" onfocus"), "{html}");
        assert!(
            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
            "{html}"
        );
    }

    #[test]
    fn a_label_cannot_open_a_tag() {
        let mut f = field(FieldKind::Text);
        f.label = "<script>alert(1)</script>";
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(!html.contains("<script>"), "{html}");
        assert!(html.contains("&lt;script&gt;"), "{html}");
    }

    #[test]
    fn every_escaped_sink_is_covered_by_the_one_escaper() {
        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
        // The character `textContent` serialization leaves alone, which is why
        // the app needs two escapers and this needs one.
        assert!(escape("\"").contains("&quot;"));
    }

    #[test]
    fn markup_is_the_only_way_past_the_escaping() {
        let filling = Filling {
            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
            ..Filling::default()
        };
        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
        assert!(
            html.contains("<div class=\"recurrence-config\"></div>"),
            "{html}"
        );
    }

    #[test]
    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
        let mut f = field(FieldKind::Text);
        f.error = Some("Required");
        let opts = Emit::default();
        let html = field_html(&f, &Filling::default(), &opts);
        assert!(html.contains("aria-invalid=\"true\""), "{html}");
        // The selector the CSS side emits for exactly this state.
        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
        // And the group is marked too, which a renderer without descendant
        // selectors depends on.
        assert!(html.contains("has-error"), "{html}");
    }

    #[test]
    fn a_valid_field_claims_nothing_about_being_invalid() {
        let html = field_html(
            &field(FieldKind::Text),
            &Filling::default(),
            &Emit::default(),
        );
        assert!(!html.contains("aria-invalid"), "{html}");
        assert!(!html.contains("has-error"), "{html}");
    }

    #[test]
    fn the_hint_survives_an_error_arriving() {
        let mut f = field(FieldKind::Text);
        f.hint = Some("Keep it short");
        f.error = Some("Required");
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(
            html.contains("aria-describedby=\"title-hint title-error\""),
            "{html}"
        );
    }

    #[test]
    fn a_secret_never_carries_its_value_into_the_markup() {
        let filling = Filling::of(Value::Text("hunter2"));
        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
        assert!(!html.contains("hunter2"), "{html}");
        assert!(html.contains("type=\"password\""), "{html}");
    }

    #[test]
    fn a_hidden_field_is_the_input_and_nothing_else() {
        let filling = Filling::of(Value::Text("42"));
        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
    }

    #[test]
    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
        let html = field_html(
            &field(FieldKind::Checkbox),
            &Filling::of(Value::On(true)),
            &Emit::default(),
        );
        assert!(!html.contains("form-label"), "{html}");
        assert!(html.contains("checked"), "{html}");
        assert!(html.contains("<span>Title</span>"), "{html}");
    }

    #[test]
    fn a_select_keeps_a_value_no_option_carries() {
        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
        let f = Field::select("title", "Title", &options);
        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
        assert!(html.contains("data-unmatched=\"true\""), "{html}");
        // Selected, so the next save round-trips it rather than writing the
        // first option over the top of it.
        assert!(html.contains("<option value=\"10\" selected"), "{html}");
    }

    #[test]
    fn a_select_with_no_options_emits_an_empty_select() {
        // The description says a select with no options is sayable, because an
        // app whose option list has not loaded has exactly that. Emitting the
        // empty select reports it on screen rather than in a log.
        let f = Field::select("title", "Title", &[]);
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(html.contains("<select"), "{html}");
        assert!(!html.contains("<option"), "{html}");
    }

    #[test]
    fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
        // The association inverts, and getting it wrong is silent: a
        // `<label for>` aimed at a group points at no element, so the group
        // simply has no accessible name and nothing reports that.
        let options = [Choice::plain("copy"), Choice::plain("reference")];
        let f = Field::radio("storage", "Storage style", &options);
        let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());

        assert!(html.contains("id=\"storage-label\""), "{html}");
        assert!(!html.contains("for=\"storage\""), "{html}");
        assert!(html.contains("role=\"radiogroup\""), "{html}");
        assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
    }

    #[test]
    fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
        // One `name` is what makes them one answer rather than three; distinct
        // ids are what keep each `<label>` wrapping its own input.
        let options = [
            Choice::plain("copy"),
            Choice::plain("reference"),
            Choice::plain("link"),
        ];
        let f = Field::radio("storage", "Storage style", &options);
        let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());

        assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
        assert_eq!(html.matches(" checked").count(), 1, "{html}");
        assert!(
            html.contains("value=\"reference\" checked"),
            "the checked one is the one held: {html}"
        );
        for index in 0..3 {
            assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
        }
    }

    #[test]
    fn a_radio_group_carries_the_error_rather_than_any_one_option() {
        // What is wrong is the answer, not one of the alternatives, so marking
        // a single input invalid would say something false. Same reading
        // `Field::invalid` gives one level up.
        let options = [Choice::plain("copy"), Choice::plain("reference")];
        let f = Field {
            error: Some("Pick one."),
            hint: Some("Cannot be changed later."),
            ..Field::radio("storage", "Storage style", &options)
        };
        let html = field_html(&f, &Filling::default(), &Emit::default());

        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
        assert!(
            html.contains("aria-describedby=\"storage-hint storage-error\""),
            "{html}"
        );
        // The group is the element that carries them, so they land before the
        // first option rather than on it.
        let group = html.find("role=\"radiogroup\"").expect("group");
        let first = html.find("type=\"radio\"").expect("an option");
        assert!(group < first, "{html}");
    }

    #[test]
    fn a_compulsory_radio_group_marks_every_option() {
        // How HTML says a group is compulsory: the constraint reads as
        // satisfied when any one of them is checked.
        let options = [Choice::plain("copy"), Choice::plain("reference")];
        let f = Field {
            required: true,
            ..Field::radio("storage", "Storage style", &options)
        };
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert_eq!(html.matches(" required").count(), 2, "{html}");
    }

    #[test]
    fn a_radio_option_cannot_break_out_of_its_attribute() {
        // Values are `&str` and carry whatever the app put in them. The ids are
        // numbered rather than derived from the value for the same reason.
        let hostile = [Choice {
            value: "x\" onclick=alert(1) data-x=\"",
            label: "<script>alert(1)</script>",
        }];
        let f = Field::radio("storage", "Storage style", &hostile);
        let html = field_html(&f, &Filling::default(), &Emit::default());

        // The payload survives as text; what must not survive is the quote
        // that would end the attribute and let the rest of it become markup.
        assert!(html.contains("value=\"x&quot; onclick=alert(1)"), "{html}");
        assert!(!html.contains("<script>"), "{html}");
        assert!(html.contains("id=\"storage-0\""), "{html}");
    }

    #[test]
    fn a_radio_group_with_no_options_emits_an_empty_group() {
        // Same position the select takes, and the description's own.
        let f = Field::radio("storage", "Storage style", &[]);
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(html.contains("role=\"radiogroup\""), "{html}");
        assert!(!html.contains("type=\"radio\""), "{html}");
    }

    #[test]
    fn a_placeholder_comes_off_the_description_and_is_escaped() {
        // It arrived in `Filling` until makeover-layout 0.8.0 and was never
        // covered here; it is a value in an attribute like any other.
        let f = Field {
            placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
            ..field(FieldKind::Text)
        };
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(html.contains("placeholder=\""), "{html}");
        assert!(!html.contains("\" onfocus"), "{html}");
    }

    #[test]
    fn a_select_marks_the_option_that_matches() {
        let options = [Choice::plain("1"), Choice::plain("3")];
        let f = Field::select("title", "Title", &options);
        let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
        assert!(
            html.contains("<option value=\"3\" selected>3</option>"),
            "{html}"
        );
        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
        assert!(!html.contains("data-unmatched"), "{html}");
    }

    #[test]
    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
        let filling = Filling::of(Value::Text("two\nlines"));
        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
        assert!(html.contains(">two\nlines</textarea>"), "{html}");
    }

    #[test]
    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
        let opts = Emit {
            class_prefix: "mk-",
            ..Emit::default()
        };
        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
        assert!(html.contains("class=\"mk-form-group\""), "{html}");
        assert!(html.contains("class=\"mk-field\""), "{html}");
    }

    #[test]
    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
        let mut f = field(FieldKind::Text);
        f.extended = true;
        let html = field_html(&f, &Filling::default(), &Emit::default());
        assert!(html.contains("data-extended=\"true\""), "{html}");
    }

    /// The prefix scopes the id and leaves the name alone. Prefixing the name
    /// too would change what the form submits, which is the failure this pair
    /// of assertions exists to catch rather than describe.
    #[test]
    fn the_id_prefix_scopes_the_id_and_never_the_name() {
        let mut f = field(FieldKind::Text);
        f.hint = Some("Keep it short");
        f.error = Some("Required");
        let filling = Filling {
            id_prefix: Some("form-modal-task-edit"),
            ..Filling::default()
        };
        let html = field_html(&f, &filling, &Emit::default());

        assert!(
            html.contains(r#"id="form-modal-task-edit-title""#),
            "{html}"
        );
        assert!(html.contains(r#"name="title""#), "{html}");
        assert!(
            !html.contains(r#"name="form-modal-task-edit-title""#),
            "{html}"
        );

        // The label and both associations follow the id, or they point at
        // nothing once the same form is on screen twice.
        assert!(
            html.contains(r#"for="form-modal-task-edit-title""#),
            "{html}"
        );
        assert!(
            html.contains(
                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
            ),
            "{html}"
        );
        assert!(
            html.contains(r#"id="form-modal-task-edit-title-hint""#),
            "{html}"
        );
    }

    #[test]
    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
        let filling = Filling {
            value: Value::Text("42"),
            id_prefix: Some("scoped"),
            ..Filling::default()
        };
        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
    }

    /// These three exist so a touch keyboard and the platform's validation
    /// arrive with the field. Emitting text for any of them is the regression
    /// the variants were added to prevent, so the type is asserted directly.
    #[test]
    fn a_constraint_becomes_the_browsers_own_attribute() {
        // makeover-layout 0.11.0's model: the description carries the rule and
        // each renderer emits its host's idiom for it. Enforcement is still
        // whoever validated's, and arrives back as `error`.
        let html = field_html(
            &Field {
                max_length: Some(100),
                min: Some("1"),
                max: Some("240"),
                required: true,
                ..Field::new(FieldKind::Number, "minutes", "Minutes")
            },
            &Filling::default(),
            &Emit::default(),
        );
        assert!(html.contains(r#"maxlength="100""#));
        assert!(html.contains(r#"min="1""#));
        assert!(html.contains(r#"max="240""#));
        assert!(html.contains(" required"));
    }

    #[test]
    fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
        // The bound is text because it is only a number for some of the kinds
        // that take one; goingson's own sites are a duration and a datetime.
        let html = field_html(
            &Field {
                min: Some("2026-08-09T14:30"),
                ..Field::new(FieldKind::Text, "starts", "Starts")
            },
            &Filling::default(),
            &Emit::default(),
        );
        assert!(html.contains(r#"min="2026-08-09T14:30""#));
    }

    #[test]
    fn a_file_field_is_a_file_input() {
        // `844b5ae0`. It carries no `accept`, which is measured rather than
        // deferred: zero sites in either app.
        let html = field_html(
            &Field::new(FieldKind::File, "attachment", "Attachment"),
            &Filling::default(),
            &Emit::default(),
        );
        assert!(html.contains(r#"type="file""#));
        assert!(!html.contains("accept="));
        // And it never carries a value: a file input's value is not settable
        // from markup, and the browser refuses one that tries.
        assert!(!html.contains("value="));
    }

    #[test]
    fn the_typed_text_kinds_keep_their_input_type() {
        for (kind, expected) in [
            (FieldKind::Email, "email"),
            (FieldKind::Url, "url"),
            (FieldKind::Tel, "tel"),
        ] {
            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
            assert!(
                html.contains(&format!(r#"type="{expected}""#)),
                "{kind:?} emitted {html}"
            );
        }
    }

    #[test]
    fn no_prefix_leaves_the_id_as_the_name() {
        let html = field_html(
            &field(FieldKind::Text),
            &Filling::default(),
            &Emit::default(),
        );
        assert!(html.contains(r#"id="title" name="title""#), "{html}");
    }
}