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