Skip to main content

makeover_webview/
form.rs

1//! Phase B, the forms half: [`makeover_layout::Field`] rendered to HTML.
2//!
3//! # Why this emits strings
4//!
5//! Both webview apps build their markup as strings and hand it to `innerHTML`:
6//! goingson's `renderFormField` returns a template literal that fifteen call
7//! sites interpolate into larger literals, and Balanced Breakfast's builds
8//! nodes but appends them into the same string-built forms. Returning nodes
9//! would rewrite the surrounding templates as well, which makes it a migration
10//! rather than an adoption. So: strings, and the escaping comes with them.
11//!
12//! # Why one escaper is enough here
13//!
14//! goingson carries four escapers and 543 call sites that must pick between
15//! them, because `escapeHtml` is built on `textContent` serialization and
16//! **`textContent` refuses to encode `"`**. That is what makes it unsound in an
17//! attribute, and it is the whole reason the choice exists. Its `escape.js`
18//! records the finding as the CHRONIC-XSS seal, and its test suite has a gate
19//! keeping the unsafe one off the namespace.
20//!
21//! [`escape`] here is not built on that, so it encodes the quote along with
22//! everything else, which makes one function sound in both sinks. The four-way
23//! choice does not move into Rust: it disappears. Nothing in this module hands
24//! an unescaped value to the output except through [`Markup`], which a caller
25//! has to name.
26//!
27//! # What the description does not carry
28//!
29//! One thing: the **current value**, which arrives in [`Filling`].
30//!
31//! It used to be three. Writing this emitter is what found them, and the other
32//! two turned out not to be renderer state at all — the placeholder is
33//! user-facing text that sits with `label` and `hint`, and a select's options
34//! are needed by every renderer, which is how each of them ends up inventing a
35//! near-miss of the same struct. Both moved down into `makeover-layout` 0.8.0,
36//! `Choice` included, and this crate reads them off [`Field`] now.
37//!
38//! The value stays, and it is not a leftover. A webview reads it back out of
39//! the DOM, an immediate-mode renderer writes through a `&mut`, and a terminal
40//! keeps an edit buffer; a description carrying it would have to carry a way to
41//! write it back, at which point it is a form model.
42
43use crate::{Emit, class, push_class};
44use makeover_layout::{Choice, Depth, Field, FieldKind, Intent as _, Selector, State};
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    /// Attributes written onto the control element itself. Not escaped.
98    ///
99    /// [`trailing`](Self::trailing)'s argument at attribute scale: a host knows
100    /// facts about the control that no description layer carries, and until
101    /// this existed the only way to attach one was to stop calling this emitter
102    /// and write a second one. quasi's suggestion source is the first caller —
103    /// a field that owns a list of candidates is a `role="combobox"` pointing
104    /// at the list it owns, and neither half is anything
105    /// [`makeover_layout::Field`] can say.
106    ///
107    /// Written verbatim, so a caller supplies `attr="value"` pairs with no
108    /// leading space and does its own escaping. It is [`Markup`]'s hole in the
109    /// same wall, named the same way so a caller has to state that the contents
110    /// are trusted.
111    ///
112    /// A [`FieldKind::Radio`] drops them, and that is deliberate rather than an
113    /// oversight: a radio group is a set of sibling inputs with no one control
114    /// element, so there is nowhere honest to put an attribute meant for the
115    /// control. The group carries the descriptions for the same reason.
116    pub control_attrs: Option<Markup<'a>>,
117    /// Scopes the `id` attributes to one instance of the form.
118    ///
119    /// The field's `name` is what the value submits under and is the same
120    /// wherever the form appears; its `id` has to be unique in the document,
121    /// and those two facts stop agreeing the moment a form appears twice.
122    /// goingson hits this directly: its new-task and edit-task modals are the
123    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
124    /// `label for` and `aria-describedby` pointing at the right control.
125    ///
126    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
127    /// `name`, which would change what the form submits.
128    pub id_prefix: Option<&'a str>,
129}
130
131impl<'a> Filling<'a> {
132    /// A filling that carries a value and nothing else.
133    #[must_use]
134    pub const fn of(value: Value<'a>) -> Self {
135        Self {
136            value,
137            trailing: None,
138            control_attrs: None,
139            id_prefix: None,
140        }
141    }
142
143    /// The document-unique id for a field of this name.
144    fn id_for(&self, name: &str) -> String {
145        let mut id = String::new();
146        if let Some(prefix) = self.id_prefix {
147            escape_into(prefix, &mut id);
148            id.push('-');
149        }
150        escape_into(name, &mut id);
151        id
152    }
153}
154
155/// Encode the five characters that let a value stop being a value, into a
156/// buffer the caller already has.
157///
158/// The form the emitters use. [`escape`] is this with a `String` allocated
159/// around it, and the allocation is the whole difference: a described screen
160/// escapes once per attribute and once per run of text, so a function that
161/// returns a `String` allocates a few thousand times to produce one page, where
162/// a template engine writes its escaped bytes straight into the output buffer.
163/// Measured 2026-08-14 against a real pane, that gap was 85% of a 42x rendering
164/// cost, and this is the half of the fix that lives in this crate.
165///
166/// Sound in element text and in a double-quoted attribute alike, which is the
167/// property `textContent`-based escaping cannot have. Both sinks are covered by
168/// one function so that no call site has to choose, here or downstream.
169///
170/// Copies in runs rather than per character. All five encoded characters are
171/// ASCII, so a byte scan cannot land inside a multi-byte character and the
172/// slice between two of them is always a valid `&str`. Text with nothing to
173/// encode — which is most text — is one `push_str` of the whole thing.
174pub fn escape_into(text: &str, out: &mut String) {
175    let mut start = 0;
176    for (index, byte) in text.bytes().enumerate() {
177        let encoded = match byte {
178            b'&' => "&amp;",
179            b'<' => "&lt;",
180            b'>' => "&gt;",
181            b'"' => "&quot;",
182            b'\'' => "&#39;",
183            _ => continue,
184        };
185        out.push_str(&text[start..index]);
186        out.push_str(encoded);
187        start = index + 1;
188    }
189    out.push_str(&text[start..]);
190}
191
192/// Encode the five characters that let a value stop being a value.
193///
194/// [`escape_into`] with a buffer of its own, for the callers that want a value
195/// rather than an append: a caller assembling an attribute out of several
196/// pieces, and everything outside this crate that took this function before the
197/// buffer-writing form existed. Emitting into a buffer you already hold is the
198/// cheaper path and the one this crate's own emitters take.
199#[must_use]
200pub fn escape(text: &str) -> String {
201    let mut out = String::with_capacity(text.len());
202    escape_into(text, &mut out);
203    out
204}
205
206/// The `type` an input takes for a kind.
207///
208/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
209const fn input_type(kind: FieldKind) -> &'static str {
210    match kind {
211        FieldKind::Secret => "password",
212        FieldKind::Number => "number",
213        FieldKind::Checkbox => "checkbox",
214        FieldKind::File => "file",
215        FieldKind::Hidden => "hidden",
216        // Not decoration. Each of these changes the keyboard a touch device
217        // offers and turns on the platform's own validation, which is why the
218        // description names them apart from text rather than letting the app
219        // pass an HTML type through.
220        FieldKind::Email => "email",
221        FieldKind::Url => "url",
222        FieldKind::Tel => "tel",
223        // The same argument, and it buys more here than anywhere else in this
224        // list: a native picker as well as the keyboard and the validation.
225        // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
226        // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
227        FieldKind::Date => "date",
228        FieldKind::DateTime => "datetime-local",
229        FieldKind::Radio => "radio",
230        // The clearest case in this list that a kind is not decoration: a
231        // number and a range submit the same value and are different controls,
232        // and the browser is the one drawing the difference.
233        FieldKind::Range => "range",
234        // Select and Textarea are not inputs at all; they never reach here.
235        // Radio is one, but it is emitted once per option by `radio_html` and
236        // so does not reach here either.
237        FieldKind::Text | FieldKind::Select | FieldKind::Textarea | FieldKind::Rich => "text",
238        // A kind added to the description since this renderer was built. Text
239        // accepts any value the others would, so it degrades rather than
240        // dropping the field.
241        _ => "text",
242    }
243}
244
245/// The attributes every visible control carries, error state included.
246///
247/// `aria-invalid` is the whole reason the error state is readable at all: the
248/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
249/// than on a class, so a control rendered already-invalid without it is styled
250/// as if nothing were wrong. goingson's runtime validation path sets the
251/// attribute and its initial render does not, which is exactly the drift one
252/// emitter removes.
253/// `id` and `name` arrive separately because they are not the same fact. The
254/// name is what submits and is fixed by the description; the id has to be
255/// unique in the document and so carries [`Filling::id_prefix`] when a form
256/// appears more than once.
257/// The `accept` attribute, from the description's accept list.
258///
259/// makeover-layout 0.31.0. The list is comma-joined because that is the
260/// attribute's own format, and each entry writes itself: a family is its
261/// wildcard media type, a media type is itself, a suffix is itself with its
262/// leading dot. Nothing is normalised on the way through -- `.tar.gz` is two
263/// dots and the browser is fine with it.
264///
265/// An empty list emits no attribute at all, which is the browser's own "any
266/// file" and is what the description means by listing nothing. Emitting
267/// `accept=""` instead would be a filter that matches nothing on some browsers
268/// and everything on others.
269///
270/// It is a filter and not a guarantee, on the browser's side as much as here:
271/// the picker keeps an "All Files" escape and the user may take it. Whoever
272/// validated still validates.
273fn push_accept(out: &mut String, field: &Field<'_>) {
274    if field.accept.is_empty() {
275        return;
276    }
277    out.push_str(" accept=\"");
278    for (index, one) in field.accept.iter().enumerate() {
279        if index > 0 {
280            out.push(',');
281        }
282        escape_into(one.as_str(), out);
283    }
284    out.push('"');
285}
286
287fn push_control_attributes(
288    out: &mut String,
289    field: &Field<'_>,
290    filling: &Filling<'_>,
291    id: &str,
292    name: &str,
293) {
294    let _ = write!(out, " id=\"{id}\" name=\"");
295    escape_into(name, out);
296    out.push('"');
297    if field.required {
298        out.push_str(" required");
299    }
300    // makeover-layout 0.11.0's constraints. The description carries the rule and
301    // this emits the browser's idiom for it, which is the model `required` has
302    // been using since before the crate wrote down that it carried none.
303    // Enforcement is still whoever validated's, and arrives back as `error`.
304    if let Some(limit) = field.max_length {
305        let _ = write!(out, " maxlength=\"{limit}\"");
306    }
307    if let Some(min) = field.min {
308        out.push_str(" min=\"");
309        escape_into(min, out);
310        out.push('"');
311    }
312    if let Some(max) = field.max {
313        out.push_str(" max=\"");
314        escape_into(max, out);
315        out.push('"');
316    }
317    // The browser's own default is `step="1"`, which turns a 0-to-1 threshold
318    // into a two-position control. That is the granularity the description
319    // means when it says nothing, so this is emitted only when an app has said
320    // otherwise rather than defaulted here.
321    //
322    // A range takes its granularity from its curve as of makeover-layout
323    // 0.32.0, and every other kind keeps `Field::step`. See the crate header on
324    // what this renderer can and cannot do with a curve.
325    let step = if field.kind == FieldKind::Range {
326        field.curve.step()
327    } else {
328        field.step
329    };
330    if let Some(step) = step {
331        out.push_str(" step=\"");
332        escape_into(step, out);
333        out.push('"');
334    }
335    if field.invalid() {
336        out.push_str(" aria-invalid=\"true\"");
337    }
338
339    push_described_by(out, field, id);
340
341    // Last, so that a host attaching a fact of its own can see everything this
342    // emitter decided and cannot be overwritten by it. Duplicate attributes are
343    // the caller's to avoid: HTML takes the first of a repeated pair, so an
344    // attribute spelled here as well as there keeps this crate's answer.
345    if let Some(Markup(attrs)) = filling.control_attrs {
346        out.push(' ');
347        out.push_str(attrs);
348    }
349}
350
351/// The `aria-describedby` naming whatever of the hint and the error exist.
352///
353/// Both associations, in the order they are useful: the standing help, then
354/// what is currently wrong. goingson's runtime path points describedby at the
355/// error alone and drops the hint association it never made in the first place;
356/// naming both here means the hint survives an error appearing.
357///
358/// Its own function because a radio group carries it on the group rather than
359/// on a control, and one reading of "what describes this field" is the point.
360fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
361    if field.hint.is_none() && field.error.is_none() {
362        return;
363    }
364    out.push_str(" aria-describedby=\"");
365    if field.hint.is_some() {
366        let _ = write!(out, "{id}-hint");
367    }
368    if field.error.is_some() {
369        if field.hint.is_some() {
370            out.push(' ');
371        }
372        let _ = write!(out, "{id}-error");
373    }
374    out.push('"');
375}
376
377/// Whether the field's control is a set of elements rather than one.
378///
379/// A DOM concern rather than a description one, which is why it is decided here
380/// and not in `makeover-layout`: `for` and `id` are an HTML association and
381/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
382/// points at nothing, because no single element carries the group's id, so the
383/// association has to invert — the label takes an id and the group names itself
384/// with `aria-labelledby`.
385const fn is_group_control(kind: FieldKind) -> bool {
386    matches!(kind, FieldKind::Radio)
387}
388
389/// A radio group: the options as sibling inputs sharing one `name`.
390///
391/// The group carries the error state and the descriptions, and the inputs carry
392/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
393/// down: marking a single input invalid would say the wrong thing, since what
394/// is wrong is the answer to the question and not one of the alternatives.
395///
396/// Ids are numbered rather than built from the option values, which can hold
397/// anything a `&str` can — spaces and quotes included — and would otherwise
398/// have to be slugged into something unique by a rule this crate would then own.
399///
400/// `required` lands on every input, which is how HTML says a group is
401/// compulsory: the constraint is satisfied when any one of them is checked.
402fn push_radio(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
403    let id = filling.id_for(field.name);
404    let value = filling.value.as_text();
405    let name = escape(field.name);
406
407    out.push_str("<div class=\"");
408    push_class(out, "form-radio-group", opts);
409    let _ = write!(out, "\" role=\"radiogroup\" aria-labelledby=\"{id}-label\"");
410    if field.invalid() {
411        out.push_str(" aria-invalid=\"true\"");
412    }
413    push_described_by(out, field, &id);
414    out.push('>');
415
416    // A group described with no options emits an empty group, for the reason
417    // `Field::options` gives: an app whose option list has not loaded has
418    // exactly that, and an empty group says so on screen rather than in a log.
419    for (index, opt) in field.options.iter().enumerate() {
420        out.push_str("<label class=\"");
421        push_class(out, "form-radio-label", opts);
422        let _ = write!(
423            out,
424            "\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" value=\""
425        );
426        escape_into(opt.value, out);
427        out.push('"');
428        if opt.value == value {
429            out.push_str(" checked");
430        }
431        if field.required {
432            out.push_str(" required");
433        }
434        // A radio group has room a `<select>` does not, so the reason gets its
435        // own element beside the label rather than being run into it. The class
436        // is what a stylesheet mutes; the text is there either way, which is
437        // the half that matters — the finding was a greyed control with its
438        // explanation behind a hover.
439        if let Some(reason) = opt.unavailable {
440            out.push_str(" disabled");
441            out.push_str("><span>");
442            escape_into(opt.label, out);
443            out.push_str("</span><span class=\"");
444            push_class(out, "form-option-reason", opts);
445            out.push_str("\">");
446            escape_into(reason, out);
447            out.push_str("</span></label>");
448            continue;
449        }
450        out.push_str("><span>");
451        escape_into(opt.label, out);
452        out.push_str("</span></label>");
453    }
454
455    out.push_str("</div>");
456}
457
458/// The options of a select: the unanswered instruction, an unmatched current
459/// value carried as its own, then the options themselves.
460///
461/// A select handed a value no option carries renders with nothing selected, the
462/// browser falls back to the first option, and the next save writes a value
463/// nobody chose. goingson hit exactly that with a backup-retention default of
464/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
465/// here so the second app gets it without hitting the bug first.
466fn push_options(out: &mut String, field: &Field<'_>, options: &[Choice<'_>], value: &str) {
467    // The unanswered state, which HTML has no attribute for: `placeholder` is
468    // not a `<select>` attribute, and the idiom is an empty option that cannot
469    // be chosen back. `disabled` is what stops it being re-selected once the
470    // user has answered, and `selected` is what puts it in the closed control
471    // while the value is empty; together they read as an instruction rather
472    // than as an option.
473    //
474    // `required` keeps working through it rather than around it: the option's
475    // value is empty, so a required select with this showing is invalid, which
476    // is the true report on a question nobody has answered.
477    //
478    // Emitted only while the value is empty, so it does not sit in the open
479    // list once the field is answered. A non-empty value no option carries is a
480    // wrong answer rather than an absent one and takes the stray-option path
481    // below.
482    if value.is_empty()
483        && let Some(text) = field.placeholder
484    {
485        out.push_str("<option value=\"\" disabled selected>");
486        escape_into(text, out);
487        out.push_str("</option>");
488    }
489    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
490        // The one place an escaped value is worth keeping: it is written twice,
491        // as the option's value and as its text.
492        let escaped = escape(value);
493        let _ = write!(
494            out,
495            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
496        );
497    }
498    for opt in options {
499        out.push_str("<option value=\"");
500        escape_into(opt.value, out);
501        out.push('"');
502        if opt.value == value {
503            out.push_str(" selected");
504        }
505        // `disabled` is what the browser reads, and it says nothing about why.
506        // The reason goes in the option's own text, because a `<select>` gives
507        // its options no room for anything else: no title attribute the
508        // keyboard reaches, no second line, no element inside. So the row reads
509        // "Multi-sample: Drop a second sample onto the keyboard." and is the
510        // one place the precondition can be both attached to its option and
511        // read without a pointer.
512        if let Some(reason) = opt.unavailable {
513            out.push_str(" disabled");
514            out.push('>');
515            escape_into(opt.label, out);
516            out.push_str(": ");
517            escape_into(reason, out);
518            out.push_str("</option>");
519            continue;
520        }
521        out.push('>');
522        escape_into(opt.label, out);
523        out.push_str("</option>");
524    }
525}
526
527/// The control itself, without its label, hint or error.
528fn push_control(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
529    // Emitted before anything else is computed: a radio group carries its
530    // descriptions on the group rather than on a control, so none of the
531    // attributes below belong to it.
532    if matches!(field.kind, FieldKind::Radio) {
533        push_radio(out, field, filling, opts);
534        return;
535    }
536
537    let id = filling.id_for(field.name);
538    let placeholder = |out: &mut String| {
539        if let Some(text) = field.placeholder {
540            out.push_str(" placeholder=\"");
541            escape_into(text, out);
542            out.push('"');
543        }
544    };
545
546    match field.kind {
547        // Both multi-line kinds are a `<textarea>`, and the markdown one says so
548        // in an attribute rather than in a class: what the value *is* is not a
549        // styling hook, and a progressive enhancement looking for editors to
550        // upgrade needs a selector that survives `Emit`'s class prefixing.
551        // Without the mark, a described editor is a plain box and the four
552        // hand-written MNW editors have nothing to convert onto.
553        //
554        // `data-format` and not `data-value`: this names the shape of the
555        // value, and `facet` already spends `data-facet-value` on carrying an
556        // actual one. Two attributes a letter apart meaning opposite things is
557        // how a renderer's own vocabulary starts drifting.
558        kind if kind.multiline() => {
559            let rich = matches!(kind, FieldKind::Rich);
560            if rich {
561                push_editor_open(out, opts);
562            }
563            out.push_str("<textarea class=\"");
564            push_class(out, "field", opts);
565            out.push('"');
566            if rich {
567                out.push_str(" data-format=\"markdown\"");
568            }
569            push_control_attributes(out, field, filling, &id, field.name);
570            placeholder(out);
571            out.push('>');
572            escape_into(filling.value.as_text(), out);
573            out.push_str("</textarea>");
574            if rich {
575                push_editor_close(out, opts);
576            }
577        }
578        FieldKind::Select => {
579            out.push_str("<select class=\"");
580            push_class(out, "field", opts);
581            out.push('"');
582            push_control_attributes(out, field, filling, &id, field.name);
583            out.push('>');
584            // A select described with no options emits an empty select, which
585            // says so on screen rather than in a log. That is the description's
586            // own position on `Field::options`, not a fallback invented here.
587            push_options(out, field, field.options, filling.value.as_text());
588            out.push_str("</select>");
589        }
590        FieldKind::Checkbox => {
591            out.push_str("<label class=\"");
592            push_class(out, "form-checkbox-label", opts);
593            out.push_str("\"><input type=\"checkbox\"");
594            push_control_attributes(out, field, filling, &id, field.name);
595            if matches!(filling.value, Value::On(true)) {
596                out.push_str(" checked");
597            }
598            out.push_str("><span>");
599            escape_into(field.label, out);
600            out.push_str("</span></label>");
601        }
602        // A secret never carries its value into the markup. `FieldKind::secret`
603        // is documented as a value that must not be round-tripped through
604        // anything that might persist it, and the DOM is such a thing: it is
605        // read by every extension on the page and is the first thing a crash
606        // reporter serialises. Neither app pre-fills one today, so this costs
607        // nothing and closes the door before something does.
608        FieldKind::Secret => {
609            out.push_str("<input type=\"password\" class=\"");
610            push_class(out, "field", opts);
611            out.push('"');
612            push_control_attributes(out, field, filling, &id, field.name);
613            placeholder(out);
614            out.push('>');
615        }
616        // A file input carries no value, and this is the browser's rule rather
617        // than a preference: setting one from markup is refused, because a page
618        // that could preselect a path could read a file the user never offered.
619        // Nothing upstream needs to know, which is why the exception is here.
620        FieldKind::File => {
621            out.push_str("<input type=\"file\" class=\"");
622            push_class(out, "field", opts);
623            out.push('"');
624            push_control_attributes(out, field, filling, &id, field.name);
625            push_accept(out, field);
626            if field.multiple {
627                out.push_str(" multiple");
628            }
629            out.push('>');
630        }
631        kind => {
632            let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
633            push_class(out, "field", opts);
634            out.push('"');
635            push_control_attributes(out, field, filling, &id, field.name);
636            placeholder(out);
637            out.push_str(" value=\"");
638            escape_into(filling.value.as_text(), out);
639            out.push_str("\">");
640        }
641    }
642}
643
644/// The chrome a markdown field gets and a plain textarea does not: the two
645/// modes, and the pane a preview lands in.
646///
647/// # Why this is the one field with markup around it
648///
649/// [`FieldKind::Rich`]'s own doc says the mark buys a renderer permission to
650/// offer a preview or a syntax pass, and that a renderer with neither draws a
651/// textarea. A renderer taking the permission and emitting the same box as
652/// [`FieldKind::Textarea`] leaves an app converting onto the member with less
653/// than it had written by hand: MNW's `partial-item-text-editor.js` has a
654/// Write/Preview pair and a pane behind it, and describing the field without
655/// this would delete both. So the pair is here, on `facet`'s argument one
656/// field down -- the markup it replaces is not markup an app is keeping.
657///
658/// # Nothing here renders markdown, and that is where the sanitising stays
659///
660/// The pane arrives empty and this crate never turns a value into markup.
661/// Converting markdown is the host's, which is where the sanitiser already is:
662/// MNW renders through `docengine` over ammonia and holds an allowlist beside
663/// it. A converter here would move that guarantee into a crate with no view of
664/// the host's content-security posture, and `Rich`'s doc is explicit that a
665/// host with its own sanitiser still owns it. What this emits is a hook, and
666/// whatever fills it fills it with markup it has already made safe.
667///
668/// # The direction the enhancement runs
669///
670/// [`crate::stylesheet`]'s rule for a showing region, and for its reason: a
671/// control rendered into a document with no script is a control that looks live
672/// and answers nothing. Nothing is hidden here and no control is shown until
673/// whatever binds the editor sets `data-ready` on the wrapper, so a reader with
674/// no script gets the textarea alone -- what 0.50.0 emitted -- and a reader with
675/// script gets the modes. A bound editor says which mode it is in with
676/// `data-mode`, and [`editor_rules`] reads that.
677fn push_editor_open(out: &mut String, opts: &Emit) {
678    // The mark sits on the wrapper as well as on the control, saying one thing
679    // about two: this control's value is markdown, and this editor edits
680    // markdown. The rules gate on the wrapper and they are attribute rules
681    // rather than class rules for `data-format`'s own reason -- the gate has to
682    // survive `Emit`'s class prefixing, because the enhancement selects on it
683    // too.
684    out.push_str("<div data-format=\"markdown\"><div class=\"");
685    push_class(out, "form-editor-modes", opts);
686    out.push_str("\">");
687    push_mode(out, "write", "Write", true, opts);
688    push_mode(out, "preview", "Preview", false, opts);
689    out.push_str("</div>");
690}
691
692/// One of the two modes, as a segment of the pair.
693///
694/// [`crate::option_class`] for [`Selector::Segmented`] rather than a name of
695/// its own: a Write/Preview pair is a segmented control, and spelling it as one
696/// gets it the depth, the focus ring and the chosen state every described
697/// selector gets, from rules that already exist. The words are written here for
698/// the reason `facet`'s exclude button writes its own: a description carrying
699/// them would be choosing them for the terminal as well.
700fn push_mode(out: &mut String, mode: &str, label: &str, chosen: bool, opts: &Emit) {
701    out.push_str("<button type=\"button\" class=\"");
702    push_class(out, crate::option_class(Selector::Segmented), opts);
703    if chosen {
704        // The sheet keys the held-in segment on the class and a screen reader
705        // reads the attribute. Both, because they are two readings of one fact,
706        // which is the arrangement a facet value already has.
707        out.push_str(" chosen");
708    }
709    let _ = write!(
710        out,
711        "\" data-editor-mode=\"{mode}\" aria-pressed=\"{chosen}\">{label}</button>"
712    );
713}
714
715/// The preview pane, and the wrapper closing over both halves.
716fn push_editor_close(out: &mut String, opts: &Emit) {
717    out.push_str("<div class=\"");
718    push_class(out, "form-editor-preview", opts);
719    // `data-editor-preview` and not an id: a form appears twice in a document
720    // often enough that `Filling::id_prefix` exists for it, and a binder holding
721    // the control can reach this without either of them being unique.
722    out.push_str("\" data-editor-preview></div></div>");
723}
724
725/// The rules the markdown editor's chrome needs.
726///
727/// The one place this module writes CSS. The class names [`field_html`] emits
728/// are goingson's and are deliberately unruled -- `.form-group`, `.form-label`,
729/// `.form-hint` and `.form-error` are the app's own, and phase A emits only what
730/// it can generate from the description -- but the two names here have no app
731/// counterpart to keep, because the chrome did not exist before the member did.
732///
733/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
734/// off a plain textarea, and every rule that hides content is gated on
735/// `data-ready` as well, which is what keeps them out of a document with no
736/// script.
737pub(crate) fn editor_rules(opts: &Emit) -> String {
738    let mut css = String::new();
739    let modes = class("form-editor-modes", opts);
740    let preview = class("form-editor-preview", opts);
741    let field = class("field", opts);
742
743    // Hidden until something binds the editor, which is the whole argument in
744    // `push_editor_open`.
745    let _ = writeln!(
746        css,
747        "[data-format=\"markdown\"] > .{modes} {{\n    display: none;\n}}"
748    );
749    // Block, and nothing about how the two segments sit in it. A button is
750    // inline already, so they make a row without this crate saying so, and
751    // saying so is where a gap would follow -- a magnitude, and
752    // `makeover-geometry`'s.
753    let _ = writeln!(
754        css,
755        "[data-format=\"markdown\"][data-ready] > .{modes} {{\n    display: block;\n}}"
756    );
757
758    // The pane is empty until the host fills it, so it is out of flow in every
759    // state but the one where a bound editor is showing it. An empty box under
760    // the control is chrome claiming a preview nobody rendered.
761    let _ = writeln!(
762        css,
763        "[data-format=\"markdown\"] > .{preview} {{\n    display: none;\n}}"
764    );
765    let _ = writeln!(
766        css,
767        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
768         {{\n    display: block;\n}}"
769    );
770    // One at a time. The source and the preview are the same content read two
771    // ways, and a field showing both answers its own question twice.
772    let _ = writeln!(
773        css,
774        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
775         {{\n    display: none;\n}}"
776    );
777
778    // The pane stands where the control stood, so it reads as the surface the
779    // control was: `.field` is a well, and this is the well it stands in for.
780    // Nothing about size -- how tall a preview is is the app's, the way the
781    // height of a track is.
782    let _ = write!(
783        css,
784        "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
785        crate::depth_declarations(Depth::Well)
786    );
787
788    css
789}
790
791/// The rules a field's suggestion list needs.
792///
793/// [`editor_rules`]' precedent and its argument: the class names this module's
794/// markup emits are the apps' own and stay unruled, and these three have no app
795/// counterpart to keep because the list did not exist before the member did.
796/// The markup is `quasi-webview`'s rather than this crate's — a suggestion
797/// source is a route, which no description layer carries — and the look is
798/// still this crate's, because a renderer inventing how a list of candidates
799/// reads is the drift the vocabulary check exists to catch.
800///
801/// # In flow, and not floating
802///
803/// An absolutely positioned list needs a positioned ancestor, and the only
804/// candidate is `.form-group`, which is the app's class and deliberately
805/// unruled here. So the list stands under the control and moves what is below
806/// it. An app that wants it over the form positions the group itself, which is
807/// one declaration and is the app's call about its own layout.
808///
809/// `:empty` is what takes it away, so a route that answers with no candidates
810/// leaves no box behind. It is a content question rather than a whitespace one
811/// only because the emitter writes no whitespace inside the container, which is
812/// stated in `quasi-webview`'s own test.
813///
814/// # Nothing about size
815///
816/// No height, no scroll ceiling, no padding. How tall a list of candidates gets
817/// to be before it scrolls is a magnitude, and magnitudes are
818/// `makeover-geometry`'s, exactly as the preview pane's height is.
819pub(crate) fn suggestion_rules(opts: &Emit) -> String {
820    let list = class("form-suggestions", opts);
821    let entry = class("form-suggestion", opts);
822    let why = class("form-suggestion-why", opts);
823    let mut css = String::new();
824
825    let _ = writeln!(css, ".{list}:empty {{\n    display: none;\n}}");
826    // Over what it covers, which is what a list of candidates is even in flow:
827    // it is answering the box above it and goes away when the answer is taken.
828    css.push_str(&crate::depth_rule(&list, Depth::Overlay));
829    // An entry answers a click, so it gets every state one implies -- including
830    // the disabled rule, which is what draws the candidate that cannot be
831    // picked and is why `aria-disabled` is the mark rather than a class.
832    css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
833    // The keyboard's highlight and the pointer's are the same surface. They are
834    // the same fact told two ways, and a list where arrowing and hovering look
835    // different is a list that has two current entries.
836    //
837    // Keyed on `aria-selected` rather than on a class, for the reason
838    // `aria-invalid` carries the error state: it is what a screen reader hears,
839    // so a look keyed on it cannot drift from what is announced. A `.current`
840    // class would also be a name apps already spell for their own reasons --
841    // the MNW server has one -- and unlayered app CSS beats this layer in
842    // silence.
843    let _ = writeln!(
844        css,
845        ".{entry}[aria-selected=\"true\"] {{\n    background: var(--hover-surface);\n}}"
846    );
847    let _ = writeln!(
848        css,
849        ".{why} {{\n    color: var(--{});\n}}",
850        State::Disabled.token()
851    );
852
853    css
854}
855
856/// One field, as the group the app drops into its form.
857///
858/// The shape is goingson's, down to the class names, so adoption there deletes
859/// `renderFormField` rather than restyling anything. That is also why the class
860/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
861/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
862/// emits only what it can generate from the description. Whether they should
863/// move into the description is the next question this raises, not one it
864/// answers.
865///
866/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
867/// nothing drawn, which is what [`FieldKind::visible`] means.
868///
869/// The error marks the group as well as the control. That is
870/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
871/// cannot find the group from the message, so the group has to be told.
872///
873/// ```
874/// use makeover_layout::{Field, FieldKind};
875/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
876///
877/// let field = Field::new(FieldKind::Text, "title", "Title");
878/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
879///
880/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
881/// assert!(html.contains(r#"value="Ship it""#));
882/// ```
883#[must_use]
884pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
885    let mut html = String::new();
886    field_html_into(field, filling, opts, &mut html);
887    html
888}
889
890/// One field, written into a buffer the caller already has.
891///
892/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
893/// these, so a host building one should hold a single buffer and append each
894/// field into it rather than take a `String` per field and concatenate.
895pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
896    let id = filling.id_for(field.name);
897
898    if !field.kind.visible() {
899        // Name only, no id: a hidden field is never pointed at by a label or a
900        // description, so the one attribute it needs is the one that submits.
901        out.push_str("<input type=\"hidden\" name=\"");
902        escape_into(field.name, out);
903        out.push_str("\" value=\"");
904        escape_into(filling.value.as_text(), out);
905        out.push_str("\">");
906        return;
907    }
908
909    out.push_str("<div class=\"");
910    push_class(out, "form-group", opts);
911    if field.invalid() {
912        out.push_str(" has-error");
913    }
914    if field.extended {
915        // The disclosure that hides these is a property of the form, not of the
916        // field, so the field is marked and the app opens or closes the group.
917        out.push_str("\" data-extended=\"true");
918    }
919    out.push_str("\">");
920
921    // A checkbox labels itself, on the right of the box. Both apps special-case
922    // this inline today, which is the tell that it belongs in the description;
923    // `FieldKind::labels_itself` is where it went.
924    if !field.kind.labels_itself() {
925        out.push_str("<label class=\"");
926        push_class(out, "form-label", opts);
927        // A group control is named *by* its label rather than pointing at it,
928        // so the two carry opposite halves of the association. See
929        // `is_group_control`.
930        if is_group_control(field.kind) {
931            let _ = write!(out, "\" id=\"{id}-label\">");
932        } else {
933            let _ = write!(out, "\" for=\"{id}\">");
934        }
935        escape_into(field.label, out);
936        out.push_str("</label>");
937    }
938
939    push_control(out, field, filling, opts);
940
941    if let Some(hint) = field.hint {
942        out.push_str("<div class=\"");
943        push_class(out, "form-hint", opts);
944        let _ = write!(out, "\" id=\"{id}-hint\">");
945        escape_into(hint, out);
946        out.push_str("</div>");
947    }
948    if let Some(Markup(markup)) = filling.trailing {
949        out.push_str(markup);
950    }
951    if let Some(error) = field.error {
952        out.push_str("<div class=\"");
953        push_class(out, "form-error", opts);
954        let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
955        escape_into(error, out);
956        out.push_str("</div>");
957    }
958
959    out.push_str("</div>");
960}
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965    use makeover_layout::{Accepted, Curve, Family};
966
967    fn field(kind: FieldKind) -> Field<'static> {
968        Field::new(kind, "title", "Title")
969    }
970
971    #[test]
972    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
973        // The payload from goingson's own CHRONIC-XSS regression test.
974        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
975        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
976        // The payload survives as text, which is the point: it is inert
977        // because the quote that would have closed the attribute is encoded,
978        // not because the words were filtered.
979        assert!(!html.contains("\" onfocus"), "{html}");
980        assert!(
981            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
982            "{html}"
983        );
984    }
985
986    /// The seam quasi's suggestion source needs: a host's own attributes land
987    /// on the control, unescaped, and after everything this crate decided.
988    #[test]
989    fn a_host_can_write_its_own_attributes_onto_the_control() {
990        let mut filling = Filling::of(Value::Text("ru"));
991        filling.control_attrs = Some(Markup(
992            r#"role="combobox" aria-expanded="false" aria-controls="title-suggestions""#,
993        ));
994        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
995        assert!(html.contains(r#"role="combobox""#), "{html}");
996        assert!(
997            html.contains(r#"aria-controls="title-suggestions""#),
998            "{html}"
999        );
1000        // After the id, which is what "last" buys: a host can read what this
1001        // emitter wrote and cannot be overwritten by it.
1002        let id = html.find(r#"id="title""#).expect("id");
1003        let role = html.find(r#"role="combobox""#).expect("role");
1004        assert!(id < role, "{html}");
1005    }
1006
1007    /// A radio group has no one control element, so there is nowhere honest to
1008    /// put an attribute meant for the control. Documented on the member.
1009    #[test]
1010    fn a_radio_group_drops_control_attributes() {
1011        let mut f = field(FieldKind::Radio);
1012        let options = [Choice::new("a", "A")];
1013        f.options = &options;
1014        let filling = Filling {
1015            control_attrs: Some(Markup(r#"data-host="1""#)),
1016            ..Filling::default()
1017        };
1018        let html = field_html(&f, &filling, &Emit::default());
1019        assert!(!html.contains("data-host"), "{html}");
1020    }
1021
1022    #[test]
1023    fn a_label_cannot_open_a_tag() {
1024        let mut f = field(FieldKind::Text);
1025        f.label = "<script>alert(1)</script>";
1026        let html = field_html(&f, &Filling::default(), &Emit::default());
1027        assert!(!html.contains("<script>"), "{html}");
1028        assert!(html.contains("&lt;script&gt;"), "{html}");
1029    }
1030
1031    #[test]
1032    fn every_escaped_sink_is_covered_by_the_one_escaper() {
1033        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
1034        // The character `textContent` serialization leaves alone, which is why
1035        // the app needs two escapers and this needs one.
1036        assert!(escape("\"").contains("&quot;"));
1037    }
1038
1039    /// The streaming escaper is the one the emitters call and [`escape`] is a
1040    /// buffer around it, so the two cannot be allowed to drift. It copies in
1041    /// runs between the encoded characters, which is where a multi-byte
1042    /// character would break it if the scan were not restricted to ASCII.
1043    #[test]
1044    fn the_streaming_escaper_appends_what_the_returning_one_returns() {
1045        for text in [
1046            "",
1047            "plain",
1048            "&<>\"'",
1049            "&&&",
1050            "a & b",
1051            "trailing&",
1052            "&leading",
1053            "é世 & <b>naïve</b> \u{1f600}",
1054        ] {
1055            let mut out = String::from("kept: ");
1056            escape_into(text, &mut out);
1057            assert_eq!(out, format!("kept: {}", escape(text)), "{text:?}");
1058        }
1059    }
1060
1061    /// Same obligation one layer up: a form is a run of fields appended into one
1062    /// buffer, and the two ways to get one have to agree byte for byte.
1063    #[test]
1064    fn a_streamed_field_is_the_field_the_other_form_returns() {
1065        let kinds = [
1066            FieldKind::Text,
1067            FieldKind::Secret,
1068            FieldKind::Number,
1069            FieldKind::Checkbox,
1070            FieldKind::Radio,
1071            FieldKind::Select,
1072            FieldKind::Textarea,
1073            FieldKind::File,
1074            FieldKind::Hidden,
1075        ];
1076        let choices = [Choice::plain("one"), Choice::plain("two")];
1077        let opts = Emit {
1078            class_prefix: "mk-",
1079            ..Emit::default()
1080        };
1081        for kind in kinds {
1082            let described = Field {
1083                hint: Some("a hint"),
1084                error: Some("wrong <here>"),
1085                placeholder: Some("x\" y"),
1086                options: &choices,
1087                required: true,
1088                max_length: Some(40),
1089                min: Some("1"),
1090                max: Some("9"),
1091                extended: true,
1092                ..Field::new(kind, "the & name", "The <label>")
1093            };
1094            let filling = Filling {
1095                value: Value::Text("one"),
1096                trailing: Some(Markup("<i>t</i>")),
1097                control_attrs: Some(Markup(r#"data-host="1""#)),
1098                id_prefix: Some("modal"),
1099            };
1100            let mut streamed = String::new();
1101            field_html_into(&described, &filling, &opts, &mut streamed);
1102            assert_eq!(
1103                streamed,
1104                field_html(&described, &filling, &opts),
1105                "{kind:?}"
1106            );
1107
1108            // And the bare field, where every optional half is absent.
1109            let plain = Field::new(kind, "name", "Label");
1110            let mut streamed = String::new();
1111            field_html_into(&plain, &Filling::default(), &opts, &mut streamed);
1112            assert_eq!(
1113                streamed,
1114                field_html(&plain, &Filling::default(), &opts),
1115                "{kind:?}"
1116            );
1117        }
1118    }
1119
1120    #[test]
1121    fn markup_is_the_only_way_past_the_escaping() {
1122        let filling = Filling {
1123            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
1124            ..Filling::default()
1125        };
1126        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1127        assert!(
1128            html.contains("<div class=\"recurrence-config\"></div>"),
1129            "{html}"
1130        );
1131    }
1132
1133    #[test]
1134    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
1135        let mut f = field(FieldKind::Text);
1136        f.error = Some("Required");
1137        let opts = Emit::default();
1138        let html = field_html(&f, &Filling::default(), &opts);
1139        assert!(html.contains("aria-invalid=\"true\""), "{html}");
1140        // The selector the CSS side emits for exactly this state.
1141        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
1142        // And the group is marked too, which a renderer without descendant
1143        // selectors depends on.
1144        assert!(html.contains("has-error"), "{html}");
1145    }
1146
1147    #[test]
1148    fn a_valid_field_claims_nothing_about_being_invalid() {
1149        let html = field_html(
1150            &field(FieldKind::Text),
1151            &Filling::default(),
1152            &Emit::default(),
1153        );
1154        assert!(!html.contains("aria-invalid"), "{html}");
1155        assert!(!html.contains("has-error"), "{html}");
1156    }
1157
1158    #[test]
1159    fn the_hint_survives_an_error_arriving() {
1160        let mut f = field(FieldKind::Text);
1161        f.hint = Some("Keep it short");
1162        f.error = Some("Required");
1163        let html = field_html(&f, &Filling::default(), &Emit::default());
1164        assert!(
1165            html.contains("aria-describedby=\"title-hint title-error\""),
1166            "{html}"
1167        );
1168    }
1169
1170    #[test]
1171    fn a_secret_never_carries_its_value_into_the_markup() {
1172        let filling = Filling::of(Value::Text("hunter2"));
1173        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
1174        assert!(!html.contains("hunter2"), "{html}");
1175        assert!(html.contains("type=\"password\""), "{html}");
1176    }
1177
1178    #[test]
1179    fn a_hidden_field_is_the_input_and_nothing_else() {
1180        let filling = Filling::of(Value::Text("42"));
1181        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1182        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
1183    }
1184
1185    #[test]
1186    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
1187        let html = field_html(
1188            &field(FieldKind::Checkbox),
1189            &Filling::of(Value::On(true)),
1190            &Emit::default(),
1191        );
1192        assert!(!html.contains("form-label"), "{html}");
1193        assert!(html.contains("checked"), "{html}");
1194        assert!(html.contains("<span>Title</span>"), "{html}");
1195    }
1196
1197    #[test]
1198    fn a_select_keeps_a_value_no_option_carries() {
1199        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
1200        let f = Field::select("title", "Title", &options);
1201        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1202        assert!(html.contains("data-unmatched=\"true\""), "{html}");
1203        // Selected, so the next save round-trips it rather than writing the
1204        // first option over the top of it.
1205        assert!(html.contains("<option value=\"10\" selected"), "{html}");
1206    }
1207
1208    #[test]
1209    fn a_select_with_no_options_emits_an_empty_select() {
1210        // The description says a select with no options is sayable, because an
1211        // app whose option list has not loaded has exactly that. Emitting the
1212        // empty select reports it on screen rather than in a log.
1213        let f = Field::select("title", "Title", &[]);
1214        let html = field_html(&f, &Filling::default(), &Emit::default());
1215        assert!(html.contains("<select"), "{html}");
1216        assert!(!html.contains("<option"), "{html}");
1217    }
1218
1219    #[test]
1220    fn an_unanswered_select_shows_its_ghost_text_and_cannot_be_chosen_back() {
1221        let options = [Choice::new("sp404", "SP-404")];
1222        let f = Field {
1223            placeholder: Some("Select device..."),
1224            ..Field::select("device", "Conform for device", &options)
1225        };
1226        let html = field_html(&f, &Filling::default(), &Emit::default());
1227
1228        assert!(
1229            html.contains("<option value=\"\" disabled selected>Select device...</option>"),
1230            "{html}"
1231        );
1232        // First, so the closed control reads it rather than the first real
1233        // option.
1234        assert!(
1235            html.find("Select device...") < html.find("SP-404"),
1236            "{html}"
1237        );
1238    }
1239
1240    #[test]
1241    fn an_answered_select_drops_the_ghost_text() {
1242        // It is an instruction about an empty field, so it has nothing to say
1243        // once the field is answered, and leaving it in the list is one dead
1244        // row every time the control is opened afterwards.
1245        let options = [Choice::new("sp404", "SP-404")];
1246        let f = Field {
1247            placeholder: Some("Select device..."),
1248            ..Field::select("device", "Conform for device", &options)
1249        };
1250        let html = field_html(&f, &Filling::of(Value::Text("sp404")), &Emit::default());
1251        assert!(!html.contains("Select device..."), "{html}");
1252    }
1253
1254    #[test]
1255    fn a_wrong_answer_is_kept_and_is_not_the_ghost_text() {
1256        // The two paths through `push_options` meet here. An unmatched value is
1257        // an answer that is wrong and stays visible as itself; only the empty
1258        // value is unanswered.
1259        let options = [Choice::plain("1"), Choice::plain("7")];
1260        let f = Field {
1261            placeholder: Some("Pick one"),
1262            ..Field::select("retention", "Keep backups for", &options)
1263        };
1264        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1265        assert!(html.contains("data-unmatched=\"true\""), "{html}");
1266        assert!(!html.contains("Pick one"), "{html}");
1267    }
1268
1269    #[test]
1270    fn a_range_is_a_range_input_and_carries_its_extent() {
1271        let f = Field {
1272            curve: Curve::Linear { step: Some("0.01") },
1273            ..Field::range("review", "Review above", "0", "1")
1274        };
1275        let html = field_html(&f, &Filling::of(Value::Text("0.72")), &Emit::default());
1276        assert!(html.contains("type=\"range\""), "{html}");
1277        assert!(html.contains("min=\"0\""), "{html}");
1278        assert!(html.contains("max=\"1\""), "{html}");
1279        // Without it the browser steps by 1 and a 0-to-1 question becomes a
1280        // two-position control.
1281        assert!(html.contains("step=\"0.01\""), "{html}");
1282    }
1283
1284    #[test]
1285    fn a_range_reads_its_granularity_off_the_curve_and_not_off_field_step() {
1286        // The 0.32.0 narrowing, at the renderer. `Field::step` on a range is a
1287        // site that has not been moved over, and emitting it would make the
1288        // control step by a number the curve never agreed to.
1289        let f = Field {
1290            step: Some("99"),
1291            ..Field::range("review", "Review above", "0", "1")
1292        };
1293        let html = field_html(&f, &Filling::of(Value::Text("0.5")), &Emit::default());
1294        assert!(!html.contains("step="), "{html}");
1295    }
1296
1297    #[test]
1298    fn a_constant_ratio_curve_still_emits_a_linear_track() {
1299        // Honest shortfall rather than a silent one: HTML has no logarithmic
1300        // range input, so the browser draws the extent linearly. The value it
1301        // submits is still a value in the field's own units, which is what
1302        // every handler on this path reads. See the crate header.
1303        let f = Field {
1304            curve: Curve::Logarithmic {
1305                step: Some("0.001"),
1306            },
1307            ..Field::range("attack", "Attack", "0.001", "5")
1308        };
1309        let html = field_html(&f, &Filling::of(Value::Text("0.005")), &Emit::default());
1310        assert!(html.contains("type=\"range\""), "{html}");
1311        assert!(html.contains("min=\"0.001\""), "{html}");
1312        assert!(html.contains("max=\"5\""), "{html}");
1313        assert!(html.contains("step=\"0.001\""), "{html}");
1314    }
1315
1316    #[test]
1317    fn a_number_with_bounds_is_still_typed_into() {
1318        // The distinction the kind exists for, at the renderer where getting it
1319        // wrong is most visible: goingson's `min="1"` duration must not come
1320        // back as a slider.
1321        let f = Field {
1322            min: Some("1"),
1323            ..Field::new(FieldKind::Number, "minutes", "Minutes")
1324        };
1325        let html = field_html(&f, &Filling::of(Value::Text("30")), &Emit::default());
1326        assert!(html.contains("type=\"number\""), "{html}");
1327        assert!(!html.contains("type=\"range\""), "{html}");
1328        // And nothing invents a step for it.
1329        assert!(!html.contains("step="), "{html}");
1330    }
1331
1332    #[test]
1333    fn an_unavailable_option_is_disabled_and_says_why() {
1334        let options = [
1335            Choice::new("chromatic", "Chromatic"),
1336            Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1337        ];
1338        let f = Field::radio("mode", "Mode", &options);
1339        let html = field_html(&f, &Filling::of(Value::Text("chromatic")), &Emit::default());
1340
1341        assert!(html.contains(" disabled"), "{html}");
1342        assert!(html.contains("Drop a second sample."), "{html}");
1343        // The option is still offered: dropping it is what costs the user the
1344        // knowledge that the mode exists.
1345        assert!(html.contains("value=\"multi\""), "{html}");
1346        // And the reason is its own element, not run into the label.
1347        assert!(html.contains("form-option-reason"), "{html}");
1348    }
1349
1350    #[test]
1351    fn an_unavailable_select_option_carries_its_reason_in_its_text() {
1352        // A `<select>` gives an option no room for a second element, so the
1353        // reason has to be in the text or be unreadable without a pointer.
1354        let options = [Choice::new("multi", "Multi-sample").unless("Drop a second sample.")];
1355        let f = Field::select("mode", "Mode", &options);
1356        let html = field_html(&f, &Filling::default(), &Emit::default());
1357        assert!(
1358            html.contains(">Multi-sample: Drop a second sample.</option>"),
1359            "{html}"
1360        );
1361        assert!(html.contains("disabled"), "{html}");
1362    }
1363
1364    #[test]
1365    fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
1366        // The association inverts, and getting it wrong is silent: a
1367        // `<label for>` aimed at a group points at no element, so the group
1368        // simply has no accessible name and nothing reports that.
1369        let options = [Choice::plain("copy"), Choice::plain("reference")];
1370        let f = Field::radio("storage", "Storage style", &options);
1371        let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
1372
1373        assert!(html.contains("id=\"storage-label\""), "{html}");
1374        assert!(!html.contains("for=\"storage\""), "{html}");
1375        assert!(html.contains("role=\"radiogroup\""), "{html}");
1376        assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
1377    }
1378
1379    #[test]
1380    fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
1381        // One `name` is what makes them one answer rather than three; distinct
1382        // ids are what keep each `<label>` wrapping its own input.
1383        let options = [
1384            Choice::plain("copy"),
1385            Choice::plain("reference"),
1386            Choice::plain("link"),
1387        ];
1388        let f = Field::radio("storage", "Storage style", &options);
1389        let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
1390
1391        assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
1392        assert_eq!(html.matches(" checked").count(), 1, "{html}");
1393        assert!(
1394            html.contains("value=\"reference\" checked"),
1395            "the checked one is the one held: {html}"
1396        );
1397        for index in 0..3 {
1398            assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
1399        }
1400    }
1401
1402    #[test]
1403    fn a_radio_group_carries_the_error_rather_than_any_one_option() {
1404        // What is wrong is the answer, not one of the alternatives, so marking
1405        // a single input invalid would say something false. Same reading
1406        // `Field::invalid` gives one level up.
1407        let options = [Choice::plain("copy"), Choice::plain("reference")];
1408        let f = Field {
1409            error: Some("Pick one."),
1410            hint: Some("Cannot be changed later."),
1411            ..Field::radio("storage", "Storage style", &options)
1412        };
1413        let html = field_html(&f, &Filling::default(), &Emit::default());
1414
1415        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
1416        assert!(
1417            html.contains("aria-describedby=\"storage-hint storage-error\""),
1418            "{html}"
1419        );
1420        // The group is the element that carries them, so they land before the
1421        // first option rather than on it.
1422        let group = html.find("role=\"radiogroup\"").expect("group");
1423        let first = html.find("type=\"radio\"").expect("an option");
1424        assert!(group < first, "{html}");
1425    }
1426
1427    #[test]
1428    fn a_compulsory_radio_group_marks_every_option() {
1429        // How HTML says a group is compulsory: the constraint reads as
1430        // satisfied when any one of them is checked.
1431        let options = [Choice::plain("copy"), Choice::plain("reference")];
1432        let f = Field {
1433            required: true,
1434            ..Field::radio("storage", "Storage style", &options)
1435        };
1436        let html = field_html(&f, &Filling::default(), &Emit::default());
1437        assert_eq!(html.matches(" required").count(), 2, "{html}");
1438    }
1439
1440    #[test]
1441    fn a_radio_option_cannot_break_out_of_its_attribute() {
1442        // Values are `&str` and carry whatever the app put in them. The ids are
1443        // numbered rather than derived from the value for the same reason.
1444        let hostile = [Choice::new(
1445            "x\" onclick=alert(1) data-x=\"",
1446            "<script>alert(1)</script>",
1447        )];
1448        let f = Field::radio("storage", "Storage style", &hostile);
1449        let html = field_html(&f, &Filling::default(), &Emit::default());
1450
1451        // The payload survives as text; what must not survive is the quote
1452        // that would end the attribute and let the rest of it become markup.
1453        assert!(html.contains("value=\"x&quot; onclick=alert(1)"), "{html}");
1454        assert!(!html.contains("<script>"), "{html}");
1455        assert!(html.contains("id=\"storage-0\""), "{html}");
1456    }
1457
1458    #[test]
1459    fn a_radio_group_with_no_options_emits_an_empty_group() {
1460        // Same position the select takes, and the description's own.
1461        let f = Field::radio("storage", "Storage style", &[]);
1462        let html = field_html(&f, &Filling::default(), &Emit::default());
1463        assert!(html.contains("role=\"radiogroup\""), "{html}");
1464        assert!(!html.contains("type=\"radio\""), "{html}");
1465    }
1466
1467    #[test]
1468    fn a_placeholder_comes_off_the_description_and_is_escaped() {
1469        // It arrived in `Filling` until makeover-layout 0.8.0 and was never
1470        // covered here; it is a value in an attribute like any other.
1471        let f = Field {
1472            placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
1473            ..field(FieldKind::Text)
1474        };
1475        let html = field_html(&f, &Filling::default(), &Emit::default());
1476        assert!(html.contains("placeholder=\""), "{html}");
1477        assert!(!html.contains("\" onfocus"), "{html}");
1478    }
1479
1480    #[test]
1481    fn a_select_marks_the_option_that_matches() {
1482        let options = [Choice::plain("1"), Choice::plain("3")];
1483        let f = Field::select("title", "Title", &options);
1484        let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
1485        assert!(
1486            html.contains("<option value=\"3\" selected>3</option>"),
1487            "{html}"
1488        );
1489        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
1490        assert!(!html.contains("data-unmatched"), "{html}");
1491    }
1492
1493    #[test]
1494    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
1495        let filling = Filling::of(Value::Text("two\nlines"));
1496        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1497        assert!(html.contains(">two\nlines</textarea>"), "{html}");
1498    }
1499
1500    #[test]
1501    fn a_markdown_field_is_a_textarea_that_says_what_its_value_is() {
1502        // The mark is the whole difference. Without it a described editor is a
1503        // plain box, and an enhancement looking for editors to upgrade has
1504        // nothing to find -- which is the state MNW's four hand-written section
1505        // editors would have had to keep living in.
1506        let filling = Filling::of(Value::Text("# Heading"));
1507        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1508        assert!(html.contains("<textarea"), "{html}");
1509        assert!(html.contains(r#"data-format="markdown""#), "{html}");
1510        assert!(html.contains("># Heading</textarea>"), "{html}");
1511
1512        // A plain textarea claims nothing about its value, so the marker has to
1513        // be absent rather than present-and-different.
1514        let plain = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1515        assert!(!plain.contains("data-format"), "{plain}");
1516
1517        // And it is not an input: the catch-all in `input_type` would have
1518        // degraded it to a single-line text box, which is the wrong shape for
1519        // markdown rather than a lossless fallback.
1520        assert!(!html.contains("<input"), "{html}");
1521    }
1522
1523    #[test]
1524    fn a_markdown_field_gets_the_preview_the_member_permits() {
1525        // The mark on its own is what 0.50.0 shipped, and nothing read it. What
1526        // a conversion needs is the pair MNW's `partial-item-text-editor.js`
1527        // already draws, so describing the field is not a way to lose it.
1528        let filling = Filling::of(Value::Text("# Heading"));
1529        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1530        assert!(html.contains("data-editor-mode=\"write\""), "{html}");
1531        assert!(html.contains("data-editor-mode=\"preview\""), "{html}");
1532        assert!(html.contains("data-editor-preview"), "{html}");
1533        // Write is the mode a fresh editor is in, and the segment says so twice
1534        // because the sheet reads one and a screen reader reads the other.
1535        assert!(
1536            html.contains(
1537                "class=\"segment chosen\" data-editor-mode=\"write\" aria-pressed=\"true\""
1538            ),
1539            "{html}"
1540        );
1541        assert!(
1542            html.contains("data-editor-mode=\"preview\" aria-pressed=\"false\""),
1543            "{html}"
1544        );
1545        // The value is still the textarea's, and still text rather than an
1546        // attribute. The chrome sits around the control, not in place of it.
1547        assert!(html.contains("># Heading</textarea>"), "{html}");
1548    }
1549
1550    #[test]
1551    fn a_plain_textarea_gets_no_editor_chrome() {
1552        let filling = Filling::of(Value::Text("plain"));
1553        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1554        assert!(!html.contains("data-editor-mode"), "{html}");
1555        assert!(!html.contains("data-editor-preview"), "{html}");
1556        assert!(!html.contains("segment"), "{html}");
1557    }
1558
1559    #[test]
1560    fn nothing_the_editor_emits_renders_the_value_as_markup() {
1561        // The whole of this crate's half of the sanitising question: the pane is
1562        // empty, so no value reaches markup through it, and the host's own
1563        // renderer keeps the guarantee it already has.
1564        let filling = Filling::of(Value::Text("<img src=x onerror=alert(1)>"));
1565        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1566        assert!(html.contains("data-editor-preview></div>"), "{html}");
1567        assert!(!html.contains("<img"), "{html}");
1568        assert!(
1569            html.contains("&lt;img src=x onerror=alert(1)&gt;"),
1570            "{html}"
1571        );
1572    }
1573
1574    #[test]
1575    fn the_editor_rules_gate_on_the_attribute_and_on_a_binding() {
1576        let css = editor_rules(&Emit::default());
1577        // Behind the attribute, which is the reason the mark is an attribute:
1578        // a class-keyed gate would be prefixed away from the enhancement that
1579        // selects on it.
1580        for line in css.lines().filter(|line| line.contains('{')) {
1581            assert!(line.contains("[data-format=\"markdown\"]"), "{line}");
1582        }
1583        // Nothing is hidden and no control appears until something binds the
1584        // editor. A reader with no script gets the textarea alone.
1585        assert!(
1586            css.contains(
1587                "[data-format=\"markdown\"] > .form-editor-modes {\n    display: none;\n}"
1588            )
1589        );
1590        assert!(css.contains(
1591            "[data-format=\"markdown\"][data-ready] > .form-editor-modes {\n    display: block;\n}"
1592        ));
1593        assert!(css.contains(
1594            "[data-ready][data-mode=\"preview\"] > .form-editor-preview {\n    display: block;\n}"
1595        ));
1596        assert!(
1597            css.contains("[data-ready][data-mode=\"preview\"] > .field {\n    display: none;\n}")
1598        );
1599        // No magnitude, the line this crate holds everywhere else.
1600        assert!(!css.contains("px"), "{css}");
1601        assert!(!css.contains("rem"), "{css}");
1602    }
1603
1604    /// The prefix reaches the chrome as well, and the gate deliberately does
1605    /// not: an app assembling the sheet with its own prefix still has the
1606    /// selector an enhancement finds the editors by.
1607    #[test]
1608    fn the_editor_chrome_is_prefixed_and_its_gate_is_not() {
1609        let opts = Emit {
1610            class_prefix: "mk-",
1611            ..Emit::default()
1612        };
1613        let html = field_html(&field(FieldKind::Rich), &Filling::default(), &opts);
1614        assert!(html.contains("class=\"mk-form-editor-modes\""), "{html}");
1615        assert!(html.contains("class=\"mk-form-editor-preview\""), "{html}");
1616        assert!(html.contains("class=\"mk-segment chosen\""), "{html}");
1617        assert!(html.contains("data-format=\"markdown\""), "{html}");
1618
1619        let css = editor_rules(&opts);
1620        assert!(css.contains(".mk-form-editor-modes"), "{css}");
1621        assert!(css.contains("[data-format=\"markdown\"]"), "{css}");
1622    }
1623
1624    /// Every class the editor puts in markup is one the generated sheet rules,
1625    /// which is `FACET_CLASSES`' obligation without a list to keep: these two
1626    /// have rules, so the vocabulary seal picks them up from the sheet itself.
1627    #[test]
1628    fn the_editor_classes_are_in_the_vocabulary() {
1629        let opts = Emit::default();
1630        let names = crate::vocabulary::names(&opts);
1631        for name in ["form-editor-modes", "form-editor-preview", "segment"] {
1632            assert!(names.contains(name), "{name} is not in the vocabulary");
1633        }
1634    }
1635
1636    #[test]
1637    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
1638        let opts = Emit {
1639            class_prefix: "mk-",
1640            ..Emit::default()
1641        };
1642        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
1643        assert!(html.contains("class=\"mk-form-group\""), "{html}");
1644        assert!(html.contains("class=\"mk-field\""), "{html}");
1645    }
1646
1647    #[test]
1648    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
1649        let mut f = field(FieldKind::Text);
1650        f.extended = true;
1651        let html = field_html(&f, &Filling::default(), &Emit::default());
1652        assert!(html.contains("data-extended=\"true\""), "{html}");
1653    }
1654
1655    /// The prefix scopes the id and leaves the name alone. Prefixing the name
1656    /// too would change what the form submits, which is the failure this pair
1657    /// of assertions exists to catch rather than describe.
1658    #[test]
1659    fn the_id_prefix_scopes_the_id_and_never_the_name() {
1660        let mut f = field(FieldKind::Text);
1661        f.hint = Some("Keep it short");
1662        f.error = Some("Required");
1663        let filling = Filling {
1664            id_prefix: Some("form-modal-task-edit"),
1665            ..Filling::default()
1666        };
1667        let html = field_html(&f, &filling, &Emit::default());
1668
1669        assert!(
1670            html.contains(r#"id="form-modal-task-edit-title""#),
1671            "{html}"
1672        );
1673        assert!(html.contains(r#"name="title""#), "{html}");
1674        assert!(
1675            !html.contains(r#"name="form-modal-task-edit-title""#),
1676            "{html}"
1677        );
1678
1679        // The label and both associations follow the id, or they point at
1680        // nothing once the same form is on screen twice.
1681        assert!(
1682            html.contains(r#"for="form-modal-task-edit-title""#),
1683            "{html}"
1684        );
1685        assert!(
1686            html.contains(
1687                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
1688            ),
1689            "{html}"
1690        );
1691        assert!(
1692            html.contains(r#"id="form-modal-task-edit-title-hint""#),
1693            "{html}"
1694        );
1695    }
1696
1697    #[test]
1698    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
1699        let filling = Filling {
1700            value: Value::Text("42"),
1701            id_prefix: Some("scoped"),
1702            ..Filling::default()
1703        };
1704        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1705        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
1706    }
1707
1708    /// These three exist so a touch keyboard and the platform's validation
1709    /// arrive with the field. Emitting text for any of them is the regression
1710    /// the variants were added to prevent, so the type is asserted directly.
1711    #[test]
1712    fn a_constraint_becomes_the_browsers_own_attribute() {
1713        // makeover-layout 0.11.0's model: the description carries the rule and
1714        // each renderer emits its host's idiom for it. Enforcement is still
1715        // whoever validated's, and arrives back as `error`.
1716        let html = field_html(
1717            &Field {
1718                max_length: Some(100),
1719                min: Some("1"),
1720                max: Some("240"),
1721                required: true,
1722                ..Field::new(FieldKind::Number, "minutes", "Minutes")
1723            },
1724            &Filling::default(),
1725            &Emit::default(),
1726        );
1727        assert!(html.contains(r#"maxlength="100""#));
1728        assert!(html.contains(r#"min="1""#));
1729        assert!(html.contains(r#"max="240""#));
1730        assert!(html.contains(" required"));
1731    }
1732
1733    #[test]
1734    fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
1735        // The bound is text because it is only a number for some of the kinds
1736        // that take one; goingson's own sites are a duration and a datetime.
1737        let html = field_html(
1738            &Field {
1739                min: Some("2026-08-09T14:30"),
1740                ..Field::new(FieldKind::Text, "starts", "Starts")
1741            },
1742            &Filling::default(),
1743            &Emit::default(),
1744        );
1745        assert!(html.contains(r#"min="2026-08-09T14:30""#));
1746    }
1747
1748    #[test]
1749    fn a_file_field_is_a_file_input() {
1750        // `844b5ae0`. A field that takes any file emits no `accept` at all,
1751        // which is the browser's own "any file". `accept=""` is a filter that
1752        // means nothing on one browser and everything on another.
1753        let html = field_html(
1754            &Field::new(FieldKind::File, "attachment", "Attachment"),
1755            &Filling::default(),
1756            &Emit::default(),
1757        );
1758        assert!(html.contains(r#"type="file""#));
1759        assert!(!html.contains("accept="));
1760        assert!(!html.contains("multiple"));
1761        // And it never carries a value: a file input's value is not settable
1762        // from markup, and the browser refuses one that tries.
1763        assert!(!html.contains("value="));
1764    }
1765
1766    #[test]
1767    fn an_accept_list_is_comma_joined_in_the_attributes_own_format() {
1768        // `f7261a5a`, makeover-layout 0.31.0. Each entry writes itself: a
1769        // family is its wildcard, a media type is itself, a suffix keeps its
1770        // leading dot and however many more it has.
1771        const MIXED: &[Accepted<'_>] = &[
1772            Accepted::Family(Family::Image),
1773            Accepted::Type("text/csv"),
1774            Accepted::Suffix(".tar.gz"),
1775        ];
1776        let html = field_html(
1777            &Field {
1778                multiple: true,
1779                ..Field::upload("drop", "Drop files", MIXED)
1780            },
1781            &Filling::default(),
1782            &Emit::default(),
1783        );
1784        assert!(
1785            html.contains(r#"accept="image/*,text/csv,.tar.gz""#),
1786            "{html}"
1787        );
1788        assert!(html.contains(" multiple"), "{html}");
1789    }
1790
1791    #[test]
1792    fn an_accept_entry_cannot_end_the_attribute_it_sits_in() {
1793        // The list reaches an attribute value, so it is escaped like every
1794        // other string that does. Nothing in the tree writes a quote into one;
1795        // that it cannot is the point.
1796        const HOSTILE: &[Accepted<'_>] = &[Accepted::Type(r#"image/x" onload="x"#)];
1797        let html = field_html(
1798            &Field::upload("cover", "Cover", HOSTILE),
1799            &Filling::default(),
1800            &Emit::default(),
1801        );
1802        assert!(!html.contains(r#"onload="x"#), "{html}");
1803    }
1804
1805    #[test]
1806    fn the_typed_text_kinds_keep_their_input_type() {
1807        for (kind, expected) in [
1808            (FieldKind::Email, "email"),
1809            (FieldKind::Url, "url"),
1810            (FieldKind::Tel, "tel"),
1811            (FieldKind::Date, "date"),
1812            (FieldKind::DateTime, "datetime-local"),
1813        ] {
1814            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1815            assert!(
1816                html.contains(&format!(r#"type="{expected}""#)),
1817                "{kind:?} emitted {html}"
1818            );
1819        }
1820    }
1821
1822    #[test]
1823    fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
1824        // The regression this closes: described as text with a hint reading
1825        // "YYYY-MM-DD", which loses the picker, the platform's validation and
1826        // the touch keyboard, and asks prose to do all three.
1827        for kind in [FieldKind::Date, FieldKind::DateTime] {
1828            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
1829            assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
1830        }
1831    }
1832
1833    #[test]
1834    fn no_prefix_leaves_the_id_as_the_name() {
1835        let html = field_html(
1836            &field(FieldKind::Text),
1837            &Filling::default(),
1838            &Emit::default(),
1839        );
1840        assert!(html.contains(r#"id="title" name="title""#), "{html}");
1841    }
1842}