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