makeover-webview 0.8.0

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
//! 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
//!
//! [`Field`] describes the field and not its contents, so three things arrive
//! from the renderer side in [`Filling`]: the current value, the options of a
//! select, and the placeholder. The first two are genuinely renderer state. The
//! third is user-facing text and belongs with `label` and `hint` in
//! makeover-layout; it lives here because that crate is published and adding a
//! field to `Field` is a breaking change, not because this is its home.

use crate::{Emit, class};
use makeover_layout::{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);

/// One option of a select.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Choice<'a> {
    /// What is submitted.
    pub value: &'a str,
    /// What is read.
    pub label: &'a str,
}

impl<'a> Choice<'a> {
    /// An option whose submitted value is also its label.
    #[must_use]
    pub const fn plain(value: &'a str) -> Self {
        Self {
            value,
            label: value,
        }
    }
}

/// What the field currently holds.
///
/// An enum rather than a bag of optional fields, on the same reasoning
/// [`makeover_layout::Depth`] is one: a select with no options and a checkbox
/// with a string value are both unsayable here, where a struct would let them
/// 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.
    Text(&'a str),
    /// The options of a select, and which of them is current.
    Chosen {
        /// Every option, in the order they are offered.
        options: &'a [Choice<'a>],
        /// The current value. Matched against each option's `value`.
        value: &'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) | Self::Chosen { value: 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>,
    /// Ghost text shown while the field is empty.
    pub placeholder: Option<&'a str>,
    /// 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,
            placeholder: None,
            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::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",
        // Select and Textarea are not inputs at all; they never reach here.
        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");
    }
    if field.invalid() {
        attrs.push_str(" aria-invalid=\"true\"");
    }

    // 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.
    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() {
        let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" "));
    }
    attrs
}

/// 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 = filling.placeholder.map_or_else(String::new, |text| {
        format!(" placeholder=\"{}\"", escape(text))
    });

    match field.kind {
        FieldKind::Textarea => format!(
            "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
            escape(filling.value.as_text())
        ),
        FieldKind::Select => {
            let options = match filling.value {
                Value::Chosen { options, value } => options_html(options, value),
                // Described as a select and filled as something else. Emitting
                // an empty select says so on screen rather than in a log.
                _ => String::new(),
            };
            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}>"
        ),
        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() {
        let _ = write!(
            html,
            "<label class=\"{}\" for=\"{id}\">{}</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 filling = Filling::of(Value::Chosen {
            options: &options,
            value: "10",
        });
        let html = field_html(&field(FieldKind::Select), &filling, &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_marks_the_option_that_matches() {
        let options = [Choice::plain("1"), Choice::plain("3")];
        let filling = Filling::of(Value::Chosen {
            options: &options,
            value: "3",
        });
        let html = field_html(&field(FieldKind::Select), &filling, &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 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}");
    }
}