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        FieldKind::Radio => "radio",
170        // Select and Textarea are not inputs at all; they never reach here.
171        // Radio is one, but it is emitted once per option by `radio_html` and
172        // so does not reach here either.
173        FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
174        // A kind added to the description since this renderer was built. Text
175        // accepts any value the others would, so it degrades rather than
176        // dropping the field.
177        _ => "text",
178    }
179}
180
181/// The attributes every visible control carries, error state included.
182///
183/// `aria-invalid` is the whole reason the error state is readable at all: the
184/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
185/// than on a class, so a control rendered already-invalid without it is styled
186/// as if nothing were wrong. goingson's runtime validation path sets the
187/// attribute and its initial render does not, which is exactly the drift one
188/// emitter removes.
189/// `id` and `name` arrive separately because they are not the same fact. The
190/// name is what submits and is fixed by the description; the id has to be
191/// unique in the document and so carries [`Filling::id_prefix`] when a form
192/// appears more than once.
193fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
194    let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
195    if field.required {
196        attrs.push_str(" required");
197    }
198    // makeover-layout 0.11.0's constraints. The description carries the rule and
199    // this emits the browser's idiom for it, which is the model `required` has
200    // been using since before the crate wrote down that it carried none.
201    // Enforcement is still whoever validated's, and arrives back as `error`.
202    if let Some(limit) = field.max_length {
203        let _ = write!(attrs, " maxlength=\"{limit}\"");
204    }
205    if let Some(min) = field.min {
206        let _ = write!(attrs, " min=\"{}\"", escape(min));
207    }
208    if let Some(max) = field.max {
209        let _ = write!(attrs, " max=\"{}\"", escape(max));
210    }
211    if field.invalid() {
212        attrs.push_str(" aria-invalid=\"true\"");
213    }
214
215    attrs.push_str(&described_by(field, id));
216    attrs
217}
218
219/// The `aria-describedby` naming whatever of the hint and the error exist.
220///
221/// Both associations, in the order they are useful: the standing help, then
222/// what is currently wrong. goingson's runtime path points describedby at the
223/// error alone and drops the hint association it never made in the first place;
224/// naming both here means the hint survives an error appearing.
225///
226/// Its own function because a radio group carries it on the group rather than
227/// on a control, and one reading of "what describes this field" is the point.
228fn described_by(field: &Field<'_>, id: &str) -> String {
229    let mut described = Vec::new();
230    if field.hint.is_some() {
231        described.push(format!("{id}-hint"));
232    }
233    if field.error.is_some() {
234        described.push(format!("{id}-error"));
235    }
236    if described.is_empty() {
237        return String::new();
238    }
239    format!(" aria-describedby=\"{}\"", described.join(" "))
240}
241
242/// Whether the field's control is a set of elements rather than one.
243///
244/// A DOM concern rather than a description one, which is why it is decided here
245/// and not in `makeover-layout`: `for` and `id` are an HTML association and
246/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
247/// points at nothing, because no single element carries the group's id, so the
248/// association has to invert — the label takes an id and the group names itself
249/// with `aria-labelledby`.
250const fn is_group_control(kind: FieldKind) -> bool {
251    matches!(kind, FieldKind::Radio)
252}
253
254/// A radio group: the options as sibling inputs sharing one `name`.
255///
256/// The group carries the error state and the descriptions, and the inputs carry
257/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
258/// down: marking a single input invalid would say the wrong thing, since what
259/// is wrong is the answer to the question and not one of the alternatives.
260///
261/// Ids are numbered rather than built from the option values, which can hold
262/// anything a `&str` can — spaces and quotes included — and would otherwise
263/// have to be slugged into something unique by a rule this crate would then own.
264///
265/// `required` lands on every input, which is how HTML says a group is
266/// compulsory: the constraint is satisfied when any one of them is checked.
267fn radio_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
268    let id = filling.id_for(field.name);
269    let value = filling.value.as_text();
270    let name = escape(field.name);
271
272    let mut html = format!(
273        "<div class=\"{}\" role=\"radiogroup\"",
274        class("form-radio-group", opts)
275    );
276    let _ = write!(html, " aria-labelledby=\"{id}-label\"");
277    if field.invalid() {
278        html.push_str(" aria-invalid=\"true\"");
279    }
280    html.push_str(&described_by(field, &id));
281    html.push('>');
282
283    // A group described with no options emits an empty group, for the reason
284    // `Field::options` gives: an app whose option list has not loaded has
285    // exactly that, and an empty group says so on screen rather than in a log.
286    for (index, opt) in field.options.iter().enumerate() {
287        let checked = if opt.value == value { " checked" } else { "" };
288        let required = if field.required { " required" } else { "" };
289        let _ = write!(
290            html,
291            "<label class=\"{}\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" \
292             value=\"{}\"{checked}{required}><span>{}</span></label>",
293            class("form-radio-label", opts),
294            escape(opt.value),
295            escape(opt.label)
296        );
297    }
298
299    html.push_str("</div>");
300    html
301}
302
303/// The options of a select, with an unmatched current value carried as its own.
304///
305/// A select handed a value no option carries renders with nothing selected, the
306/// browser falls back to the first option, and the next save writes a value
307/// nobody chose. goingson hit exactly that with a backup-retention default of
308/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
309/// here so the second app gets it without hitting the bug first.
310fn options_html(options: &[Choice<'_>], value: &str) -> String {
311    let mut html = String::new();
312    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
313        let escaped = escape(value);
314        let _ = write!(
315            html,
316            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
317        );
318    }
319    for opt in options {
320        let selected = if opt.value == value { " selected" } else { "" };
321        let _ = write!(
322            html,
323            "<option value=\"{}\"{selected}>{}</option>",
324            escape(opt.value),
325            escape(opt.label)
326        );
327    }
328    html
329}
330
331/// The control itself, without its label, hint or error.
332fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
333    let id = filling.id_for(field.name);
334    let attrs = control_attributes(field, &id, field.name);
335    let field_class = class("field", opts);
336    let placeholder = field.placeholder.map_or_else(String::new, |text| {
337        format!(" placeholder=\"{}\"", escape(text))
338    });
339
340    match field.kind {
341        FieldKind::Radio => radio_html(field, filling, opts),
342        FieldKind::Textarea => format!(
343            "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
344            escape(filling.value.as_text())
345        ),
346        FieldKind::Select => {
347            // A select described with no options emits an empty select, which
348            // says so on screen rather than in a log. That is the description's
349            // own position on `Field::options`, not a fallback invented here.
350            let options = options_html(field.options, filling.value.as_text());
351            format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
352        }
353        FieldKind::Checkbox => {
354            let checked = if matches!(filling.value, Value::On(true)) {
355                " checked"
356            } else {
357                ""
358            };
359            format!(
360                "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
361                class("form-checkbox-label", opts),
362                escape(field.label)
363            )
364        }
365        // A secret never carries its value into the markup. `FieldKind::secret`
366        // is documented as a value that must not be round-tripped through
367        // anything that might persist it, and the DOM is such a thing: it is
368        // read by every extension on the page and is the first thing a crash
369        // reporter serialises. Neither app pre-fills one today, so this costs
370        // nothing and closes the door before something does.
371        FieldKind::Secret => {
372            format!("<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>")
373        }
374        // A file input carries no value, and this is the browser's rule rather
375        // than a preference: setting one from markup is refused, because a page
376        // that could preselect a path could read a file the user never offered.
377        // Nothing upstream needs to know, which is why the exception is here.
378        FieldKind::File => {
379            format!("<input type=\"file\" class=\"{field_class}\"{attrs}>")
380        }
381        kind => format!(
382            "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
383            input_type(kind),
384            escape(filling.value.as_text())
385        ),
386    }
387}
388
389/// One field, as the group the app drops into its form.
390///
391/// The shape is goingson's, down to the class names, so adoption there deletes
392/// `renderFormField` rather than restyling anything. That is also why the class
393/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
394/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
395/// emits only what it can generate from the description. Whether they should
396/// move into the description is the next question this raises, not one it
397/// answers.
398///
399/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
400/// nothing drawn, which is what [`FieldKind::visible`] means.
401///
402/// The error marks the group as well as the control. That is
403/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
404/// cannot find the group from the message, so the group has to be told.
405///
406/// ```
407/// use makeover_layout::{Field, FieldKind};
408/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
409///
410/// let field = Field::new(FieldKind::Text, "title", "Title");
411/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
412///
413/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
414/// assert!(html.contains(r#"value="Ship it""#));
415/// ```
416#[must_use]
417pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
418    let id = filling.id_for(field.name);
419
420    if !field.kind.visible() {
421        // Name only, no id: a hidden field is never pointed at by a label or a
422        // description, so the one attribute it needs is the one that submits.
423        return format!(
424            "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
425            escape(field.name),
426            escape(filling.value.as_text())
427        );
428    }
429
430    let mut html = format!("<div class=\"{}", class("form-group", opts));
431    if field.invalid() {
432        html.push_str(" has-error");
433    }
434    if field.extended {
435        // The disclosure that hides these is a property of the form, not of the
436        // field, so the field is marked and the app opens or closes the group.
437        html.push_str("\" data-extended=\"true");
438    }
439    html.push_str("\">");
440
441    // A checkbox labels itself, on the right of the box. Both apps special-case
442    // this inline today, which is the tell that it belongs in the description;
443    // `FieldKind::labels_itself` is where it went.
444    if !field.kind.labels_itself() {
445        // A group control is named *by* its label rather than pointing at it,
446        // so the two carry opposite halves of the association. See
447        // `is_group_control`.
448        let association = if is_group_control(field.kind) {
449            format!(" id=\"{id}-label\"")
450        } else {
451            format!(" for=\"{id}\"")
452        };
453        let _ = write!(
454            html,
455            "<label class=\"{}\"{association}>{}</label>",
456            class("form-label", opts),
457            escape(field.label)
458        );
459    }
460
461    html.push_str(&control_html(field, filling, opts));
462
463    if let Some(hint) = field.hint {
464        let _ = write!(
465            html,
466            "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
467            class("form-hint", opts),
468            escape(hint)
469        );
470    }
471    if let Some(Markup(markup)) = filling.trailing {
472        html.push_str(markup);
473    }
474    if let Some(error) = field.error {
475        let _ = write!(
476            html,
477            "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
478            class("form-error", opts),
479            escape(error)
480        );
481    }
482
483    html.push_str("</div>");
484    html
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    fn field(kind: FieldKind) -> Field<'static> {
492        Field::new(kind, "title", "Title")
493    }
494
495    #[test]
496    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
497        // The payload from goingson's own CHRONIC-XSS regression test.
498        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
499        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
500        // The payload survives as text, which is the point: it is inert
501        // because the quote that would have closed the attribute is encoded,
502        // not because the words were filtered.
503        assert!(!html.contains("\" onfocus"), "{html}");
504        assert!(
505            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
506            "{html}"
507        );
508    }
509
510    #[test]
511    fn a_label_cannot_open_a_tag() {
512        let mut f = field(FieldKind::Text);
513        f.label = "<script>alert(1)</script>";
514        let html = field_html(&f, &Filling::default(), &Emit::default());
515        assert!(!html.contains("<script>"), "{html}");
516        assert!(html.contains("&lt;script&gt;"), "{html}");
517    }
518
519    #[test]
520    fn every_escaped_sink_is_covered_by_the_one_escaper() {
521        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
522        // The character `textContent` serialization leaves alone, which is why
523        // the app needs two escapers and this needs one.
524        assert!(escape("\"").contains("&quot;"));
525    }
526
527    #[test]
528    fn markup_is_the_only_way_past_the_escaping() {
529        let filling = Filling {
530            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
531            ..Filling::default()
532        };
533        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
534        assert!(
535            html.contains("<div class=\"recurrence-config\"></div>"),
536            "{html}"
537        );
538    }
539
540    #[test]
541    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
542        let mut f = field(FieldKind::Text);
543        f.error = Some("Required");
544        let opts = Emit::default();
545        let html = field_html(&f, &Filling::default(), &opts);
546        assert!(html.contains("aria-invalid=\"true\""), "{html}");
547        // The selector the CSS side emits for exactly this state.
548        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
549        // And the group is marked too, which a renderer without descendant
550        // selectors depends on.
551        assert!(html.contains("has-error"), "{html}");
552    }
553
554    #[test]
555    fn a_valid_field_claims_nothing_about_being_invalid() {
556        let html = field_html(
557            &field(FieldKind::Text),
558            &Filling::default(),
559            &Emit::default(),
560        );
561        assert!(!html.contains("aria-invalid"), "{html}");
562        assert!(!html.contains("has-error"), "{html}");
563    }
564
565    #[test]
566    fn the_hint_survives_an_error_arriving() {
567        let mut f = field(FieldKind::Text);
568        f.hint = Some("Keep it short");
569        f.error = Some("Required");
570        let html = field_html(&f, &Filling::default(), &Emit::default());
571        assert!(
572            html.contains("aria-describedby=\"title-hint title-error\""),
573            "{html}"
574        );
575    }
576
577    #[test]
578    fn a_secret_never_carries_its_value_into_the_markup() {
579        let filling = Filling::of(Value::Text("hunter2"));
580        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
581        assert!(!html.contains("hunter2"), "{html}");
582        assert!(html.contains("type=\"password\""), "{html}");
583    }
584
585    #[test]
586    fn a_hidden_field_is_the_input_and_nothing_else() {
587        let filling = Filling::of(Value::Text("42"));
588        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
589        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
590    }
591
592    #[test]
593    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
594        let html = field_html(
595            &field(FieldKind::Checkbox),
596            &Filling::of(Value::On(true)),
597            &Emit::default(),
598        );
599        assert!(!html.contains("form-label"), "{html}");
600        assert!(html.contains("checked"), "{html}");
601        assert!(html.contains("<span>Title</span>"), "{html}");
602    }
603
604    #[test]
605    fn a_select_keeps_a_value_no_option_carries() {
606        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
607        let f = Field::select("title", "Title", &options);
608        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
609        assert!(html.contains("data-unmatched=\"true\""), "{html}");
610        // Selected, so the next save round-trips it rather than writing the
611        // first option over the top of it.
612        assert!(html.contains("<option value=\"10\" selected"), "{html}");
613    }
614
615    #[test]
616    fn a_select_with_no_options_emits_an_empty_select() {
617        // The description says a select with no options is sayable, because an
618        // app whose option list has not loaded has exactly that. Emitting the
619        // empty select reports it on screen rather than in a log.
620        let f = Field::select("title", "Title", &[]);
621        let html = field_html(&f, &Filling::default(), &Emit::default());
622        assert!(html.contains("<select"), "{html}");
623        assert!(!html.contains("<option"), "{html}");
624    }
625
626    #[test]
627    fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
628        // The association inverts, and getting it wrong is silent: a
629        // `<label for>` aimed at a group points at no element, so the group
630        // simply has no accessible name and nothing reports that.
631        let options = [Choice::plain("copy"), Choice::plain("reference")];
632        let f = Field::radio("storage", "Storage style", &options);
633        let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
634
635        assert!(html.contains("id=\"storage-label\""), "{html}");
636        assert!(!html.contains("for=\"storage\""), "{html}");
637        assert!(html.contains("role=\"radiogroup\""), "{html}");
638        assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
639    }
640
641    #[test]
642    fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
643        // One `name` is what makes them one answer rather than three; distinct
644        // ids are what keep each `<label>` wrapping its own input.
645        let options = [
646            Choice::plain("copy"),
647            Choice::plain("reference"),
648            Choice::plain("link"),
649        ];
650        let f = Field::radio("storage", "Storage style", &options);
651        let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
652
653        assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
654        assert_eq!(html.matches(" checked").count(), 1, "{html}");
655        assert!(
656            html.contains("value=\"reference\" checked"),
657            "the checked one is the one held: {html}"
658        );
659        for index in 0..3 {
660            assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
661        }
662    }
663
664    #[test]
665    fn a_radio_group_carries_the_error_rather_than_any_one_option() {
666        // What is wrong is the answer, not one of the alternatives, so marking
667        // a single input invalid would say something false. Same reading
668        // `Field::invalid` gives one level up.
669        let options = [Choice::plain("copy"), Choice::plain("reference")];
670        let f = Field {
671            error: Some("Pick one."),
672            hint: Some("Cannot be changed later."),
673            ..Field::radio("storage", "Storage style", &options)
674        };
675        let html = field_html(&f, &Filling::default(), &Emit::default());
676
677        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
678        assert!(
679            html.contains("aria-describedby=\"storage-hint storage-error\""),
680            "{html}"
681        );
682        // The group is the element that carries them, so they land before the
683        // first option rather than on it.
684        let group = html.find("role=\"radiogroup\"").expect("group");
685        let first = html.find("type=\"radio\"").expect("an option");
686        assert!(group < first, "{html}");
687    }
688
689    #[test]
690    fn a_compulsory_radio_group_marks_every_option() {
691        // How HTML says a group is compulsory: the constraint reads as
692        // satisfied when any one of them is checked.
693        let options = [Choice::plain("copy"), Choice::plain("reference")];
694        let f = Field {
695            required: true,
696            ..Field::radio("storage", "Storage style", &options)
697        };
698        let html = field_html(&f, &Filling::default(), &Emit::default());
699        assert_eq!(html.matches(" required").count(), 2, "{html}");
700    }
701
702    #[test]
703    fn a_radio_option_cannot_break_out_of_its_attribute() {
704        // Values are `&str` and carry whatever the app put in them. The ids are
705        // numbered rather than derived from the value for the same reason.
706        let hostile = [Choice {
707            value: "x\" onclick=alert(1) data-x=\"",
708            label: "<script>alert(1)</script>",
709        }];
710        let f = Field::radio("storage", "Storage style", &hostile);
711        let html = field_html(&f, &Filling::default(), &Emit::default());
712
713        // The payload survives as text; what must not survive is the quote
714        // that would end the attribute and let the rest of it become markup.
715        assert!(html.contains("value=\"x&quot; onclick=alert(1)"), "{html}");
716        assert!(!html.contains("<script>"), "{html}");
717        assert!(html.contains("id=\"storage-0\""), "{html}");
718    }
719
720    #[test]
721    fn a_radio_group_with_no_options_emits_an_empty_group() {
722        // Same position the select takes, and the description's own.
723        let f = Field::radio("storage", "Storage style", &[]);
724        let html = field_html(&f, &Filling::default(), &Emit::default());
725        assert!(html.contains("role=\"radiogroup\""), "{html}");
726        assert!(!html.contains("type=\"radio\""), "{html}");
727    }
728
729    #[test]
730    fn a_placeholder_comes_off_the_description_and_is_escaped() {
731        // It arrived in `Filling` until makeover-layout 0.8.0 and was never
732        // covered here; it is a value in an attribute like any other.
733        let f = Field {
734            placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
735            ..field(FieldKind::Text)
736        };
737        let html = field_html(&f, &Filling::default(), &Emit::default());
738        assert!(html.contains("placeholder=\""), "{html}");
739        assert!(!html.contains("\" onfocus"), "{html}");
740    }
741
742    #[test]
743    fn a_select_marks_the_option_that_matches() {
744        let options = [Choice::plain("1"), Choice::plain("3")];
745        let f = Field::select("title", "Title", &options);
746        let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
747        assert!(
748            html.contains("<option value=\"3\" selected>3</option>"),
749            "{html}"
750        );
751        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
752        assert!(!html.contains("data-unmatched"), "{html}");
753    }
754
755    #[test]
756    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
757        let filling = Filling::of(Value::Text("two\nlines"));
758        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
759        assert!(html.contains(">two\nlines</textarea>"), "{html}");
760    }
761
762    #[test]
763    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
764        let opts = Emit {
765            class_prefix: "mk-",
766            ..Emit::default()
767        };
768        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
769        assert!(html.contains("class=\"mk-form-group\""), "{html}");
770        assert!(html.contains("class=\"mk-field\""), "{html}");
771    }
772
773    #[test]
774    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
775        let mut f = field(FieldKind::Text);
776        f.extended = true;
777        let html = field_html(&f, &Filling::default(), &Emit::default());
778        assert!(html.contains("data-extended=\"true\""), "{html}");
779    }
780
781    /// The prefix scopes the id and leaves the name alone. Prefixing the name
782    /// too would change what the form submits, which is the failure this pair
783    /// of assertions exists to catch rather than describe.
784    #[test]
785    fn the_id_prefix_scopes_the_id_and_never_the_name() {
786        let mut f = field(FieldKind::Text);
787        f.hint = Some("Keep it short");
788        f.error = Some("Required");
789        let filling = Filling {
790            id_prefix: Some("form-modal-task-edit"),
791            ..Filling::default()
792        };
793        let html = field_html(&f, &filling, &Emit::default());
794
795        assert!(
796            html.contains(r#"id="form-modal-task-edit-title""#),
797            "{html}"
798        );
799        assert!(html.contains(r#"name="title""#), "{html}");
800        assert!(
801            !html.contains(r#"name="form-modal-task-edit-title""#),
802            "{html}"
803        );
804
805        // The label and both associations follow the id, or they point at
806        // nothing once the same form is on screen twice.
807        assert!(
808            html.contains(r#"for="form-modal-task-edit-title""#),
809            "{html}"
810        );
811        assert!(
812            html.contains(
813                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
814            ),
815            "{html}"
816        );
817        assert!(
818            html.contains(r#"id="form-modal-task-edit-title-hint""#),
819            "{html}"
820        );
821    }
822
823    #[test]
824    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
825        let filling = Filling {
826            value: Value::Text("42"),
827            id_prefix: Some("scoped"),
828            ..Filling::default()
829        };
830        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
831        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
832    }
833
834    /// These three exist so a touch keyboard and the platform's validation
835    /// arrive with the field. Emitting text for any of them is the regression
836    /// the variants were added to prevent, so the type is asserted directly.
837    #[test]
838    fn a_constraint_becomes_the_browsers_own_attribute() {
839        // makeover-layout 0.11.0's model: the description carries the rule and
840        // each renderer emits its host's idiom for it. Enforcement is still
841        // whoever validated's, and arrives back as `error`.
842        let html = field_html(
843            &Field {
844                max_length: Some(100),
845                min: Some("1"),
846                max: Some("240"),
847                required: true,
848                ..Field::new(FieldKind::Number, "minutes", "Minutes")
849            },
850            &Filling::default(),
851            &Emit::default(),
852        );
853        assert!(html.contains(r#"maxlength="100""#));
854        assert!(html.contains(r#"min="1""#));
855        assert!(html.contains(r#"max="240""#));
856        assert!(html.contains(" required"));
857    }
858
859    #[test]
860    fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
861        // The bound is text because it is only a number for some of the kinds
862        // that take one; goingson's own sites are a duration and a datetime.
863        let html = field_html(
864            &Field {
865                min: Some("2026-08-09T14:30"),
866                ..Field::new(FieldKind::Text, "starts", "Starts")
867            },
868            &Filling::default(),
869            &Emit::default(),
870        );
871        assert!(html.contains(r#"min="2026-08-09T14:30""#));
872    }
873
874    #[test]
875    fn a_file_field_is_a_file_input() {
876        // `844b5ae0`. It carries no `accept`, which is measured rather than
877        // deferred: zero sites in either app.
878        let html = field_html(
879            &Field::new(FieldKind::File, "attachment", "Attachment"),
880            &Filling::default(),
881            &Emit::default(),
882        );
883        assert!(html.contains(r#"type="file""#));
884        assert!(!html.contains("accept="));
885        // And it never carries a value: a file input's value is not settable
886        // from markup, and the browser refuses one that tries.
887        assert!(!html.contains("value="));
888    }
889
890    #[test]
891    fn the_typed_text_kinds_keep_their_input_type() {
892        for (kind, expected) in [
893            (FieldKind::Email, "email"),
894            (FieldKind::Url, "url"),
895            (FieldKind::Tel, "tel"),
896        ] {
897            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
898            assert!(
899                html.contains(&format!(r#"type="{expected}""#)),
900                "{kind:?} emitted {html}"
901            );
902        }
903    }
904
905    #[test]
906    fn no_prefix_leaves_the_id_as_the_name() {
907        let html = field_html(
908            &field(FieldKind::Text),
909            &Filling::default(),
910            &Emit::default(),
911        );
912        assert!(html.contains(r#"id="title" name="title""#), "{html}");
913    }
914}