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//! [`Field`] describes the field and not its contents, so three things arrive
30//! from the renderer side in [`Filling`]: the current value, the options of a
31//! select, and the placeholder. The first two are genuinely renderer state. The
32//! third is user-facing text and belongs with `label` and `hint` in
33//! makeover-layout; it lives here because that crate is published and adding a
34//! field to `Field` is a breaking change, not because this is its home.
35
36use crate::{Emit, class};
37use makeover_layout::{Field, FieldKind};
38use std::fmt::Write as _;
39
40/// A string that is already markup, and is emitted without escaping.
41///
42/// The one hole in the escaping, and it has to be named to be used. goingson
43/// has two live callers that need it, both passing a recurrence-config block
44/// built elsewhere, and both would otherwise have their markup rendered as
45/// visible angle brackets. A caller constructing this is stating that the
46/// contents are trusted; nothing here can check that for them.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct Markup<'a>(pub &'a str);
49
50/// One option of a select.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Choice<'a> {
53    /// What is submitted.
54    pub value: &'a str,
55    /// What is read.
56    pub label: &'a str,
57}
58
59impl<'a> Choice<'a> {
60    /// An option whose submitted value is also its label.
61    #[must_use]
62    pub const fn plain(value: &'a str) -> Self {
63        Self {
64            value,
65            label: value,
66        }
67    }
68}
69
70/// What the field currently holds.
71///
72/// An enum rather than a bag of optional fields, on the same reasoning
73/// [`makeover_layout::Depth`] is one: a select with no options and a checkbox
74/// with a string value are both unsayable here, where a struct would let them
75/// be said and then have to cope.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub enum Value<'a> {
78    /// Nothing yet.
79    #[default]
80    Absent,
81    /// The value of anything that takes typed text.
82    Text(&'a str),
83    /// The options of a select, and which of them is current.
84    Chosen {
85        /// Every option, in the order they are offered.
86        options: &'a [Choice<'a>],
87        /// The current value. Matched against each option's `value`.
88        value: &'a str,
89    },
90    /// A checkbox, on or off.
91    On(bool),
92}
93
94impl<'a> Value<'a> {
95    /// The value as text, for the kinds that submit one.
96    const fn as_text(&self) -> &'a str {
97        match self {
98            Self::Text(text) | Self::Chosen { value: text, .. } => text,
99            Self::Absent | Self::On(_) => "",
100        }
101    }
102}
103
104/// Everything about the field that the description does not carry.
105#[derive(Debug, Clone, Copy, Default)]
106pub struct Filling<'a> {
107    /// What the field holds now.
108    pub value: Value<'a>,
109    /// Ghost text shown while the field is empty.
110    pub placeholder: Option<&'a str>,
111    /// Markup appended inside the group, after the hint. Not escaped.
112    pub trailing: Option<Markup<'a>>,
113    /// Scopes the `id` attributes to one instance of the form.
114    ///
115    /// The field's `name` is what the value submits under and is the same
116    /// wherever the form appears; its `id` has to be unique in the document,
117    /// and those two facts stop agreeing the moment a form appears twice.
118    /// goingson hits this directly: its new-task and edit-task modals are the
119    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
120    /// `label for` and `aria-describedby` pointing at the right control.
121    ///
122    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
123    /// `name`, which would change what the form submits.
124    pub id_prefix: Option<&'a str>,
125}
126
127impl<'a> Filling<'a> {
128    /// A filling that carries a value and nothing else.
129    #[must_use]
130    pub const fn of(value: Value<'a>) -> Self {
131        Self {
132            value,
133            placeholder: None,
134            trailing: None,
135            id_prefix: None,
136        }
137    }
138
139    /// The document-unique id for a field of this name.
140    fn id_for(&self, name: &str) -> String {
141        match self.id_prefix {
142            Some(prefix) => format!("{}-{}", escape(prefix), escape(name)),
143            None => escape(name),
144        }
145    }
146}
147
148/// Encode the five characters that let a value stop being a value.
149///
150/// Sound in element text and in a double-quoted attribute alike, which is the
151/// property `textContent`-based escaping cannot have. Both sinks are covered by
152/// one function so that no call site has to choose, here or downstream.
153#[must_use]
154pub fn escape(text: &str) -> String {
155    let mut out = String::with_capacity(text.len());
156    for ch in text.chars() {
157        match ch {
158            '&' => out.push_str("&amp;"),
159            '<' => out.push_str("&lt;"),
160            '>' => out.push_str("&gt;"),
161            '"' => out.push_str("&quot;"),
162            '\'' => out.push_str("&#39;"),
163            other => out.push(other),
164        }
165    }
166    out
167}
168
169/// The `type` an input takes for a kind.
170///
171/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
172const fn input_type(kind: FieldKind) -> &'static str {
173    match kind {
174        FieldKind::Secret => "password",
175        FieldKind::Number => "number",
176        FieldKind::Checkbox => "checkbox",
177        FieldKind::Hidden => "hidden",
178        // Not decoration. Each of these changes the keyboard a touch device
179        // offers and turns on the platform's own validation, which is why the
180        // description names them apart from text rather than letting the app
181        // pass an HTML type through.
182        FieldKind::Email => "email",
183        FieldKind::Url => "url",
184        FieldKind::Tel => "tel",
185        // Select and Textarea are not inputs at all; they never reach here.
186        FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
187        // A kind added to the description since this renderer was built. Text
188        // accepts any value the others would, so it degrades rather than
189        // dropping the field.
190        _ => "text",
191    }
192}
193
194/// The attributes every visible control carries, error state included.
195///
196/// `aria-invalid` is the whole reason the error state is readable at all: the
197/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
198/// than on a class, so a control rendered already-invalid without it is styled
199/// as if nothing were wrong. goingson's runtime validation path sets the
200/// attribute and its initial render does not, which is exactly the drift one
201/// emitter removes.
202/// `id` and `name` arrive separately because they are not the same fact. The
203/// name is what submits and is fixed by the description; the id has to be
204/// unique in the document and so carries [`Filling::id_prefix`] when a form
205/// appears more than once.
206fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
207    let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
208    if field.required {
209        attrs.push_str(" required");
210    }
211    if field.invalid() {
212        attrs.push_str(" aria-invalid=\"true\"");
213    }
214
215    // Both associations, in the order they are useful: the standing help, then
216    // what is currently wrong. goingson's runtime path points describedby at
217    // the error alone and drops the hint association it never made in the first
218    // place; naming both here means the hint survives an error appearing.
219    let mut described = Vec::new();
220    if field.hint.is_some() {
221        described.push(format!("{id}-hint"));
222    }
223    if field.error.is_some() {
224        described.push(format!("{id}-error"));
225    }
226    if !described.is_empty() {
227        let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" "));
228    }
229    attrs
230}
231
232/// The options of a select, with an unmatched current value carried as its own.
233///
234/// A select handed a value no option carries renders with nothing selected, the
235/// browser falls back to the first option, and the next save writes a value
236/// nobody chose. goingson hit exactly that with a backup-retention default of
237/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
238/// here so the second app gets it without hitting the bug first.
239fn options_html(options: &[Choice<'_>], value: &str) -> String {
240    let mut html = String::new();
241    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
242        let escaped = escape(value);
243        let _ = write!(
244            html,
245            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
246        );
247    }
248    for opt in options {
249        let selected = if opt.value == value { " selected" } else { "" };
250        let _ = write!(
251            html,
252            "<option value=\"{}\"{selected}>{}</option>",
253            escape(opt.value),
254            escape(opt.label)
255        );
256    }
257    html
258}
259
260/// The control itself, without its label, hint or error.
261fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
262    let id = filling.id_for(field.name);
263    let attrs = control_attributes(field, &id, field.name);
264    let field_class = class("field", opts);
265    let placeholder = filling.placeholder.map_or_else(String::new, |text| {
266        format!(" placeholder=\"{}\"", escape(text))
267    });
268
269    match field.kind {
270        FieldKind::Textarea => format!(
271            "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
272            escape(filling.value.as_text())
273        ),
274        FieldKind::Select => {
275            let options = match filling.value {
276                Value::Chosen { options, value } => options_html(options, value),
277                // Described as a select and filled as something else. Emitting
278                // an empty select says so on screen rather than in a log.
279                _ => String::new(),
280            };
281            format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
282        }
283        FieldKind::Checkbox => {
284            let checked = if matches!(filling.value, Value::On(true)) {
285                " checked"
286            } else {
287                ""
288            };
289            format!(
290                "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
291                class("form-checkbox-label", opts),
292                escape(field.label)
293            )
294        }
295        // A secret never carries its value into the markup. `FieldKind::secret`
296        // is documented as a value that must not be round-tripped through
297        // anything that might persist it, and the DOM is such a thing: it is
298        // read by every extension on the page and is the first thing a crash
299        // reporter serialises. Neither app pre-fills one today, so this costs
300        // nothing and closes the door before something does.
301        FieldKind::Secret => {
302            format!("<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>")
303        }
304        kind => format!(
305            "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
306            input_type(kind),
307            escape(filling.value.as_text())
308        ),
309    }
310}
311
312/// One field, as the group the app drops into its form.
313///
314/// The shape is goingson's, down to the class names, so adoption there deletes
315/// `renderFormField` rather than restyling anything. That is also why the class
316/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
317/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
318/// emits only what it can generate from the description. Whether they should
319/// move into the description is the next question this raises, not one it
320/// answers.
321///
322/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
323/// nothing drawn, which is what [`FieldKind::visible`] means.
324///
325/// The error marks the group as well as the control. That is
326/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
327/// cannot find the group from the message, so the group has to be told.
328///
329/// ```
330/// use makeover_layout::{Field, FieldKind};
331/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
332///
333/// let field = Field::new(FieldKind::Text, "title", "Title");
334/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
335///
336/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
337/// assert!(html.contains(r#"value="Ship it""#));
338/// ```
339#[must_use]
340pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
341    let id = filling.id_for(field.name);
342
343    if !field.kind.visible() {
344        // Name only, no id: a hidden field is never pointed at by a label or a
345        // description, so the one attribute it needs is the one that submits.
346        return format!(
347            "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
348            escape(field.name),
349            escape(filling.value.as_text())
350        );
351    }
352
353    let mut html = format!("<div class=\"{}", class("form-group", opts));
354    if field.invalid() {
355        html.push_str(" has-error");
356    }
357    if field.extended {
358        // The disclosure that hides these is a property of the form, not of the
359        // field, so the field is marked and the app opens or closes the group.
360        html.push_str("\" data-extended=\"true");
361    }
362    html.push_str("\">");
363
364    // A checkbox labels itself, on the right of the box. Both apps special-case
365    // this inline today, which is the tell that it belongs in the description;
366    // `FieldKind::labels_itself` is where it went.
367    if !field.kind.labels_itself() {
368        let _ = write!(
369            html,
370            "<label class=\"{}\" for=\"{id}\">{}</label>",
371            class("form-label", opts),
372            escape(field.label)
373        );
374    }
375
376    html.push_str(&control_html(field, filling, opts));
377
378    if let Some(hint) = field.hint {
379        let _ = write!(
380            html,
381            "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
382            class("form-hint", opts),
383            escape(hint)
384        );
385    }
386    if let Some(Markup(markup)) = filling.trailing {
387        html.push_str(markup);
388    }
389    if let Some(error) = field.error {
390        let _ = write!(
391            html,
392            "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
393            class("form-error", opts),
394            escape(error)
395        );
396    }
397
398    html.push_str("</div>");
399    html
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    fn field(kind: FieldKind) -> Field<'static> {
407        Field::new(kind, "title", "Title")
408    }
409
410    #[test]
411    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
412        // The payload from goingson's own CHRONIC-XSS regression test.
413        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
414        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
415        // The payload survives as text, which is the point: it is inert
416        // because the quote that would have closed the attribute is encoded,
417        // not because the words were filtered.
418        assert!(!html.contains("\" onfocus"), "{html}");
419        assert!(
420            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
421            "{html}"
422        );
423    }
424
425    #[test]
426    fn a_label_cannot_open_a_tag() {
427        let mut f = field(FieldKind::Text);
428        f.label = "<script>alert(1)</script>";
429        let html = field_html(&f, &Filling::default(), &Emit::default());
430        assert!(!html.contains("<script>"), "{html}");
431        assert!(html.contains("&lt;script&gt;"), "{html}");
432    }
433
434    #[test]
435    fn every_escaped_sink_is_covered_by_the_one_escaper() {
436        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
437        // The character `textContent` serialization leaves alone, which is why
438        // the app needs two escapers and this needs one.
439        assert!(escape("\"").contains("&quot;"));
440    }
441
442    #[test]
443    fn markup_is_the_only_way_past_the_escaping() {
444        let filling = Filling {
445            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
446            ..Filling::default()
447        };
448        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
449        assert!(
450            html.contains("<div class=\"recurrence-config\"></div>"),
451            "{html}"
452        );
453    }
454
455    #[test]
456    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
457        let mut f = field(FieldKind::Text);
458        f.error = Some("Required");
459        let opts = Emit::default();
460        let html = field_html(&f, &Filling::default(), &opts);
461        assert!(html.contains("aria-invalid=\"true\""), "{html}");
462        // The selector the CSS side emits for exactly this state.
463        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
464        // And the group is marked too, which a renderer without descendant
465        // selectors depends on.
466        assert!(html.contains("has-error"), "{html}");
467    }
468
469    #[test]
470    fn a_valid_field_claims_nothing_about_being_invalid() {
471        let html = field_html(
472            &field(FieldKind::Text),
473            &Filling::default(),
474            &Emit::default(),
475        );
476        assert!(!html.contains("aria-invalid"), "{html}");
477        assert!(!html.contains("has-error"), "{html}");
478    }
479
480    #[test]
481    fn the_hint_survives_an_error_arriving() {
482        let mut f = field(FieldKind::Text);
483        f.hint = Some("Keep it short");
484        f.error = Some("Required");
485        let html = field_html(&f, &Filling::default(), &Emit::default());
486        assert!(
487            html.contains("aria-describedby=\"title-hint title-error\""),
488            "{html}"
489        );
490    }
491
492    #[test]
493    fn a_secret_never_carries_its_value_into_the_markup() {
494        let filling = Filling::of(Value::Text("hunter2"));
495        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
496        assert!(!html.contains("hunter2"), "{html}");
497        assert!(html.contains("type=\"password\""), "{html}");
498    }
499
500    #[test]
501    fn a_hidden_field_is_the_input_and_nothing_else() {
502        let filling = Filling::of(Value::Text("42"));
503        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
504        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
505    }
506
507    #[test]
508    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
509        let html = field_html(
510            &field(FieldKind::Checkbox),
511            &Filling::of(Value::On(true)),
512            &Emit::default(),
513        );
514        assert!(!html.contains("form-label"), "{html}");
515        assert!(html.contains("checked"), "{html}");
516        assert!(html.contains("<span>Title</span>"), "{html}");
517    }
518
519    #[test]
520    fn a_select_keeps_a_value_no_option_carries() {
521        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
522        let filling = Filling::of(Value::Chosen {
523            options: &options,
524            value: "10",
525        });
526        let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
527        assert!(html.contains("data-unmatched=\"true\""), "{html}");
528        // Selected, so the next save round-trips it rather than writing the
529        // first option over the top of it.
530        assert!(html.contains("<option value=\"10\" selected"), "{html}");
531    }
532
533    #[test]
534    fn a_select_marks_the_option_that_matches() {
535        let options = [Choice::plain("1"), Choice::plain("3")];
536        let filling = Filling::of(Value::Chosen {
537            options: &options,
538            value: "3",
539        });
540        let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
541        assert!(
542            html.contains("<option value=\"3\" selected>3</option>"),
543            "{html}"
544        );
545        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
546        assert!(!html.contains("data-unmatched"), "{html}");
547    }
548
549    #[test]
550    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
551        let filling = Filling::of(Value::Text("two\nlines"));
552        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
553        assert!(html.contains(">two\nlines</textarea>"), "{html}");
554    }
555
556    #[test]
557    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
558        let opts = Emit {
559            class_prefix: "mk-",
560            ..Emit::default()
561        };
562        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
563        assert!(html.contains("class=\"mk-form-group\""), "{html}");
564        assert!(html.contains("class=\"mk-field\""), "{html}");
565    }
566
567    #[test]
568    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
569        let mut f = field(FieldKind::Text);
570        f.extended = true;
571        let html = field_html(&f, &Filling::default(), &Emit::default());
572        assert!(html.contains("data-extended=\"true\""), "{html}");
573    }
574
575    /// The prefix scopes the id and leaves the name alone. Prefixing the name
576    /// too would change what the form submits, which is the failure this pair
577    /// of assertions exists to catch rather than describe.
578    #[test]
579    fn the_id_prefix_scopes_the_id_and_never_the_name() {
580        let mut f = field(FieldKind::Text);
581        f.hint = Some("Keep it short");
582        f.error = Some("Required");
583        let filling = Filling {
584            id_prefix: Some("form-modal-task-edit"),
585            ..Filling::default()
586        };
587        let html = field_html(&f, &filling, &Emit::default());
588
589        assert!(
590            html.contains(r#"id="form-modal-task-edit-title""#),
591            "{html}"
592        );
593        assert!(html.contains(r#"name="title""#), "{html}");
594        assert!(
595            !html.contains(r#"name="form-modal-task-edit-title""#),
596            "{html}"
597        );
598
599        // The label and both associations follow the id, or they point at
600        // nothing once the same form is on screen twice.
601        assert!(
602            html.contains(r#"for="form-modal-task-edit-title""#),
603            "{html}"
604        );
605        assert!(
606            html.contains(
607                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
608            ),
609            "{html}"
610        );
611        assert!(
612            html.contains(r#"id="form-modal-task-edit-title-hint""#),
613            "{html}"
614        );
615    }
616
617    #[test]
618    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
619        let filling = Filling {
620            value: Value::Text("42"),
621            id_prefix: Some("scoped"),
622            ..Filling::default()
623        };
624        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
625        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
626    }
627
628    /// These three exist so a touch keyboard and the platform's validation
629    /// arrive with the field. Emitting text for any of them is the regression
630    /// the variants were added to prevent, so the type is asserted directly.
631    #[test]
632    fn the_typed_text_kinds_keep_their_input_type() {
633        for (kind, expected) in [
634            (FieldKind::Email, "email"),
635            (FieldKind::Url, "url"),
636            (FieldKind::Tel, "tel"),
637        ] {
638            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
639            assert!(
640                html.contains(&format!(r#"type="{expected}""#)),
641                "{kind:?} emitted {html}"
642            );
643        }
644    }
645
646    #[test]
647    fn no_prefix_leaves_the_id_as_the_name() {
648        let html = field_html(
649            &field(FieldKind::Text),
650            &Filling::default(),
651            &Emit::default(),
652        );
653        assert!(html.contains(r#"id="title" name="title""#), "{html}");
654    }
655}