Skip to main content

makeover_webview/
form.rs

1//! Phase B, the forms half: [`makeover_layout::Field`] rendered to HTML.
2//!
3//! # Why this emits strings
4//!
5//! Both webview apps build their markup as strings and hand it to `innerHTML`:
6//! goingson's `renderFormField` returns a template literal that fifteen call
7//! sites interpolate into larger literals, and Balanced Breakfast's builds
8//! nodes but appends them into the same string-built forms. Returning nodes
9//! would rewrite the surrounding templates as well, which makes it a migration
10//! rather than an adoption. So: strings, and the escaping comes with them.
11//!
12//! # Why one escaper is enough here
13//!
14//! goingson carries four escapers and 543 call sites that must pick between
15//! them, because `escapeHtml` is built on `textContent` serialization and
16//! **`textContent` refuses to encode `"`**. That is what makes it unsound in an
17//! attribute, and it is the whole reason the choice exists. Its `escape.js`
18//! records the finding as the CHRONIC-XSS seal, and its test suite has a gate
19//! keeping the unsafe one off the namespace.
20//!
21//! [`escape`] here is not built on that, so it encodes the quote along with
22//! everything else, which makes one function sound in both sinks. The four-way
23//! choice does not move into Rust: it disappears. Nothing in this module hands
24//! an unescaped value to the output except through [`Markup`], which a caller
25//! has to name.
26//!
27//! # What the description does not carry
28//!
29//! One thing: the **current value**, which arrives in [`Filling`].
30//!
31//! It used to be three. Writing this emitter is what found them, and the other
32//! two turned out not to be renderer state at all — the placeholder is
33//! user-facing text that sits with `label` and `hint`, and a select's options
34//! are needed by every renderer, which is how each of them ends up inventing a
35//! near-miss of the same struct. Both moved down into `makeover-layout` 0.8.0,
36//! `Choice` included, and this crate reads them off [`Field`] now.
37//!
38//! The value stays, and it is not a leftover. A webview reads it back out of
39//! the DOM, an immediate-mode renderer writes through a `&mut`, and a terminal
40//! keeps an edit buffer; a description carrying it would have to carry a way to
41//! write it back, at which point it is a form model.
42
43use crate::{Emit, class};
44use makeover_layout::{Choice, Field, FieldKind};
45use std::fmt::Write as _;
46
47/// A string that is already markup, and is emitted without escaping.
48///
49/// The one hole in the escaping, and it has to be named to be used. goingson
50/// has two live callers that need it, both passing a recurrence-config block
51/// built elsewhere, and both would otherwise have their markup rendered as
52/// visible angle brackets. A caller constructing this is stating that the
53/// contents are trusted; nothing here can check that for them.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct Markup<'a>(pub &'a str);
56
57/// What the field currently holds.
58///
59/// An enum rather than a bag of optional fields, on the same reasoning
60/// [`makeover_layout::Depth`] is one: a checkbox holding a string is unsayable
61/// here, where a struct would let it be said and then have to cope.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63pub enum Value<'a> {
64    /// Nothing yet.
65    #[default]
66    Absent,
67    /// The value of anything that takes typed text, a select included: what a
68    /// select holds is the `value` of one of [`Field::options`]'s
69    /// [`Choice`]s.
70    ///
71    /// It carried the options too until makeover-layout 0.8.0 moved them onto
72    /// the field, which collapsed a `Chosen { options, value }` variant into
73    /// this one. `makeover-immediate` arrived at the same single-variant shape
74    /// on its own, from the other direction.
75    Text(&'a str),
76    /// A checkbox, on or off.
77    On(bool),
78}
79
80impl<'a> Value<'a> {
81    /// The value as text, for the kinds that submit one.
82    const fn as_text(&self) -> &'a str {
83        match self {
84            Self::Text(text) => text,
85            Self::Absent | Self::On(_) => "",
86        }
87    }
88}
89
90/// Everything about the field that the description does not carry.
91#[derive(Debug, Clone, Copy, Default)]
92pub struct Filling<'a> {
93    /// What the field holds now.
94    pub value: Value<'a>,
95    /// Markup appended inside the group, after the hint. Not escaped.
96    pub trailing: Option<Markup<'a>>,
97    /// Scopes the `id` attributes to one instance of the form.
98    ///
99    /// The field's `name` is what the value submits under and is the same
100    /// wherever the form appears; its `id` has to be unique in the document,
101    /// and those two facts stop agreeing the moment a form appears twice.
102    /// goingson hits this directly: its new-task and edit-task modals are the
103    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
104    /// `label for` and `aria-describedby` pointing at the right control.
105    ///
106    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
107    /// `name`, which would change what the form submits.
108    pub id_prefix: Option<&'a str>,
109}
110
111impl<'a> Filling<'a> {
112    /// A filling that carries a value and nothing else.
113    #[must_use]
114    pub const fn of(value: Value<'a>) -> Self {
115        Self {
116            value,
117            trailing: None,
118            id_prefix: None,
119        }
120    }
121
122    /// The document-unique id for a field of this name.
123    fn id_for(&self, name: &str) -> String {
124        match self.id_prefix {
125            Some(prefix) => format!("{}-{}", escape(prefix), escape(name)),
126            None => escape(name),
127        }
128    }
129}
130
131/// Encode the five characters that let a value stop being a value.
132///
133/// Sound in element text and in a double-quoted attribute alike, which is the
134/// property `textContent`-based escaping cannot have. Both sinks are covered by
135/// one function so that no call site has to choose, here or downstream.
136#[must_use]
137pub fn escape(text: &str) -> String {
138    let mut out = String::with_capacity(text.len());
139    for ch in text.chars() {
140        match ch {
141            '&' => out.push_str("&amp;"),
142            '<' => out.push_str("&lt;"),
143            '>' => out.push_str("&gt;"),
144            '"' => out.push_str("&quot;"),
145            '\'' => out.push_str("&#39;"),
146            other => out.push(other),
147        }
148    }
149    out
150}
151
152/// The `type` an input takes for a kind.
153///
154/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
155const fn input_type(kind: FieldKind) -> &'static str {
156    match kind {
157        FieldKind::Secret => "password",
158        FieldKind::Number => "number",
159        FieldKind::Checkbox => "checkbox",
160        FieldKind::File => "file",
161        FieldKind::Hidden => "hidden",
162        // Not decoration. Each of these changes the keyboard a touch device
163        // offers and turns on the platform's own validation, which is why the
164        // description names them apart from text rather than letting the app
165        // pass an HTML type through.
166        FieldKind::Email => "email",
167        FieldKind::Url => "url",
168        FieldKind::Tel => "tel",
169        // The same argument, and it buys more here than anywhere else in this
170        // list: a native picker as well as the keyboard and the validation.
171        // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
172        // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
173        FieldKind::Date => "date",
174        FieldKind::DateTime => "datetime-local",
175        FieldKind::Radio => "radio",
176        // Select and Textarea are not inputs at all; they never reach here.
177        // Radio is one, but it is emitted once per option by `radio_html` and
178        // so does not reach here either.
179        FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
180        // A kind added to the description since this renderer was built. Text
181        // accepts any value the others would, so it degrades rather than
182        // dropping the field.
183        _ => "text",
184    }
185}
186
187/// The attributes every visible control carries, error state included.
188///
189/// `aria-invalid` is the whole reason the error state is readable at all: the
190/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
191/// than on a class, so a control rendered already-invalid without it is styled
192/// as if nothing were wrong. goingson's runtime validation path sets the
193/// attribute and its initial render does not, which is exactly the drift one
194/// emitter removes.
195/// `id` and `name` arrive separately because they are not the same fact. The
196/// name is what submits and is fixed by the description; the id has to be
197/// unique in the document and so carries [`Filling::id_prefix`] when a form
198/// appears more than once.
199fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
200    let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
201    if field.required {
202        attrs.push_str(" required");
203    }
204    // makeover-layout 0.11.0's constraints. The description carries the rule and
205    // this emits the browser's idiom for it, which is the model `required` has
206    // been using since before the crate wrote down that it carried none.
207    // Enforcement is still whoever validated's, and arrives back as `error`.
208    if let Some(limit) = field.max_length {
209        let _ = write!(attrs, " maxlength=\"{limit}\"");
210    }
211    if let Some(min) = field.min {
212        let _ = write!(attrs, " min=\"{}\"", escape(min));
213    }
214    if let Some(max) = field.max {
215        let _ = write!(attrs, " max=\"{}\"", escape(max));
216    }
217    if field.invalid() {
218        attrs.push_str(" aria-invalid=\"true\"");
219    }
220
221    attrs.push_str(&described_by(field, id));
222    attrs
223}
224
225/// The `aria-describedby` naming whatever of the hint and the error exist.
226///
227/// Both associations, in the order they are useful: the standing help, then
228/// what is currently wrong. goingson's runtime path points describedby at the
229/// error alone and drops the hint association it never made in the first place;
230/// naming both here means the hint survives an error appearing.
231///
232/// Its own function because a radio group carries it on the group rather than
233/// on a control, and one reading of "what describes this field" is the point.
234fn described_by(field: &Field<'_>, id: &str) -> String {
235    let mut described = Vec::new();
236    if field.hint.is_some() {
237        described.push(format!("{id}-hint"));
238    }
239    if field.error.is_some() {
240        described.push(format!("{id}-error"));
241    }
242    if described.is_empty() {
243        return String::new();
244    }
245    format!(" aria-describedby=\"{}\"", described.join(" "))
246}
247
248/// Whether the field's control is a set of elements rather than one.
249///
250/// A DOM concern rather than a description one, which is why it is decided here
251/// and not in `makeover-layout`: `for` and `id` are an HTML association and
252/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
253/// points at nothing, because no single element carries the group's id, so the
254/// association has to invert — the label takes an id and the group names itself
255/// with `aria-labelledby`.
256const fn is_group_control(kind: FieldKind) -> bool {
257    matches!(kind, FieldKind::Radio)
258}
259
260/// A radio group: the options as sibling inputs sharing one `name`.
261///
262/// The group carries the error state and the descriptions, and the inputs carry
263/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
264/// down: marking a single input invalid would say the wrong thing, since what
265/// is wrong is the answer to the question and not one of the alternatives.
266///
267/// Ids are numbered rather than built from the option values, which can hold
268/// anything a `&str` can — spaces and quotes included — and would otherwise
269/// have to be slugged into something unique by a rule this crate would then own.
270///
271/// `required` lands on every input, which is how HTML says a group is
272/// compulsory: the constraint is satisfied when any one of them is checked.
273fn radio_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
274    let id = filling.id_for(field.name);
275    let value = filling.value.as_text();
276    let name = escape(field.name);
277
278    let mut html = format!(
279        "<div class=\"{}\" role=\"radiogroup\"",
280        class("form-radio-group", opts)
281    );
282    let _ = write!(html, " aria-labelledby=\"{id}-label\"");
283    if field.invalid() {
284        html.push_str(" aria-invalid=\"true\"");
285    }
286    html.push_str(&described_by(field, &id));
287    html.push('>');
288
289    // A group described with no options emits an empty group, for the reason
290    // `Field::options` gives: an app whose option list has not loaded has
291    // exactly that, and an empty group says so on screen rather than in a log.
292    for (index, opt) in field.options.iter().enumerate() {
293        let checked = if opt.value == value { " checked" } else { "" };
294        let required = if field.required { " required" } else { "" };
295        let _ = write!(
296            html,
297            "<label class=\"{}\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" \
298             value=\"{}\"{checked}{required}><span>{}</span></label>",
299            class("form-radio-label", opts),
300            escape(opt.value),
301            escape(opt.label)
302        );
303    }
304
305    html.push_str("</div>");
306    html
307}
308
309/// The options of a select, with an unmatched current value carried as its own.
310///
311/// A select handed a value no option carries renders with nothing selected, the
312/// browser falls back to the first option, and the next save writes a value
313/// nobody chose. goingson hit exactly that with a backup-retention default of
314/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
315/// here so the second app gets it without hitting the bug first.
316fn options_html(options: &[Choice<'_>], value: &str) -> String {
317    let mut html = String::new();
318    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
319        let escaped = escape(value);
320        let _ = write!(
321            html,
322            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
323        );
324    }
325    for opt in options {
326        let selected = if opt.value == value { " selected" } else { "" };
327        let _ = write!(
328            html,
329            "<option value=\"{}\"{selected}>{}</option>",
330            escape(opt.value),
331            escape(opt.label)
332        );
333    }
334    html
335}
336
337/// The control itself, without its label, hint or error.
338fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
339    let id = filling.id_for(field.name);
340    let attrs = control_attributes(field, &id, field.name);
341    let field_class = class("field", opts);
342    let placeholder = field.placeholder.map_or_else(String::new, |text| {
343        format!(" placeholder=\"{}\"", escape(text))
344    });
345
346    match field.kind {
347        FieldKind::Radio => radio_html(field, filling, opts),
348        FieldKind::Textarea => format!(
349            "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
350            escape(filling.value.as_text())
351        ),
352        FieldKind::Select => {
353            // A select described with no options emits an empty select, which
354            // says so on screen rather than in a log. That is the description's
355            // own position on `Field::options`, not a fallback invented here.
356            let options = options_html(field.options, filling.value.as_text());
357            format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
358        }
359        FieldKind::Checkbox => {
360            let checked = if matches!(filling.value, Value::On(true)) {
361                " checked"
362            } else {
363                ""
364            };
365            format!(
366                "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
367                class("form-checkbox-label", opts),
368                escape(field.label)
369            )
370        }
371        // A secret never carries its value into the markup. `FieldKind::secret`
372        // is documented as a value that must not be round-tripped through
373        // anything that might persist it, and the DOM is such a thing: it is
374        // read by every extension on the page and is the first thing a crash
375        // reporter serialises. Neither app pre-fills one today, so this costs
376        // nothing and closes the door before something does.
377        FieldKind::Secret => {
378            format!("<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>")
379        }
380        // A file input carries no value, and this is the browser's rule rather
381        // than a preference: setting one from markup is refused, because a page
382        // that could preselect a path could read a file the user never offered.
383        // Nothing upstream needs to know, which is why the exception is here.
384        FieldKind::File => {
385            format!("<input type=\"file\" class=\"{field_class}\"{attrs}>")
386        }
387        kind => format!(
388            "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
389            input_type(kind),
390            escape(filling.value.as_text())
391        ),
392    }
393}
394
395/// One field, as the group the app drops into its form.
396///
397/// The shape is goingson's, down to the class names, so adoption there deletes
398/// `renderFormField` rather than restyling anything. That is also why the class
399/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
400/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
401/// emits only what it can generate from the description. Whether they should
402/// move into the description is the next question this raises, not one it
403/// answers.
404///
405/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
406/// nothing drawn, which is what [`FieldKind::visible`] means.
407///
408/// The error marks the group as well as the control. That is
409/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
410/// cannot find the group from the message, so the group has to be told.
411///
412/// ```
413/// use makeover_layout::{Field, FieldKind};
414/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
415///
416/// let field = Field::new(FieldKind::Text, "title", "Title");
417/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
418///
419/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
420/// assert!(html.contains(r#"value="Ship it""#));
421/// ```
422#[must_use]
423pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
424    let id = filling.id_for(field.name);
425
426    if !field.kind.visible() {
427        // Name only, no id: a hidden field is never pointed at by a label or a
428        // description, so the one attribute it needs is the one that submits.
429        return format!(
430            "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
431            escape(field.name),
432            escape(filling.value.as_text())
433        );
434    }
435
436    let mut html = format!("<div class=\"{}", class("form-group", opts));
437    if field.invalid() {
438        html.push_str(" has-error");
439    }
440    if field.extended {
441        // The disclosure that hides these is a property of the form, not of the
442        // field, so the field is marked and the app opens or closes the group.
443        html.push_str("\" data-extended=\"true");
444    }
445    html.push_str("\">");
446
447    // A checkbox labels itself, on the right of the box. Both apps special-case
448    // this inline today, which is the tell that it belongs in the description;
449    // `FieldKind::labels_itself` is where it went.
450    if !field.kind.labels_itself() {
451        // A group control is named *by* its label rather than pointing at it,
452        // so the two carry opposite halves of the association. See
453        // `is_group_control`.
454        let association = if is_group_control(field.kind) {
455            format!(" id=\"{id}-label\"")
456        } else {
457            format!(" for=\"{id}\"")
458        };
459        let _ = write!(
460            html,
461            "<label class=\"{}\"{association}>{}</label>",
462            class("form-label", opts),
463            escape(field.label)
464        );
465    }
466
467    html.push_str(&control_html(field, filling, opts));
468
469    if let Some(hint) = field.hint {
470        let _ = write!(
471            html,
472            "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
473            class("form-hint", opts),
474            escape(hint)
475        );
476    }
477    if let Some(Markup(markup)) = filling.trailing {
478        html.push_str(markup);
479    }
480    if let Some(error) = field.error {
481        let _ = write!(
482            html,
483            "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
484            class("form-error", opts),
485            escape(error)
486        );
487    }
488
489    html.push_str("</div>");
490    html
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    fn field(kind: FieldKind) -> Field<'static> {
498        Field::new(kind, "title", "Title")
499    }
500
501    #[test]
502    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
503        // The payload from goingson's own CHRONIC-XSS regression test.
504        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
505        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
506        // The payload survives as text, which is the point: it is inert
507        // because the quote that would have closed the attribute is encoded,
508        // not because the words were filtered.
509        assert!(!html.contains("\" onfocus"), "{html}");
510        assert!(
511            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
512            "{html}"
513        );
514    }
515
516    #[test]
517    fn a_label_cannot_open_a_tag() {
518        let mut f = field(FieldKind::Text);
519        f.label = "<script>alert(1)</script>";
520        let html = field_html(&f, &Filling::default(), &Emit::default());
521        assert!(!html.contains("<script>"), "{html}");
522        assert!(html.contains("&lt;script&gt;"), "{html}");
523    }
524
525    #[test]
526    fn every_escaped_sink_is_covered_by_the_one_escaper() {
527        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
528        // The character `textContent` serialization leaves alone, which is why
529        // the app needs two escapers and this needs one.
530        assert!(escape("\"").contains("&quot;"));
531    }
532
533    #[test]
534    fn markup_is_the_only_way_past_the_escaping() {
535        let filling = Filling {
536            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
537            ..Filling::default()
538        };
539        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
540        assert!(
541            html.contains("<div class=\"recurrence-config\"></div>"),
542            "{html}"
543        );
544    }
545
546    #[test]
547    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
548        let mut f = field(FieldKind::Text);
549        f.error = Some("Required");
550        let opts = Emit::default();
551        let html = field_html(&f, &Filling::default(), &opts);
552        assert!(html.contains("aria-invalid=\"true\""), "{html}");
553        // The selector the CSS side emits for exactly this state.
554        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
555        // And the group is marked too, which a renderer without descendant
556        // selectors depends on.
557        assert!(html.contains("has-error"), "{html}");
558    }
559
560    #[test]
561    fn a_valid_field_claims_nothing_about_being_invalid() {
562        let html = field_html(
563            &field(FieldKind::Text),
564            &Filling::default(),
565            &Emit::default(),
566        );
567        assert!(!html.contains("aria-invalid"), "{html}");
568        assert!(!html.contains("has-error"), "{html}");
569    }
570
571    #[test]
572    fn the_hint_survives_an_error_arriving() {
573        let mut f = field(FieldKind::Text);
574        f.hint = Some("Keep it short");
575        f.error = Some("Required");
576        let html = field_html(&f, &Filling::default(), &Emit::default());
577        assert!(
578            html.contains("aria-describedby=\"title-hint title-error\""),
579            "{html}"
580        );
581    }
582
583    #[test]
584    fn a_secret_never_carries_its_value_into_the_markup() {
585        let filling = Filling::of(Value::Text("hunter2"));
586        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
587        assert!(!html.contains("hunter2"), "{html}");
588        assert!(html.contains("type=\"password\""), "{html}");
589    }
590
591    #[test]
592    fn a_hidden_field_is_the_input_and_nothing_else() {
593        let filling = Filling::of(Value::Text("42"));
594        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
595        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
596    }
597
598    #[test]
599    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
600        let html = field_html(
601            &field(FieldKind::Checkbox),
602            &Filling::of(Value::On(true)),
603            &Emit::default(),
604        );
605        assert!(!html.contains("form-label"), "{html}");
606        assert!(html.contains("checked"), "{html}");
607        assert!(html.contains("<span>Title</span>"), "{html}");
608    }
609
610    #[test]
611    fn a_select_keeps_a_value_no_option_carries() {
612        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
613        let f = Field::select("title", "Title", &options);
614        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
615        assert!(html.contains("data-unmatched=\"true\""), "{html}");
616        // Selected, so the next save round-trips it rather than writing the
617        // first option over the top of it.
618        assert!(html.contains("<option value=\"10\" selected"), "{html}");
619    }
620
621    #[test]
622    fn a_select_with_no_options_emits_an_empty_select() {
623        // The description says a select with no options is sayable, because an
624        // app whose option list has not loaded has exactly that. Emitting the
625        // empty select reports it on screen rather than in a log.
626        let f = Field::select("title", "Title", &[]);
627        let html = field_html(&f, &Filling::default(), &Emit::default());
628        assert!(html.contains("<select"), "{html}");
629        assert!(!html.contains("<option"), "{html}");
630    }
631
632    #[test]
633    fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
634        // The association inverts, and getting it wrong is silent: a
635        // `<label for>` aimed at a group points at no element, so the group
636        // simply has no accessible name and nothing reports that.
637        let options = [Choice::plain("copy"), Choice::plain("reference")];
638        let f = Field::radio("storage", "Storage style", &options);
639        let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
640
641        assert!(html.contains("id=\"storage-label\""), "{html}");
642        assert!(!html.contains("for=\"storage\""), "{html}");
643        assert!(html.contains("role=\"radiogroup\""), "{html}");
644        assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
645    }
646
647    #[test]
648    fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
649        // One `name` is what makes them one answer rather than three; distinct
650        // ids are what keep each `<label>` wrapping its own input.
651        let options = [
652            Choice::plain("copy"),
653            Choice::plain("reference"),
654            Choice::plain("link"),
655        ];
656        let f = Field::radio("storage", "Storage style", &options);
657        let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
658
659        assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
660        assert_eq!(html.matches(" checked").count(), 1, "{html}");
661        assert!(
662            html.contains("value=\"reference\" checked"),
663            "the checked one is the one held: {html}"
664        );
665        for index in 0..3 {
666            assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
667        }
668    }
669
670    #[test]
671    fn a_radio_group_carries_the_error_rather_than_any_one_option() {
672        // What is wrong is the answer, not one of the alternatives, so marking
673        // a single input invalid would say something false. Same reading
674        // `Field::invalid` gives one level up.
675        let options = [Choice::plain("copy"), Choice::plain("reference")];
676        let f = Field {
677            error: Some("Pick one."),
678            hint: Some("Cannot be changed later."),
679            ..Field::radio("storage", "Storage style", &options)
680        };
681        let html = field_html(&f, &Filling::default(), &Emit::default());
682
683        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
684        assert!(
685            html.contains("aria-describedby=\"storage-hint storage-error\""),
686            "{html}"
687        );
688        // The group is the element that carries them, so they land before the
689        // first option rather than on it.
690        let group = html.find("role=\"radiogroup\"").expect("group");
691        let first = html.find("type=\"radio\"").expect("an option");
692        assert!(group < first, "{html}");
693    }
694
695    #[test]
696    fn a_compulsory_radio_group_marks_every_option() {
697        // How HTML says a group is compulsory: the constraint reads as
698        // satisfied when any one of them is checked.
699        let options = [Choice::plain("copy"), Choice::plain("reference")];
700        let f = Field {
701            required: true,
702            ..Field::radio("storage", "Storage style", &options)
703        };
704        let html = field_html(&f, &Filling::default(), &Emit::default());
705        assert_eq!(html.matches(" required").count(), 2, "{html}");
706    }
707
708    #[test]
709    fn a_radio_option_cannot_break_out_of_its_attribute() {
710        // Values are `&str` and carry whatever the app put in them. The ids are
711        // numbered rather than derived from the value for the same reason.
712        let hostile = [Choice {
713            value: "x\" onclick=alert(1) data-x=\"",
714            label: "<script>alert(1)</script>",
715        }];
716        let f = Field::radio("storage", "Storage style", &hostile);
717        let html = field_html(&f, &Filling::default(), &Emit::default());
718
719        // The payload survives as text; what must not survive is the quote
720        // that would end the attribute and let the rest of it become markup.
721        assert!(html.contains("value=\"x&quot; onclick=alert(1)"), "{html}");
722        assert!(!html.contains("<script>"), "{html}");
723        assert!(html.contains("id=\"storage-0\""), "{html}");
724    }
725
726    #[test]
727    fn a_radio_group_with_no_options_emits_an_empty_group() {
728        // Same position the select takes, and the description's own.
729        let f = Field::radio("storage", "Storage style", &[]);
730        let html = field_html(&f, &Filling::default(), &Emit::default());
731        assert!(html.contains("role=\"radiogroup\""), "{html}");
732        assert!(!html.contains("type=\"radio\""), "{html}");
733    }
734
735    #[test]
736    fn a_placeholder_comes_off_the_description_and_is_escaped() {
737        // It arrived in `Filling` until makeover-layout 0.8.0 and was never
738        // covered here; it is a value in an attribute like any other.
739        let f = Field {
740            placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
741            ..field(FieldKind::Text)
742        };
743        let html = field_html(&f, &Filling::default(), &Emit::default());
744        assert!(html.contains("placeholder=\""), "{html}");
745        assert!(!html.contains("\" onfocus"), "{html}");
746    }
747
748    #[test]
749    fn a_select_marks_the_option_that_matches() {
750        let options = [Choice::plain("1"), Choice::plain("3")];
751        let f = Field::select("title", "Title", &options);
752        let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
753        assert!(
754            html.contains("<option value=\"3\" selected>3</option>"),
755            "{html}"
756        );
757        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
758        assert!(!html.contains("data-unmatched"), "{html}");
759    }
760
761    #[test]
762    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
763        let filling = Filling::of(Value::Text("two\nlines"));
764        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
765        assert!(html.contains(">two\nlines</textarea>"), "{html}");
766    }
767
768    #[test]
769    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
770        let opts = Emit {
771            class_prefix: "mk-",
772            ..Emit::default()
773        };
774        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
775        assert!(html.contains("class=\"mk-form-group\""), "{html}");
776        assert!(html.contains("class=\"mk-field\""), "{html}");
777    }
778
779    #[test]
780    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
781        let mut f = field(FieldKind::Text);
782        f.extended = true;
783        let html = field_html(&f, &Filling::default(), &Emit::default());
784        assert!(html.contains("data-extended=\"true\""), "{html}");
785    }
786
787    /// The prefix scopes the id and leaves the name alone. Prefixing the name
788    /// too would change what the form submits, which is the failure this pair
789    /// of assertions exists to catch rather than describe.
790    #[test]
791    fn the_id_prefix_scopes_the_id_and_never_the_name() {
792        let mut f = field(FieldKind::Text);
793        f.hint = Some("Keep it short");
794        f.error = Some("Required");
795        let filling = Filling {
796            id_prefix: Some("form-modal-task-edit"),
797            ..Filling::default()
798        };
799        let html = field_html(&f, &filling, &Emit::default());
800
801        assert!(
802            html.contains(r#"id="form-modal-task-edit-title""#),
803            "{html}"
804        );
805        assert!(html.contains(r#"name="title""#), "{html}");
806        assert!(
807            !html.contains(r#"name="form-modal-task-edit-title""#),
808            "{html}"
809        );
810
811        // The label and both associations follow the id, or they point at
812        // nothing once the same form is on screen twice.
813        assert!(
814            html.contains(r#"for="form-modal-task-edit-title""#),
815            "{html}"
816        );
817        assert!(
818            html.contains(
819                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
820            ),
821            "{html}"
822        );
823        assert!(
824            html.contains(r#"id="form-modal-task-edit-title-hint""#),
825            "{html}"
826        );
827    }
828
829    #[test]
830    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
831        let filling = Filling {
832            value: Value::Text("42"),
833            id_prefix: Some("scoped"),
834            ..Filling::default()
835        };
836        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
837        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
838    }
839
840    /// These three exist so a touch keyboard and the platform's validation
841    /// arrive with the field. Emitting text for any of them is the regression
842    /// the variants were added to prevent, so the type is asserted directly.
843    #[test]
844    fn a_constraint_becomes_the_browsers_own_attribute() {
845        // makeover-layout 0.11.0's model: the description carries the rule and
846        // each renderer emits its host's idiom for it. Enforcement is still
847        // whoever validated's, and arrives back as `error`.
848        let html = field_html(
849            &Field {
850                max_length: Some(100),
851                min: Some("1"),
852                max: Some("240"),
853                required: true,
854                ..Field::new(FieldKind::Number, "minutes", "Minutes")
855            },
856            &Filling::default(),
857            &Emit::default(),
858        );
859        assert!(html.contains(r#"maxlength="100""#));
860        assert!(html.contains(r#"min="1""#));
861        assert!(html.contains(r#"max="240""#));
862        assert!(html.contains(" required"));
863    }
864
865    #[test]
866    fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
867        // The bound is text because it is only a number for some of the kinds
868        // that take one; goingson's own sites are a duration and a datetime.
869        let html = field_html(
870            &Field {
871                min: Some("2026-08-09T14:30"),
872                ..Field::new(FieldKind::Text, "starts", "Starts")
873            },
874            &Filling::default(),
875            &Emit::default(),
876        );
877        assert!(html.contains(r#"min="2026-08-09T14:30""#));
878    }
879
880    #[test]
881    fn a_file_field_is_a_file_input() {
882        // `844b5ae0`. It carries no `accept`, which is measured rather than
883        // deferred: zero sites in either app.
884        let html = field_html(
885            &Field::new(FieldKind::File, "attachment", "Attachment"),
886            &Filling::default(),
887            &Emit::default(),
888        );
889        assert!(html.contains(r#"type="file""#));
890        assert!(!html.contains("accept="));
891        // And it never carries a value: a file input's value is not settable
892        // from markup, and the browser refuses one that tries.
893        assert!(!html.contains("value="));
894    }
895
896    #[test]
897    fn the_typed_text_kinds_keep_their_input_type() {
898        for (kind, expected) in [
899            (FieldKind::Email, "email"),
900            (FieldKind::Url, "url"),
901            (FieldKind::Tel, "tel"),
902            (FieldKind::Date, "date"),
903            (FieldKind::DateTime, "datetime-local"),
904        ] {
905            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
906            assert!(
907                html.contains(&format!(r#"type="{expected}""#)),
908                "{kind:?} emitted {html}"
909            );
910        }
911    }
912
913    #[test]
914    fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
915        // The regression this closes: described as text with a hint reading
916        // "YYYY-MM-DD", which loses the picker, the platform's validation and
917        // the touch keyboard, and asks prose to do all three.
918        for kind in [FieldKind::Date, FieldKind::DateTime] {
919            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
920            assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
921        }
922    }
923
924    #[test]
925    fn no_prefix_leaves_the_id_as_the_name() {
926        let html = field_html(
927            &field(FieldKind::Text),
928            &Filling::default(),
929            &Emit::default(),
930        );
931        assert!(html.contains(r#"id="title" name="title""#), "{html}");
932    }
933}