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, push_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 let mut id = String::new();
125 if let Some(prefix) = self.id_prefix {
126 escape_into(prefix, &mut id);
127 id.push('-');
128 }
129 escape_into(name, &mut id);
130 id
131 }
132}
133
134/// Encode the five characters that let a value stop being a value, into a
135/// buffer the caller already has.
136///
137/// The form the emitters use. [`escape`] is this with a `String` allocated
138/// around it, and the allocation is the whole difference: a described screen
139/// escapes once per attribute and once per run of text, so a function that
140/// returns a `String` allocates a few thousand times to produce one page, where
141/// a template engine writes its escaped bytes straight into the output buffer.
142/// Measured 2026-08-14 against a real pane, that gap was 85% of a 42x rendering
143/// cost, and this is the half of the fix that lives in this crate.
144///
145/// Sound in element text and in a double-quoted attribute alike, which is the
146/// property `textContent`-based escaping cannot have. Both sinks are covered by
147/// one function so that no call site has to choose, here or downstream.
148///
149/// Copies in runs rather than per character. All five encoded characters are
150/// ASCII, so a byte scan cannot land inside a multi-byte character and the
151/// slice between two of them is always a valid `&str`. Text with nothing to
152/// encode — which is most text — is one `push_str` of the whole thing.
153pub fn escape_into(text: &str, out: &mut String) {
154 let mut start = 0;
155 for (index, byte) in text.bytes().enumerate() {
156 let encoded = match byte {
157 b'&' => "&",
158 b'<' => "<",
159 b'>' => ">",
160 b'"' => """,
161 b'\'' => "'",
162 _ => continue,
163 };
164 out.push_str(&text[start..index]);
165 out.push_str(encoded);
166 start = index + 1;
167 }
168 out.push_str(&text[start..]);
169}
170
171/// Encode the five characters that let a value stop being a value.
172///
173/// [`escape_into`] with a buffer of its own, for the callers that want a value
174/// rather than an append: a caller assembling an attribute out of several
175/// pieces, and everything outside this crate that took this function before the
176/// buffer-writing form existed. Emitting into a buffer you already hold is the
177/// cheaper path and the one this crate's own emitters take.
178#[must_use]
179pub fn escape(text: &str) -> String {
180 let mut out = String::with_capacity(text.len());
181 escape_into(text, &mut out);
182 out
183}
184
185/// The `type` an input takes for a kind.
186///
187/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
188const fn input_type(kind: FieldKind) -> &'static str {
189 match kind {
190 FieldKind::Secret => "password",
191 FieldKind::Number => "number",
192 FieldKind::Checkbox => "checkbox",
193 FieldKind::File => "file",
194 FieldKind::Hidden => "hidden",
195 // Not decoration. Each of these changes the keyboard a touch device
196 // offers and turns on the platform's own validation, which is why the
197 // description names them apart from text rather than letting the app
198 // pass an HTML type through.
199 FieldKind::Email => "email",
200 FieldKind::Url => "url",
201 FieldKind::Tel => "tel",
202 // The same argument, and it buys more here than anywhere else in this
203 // list: a native picker as well as the keyboard and the validation.
204 // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
205 // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
206 FieldKind::Date => "date",
207 FieldKind::DateTime => "datetime-local",
208 FieldKind::Radio => "radio",
209 // Select and Textarea are not inputs at all; they never reach here.
210 // Radio is one, but it is emitted once per option by `radio_html` and
211 // so does not reach here either.
212 FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
213 // A kind added to the description since this renderer was built. Text
214 // accepts any value the others would, so it degrades rather than
215 // dropping the field.
216 _ => "text",
217 }
218}
219
220/// The attributes every visible control carries, error state included.
221///
222/// `aria-invalid` is the whole reason the error state is readable at all: the
223/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
224/// than on a class, so a control rendered already-invalid without it is styled
225/// as if nothing were wrong. goingson's runtime validation path sets the
226/// attribute and its initial render does not, which is exactly the drift one
227/// emitter removes.
228/// `id` and `name` arrive separately because they are not the same fact. The
229/// name is what submits and is fixed by the description; the id has to be
230/// unique in the document and so carries [`Filling::id_prefix`] when a form
231/// appears more than once.
232fn push_control_attributes(out: &mut String, field: &Field<'_>, id: &str, name: &str) {
233 let _ = write!(out, " id=\"{id}\" name=\"");
234 escape_into(name, out);
235 out.push('"');
236 if field.required {
237 out.push_str(" required");
238 }
239 // makeover-layout 0.11.0's constraints. The description carries the rule and
240 // this emits the browser's idiom for it, which is the model `required` has
241 // been using since before the crate wrote down that it carried none.
242 // Enforcement is still whoever validated's, and arrives back as `error`.
243 if let Some(limit) = field.max_length {
244 let _ = write!(out, " maxlength=\"{limit}\"");
245 }
246 if let Some(min) = field.min {
247 out.push_str(" min=\"");
248 escape_into(min, out);
249 out.push('"');
250 }
251 if let Some(max) = field.max {
252 out.push_str(" max=\"");
253 escape_into(max, out);
254 out.push('"');
255 }
256 if field.invalid() {
257 out.push_str(" aria-invalid=\"true\"");
258 }
259
260 push_described_by(out, field, id);
261}
262
263/// The `aria-describedby` naming whatever of the hint and the error exist.
264///
265/// Both associations, in the order they are useful: the standing help, then
266/// what is currently wrong. goingson's runtime path points describedby at the
267/// error alone and drops the hint association it never made in the first place;
268/// naming both here means the hint survives an error appearing.
269///
270/// Its own function because a radio group carries it on the group rather than
271/// on a control, and one reading of "what describes this field" is the point.
272fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
273 if field.hint.is_none() && field.error.is_none() {
274 return;
275 }
276 out.push_str(" aria-describedby=\"");
277 if field.hint.is_some() {
278 let _ = write!(out, "{id}-hint");
279 }
280 if field.error.is_some() {
281 if field.hint.is_some() {
282 out.push(' ');
283 }
284 let _ = write!(out, "{id}-error");
285 }
286 out.push('"');
287}
288
289/// Whether the field's control is a set of elements rather than one.
290///
291/// A DOM concern rather than a description one, which is why it is decided here
292/// and not in `makeover-layout`: `for` and `id` are an HTML association and
293/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
294/// points at nothing, because no single element carries the group's id, so the
295/// association has to invert — the label takes an id and the group names itself
296/// with `aria-labelledby`.
297const fn is_group_control(kind: FieldKind) -> bool {
298 matches!(kind, FieldKind::Radio)
299}
300
301/// A radio group: the options as sibling inputs sharing one `name`.
302///
303/// The group carries the error state and the descriptions, and the inputs carry
304/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
305/// down: marking a single input invalid would say the wrong thing, since what
306/// is wrong is the answer to the question and not one of the alternatives.
307///
308/// Ids are numbered rather than built from the option values, which can hold
309/// anything a `&str` can — spaces and quotes included — and would otherwise
310/// have to be slugged into something unique by a rule this crate would then own.
311///
312/// `required` lands on every input, which is how HTML says a group is
313/// compulsory: the constraint is satisfied when any one of them is checked.
314fn push_radio(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
315 let id = filling.id_for(field.name);
316 let value = filling.value.as_text();
317 let name = escape(field.name);
318
319 out.push_str("<div class=\"");
320 push_class(out, "form-radio-group", opts);
321 let _ = write!(out, "\" role=\"radiogroup\" aria-labelledby=\"{id}-label\"");
322 if field.invalid() {
323 out.push_str(" aria-invalid=\"true\"");
324 }
325 push_described_by(out, field, &id);
326 out.push('>');
327
328 // A group described with no options emits an empty group, for the reason
329 // `Field::options` gives: an app whose option list has not loaded has
330 // exactly that, and an empty group says so on screen rather than in a log.
331 for (index, opt) in field.options.iter().enumerate() {
332 out.push_str("<label class=\"");
333 push_class(out, "form-radio-label", opts);
334 let _ = write!(
335 out,
336 "\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" value=\""
337 );
338 escape_into(opt.value, out);
339 out.push('"');
340 if opt.value == value {
341 out.push_str(" checked");
342 }
343 if field.required {
344 out.push_str(" required");
345 }
346 out.push_str("><span>");
347 escape_into(opt.label, out);
348 out.push_str("</span></label>");
349 }
350
351 out.push_str("</div>");
352}
353
354/// The options of a select, with an unmatched current value carried as its own.
355///
356/// A select handed a value no option carries renders with nothing selected, the
357/// browser falls back to the first option, and the next save writes a value
358/// nobody chose. goingson hit exactly that with a backup-retention default of
359/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
360/// here so the second app gets it without hitting the bug first.
361fn push_options(out: &mut String, options: &[Choice<'_>], value: &str) {
362 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
363 // The one place an escaped value is worth keeping: it is written twice,
364 // as the option's value and as its text.
365 let escaped = escape(value);
366 let _ = write!(
367 out,
368 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
369 );
370 }
371 for opt in options {
372 out.push_str("<option value=\"");
373 escape_into(opt.value, out);
374 out.push('"');
375 if opt.value == value {
376 out.push_str(" selected");
377 }
378 out.push('>');
379 escape_into(opt.label, out);
380 out.push_str("</option>");
381 }
382}
383
384/// The control itself, without its label, hint or error.
385fn push_control(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
386 // Emitted before anything else is computed: a radio group carries its
387 // descriptions on the group rather than on a control, so none of the
388 // attributes below belong to it.
389 if matches!(field.kind, FieldKind::Radio) {
390 push_radio(out, field, filling, opts);
391 return;
392 }
393
394 let id = filling.id_for(field.name);
395 let placeholder = |out: &mut String| {
396 if let Some(text) = field.placeholder {
397 out.push_str(" placeholder=\"");
398 escape_into(text, out);
399 out.push('"');
400 }
401 };
402
403 match field.kind {
404 FieldKind::Textarea => {
405 out.push_str("<textarea class=\"");
406 push_class(out, "field", opts);
407 out.push('"');
408 push_control_attributes(out, field, &id, field.name);
409 placeholder(out);
410 out.push('>');
411 escape_into(filling.value.as_text(), out);
412 out.push_str("</textarea>");
413 }
414 FieldKind::Select => {
415 out.push_str("<select class=\"");
416 push_class(out, "field", opts);
417 out.push('"');
418 push_control_attributes(out, field, &id, field.name);
419 out.push('>');
420 // A select described with no options emits an empty select, which
421 // says so on screen rather than in a log. That is the description's
422 // own position on `Field::options`, not a fallback invented here.
423 push_options(out, field.options, filling.value.as_text());
424 out.push_str("</select>");
425 }
426 FieldKind::Checkbox => {
427 out.push_str("<label class=\"");
428 push_class(out, "form-checkbox-label", opts);
429 out.push_str("\"><input type=\"checkbox\"");
430 push_control_attributes(out, field, &id, field.name);
431 if matches!(filling.value, Value::On(true)) {
432 out.push_str(" checked");
433 }
434 out.push_str("><span>");
435 escape_into(field.label, out);
436 out.push_str("</span></label>");
437 }
438 // A secret never carries its value into the markup. `FieldKind::secret`
439 // is documented as a value that must not be round-tripped through
440 // anything that might persist it, and the DOM is such a thing: it is
441 // read by every extension on the page and is the first thing a crash
442 // reporter serialises. Neither app pre-fills one today, so this costs
443 // nothing and closes the door before something does.
444 FieldKind::Secret => {
445 out.push_str("<input type=\"password\" class=\"");
446 push_class(out, "field", opts);
447 out.push('"');
448 push_control_attributes(out, field, &id, field.name);
449 placeholder(out);
450 out.push('>');
451 }
452 // A file input carries no value, and this is the browser's rule rather
453 // than a preference: setting one from markup is refused, because a page
454 // that could preselect a path could read a file the user never offered.
455 // Nothing upstream needs to know, which is why the exception is here.
456 FieldKind::File => {
457 out.push_str("<input type=\"file\" class=\"");
458 push_class(out, "field", opts);
459 out.push('"');
460 push_control_attributes(out, field, &id, field.name);
461 out.push('>');
462 }
463 kind => {
464 let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
465 push_class(out, "field", opts);
466 out.push('"');
467 push_control_attributes(out, field, &id, field.name);
468 placeholder(out);
469 out.push_str(" value=\"");
470 escape_into(filling.value.as_text(), out);
471 out.push_str("\">");
472 }
473 }
474}
475
476/// One field, as the group the app drops into its form.
477///
478/// The shape is goingson's, down to the class names, so adoption there deletes
479/// `renderFormField` rather than restyling anything. That is also why the class
480/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
481/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
482/// emits only what it can generate from the description. Whether they should
483/// move into the description is the next question this raises, not one it
484/// answers.
485///
486/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
487/// nothing drawn, which is what [`FieldKind::visible`] means.
488///
489/// The error marks the group as well as the control. That is
490/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
491/// cannot find the group from the message, so the group has to be told.
492///
493/// ```
494/// use makeover_layout::{Field, FieldKind};
495/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
496///
497/// let field = Field::new(FieldKind::Text, "title", "Title");
498/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
499///
500/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
501/// assert!(html.contains(r#"value="Ship it""#));
502/// ```
503#[must_use]
504pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
505 let mut html = String::new();
506 field_html_into(field, filling, opts, &mut html);
507 html
508}
509
510/// One field, written into a buffer the caller already has.
511///
512/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
513/// these, so a host building one should hold a single buffer and append each
514/// field into it rather than take a `String` per field and concatenate.
515pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
516 let id = filling.id_for(field.name);
517
518 if !field.kind.visible() {
519 // Name only, no id: a hidden field is never pointed at by a label or a
520 // description, so the one attribute it needs is the one that submits.
521 out.push_str("<input type=\"hidden\" name=\"");
522 escape_into(field.name, out);
523 out.push_str("\" value=\"");
524 escape_into(filling.value.as_text(), out);
525 out.push_str("\">");
526 return;
527 }
528
529 out.push_str("<div class=\"");
530 push_class(out, "form-group", opts);
531 if field.invalid() {
532 out.push_str(" has-error");
533 }
534 if field.extended {
535 // The disclosure that hides these is a property of the form, not of the
536 // field, so the field is marked and the app opens or closes the group.
537 out.push_str("\" data-extended=\"true");
538 }
539 out.push_str("\">");
540
541 // A checkbox labels itself, on the right of the box. Both apps special-case
542 // this inline today, which is the tell that it belongs in the description;
543 // `FieldKind::labels_itself` is where it went.
544 if !field.kind.labels_itself() {
545 out.push_str("<label class=\"");
546 push_class(out, "form-label", opts);
547 // A group control is named *by* its label rather than pointing at it,
548 // so the two carry opposite halves of the association. See
549 // `is_group_control`.
550 if is_group_control(field.kind) {
551 let _ = write!(out, "\" id=\"{id}-label\">");
552 } else {
553 let _ = write!(out, "\" for=\"{id}\">");
554 }
555 escape_into(field.label, out);
556 out.push_str("</label>");
557 }
558
559 push_control(out, field, filling, opts);
560
561 if let Some(hint) = field.hint {
562 out.push_str("<div class=\"");
563 push_class(out, "form-hint", opts);
564 let _ = write!(out, "\" id=\"{id}-hint\">");
565 escape_into(hint, out);
566 out.push_str("</div>");
567 }
568 if let Some(Markup(markup)) = filling.trailing {
569 out.push_str(markup);
570 }
571 if let Some(error) = field.error {
572 out.push_str("<div class=\"");
573 push_class(out, "form-error", opts);
574 let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
575 escape_into(error, out);
576 out.push_str("</div>");
577 }
578
579 out.push_str("</div>");
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585
586 fn field(kind: FieldKind) -> Field<'static> {
587 Field::new(kind, "title", "Title")
588 }
589
590 #[test]
591 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
592 // The payload from goingson's own CHRONIC-XSS regression test.
593 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
594 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
595 // The payload survives as text, which is the point: it is inert
596 // because the quote that would have closed the attribute is encoded,
597 // not because the words were filtered.
598 assert!(!html.contains("\" onfocus"), "{html}");
599 assert!(
600 html.contains("value=\"x" onfocus=alert(1) autofocus="\""),
601 "{html}"
602 );
603 }
604
605 #[test]
606 fn a_label_cannot_open_a_tag() {
607 let mut f = field(FieldKind::Text);
608 f.label = "<script>alert(1)</script>";
609 let html = field_html(&f, &Filling::default(), &Emit::default());
610 assert!(!html.contains("<script>"), "{html}");
611 assert!(html.contains("<script>"), "{html}");
612 }
613
614 #[test]
615 fn every_escaped_sink_is_covered_by_the_one_escaper() {
616 assert_eq!(escape("&<>\"'"), "&<>"'");
617 // The character `textContent` serialization leaves alone, which is why
618 // the app needs two escapers and this needs one.
619 assert!(escape("\"").contains("""));
620 }
621
622 /// The streaming escaper is the one the emitters call and [`escape`] is a
623 /// buffer around it, so the two cannot be allowed to drift. It copies in
624 /// runs between the encoded characters, which is where a multi-byte
625 /// character would break it if the scan were not restricted to ASCII.
626 #[test]
627 fn the_streaming_escaper_appends_what_the_returning_one_returns() {
628 for text in [
629 "",
630 "plain",
631 "&<>\"'",
632 "&&&",
633 "a & b",
634 "trailing&",
635 "&leading",
636 "é世 & <b>naïve</b> \u{1f600}",
637 ] {
638 let mut out = String::from("kept: ");
639 escape_into(text, &mut out);
640 assert_eq!(out, format!("kept: {}", escape(text)), "{text:?}");
641 }
642 }
643
644 /// Same obligation one layer up: a form is a run of fields appended into one
645 /// buffer, and the two ways to get one have to agree byte for byte.
646 #[test]
647 fn a_streamed_field_is_the_field_the_other_form_returns() {
648 let kinds = [
649 FieldKind::Text,
650 FieldKind::Secret,
651 FieldKind::Number,
652 FieldKind::Checkbox,
653 FieldKind::Radio,
654 FieldKind::Select,
655 FieldKind::Textarea,
656 FieldKind::File,
657 FieldKind::Hidden,
658 ];
659 let choices = [Choice::plain("one"), Choice::plain("two")];
660 let opts = Emit {
661 class_prefix: "mk-",
662 ..Emit::default()
663 };
664 for kind in kinds {
665 let described = Field {
666 hint: Some("a hint"),
667 error: Some("wrong <here>"),
668 placeholder: Some("x\" y"),
669 options: &choices,
670 required: true,
671 max_length: Some(40),
672 min: Some("1"),
673 max: Some("9"),
674 extended: true,
675 ..Field::new(kind, "the & name", "The <label>")
676 };
677 let filling = Filling {
678 value: Value::Text("one"),
679 trailing: Some(Markup("<i>t</i>")),
680 id_prefix: Some("modal"),
681 };
682 let mut streamed = String::new();
683 field_html_into(&described, &filling, &opts, &mut streamed);
684 assert_eq!(
685 streamed,
686 field_html(&described, &filling, &opts),
687 "{kind:?}"
688 );
689
690 // And the bare field, where every optional half is absent.
691 let plain = Field::new(kind, "name", "Label");
692 let mut streamed = String::new();
693 field_html_into(&plain, &Filling::default(), &opts, &mut streamed);
694 assert_eq!(
695 streamed,
696 field_html(&plain, &Filling::default(), &opts),
697 "{kind:?}"
698 );
699 }
700 }
701
702 #[test]
703 fn markup_is_the_only_way_past_the_escaping() {
704 let filling = Filling {
705 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
706 ..Filling::default()
707 };
708 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
709 assert!(
710 html.contains("<div class=\"recurrence-config\"></div>"),
711 "{html}"
712 );
713 }
714
715 #[test]
716 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
717 let mut f = field(FieldKind::Text);
718 f.error = Some("Required");
719 let opts = Emit::default();
720 let html = field_html(&f, &Filling::default(), &opts);
721 assert!(html.contains("aria-invalid=\"true\""), "{html}");
722 // The selector the CSS side emits for exactly this state.
723 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
724 // And the group is marked too, which a renderer without descendant
725 // selectors depends on.
726 assert!(html.contains("has-error"), "{html}");
727 }
728
729 #[test]
730 fn a_valid_field_claims_nothing_about_being_invalid() {
731 let html = field_html(
732 &field(FieldKind::Text),
733 &Filling::default(),
734 &Emit::default(),
735 );
736 assert!(!html.contains("aria-invalid"), "{html}");
737 assert!(!html.contains("has-error"), "{html}");
738 }
739
740 #[test]
741 fn the_hint_survives_an_error_arriving() {
742 let mut f = field(FieldKind::Text);
743 f.hint = Some("Keep it short");
744 f.error = Some("Required");
745 let html = field_html(&f, &Filling::default(), &Emit::default());
746 assert!(
747 html.contains("aria-describedby=\"title-hint title-error\""),
748 "{html}"
749 );
750 }
751
752 #[test]
753 fn a_secret_never_carries_its_value_into_the_markup() {
754 let filling = Filling::of(Value::Text("hunter2"));
755 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
756 assert!(!html.contains("hunter2"), "{html}");
757 assert!(html.contains("type=\"password\""), "{html}");
758 }
759
760 #[test]
761 fn a_hidden_field_is_the_input_and_nothing_else() {
762 let filling = Filling::of(Value::Text("42"));
763 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
764 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
765 }
766
767 #[test]
768 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
769 let html = field_html(
770 &field(FieldKind::Checkbox),
771 &Filling::of(Value::On(true)),
772 &Emit::default(),
773 );
774 assert!(!html.contains("form-label"), "{html}");
775 assert!(html.contains("checked"), "{html}");
776 assert!(html.contains("<span>Title</span>"), "{html}");
777 }
778
779 #[test]
780 fn a_select_keeps_a_value_no_option_carries() {
781 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
782 let f = Field::select("title", "Title", &options);
783 let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
784 assert!(html.contains("data-unmatched=\"true\""), "{html}");
785 // Selected, so the next save round-trips it rather than writing the
786 // first option over the top of it.
787 assert!(html.contains("<option value=\"10\" selected"), "{html}");
788 }
789
790 #[test]
791 fn a_select_with_no_options_emits_an_empty_select() {
792 // The description says a select with no options is sayable, because an
793 // app whose option list has not loaded has exactly that. Emitting the
794 // empty select reports it on screen rather than in a log.
795 let f = Field::select("title", "Title", &[]);
796 let html = field_html(&f, &Filling::default(), &Emit::default());
797 assert!(html.contains("<select"), "{html}");
798 assert!(!html.contains("<option"), "{html}");
799 }
800
801 #[test]
802 fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
803 // The association inverts, and getting it wrong is silent: a
804 // `<label for>` aimed at a group points at no element, so the group
805 // simply has no accessible name and nothing reports that.
806 let options = [Choice::plain("copy"), Choice::plain("reference")];
807 let f = Field::radio("storage", "Storage style", &options);
808 let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
809
810 assert!(html.contains("id=\"storage-label\""), "{html}");
811 assert!(!html.contains("for=\"storage\""), "{html}");
812 assert!(html.contains("role=\"radiogroup\""), "{html}");
813 assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
814 }
815
816 #[test]
817 fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
818 // One `name` is what makes them one answer rather than three; distinct
819 // ids are what keep each `<label>` wrapping its own input.
820 let options = [
821 Choice::plain("copy"),
822 Choice::plain("reference"),
823 Choice::plain("link"),
824 ];
825 let f = Field::radio("storage", "Storage style", &options);
826 let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
827
828 assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
829 assert_eq!(html.matches(" checked").count(), 1, "{html}");
830 assert!(
831 html.contains("value=\"reference\" checked"),
832 "the checked one is the one held: {html}"
833 );
834 for index in 0..3 {
835 assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
836 }
837 }
838
839 #[test]
840 fn a_radio_group_carries_the_error_rather_than_any_one_option() {
841 // What is wrong is the answer, not one of the alternatives, so marking
842 // a single input invalid would say something false. Same reading
843 // `Field::invalid` gives one level up.
844 let options = [Choice::plain("copy"), Choice::plain("reference")];
845 let f = Field {
846 error: Some("Pick one."),
847 hint: Some("Cannot be changed later."),
848 ..Field::radio("storage", "Storage style", &options)
849 };
850 let html = field_html(&f, &Filling::default(), &Emit::default());
851
852 assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
853 assert!(
854 html.contains("aria-describedby=\"storage-hint storage-error\""),
855 "{html}"
856 );
857 // The group is the element that carries them, so they land before the
858 // first option rather than on it.
859 let group = html.find("role=\"radiogroup\"").expect("group");
860 let first = html.find("type=\"radio\"").expect("an option");
861 assert!(group < first, "{html}");
862 }
863
864 #[test]
865 fn a_compulsory_radio_group_marks_every_option() {
866 // How HTML says a group is compulsory: the constraint reads as
867 // satisfied when any one of them is checked.
868 let options = [Choice::plain("copy"), Choice::plain("reference")];
869 let f = Field {
870 required: true,
871 ..Field::radio("storage", "Storage style", &options)
872 };
873 let html = field_html(&f, &Filling::default(), &Emit::default());
874 assert_eq!(html.matches(" required").count(), 2, "{html}");
875 }
876
877 #[test]
878 fn a_radio_option_cannot_break_out_of_its_attribute() {
879 // Values are `&str` and carry whatever the app put in them. The ids are
880 // numbered rather than derived from the value for the same reason.
881 let hostile = [Choice {
882 value: "x\" onclick=alert(1) data-x=\"",
883 label: "<script>alert(1)</script>",
884 }];
885 let f = Field::radio("storage", "Storage style", &hostile);
886 let html = field_html(&f, &Filling::default(), &Emit::default());
887
888 // The payload survives as text; what must not survive is the quote
889 // that would end the attribute and let the rest of it become markup.
890 assert!(html.contains("value=\"x" onclick=alert(1)"), "{html}");
891 assert!(!html.contains("<script>"), "{html}");
892 assert!(html.contains("id=\"storage-0\""), "{html}");
893 }
894
895 #[test]
896 fn a_radio_group_with_no_options_emits_an_empty_group() {
897 // Same position the select takes, and the description's own.
898 let f = Field::radio("storage", "Storage style", &[]);
899 let html = field_html(&f, &Filling::default(), &Emit::default());
900 assert!(html.contains("role=\"radiogroup\""), "{html}");
901 assert!(!html.contains("type=\"radio\""), "{html}");
902 }
903
904 #[test]
905 fn a_placeholder_comes_off_the_description_and_is_escaped() {
906 // It arrived in `Filling` until makeover-layout 0.8.0 and was never
907 // covered here; it is a value in an attribute like any other.
908 let f = Field {
909 placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
910 ..field(FieldKind::Text)
911 };
912 let html = field_html(&f, &Filling::default(), &Emit::default());
913 assert!(html.contains("placeholder=\""), "{html}");
914 assert!(!html.contains("\" onfocus"), "{html}");
915 }
916
917 #[test]
918 fn a_select_marks_the_option_that_matches() {
919 let options = [Choice::plain("1"), Choice::plain("3")];
920 let f = Field::select("title", "Title", &options);
921 let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
922 assert!(
923 html.contains("<option value=\"3\" selected>3</option>"),
924 "{html}"
925 );
926 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
927 assert!(!html.contains("data-unmatched"), "{html}");
928 }
929
930 #[test]
931 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
932 let filling = Filling::of(Value::Text("two\nlines"));
933 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
934 assert!(html.contains(">two\nlines</textarea>"), "{html}");
935 }
936
937 #[test]
938 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
939 let opts = Emit {
940 class_prefix: "mk-",
941 ..Emit::default()
942 };
943 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
944 assert!(html.contains("class=\"mk-form-group\""), "{html}");
945 assert!(html.contains("class=\"mk-field\""), "{html}");
946 }
947
948 #[test]
949 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
950 let mut f = field(FieldKind::Text);
951 f.extended = true;
952 let html = field_html(&f, &Filling::default(), &Emit::default());
953 assert!(html.contains("data-extended=\"true\""), "{html}");
954 }
955
956 /// The prefix scopes the id and leaves the name alone. Prefixing the name
957 /// too would change what the form submits, which is the failure this pair
958 /// of assertions exists to catch rather than describe.
959 #[test]
960 fn the_id_prefix_scopes_the_id_and_never_the_name() {
961 let mut f = field(FieldKind::Text);
962 f.hint = Some("Keep it short");
963 f.error = Some("Required");
964 let filling = Filling {
965 id_prefix: Some("form-modal-task-edit"),
966 ..Filling::default()
967 };
968 let html = field_html(&f, &filling, &Emit::default());
969
970 assert!(
971 html.contains(r#"id="form-modal-task-edit-title""#),
972 "{html}"
973 );
974 assert!(html.contains(r#"name="title""#), "{html}");
975 assert!(
976 !html.contains(r#"name="form-modal-task-edit-title""#),
977 "{html}"
978 );
979
980 // The label and both associations follow the id, or they point at
981 // nothing once the same form is on screen twice.
982 assert!(
983 html.contains(r#"for="form-modal-task-edit-title""#),
984 "{html}"
985 );
986 assert!(
987 html.contains(
988 r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
989 ),
990 "{html}"
991 );
992 assert!(
993 html.contains(r#"id="form-modal-task-edit-title-hint""#),
994 "{html}"
995 );
996 }
997
998 #[test]
999 fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
1000 let filling = Filling {
1001 value: Value::Text("42"),
1002 id_prefix: Some("scoped"),
1003 ..Filling::default()
1004 };
1005 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1006 assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
1007 }
1008
1009 /// These three exist so a touch keyboard and the platform's validation
1010 /// arrive with the field. Emitting text for any of them is the regression
1011 /// the variants were added to prevent, so the type is asserted directly.
1012 #[test]
1013 fn a_constraint_becomes_the_browsers_own_attribute() {
1014 // makeover-layout 0.11.0's model: the description carries the rule and
1015 // each renderer emits its host's idiom for it. Enforcement is still
1016 // whoever validated's, and arrives back as `error`.
1017 let html = field_html(
1018 &Field {
1019 max_length: Some(100),
1020 min: Some("1"),
1021 max: Some("240"),
1022 required: true,
1023 ..Field::new(FieldKind::Number, "minutes", "Minutes")
1024 },
1025 &Filling::default(),
1026 &Emit::default(),
1027 );
1028 assert!(html.contains(r#"maxlength="100""#));
1029 assert!(html.contains(r#"min="1""#));
1030 assert!(html.contains(r#"max="240""#));
1031 assert!(html.contains(" required"));
1032 }
1033
1034 #[test]
1035 fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
1036 // The bound is text because it is only a number for some of the kinds
1037 // that take one; goingson's own sites are a duration and a datetime.
1038 let html = field_html(
1039 &Field {
1040 min: Some("2026-08-09T14:30"),
1041 ..Field::new(FieldKind::Text, "starts", "Starts")
1042 },
1043 &Filling::default(),
1044 &Emit::default(),
1045 );
1046 assert!(html.contains(r#"min="2026-08-09T14:30""#));
1047 }
1048
1049 #[test]
1050 fn a_file_field_is_a_file_input() {
1051 // `844b5ae0`. It carries no `accept`, which is measured rather than
1052 // deferred: zero sites in either app.
1053 let html = field_html(
1054 &Field::new(FieldKind::File, "attachment", "Attachment"),
1055 &Filling::default(),
1056 &Emit::default(),
1057 );
1058 assert!(html.contains(r#"type="file""#));
1059 assert!(!html.contains("accept="));
1060 // And it never carries a value: a file input's value is not settable
1061 // from markup, and the browser refuses one that tries.
1062 assert!(!html.contains("value="));
1063 }
1064
1065 #[test]
1066 fn the_typed_text_kinds_keep_their_input_type() {
1067 for (kind, expected) in [
1068 (FieldKind::Email, "email"),
1069 (FieldKind::Url, "url"),
1070 (FieldKind::Tel, "tel"),
1071 (FieldKind::Date, "date"),
1072 (FieldKind::DateTime, "datetime-local"),
1073 ] {
1074 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1075 assert!(
1076 html.contains(&format!(r#"type="{expected}""#)),
1077 "{kind:?} emitted {html}"
1078 );
1079 }
1080 }
1081
1082 #[test]
1083 fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
1084 // The regression this closes: described as text with a hint reading
1085 // "YYYY-MM-DD", which loses the picker, the platform's validation and
1086 // the touch keyboard, and asks prose to do all three.
1087 for kind in [FieldKind::Date, FieldKind::DateTime] {
1088 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1089 assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
1090 }
1091 }
1092
1093 #[test]
1094 fn no_prefix_leaves_the_id_as_the_name() {
1095 let html = field_html(
1096 &field(FieldKind::Text),
1097 &Filling::default(),
1098 &Emit::default(),
1099 );
1100 assert!(html.contains(r#"id="title" name="title""#), "{html}");
1101 }
1102}