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 // The clearest case in this list that a kind is not decoration: a
210 // number and a range submit the same value and are different controls,
211 // and the browser is the one drawing the difference.
212 FieldKind::Range => "range",
213 // Select and Textarea are not inputs at all; they never reach here.
214 // Radio is one, but it is emitted once per option by `radio_html` and
215 // so does not reach here either.
216 FieldKind::Text | FieldKind::Select | FieldKind::Textarea | FieldKind::Rich => "text",
217 // A kind added to the description since this renderer was built. Text
218 // accepts any value the others would, so it degrades rather than
219 // dropping the field.
220 _ => "text",
221 }
222}
223
224/// The attributes every visible control carries, error state included.
225///
226/// `aria-invalid` is the whole reason the error state is readable at all: the
227/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
228/// than on a class, so a control rendered already-invalid without it is styled
229/// as if nothing were wrong. goingson's runtime validation path sets the
230/// attribute and its initial render does not, which is exactly the drift one
231/// emitter removes.
232/// `id` and `name` arrive separately because they are not the same fact. The
233/// name is what submits and is fixed by the description; the id has to be
234/// unique in the document and so carries [`Filling::id_prefix`] when a form
235/// appears more than once.
236/// The `accept` attribute, from the description's accept list.
237///
238/// makeover-layout 0.31.0. The list is comma-joined because that is the
239/// attribute's own format, and each entry writes itself: a family is its
240/// wildcard media type, a media type is itself, a suffix is itself with its
241/// leading dot. Nothing is normalised on the way through -- `.tar.gz` is two
242/// dots and the browser is fine with it.
243///
244/// An empty list emits no attribute at all, which is the browser's own "any
245/// file" and is what the description means by listing nothing. Emitting
246/// `accept=""` instead would be a filter that matches nothing on some browsers
247/// and everything on others.
248///
249/// It is a filter and not a guarantee, on the browser's side as much as here:
250/// the picker keeps an "All Files" escape and the user may take it. Whoever
251/// validated still validates.
252fn push_accept(out: &mut String, field: &Field<'_>) {
253 if field.accept.is_empty() {
254 return;
255 }
256 out.push_str(" accept=\"");
257 for (index, one) in field.accept.iter().enumerate() {
258 if index > 0 {
259 out.push(',');
260 }
261 escape_into(one.as_str(), out);
262 }
263 out.push('"');
264}
265
266fn push_control_attributes(out: &mut String, field: &Field<'_>, id: &str, name: &str) {
267 let _ = write!(out, " id=\"{id}\" name=\"");
268 escape_into(name, out);
269 out.push('"');
270 if field.required {
271 out.push_str(" required");
272 }
273 // makeover-layout 0.11.0's constraints. The description carries the rule and
274 // this emits the browser's idiom for it, which is the model `required` has
275 // been using since before the crate wrote down that it carried none.
276 // Enforcement is still whoever validated's, and arrives back as `error`.
277 if let Some(limit) = field.max_length {
278 let _ = write!(out, " maxlength=\"{limit}\"");
279 }
280 if let Some(min) = field.min {
281 out.push_str(" min=\"");
282 escape_into(min, out);
283 out.push('"');
284 }
285 if let Some(max) = field.max {
286 out.push_str(" max=\"");
287 escape_into(max, out);
288 out.push('"');
289 }
290 // The browser's own default is `step="1"`, which turns a 0-to-1 threshold
291 // into a two-position control. That is the granularity the description
292 // means when it says nothing, so this is emitted only when an app has said
293 // otherwise rather than defaulted here.
294 if let Some(step) = field.step {
295 out.push_str(" step=\"");
296 escape_into(step, out);
297 out.push('"');
298 }
299 if field.invalid() {
300 out.push_str(" aria-invalid=\"true\"");
301 }
302
303 push_described_by(out, field, id);
304}
305
306/// The `aria-describedby` naming whatever of the hint and the error exist.
307///
308/// Both associations, in the order they are useful: the standing help, then
309/// what is currently wrong. goingson's runtime path points describedby at the
310/// error alone and drops the hint association it never made in the first place;
311/// naming both here means the hint survives an error appearing.
312///
313/// Its own function because a radio group carries it on the group rather than
314/// on a control, and one reading of "what describes this field" is the point.
315fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
316 if field.hint.is_none() && field.error.is_none() {
317 return;
318 }
319 out.push_str(" aria-describedby=\"");
320 if field.hint.is_some() {
321 let _ = write!(out, "{id}-hint");
322 }
323 if field.error.is_some() {
324 if field.hint.is_some() {
325 out.push(' ');
326 }
327 let _ = write!(out, "{id}-error");
328 }
329 out.push('"');
330}
331
332/// Whether the field's control is a set of elements rather than one.
333///
334/// A DOM concern rather than a description one, which is why it is decided here
335/// and not in `makeover-layout`: `for` and `id` are an HTML association and
336/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
337/// points at nothing, because no single element carries the group's id, so the
338/// association has to invert — the label takes an id and the group names itself
339/// with `aria-labelledby`.
340const fn is_group_control(kind: FieldKind) -> bool {
341 matches!(kind, FieldKind::Radio)
342}
343
344/// A radio group: the options as sibling inputs sharing one `name`.
345///
346/// The group carries the error state and the descriptions, and the inputs carry
347/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
348/// down: marking a single input invalid would say the wrong thing, since what
349/// is wrong is the answer to the question and not one of the alternatives.
350///
351/// Ids are numbered rather than built from the option values, which can hold
352/// anything a `&str` can — spaces and quotes included — and would otherwise
353/// have to be slugged into something unique by a rule this crate would then own.
354///
355/// `required` lands on every input, which is how HTML says a group is
356/// compulsory: the constraint is satisfied when any one of them is checked.
357fn push_radio(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
358 let id = filling.id_for(field.name);
359 let value = filling.value.as_text();
360 let name = escape(field.name);
361
362 out.push_str("<div class=\"");
363 push_class(out, "form-radio-group", opts);
364 let _ = write!(out, "\" role=\"radiogroup\" aria-labelledby=\"{id}-label\"");
365 if field.invalid() {
366 out.push_str(" aria-invalid=\"true\"");
367 }
368 push_described_by(out, field, &id);
369 out.push('>');
370
371 // A group described with no options emits an empty group, for the reason
372 // `Field::options` gives: an app whose option list has not loaded has
373 // exactly that, and an empty group says so on screen rather than in a log.
374 for (index, opt) in field.options.iter().enumerate() {
375 out.push_str("<label class=\"");
376 push_class(out, "form-radio-label", opts);
377 let _ = write!(
378 out,
379 "\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" value=\""
380 );
381 escape_into(opt.value, out);
382 out.push('"');
383 if opt.value == value {
384 out.push_str(" checked");
385 }
386 if field.required {
387 out.push_str(" required");
388 }
389 // A radio group has room a `<select>` does not, so the reason gets its
390 // own element beside the label rather than being run into it. The class
391 // is what a stylesheet mutes; the text is there either way, which is
392 // the half that matters — the finding was a greyed control with its
393 // explanation behind a hover.
394 if let Some(reason) = opt.unavailable {
395 out.push_str(" disabled");
396 out.push_str("><span>");
397 escape_into(opt.label, out);
398 out.push_str("</span><span class=\"");
399 push_class(out, "form-option-reason", opts);
400 out.push_str("\">");
401 escape_into(reason, out);
402 out.push_str("</span></label>");
403 continue;
404 }
405 out.push_str("><span>");
406 escape_into(opt.label, out);
407 out.push_str("</span></label>");
408 }
409
410 out.push_str("</div>");
411}
412
413/// The options of a select: the unanswered instruction, an unmatched current
414/// value carried as its own, then the options themselves.
415///
416/// A select handed a value no option carries renders with nothing selected, the
417/// browser falls back to the first option, and the next save writes a value
418/// nobody chose. goingson hit exactly that with a backup-retention default of
419/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
420/// here so the second app gets it without hitting the bug first.
421fn push_options(out: &mut String, field: &Field<'_>, options: &[Choice<'_>], value: &str) {
422 // The unanswered state, which HTML has no attribute for: `placeholder` is
423 // not a `<select>` attribute, and the idiom is an empty option that cannot
424 // be chosen back. `disabled` is what stops it being re-selected once the
425 // user has answered, and `selected` is what puts it in the closed control
426 // while the value is empty; together they read as an instruction rather
427 // than as an option.
428 //
429 // `required` keeps working through it rather than around it: the option's
430 // value is empty, so a required select with this showing is invalid, which
431 // is the true report on a question nobody has answered.
432 //
433 // Emitted only while the value is empty, so it does not sit in the open
434 // list once the field is answered. A non-empty value no option carries is a
435 // wrong answer rather than an absent one and takes the stray-option path
436 // below.
437 if value.is_empty()
438 && let Some(text) = field.placeholder
439 {
440 out.push_str("<option value=\"\" disabled selected>");
441 escape_into(text, out);
442 out.push_str("</option>");
443 }
444 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
445 // The one place an escaped value is worth keeping: it is written twice,
446 // as the option's value and as its text.
447 let escaped = escape(value);
448 let _ = write!(
449 out,
450 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
451 );
452 }
453 for opt in options {
454 out.push_str("<option value=\"");
455 escape_into(opt.value, out);
456 out.push('"');
457 if opt.value == value {
458 out.push_str(" selected");
459 }
460 // `disabled` is what the browser reads, and it says nothing about why.
461 // The reason goes in the option's own text, because a `<select>` gives
462 // its options no room for anything else: no title attribute the
463 // keyboard reaches, no second line, no element inside. So the row reads
464 // "Multi-sample: Drop a second sample onto the keyboard." and is the
465 // one place the precondition can be both attached to its option and
466 // read without a pointer.
467 if let Some(reason) = opt.unavailable {
468 out.push_str(" disabled");
469 out.push('>');
470 escape_into(opt.label, out);
471 out.push_str(": ");
472 escape_into(reason, out);
473 out.push_str("</option>");
474 continue;
475 }
476 out.push('>');
477 escape_into(opt.label, out);
478 out.push_str("</option>");
479 }
480}
481
482/// The control itself, without its label, hint or error.
483fn push_control(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
484 // Emitted before anything else is computed: a radio group carries its
485 // descriptions on the group rather than on a control, so none of the
486 // attributes below belong to it.
487 if matches!(field.kind, FieldKind::Radio) {
488 push_radio(out, field, filling, opts);
489 return;
490 }
491
492 let id = filling.id_for(field.name);
493 let placeholder = |out: &mut String| {
494 if let Some(text) = field.placeholder {
495 out.push_str(" placeholder=\"");
496 escape_into(text, out);
497 out.push('"');
498 }
499 };
500
501 match field.kind {
502 // Both multi-line kinds are a `<textarea>`, and the markdown one says so
503 // in an attribute rather than in a class: what the value *is* is not a
504 // styling hook, and a progressive enhancement looking for editors to
505 // upgrade needs a selector that survives `Emit`'s class prefixing.
506 // Without the mark, a described editor is a plain box and the four
507 // hand-written MNW editors have nothing to convert onto.
508 //
509 // `data-format` and not `data-value`: this names the shape of the
510 // value, and `facet` already spends `data-facet-value` on carrying an
511 // actual one. Two attributes a letter apart meaning opposite things is
512 // how a renderer's own vocabulary starts drifting.
513 kind if kind.multiline() => {
514 out.push_str("<textarea class=\"");
515 push_class(out, "field", opts);
516 out.push('"');
517 if matches!(kind, FieldKind::Rich) {
518 out.push_str(" data-format=\"markdown\"");
519 }
520 push_control_attributes(out, field, &id, field.name);
521 placeholder(out);
522 out.push('>');
523 escape_into(filling.value.as_text(), out);
524 out.push_str("</textarea>");
525 }
526 FieldKind::Select => {
527 out.push_str("<select class=\"");
528 push_class(out, "field", opts);
529 out.push('"');
530 push_control_attributes(out, field, &id, field.name);
531 out.push('>');
532 // A select described with no options emits an empty select, which
533 // says so on screen rather than in a log. That is the description's
534 // own position on `Field::options`, not a fallback invented here.
535 push_options(out, field, field.options, filling.value.as_text());
536 out.push_str("</select>");
537 }
538 FieldKind::Checkbox => {
539 out.push_str("<label class=\"");
540 push_class(out, "form-checkbox-label", opts);
541 out.push_str("\"><input type=\"checkbox\"");
542 push_control_attributes(out, field, &id, field.name);
543 if matches!(filling.value, Value::On(true)) {
544 out.push_str(" checked");
545 }
546 out.push_str("><span>");
547 escape_into(field.label, out);
548 out.push_str("</span></label>");
549 }
550 // A secret never carries its value into the markup. `FieldKind::secret`
551 // is documented as a value that must not be round-tripped through
552 // anything that might persist it, and the DOM is such a thing: it is
553 // read by every extension on the page and is the first thing a crash
554 // reporter serialises. Neither app pre-fills one today, so this costs
555 // nothing and closes the door before something does.
556 FieldKind::Secret => {
557 out.push_str("<input type=\"password\" class=\"");
558 push_class(out, "field", opts);
559 out.push('"');
560 push_control_attributes(out, field, &id, field.name);
561 placeholder(out);
562 out.push('>');
563 }
564 // A file input carries no value, and this is the browser's rule rather
565 // than a preference: setting one from markup is refused, because a page
566 // that could preselect a path could read a file the user never offered.
567 // Nothing upstream needs to know, which is why the exception is here.
568 FieldKind::File => {
569 out.push_str("<input type=\"file\" class=\"");
570 push_class(out, "field", opts);
571 out.push('"');
572 push_control_attributes(out, field, &id, field.name);
573 push_accept(out, field);
574 if field.multiple {
575 out.push_str(" multiple");
576 }
577 out.push('>');
578 }
579 kind => {
580 let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
581 push_class(out, "field", opts);
582 out.push('"');
583 push_control_attributes(out, field, &id, field.name);
584 placeholder(out);
585 out.push_str(" value=\"");
586 escape_into(filling.value.as_text(), out);
587 out.push_str("\">");
588 }
589 }
590}
591
592/// One field, as the group the app drops into its form.
593///
594/// The shape is goingson's, down to the class names, so adoption there deletes
595/// `renderFormField` rather than restyling anything. That is also why the class
596/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
597/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
598/// emits only what it can generate from the description. Whether they should
599/// move into the description is the next question this raises, not one it
600/// answers.
601///
602/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
603/// nothing drawn, which is what [`FieldKind::visible`] means.
604///
605/// The error marks the group as well as the control. That is
606/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
607/// cannot find the group from the message, so the group has to be told.
608///
609/// ```
610/// use makeover_layout::{Field, FieldKind};
611/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
612///
613/// let field = Field::new(FieldKind::Text, "title", "Title");
614/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
615///
616/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
617/// assert!(html.contains(r#"value="Ship it""#));
618/// ```
619#[must_use]
620pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
621 let mut html = String::new();
622 field_html_into(field, filling, opts, &mut html);
623 html
624}
625
626/// One field, written into a buffer the caller already has.
627///
628/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
629/// these, so a host building one should hold a single buffer and append each
630/// field into it rather than take a `String` per field and concatenate.
631pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
632 let id = filling.id_for(field.name);
633
634 if !field.kind.visible() {
635 // Name only, no id: a hidden field is never pointed at by a label or a
636 // description, so the one attribute it needs is the one that submits.
637 out.push_str("<input type=\"hidden\" name=\"");
638 escape_into(field.name, out);
639 out.push_str("\" value=\"");
640 escape_into(filling.value.as_text(), out);
641 out.push_str("\">");
642 return;
643 }
644
645 out.push_str("<div class=\"");
646 push_class(out, "form-group", opts);
647 if field.invalid() {
648 out.push_str(" has-error");
649 }
650 if field.extended {
651 // The disclosure that hides these is a property of the form, not of the
652 // field, so the field is marked and the app opens or closes the group.
653 out.push_str("\" data-extended=\"true");
654 }
655 out.push_str("\">");
656
657 // A checkbox labels itself, on the right of the box. Both apps special-case
658 // this inline today, which is the tell that it belongs in the description;
659 // `FieldKind::labels_itself` is where it went.
660 if !field.kind.labels_itself() {
661 out.push_str("<label class=\"");
662 push_class(out, "form-label", opts);
663 // A group control is named *by* its label rather than pointing at it,
664 // so the two carry opposite halves of the association. See
665 // `is_group_control`.
666 if is_group_control(field.kind) {
667 let _ = write!(out, "\" id=\"{id}-label\">");
668 } else {
669 let _ = write!(out, "\" for=\"{id}\">");
670 }
671 escape_into(field.label, out);
672 out.push_str("</label>");
673 }
674
675 push_control(out, field, filling, opts);
676
677 if let Some(hint) = field.hint {
678 out.push_str("<div class=\"");
679 push_class(out, "form-hint", opts);
680 let _ = write!(out, "\" id=\"{id}-hint\">");
681 escape_into(hint, out);
682 out.push_str("</div>");
683 }
684 if let Some(Markup(markup)) = filling.trailing {
685 out.push_str(markup);
686 }
687 if let Some(error) = field.error {
688 out.push_str("<div class=\"");
689 push_class(out, "form-error", opts);
690 let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
691 escape_into(error, out);
692 out.push_str("</div>");
693 }
694
695 out.push_str("</div>");
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701 use makeover_layout::{Accepted, Family};
702
703 fn field(kind: FieldKind) -> Field<'static> {
704 Field::new(kind, "title", "Title")
705 }
706
707 #[test]
708 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
709 // The payload from goingson's own CHRONIC-XSS regression test.
710 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
711 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
712 // The payload survives as text, which is the point: it is inert
713 // because the quote that would have closed the attribute is encoded,
714 // not because the words were filtered.
715 assert!(!html.contains("\" onfocus"), "{html}");
716 assert!(
717 html.contains("value=\"x" onfocus=alert(1) autofocus="\""),
718 "{html}"
719 );
720 }
721
722 #[test]
723 fn a_label_cannot_open_a_tag() {
724 let mut f = field(FieldKind::Text);
725 f.label = "<script>alert(1)</script>";
726 let html = field_html(&f, &Filling::default(), &Emit::default());
727 assert!(!html.contains("<script>"), "{html}");
728 assert!(html.contains("<script>"), "{html}");
729 }
730
731 #[test]
732 fn every_escaped_sink_is_covered_by_the_one_escaper() {
733 assert_eq!(escape("&<>\"'"), "&<>"'");
734 // The character `textContent` serialization leaves alone, which is why
735 // the app needs two escapers and this needs one.
736 assert!(escape("\"").contains("""));
737 }
738
739 /// The streaming escaper is the one the emitters call and [`escape`] is a
740 /// buffer around it, so the two cannot be allowed to drift. It copies in
741 /// runs between the encoded characters, which is where a multi-byte
742 /// character would break it if the scan were not restricted to ASCII.
743 #[test]
744 fn the_streaming_escaper_appends_what_the_returning_one_returns() {
745 for text in [
746 "",
747 "plain",
748 "&<>\"'",
749 "&&&",
750 "a & b",
751 "trailing&",
752 "&leading",
753 "é世 & <b>naïve</b> \u{1f600}",
754 ] {
755 let mut out = String::from("kept: ");
756 escape_into(text, &mut out);
757 assert_eq!(out, format!("kept: {}", escape(text)), "{text:?}");
758 }
759 }
760
761 /// Same obligation one layer up: a form is a run of fields appended into one
762 /// buffer, and the two ways to get one have to agree byte for byte.
763 #[test]
764 fn a_streamed_field_is_the_field_the_other_form_returns() {
765 let kinds = [
766 FieldKind::Text,
767 FieldKind::Secret,
768 FieldKind::Number,
769 FieldKind::Checkbox,
770 FieldKind::Radio,
771 FieldKind::Select,
772 FieldKind::Textarea,
773 FieldKind::File,
774 FieldKind::Hidden,
775 ];
776 let choices = [Choice::plain("one"), Choice::plain("two")];
777 let opts = Emit {
778 class_prefix: "mk-",
779 ..Emit::default()
780 };
781 for kind in kinds {
782 let described = Field {
783 hint: Some("a hint"),
784 error: Some("wrong <here>"),
785 placeholder: Some("x\" y"),
786 options: &choices,
787 required: true,
788 max_length: Some(40),
789 min: Some("1"),
790 max: Some("9"),
791 extended: true,
792 ..Field::new(kind, "the & name", "The <label>")
793 };
794 let filling = Filling {
795 value: Value::Text("one"),
796 trailing: Some(Markup("<i>t</i>")),
797 id_prefix: Some("modal"),
798 };
799 let mut streamed = String::new();
800 field_html_into(&described, &filling, &opts, &mut streamed);
801 assert_eq!(
802 streamed,
803 field_html(&described, &filling, &opts),
804 "{kind:?}"
805 );
806
807 // And the bare field, where every optional half is absent.
808 let plain = Field::new(kind, "name", "Label");
809 let mut streamed = String::new();
810 field_html_into(&plain, &Filling::default(), &opts, &mut streamed);
811 assert_eq!(
812 streamed,
813 field_html(&plain, &Filling::default(), &opts),
814 "{kind:?}"
815 );
816 }
817 }
818
819 #[test]
820 fn markup_is_the_only_way_past_the_escaping() {
821 let filling = Filling {
822 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
823 ..Filling::default()
824 };
825 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
826 assert!(
827 html.contains("<div class=\"recurrence-config\"></div>"),
828 "{html}"
829 );
830 }
831
832 #[test]
833 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
834 let mut f = field(FieldKind::Text);
835 f.error = Some("Required");
836 let opts = Emit::default();
837 let html = field_html(&f, &Filling::default(), &opts);
838 assert!(html.contains("aria-invalid=\"true\""), "{html}");
839 // The selector the CSS side emits for exactly this state.
840 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
841 // And the group is marked too, which a renderer without descendant
842 // selectors depends on.
843 assert!(html.contains("has-error"), "{html}");
844 }
845
846 #[test]
847 fn a_valid_field_claims_nothing_about_being_invalid() {
848 let html = field_html(
849 &field(FieldKind::Text),
850 &Filling::default(),
851 &Emit::default(),
852 );
853 assert!(!html.contains("aria-invalid"), "{html}");
854 assert!(!html.contains("has-error"), "{html}");
855 }
856
857 #[test]
858 fn the_hint_survives_an_error_arriving() {
859 let mut f = field(FieldKind::Text);
860 f.hint = Some("Keep it short");
861 f.error = Some("Required");
862 let html = field_html(&f, &Filling::default(), &Emit::default());
863 assert!(
864 html.contains("aria-describedby=\"title-hint title-error\""),
865 "{html}"
866 );
867 }
868
869 #[test]
870 fn a_secret_never_carries_its_value_into_the_markup() {
871 let filling = Filling::of(Value::Text("hunter2"));
872 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
873 assert!(!html.contains("hunter2"), "{html}");
874 assert!(html.contains("type=\"password\""), "{html}");
875 }
876
877 #[test]
878 fn a_hidden_field_is_the_input_and_nothing_else() {
879 let filling = Filling::of(Value::Text("42"));
880 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
881 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
882 }
883
884 #[test]
885 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
886 let html = field_html(
887 &field(FieldKind::Checkbox),
888 &Filling::of(Value::On(true)),
889 &Emit::default(),
890 );
891 assert!(!html.contains("form-label"), "{html}");
892 assert!(html.contains("checked"), "{html}");
893 assert!(html.contains("<span>Title</span>"), "{html}");
894 }
895
896 #[test]
897 fn a_select_keeps_a_value_no_option_carries() {
898 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
899 let f = Field::select("title", "Title", &options);
900 let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
901 assert!(html.contains("data-unmatched=\"true\""), "{html}");
902 // Selected, so the next save round-trips it rather than writing the
903 // first option over the top of it.
904 assert!(html.contains("<option value=\"10\" selected"), "{html}");
905 }
906
907 #[test]
908 fn a_select_with_no_options_emits_an_empty_select() {
909 // The description says a select with no options is sayable, because an
910 // app whose option list has not loaded has exactly that. Emitting the
911 // empty select reports it on screen rather than in a log.
912 let f = Field::select("title", "Title", &[]);
913 let html = field_html(&f, &Filling::default(), &Emit::default());
914 assert!(html.contains("<select"), "{html}");
915 assert!(!html.contains("<option"), "{html}");
916 }
917
918 #[test]
919 fn an_unanswered_select_shows_its_ghost_text_and_cannot_be_chosen_back() {
920 let options = [Choice::new("sp404", "SP-404")];
921 let f = Field {
922 placeholder: Some("Select device..."),
923 ..Field::select("device", "Conform for device", &options)
924 };
925 let html = field_html(&f, &Filling::default(), &Emit::default());
926
927 assert!(
928 html.contains("<option value=\"\" disabled selected>Select device...</option>"),
929 "{html}"
930 );
931 // First, so the closed control reads it rather than the first real
932 // option.
933 assert!(
934 html.find("Select device...") < html.find("SP-404"),
935 "{html}"
936 );
937 }
938
939 #[test]
940 fn an_answered_select_drops_the_ghost_text() {
941 // It is an instruction about an empty field, so it has nothing to say
942 // once the field is answered, and leaving it in the list is one dead
943 // row every time the control is opened afterwards.
944 let options = [Choice::new("sp404", "SP-404")];
945 let f = Field {
946 placeholder: Some("Select device..."),
947 ..Field::select("device", "Conform for device", &options)
948 };
949 let html = field_html(&f, &Filling::of(Value::Text("sp404")), &Emit::default());
950 assert!(!html.contains("Select device..."), "{html}");
951 }
952
953 #[test]
954 fn a_wrong_answer_is_kept_and_is_not_the_ghost_text() {
955 // The two paths through `push_options` meet here. An unmatched value is
956 // an answer that is wrong and stays visible as itself; only the empty
957 // value is unanswered.
958 let options = [Choice::plain("1"), Choice::plain("7")];
959 let f = Field {
960 placeholder: Some("Pick one"),
961 ..Field::select("retention", "Keep backups for", &options)
962 };
963 let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
964 assert!(html.contains("data-unmatched=\"true\""), "{html}");
965 assert!(!html.contains("Pick one"), "{html}");
966 }
967
968 #[test]
969 fn a_range_is_a_range_input_and_carries_its_extent() {
970 let f = Field {
971 step: Some("0.01"),
972 ..Field::range("review", "Review above", "0", "1")
973 };
974 let html = field_html(&f, &Filling::of(Value::Text("0.72")), &Emit::default());
975 assert!(html.contains("type=\"range\""), "{html}");
976 assert!(html.contains("min=\"0\""), "{html}");
977 assert!(html.contains("max=\"1\""), "{html}");
978 // Without it the browser steps by 1 and a 0-to-1 question becomes a
979 // two-position control.
980 assert!(html.contains("step=\"0.01\""), "{html}");
981 }
982
983 #[test]
984 fn a_number_with_bounds_is_still_typed_into() {
985 // The distinction the kind exists for, at the renderer where getting it
986 // wrong is most visible: goingson's `min="1"` duration must not come
987 // back as a slider.
988 let f = Field {
989 min: Some("1"),
990 ..Field::new(FieldKind::Number, "minutes", "Minutes")
991 };
992 let html = field_html(&f, &Filling::of(Value::Text("30")), &Emit::default());
993 assert!(html.contains("type=\"number\""), "{html}");
994 assert!(!html.contains("type=\"range\""), "{html}");
995 // And nothing invents a step for it.
996 assert!(!html.contains("step="), "{html}");
997 }
998
999 #[test]
1000 fn an_unavailable_option_is_disabled_and_says_why() {
1001 let options = [
1002 Choice::new("chromatic", "Chromatic"),
1003 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1004 ];
1005 let f = Field::radio("mode", "Mode", &options);
1006 let html = field_html(&f, &Filling::of(Value::Text("chromatic")), &Emit::default());
1007
1008 assert!(html.contains(" disabled"), "{html}");
1009 assert!(html.contains("Drop a second sample."), "{html}");
1010 // The option is still offered: dropping it is what costs the user the
1011 // knowledge that the mode exists.
1012 assert!(html.contains("value=\"multi\""), "{html}");
1013 // And the reason is its own element, not run into the label.
1014 assert!(html.contains("form-option-reason"), "{html}");
1015 }
1016
1017 #[test]
1018 fn an_unavailable_select_option_carries_its_reason_in_its_text() {
1019 // A `<select>` gives an option no room for a second element, so the
1020 // reason has to be in the text or be unreadable without a pointer.
1021 let options = [Choice::new("multi", "Multi-sample").unless("Drop a second sample.")];
1022 let f = Field::select("mode", "Mode", &options);
1023 let html = field_html(&f, &Filling::default(), &Emit::default());
1024 assert!(
1025 html.contains(">Multi-sample: Drop a second sample.</option>"),
1026 "{html}"
1027 );
1028 assert!(html.contains("disabled"), "{html}");
1029 }
1030
1031 #[test]
1032 fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
1033 // The association inverts, and getting it wrong is silent: a
1034 // `<label for>` aimed at a group points at no element, so the group
1035 // simply has no accessible name and nothing reports that.
1036 let options = [Choice::plain("copy"), Choice::plain("reference")];
1037 let f = Field::radio("storage", "Storage style", &options);
1038 let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
1039
1040 assert!(html.contains("id=\"storage-label\""), "{html}");
1041 assert!(!html.contains("for=\"storage\""), "{html}");
1042 assert!(html.contains("role=\"radiogroup\""), "{html}");
1043 assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
1044 }
1045
1046 #[test]
1047 fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
1048 // One `name` is what makes them one answer rather than three; distinct
1049 // ids are what keep each `<label>` wrapping its own input.
1050 let options = [
1051 Choice::plain("copy"),
1052 Choice::plain("reference"),
1053 Choice::plain("link"),
1054 ];
1055 let f = Field::radio("storage", "Storage style", &options);
1056 let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
1057
1058 assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
1059 assert_eq!(html.matches(" checked").count(), 1, "{html}");
1060 assert!(
1061 html.contains("value=\"reference\" checked"),
1062 "the checked one is the one held: {html}"
1063 );
1064 for index in 0..3 {
1065 assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
1066 }
1067 }
1068
1069 #[test]
1070 fn a_radio_group_carries_the_error_rather_than_any_one_option() {
1071 // What is wrong is the answer, not one of the alternatives, so marking
1072 // a single input invalid would say something false. Same reading
1073 // `Field::invalid` gives one level up.
1074 let options = [Choice::plain("copy"), Choice::plain("reference")];
1075 let f = Field {
1076 error: Some("Pick one."),
1077 hint: Some("Cannot be changed later."),
1078 ..Field::radio("storage", "Storage style", &options)
1079 };
1080 let html = field_html(&f, &Filling::default(), &Emit::default());
1081
1082 assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
1083 assert!(
1084 html.contains("aria-describedby=\"storage-hint storage-error\""),
1085 "{html}"
1086 );
1087 // The group is the element that carries them, so they land before the
1088 // first option rather than on it.
1089 let group = html.find("role=\"radiogroup\"").expect("group");
1090 let first = html.find("type=\"radio\"").expect("an option");
1091 assert!(group < first, "{html}");
1092 }
1093
1094 #[test]
1095 fn a_compulsory_radio_group_marks_every_option() {
1096 // How HTML says a group is compulsory: the constraint reads as
1097 // satisfied when any one of them is checked.
1098 let options = [Choice::plain("copy"), Choice::plain("reference")];
1099 let f = Field {
1100 required: true,
1101 ..Field::radio("storage", "Storage style", &options)
1102 };
1103 let html = field_html(&f, &Filling::default(), &Emit::default());
1104 assert_eq!(html.matches(" required").count(), 2, "{html}");
1105 }
1106
1107 #[test]
1108 fn a_radio_option_cannot_break_out_of_its_attribute() {
1109 // Values are `&str` and carry whatever the app put in them. The ids are
1110 // numbered rather than derived from the value for the same reason.
1111 let hostile = [Choice::new(
1112 "x\" onclick=alert(1) data-x=\"",
1113 "<script>alert(1)</script>",
1114 )];
1115 let f = Field::radio("storage", "Storage style", &hostile);
1116 let html = field_html(&f, &Filling::default(), &Emit::default());
1117
1118 // The payload survives as text; what must not survive is the quote
1119 // that would end the attribute and let the rest of it become markup.
1120 assert!(html.contains("value=\"x" onclick=alert(1)"), "{html}");
1121 assert!(!html.contains("<script>"), "{html}");
1122 assert!(html.contains("id=\"storage-0\""), "{html}");
1123 }
1124
1125 #[test]
1126 fn a_radio_group_with_no_options_emits_an_empty_group() {
1127 // Same position the select takes, and the description's own.
1128 let f = Field::radio("storage", "Storage style", &[]);
1129 let html = field_html(&f, &Filling::default(), &Emit::default());
1130 assert!(html.contains("role=\"radiogroup\""), "{html}");
1131 assert!(!html.contains("type=\"radio\""), "{html}");
1132 }
1133
1134 #[test]
1135 fn a_placeholder_comes_off_the_description_and_is_escaped() {
1136 // It arrived in `Filling` until makeover-layout 0.8.0 and was never
1137 // covered here; it is a value in an attribute like any other.
1138 let f = Field {
1139 placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
1140 ..field(FieldKind::Text)
1141 };
1142 let html = field_html(&f, &Filling::default(), &Emit::default());
1143 assert!(html.contains("placeholder=\""), "{html}");
1144 assert!(!html.contains("\" onfocus"), "{html}");
1145 }
1146
1147 #[test]
1148 fn a_select_marks_the_option_that_matches() {
1149 let options = [Choice::plain("1"), Choice::plain("3")];
1150 let f = Field::select("title", "Title", &options);
1151 let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
1152 assert!(
1153 html.contains("<option value=\"3\" selected>3</option>"),
1154 "{html}"
1155 );
1156 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
1157 assert!(!html.contains("data-unmatched"), "{html}");
1158 }
1159
1160 #[test]
1161 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
1162 let filling = Filling::of(Value::Text("two\nlines"));
1163 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1164 assert!(html.contains(">two\nlines</textarea>"), "{html}");
1165 }
1166
1167 #[test]
1168 fn a_markdown_field_is_a_textarea_that_says_what_its_value_is() {
1169 // The mark is the whole difference. Without it a described editor is a
1170 // plain box, and an enhancement looking for editors to upgrade has
1171 // nothing to find -- which is the state MNW's four hand-written section
1172 // editors would have had to keep living in.
1173 let filling = Filling::of(Value::Text("# Heading"));
1174 let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1175 assert!(html.contains("<textarea"), "{html}");
1176 assert!(html.contains(r#"data-format="markdown""#), "{html}");
1177 assert!(html.contains("># Heading</textarea>"), "{html}");
1178
1179 // A plain textarea claims nothing about its value, so the marker has to
1180 // be absent rather than present-and-different.
1181 let plain = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1182 assert!(!plain.contains("data-format"), "{plain}");
1183
1184 // And it is not an input: the catch-all in `input_type` would have
1185 // degraded it to a single-line text box, which is the wrong shape for
1186 // markdown rather than a lossless fallback.
1187 assert!(!html.contains("<input"), "{html}");
1188 }
1189
1190 #[test]
1191 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
1192 let opts = Emit {
1193 class_prefix: "mk-",
1194 ..Emit::default()
1195 };
1196 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
1197 assert!(html.contains("class=\"mk-form-group\""), "{html}");
1198 assert!(html.contains("class=\"mk-field\""), "{html}");
1199 }
1200
1201 #[test]
1202 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
1203 let mut f = field(FieldKind::Text);
1204 f.extended = true;
1205 let html = field_html(&f, &Filling::default(), &Emit::default());
1206 assert!(html.contains("data-extended=\"true\""), "{html}");
1207 }
1208
1209 /// The prefix scopes the id and leaves the name alone. Prefixing the name
1210 /// too would change what the form submits, which is the failure this pair
1211 /// of assertions exists to catch rather than describe.
1212 #[test]
1213 fn the_id_prefix_scopes_the_id_and_never_the_name() {
1214 let mut f = field(FieldKind::Text);
1215 f.hint = Some("Keep it short");
1216 f.error = Some("Required");
1217 let filling = Filling {
1218 id_prefix: Some("form-modal-task-edit"),
1219 ..Filling::default()
1220 };
1221 let html = field_html(&f, &filling, &Emit::default());
1222
1223 assert!(
1224 html.contains(r#"id="form-modal-task-edit-title""#),
1225 "{html}"
1226 );
1227 assert!(html.contains(r#"name="title""#), "{html}");
1228 assert!(
1229 !html.contains(r#"name="form-modal-task-edit-title""#),
1230 "{html}"
1231 );
1232
1233 // The label and both associations follow the id, or they point at
1234 // nothing once the same form is on screen twice.
1235 assert!(
1236 html.contains(r#"for="form-modal-task-edit-title""#),
1237 "{html}"
1238 );
1239 assert!(
1240 html.contains(
1241 r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
1242 ),
1243 "{html}"
1244 );
1245 assert!(
1246 html.contains(r#"id="form-modal-task-edit-title-hint""#),
1247 "{html}"
1248 );
1249 }
1250
1251 #[test]
1252 fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
1253 let filling = Filling {
1254 value: Value::Text("42"),
1255 id_prefix: Some("scoped"),
1256 ..Filling::default()
1257 };
1258 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1259 assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
1260 }
1261
1262 /// These three exist so a touch keyboard and the platform's validation
1263 /// arrive with the field. Emitting text for any of them is the regression
1264 /// the variants were added to prevent, so the type is asserted directly.
1265 #[test]
1266 fn a_constraint_becomes_the_browsers_own_attribute() {
1267 // makeover-layout 0.11.0's model: the description carries the rule and
1268 // each renderer emits its host's idiom for it. Enforcement is still
1269 // whoever validated's, and arrives back as `error`.
1270 let html = field_html(
1271 &Field {
1272 max_length: Some(100),
1273 min: Some("1"),
1274 max: Some("240"),
1275 required: true,
1276 ..Field::new(FieldKind::Number, "minutes", "Minutes")
1277 },
1278 &Filling::default(),
1279 &Emit::default(),
1280 );
1281 assert!(html.contains(r#"maxlength="100""#));
1282 assert!(html.contains(r#"min="1""#));
1283 assert!(html.contains(r#"max="240""#));
1284 assert!(html.contains(" required"));
1285 }
1286
1287 #[test]
1288 fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
1289 // The bound is text because it is only a number for some of the kinds
1290 // that take one; goingson's own sites are a duration and a datetime.
1291 let html = field_html(
1292 &Field {
1293 min: Some("2026-08-09T14:30"),
1294 ..Field::new(FieldKind::Text, "starts", "Starts")
1295 },
1296 &Filling::default(),
1297 &Emit::default(),
1298 );
1299 assert!(html.contains(r#"min="2026-08-09T14:30""#));
1300 }
1301
1302 #[test]
1303 fn a_file_field_is_a_file_input() {
1304 // `844b5ae0`. A field that takes any file emits no `accept` at all,
1305 // which is the browser's own "any file". `accept=""` is a filter that
1306 // means nothing on one browser and everything on another.
1307 let html = field_html(
1308 &Field::new(FieldKind::File, "attachment", "Attachment"),
1309 &Filling::default(),
1310 &Emit::default(),
1311 );
1312 assert!(html.contains(r#"type="file""#));
1313 assert!(!html.contains("accept="));
1314 assert!(!html.contains("multiple"));
1315 // And it never carries a value: a file input's value is not settable
1316 // from markup, and the browser refuses one that tries.
1317 assert!(!html.contains("value="));
1318 }
1319
1320 #[test]
1321 fn an_accept_list_is_comma_joined_in_the_attributes_own_format() {
1322 // `f7261a5a`, makeover-layout 0.31.0. Each entry writes itself: a
1323 // family is its wildcard, a media type is itself, a suffix keeps its
1324 // leading dot and however many more it has.
1325 const MIXED: &[Accepted<'_>] = &[
1326 Accepted::Family(Family::Image),
1327 Accepted::Type("text/csv"),
1328 Accepted::Suffix(".tar.gz"),
1329 ];
1330 let html = field_html(
1331 &Field {
1332 multiple: true,
1333 ..Field::upload("drop", "Drop files", MIXED)
1334 },
1335 &Filling::default(),
1336 &Emit::default(),
1337 );
1338 assert!(
1339 html.contains(r#"accept="image/*,text/csv,.tar.gz""#),
1340 "{html}"
1341 );
1342 assert!(html.contains(" multiple"), "{html}");
1343 }
1344
1345 #[test]
1346 fn an_accept_entry_cannot_end_the_attribute_it_sits_in() {
1347 // The list reaches an attribute value, so it is escaped like every
1348 // other string that does. Nothing in the tree writes a quote into one;
1349 // that it cannot is the point.
1350 const HOSTILE: &[Accepted<'_>] = &[Accepted::Type(r#"image/x" onload="x"#)];
1351 let html = field_html(
1352 &Field::upload("cover", "Cover", HOSTILE),
1353 &Filling::default(),
1354 &Emit::default(),
1355 );
1356 assert!(!html.contains(r#"onload="x"#), "{html}");
1357 }
1358
1359 #[test]
1360 fn the_typed_text_kinds_keep_their_input_type() {
1361 for (kind, expected) in [
1362 (FieldKind::Email, "email"),
1363 (FieldKind::Url, "url"),
1364 (FieldKind::Tel, "tel"),
1365 (FieldKind::Date, "date"),
1366 (FieldKind::DateTime, "datetime-local"),
1367 ] {
1368 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1369 assert!(
1370 html.contains(&format!(r#"type="{expected}""#)),
1371 "{kind:?} emitted {html}"
1372 );
1373 }
1374 }
1375
1376 #[test]
1377 fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
1378 // The regression this closes: described as text with a hint reading
1379 // "YYYY-MM-DD", which loses the picker, the platform's validation and
1380 // the touch keyboard, and asks prose to do all three.
1381 for kind in [FieldKind::Date, FieldKind::DateTime] {
1382 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1383 assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
1384 }
1385 }
1386
1387 #[test]
1388 fn no_prefix_leaves_the_id_as_the_name() {
1389 let html = field_html(
1390 &field(FieldKind::Text),
1391 &Filling::default(),
1392 &Emit::default(),
1393 );
1394 assert!(html.contains(r#"id="title" name="title""#), "{html}");
1395 }
1396}