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`]. The
30//! placeholder and a select's options are not renderer state: the first is
31//! user-facing text sitting with `label` and `hint`, and the second is needed by
32//! every renderer, so both are read off [`Field`].
33//!
34//! The value stays, and it is not a leftover. A webview reads it back out of
35//! the DOM, an immediate-mode renderer writes through a `&mut`, and a terminal
36//! keeps an edit buffer; a description carrying it would have to carry a way to
37//! write it back, at which point it is a form model.
38
39use crate::{Emit, class, push_class};
40use makeover_layout::{Choice, Depth, Field, FieldKind, Intent as _, Selector, ThemeVariant, Tone};
41use std::fmt::Write as _;
42
43/// Every class this module can put in markup.
44///
45/// [`crate::facet::FACET_CLASSES`]' obligation, and the module where it was
46/// missing longest. Most of these carry no rule and never will: `.form-group`,
47/// `.form-label`, `.form-hint` and `.form-error` are the apps' own names, kept
48/// so adoption deletes goingson's `renderFormField` rather than restyling
49/// anything, and phase A emits only what it can generate from the description.
50/// A class with no rule is invisible to [`crate::vocabulary::vocabulary`],
51/// which reads the generated sheet, so the unruled half of a renderer's
52/// vocabulary can only be written down.
53///
54/// What goes wrong without it: an app checking its stylesheet against
55/// [`crate::vocabulary::names`] concludes that its live `.form-group` and
56/// `.form-label` rules match nothing and are safe to delete.
57pub const FIELD_CLASSES: &[&str] = &[
58    "field",
59    "form-checkbox-label",
60    "form-editor-modes",
61    "form-editor-preview",
62    "form-error",
63    "form-group",
64    "form-hint",
65    "form-interval",
66    "form-label",
67    "form-note",
68    "form-option-detail",
69    "form-option-reason",
70    "form-radio-group",
71    "form-radio-label",
72    "form-unit",
73];
74
75// `form-suggestions`, `form-suggestion` and `form-suggestion-detail` are
76// deliberately absent: [`suggestion_rules`] writes their look and
77// `quasi-webview` writes their markup, because a suggestion source is a route
78// and no description layer carries one. They reach the vocabulary through the
79// generated sheet, which is where a name this crate rules but does not emit
80// belongs.
81
82/// The state classes a field carries, which take no prefix.
83///
84/// `chosen` and `latched`'s convention, stated in
85/// [`crate::vocabulary::vocabulary`]: a state qualifies a prefixed component
86/// (`.mk-form-group.has-error`) rather than standing on its own, so a prefix
87/// moves the thing and not its state.
88///
89/// `has-error` marks the group and `visible` marks the message, which is
90/// [`makeover_layout::Field::invalid`]'s own reasoning: a renderer with no
91/// descendant selectors cannot find the group from the message, so both are
92/// told.
93pub const FIELD_STATE_CLASSES: &[&str] = &["has-error", "visible"];
94
95/// A string that is already markup, and is emitted without escaping.
96///
97/// The one hole in the escaping, and it has to be named to be used. goingson
98/// has two live callers that need it, both passing a recurrence-config block
99/// built elsewhere, and both would otherwise have their markup rendered as
100/// visible angle brackets. A caller constructing this is stating that the
101/// contents are trusted; nothing here can check that for them.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct Markup<'a>(pub &'a str);
104
105/// What the field currently holds.
106///
107/// An enum rather than a bag of optional fields, on the same reasoning
108/// [`makeover_layout::Depth`] is one: a checkbox holding a string is unsayable
109/// here, where a struct would let it be said and then have to cope.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111pub enum Value<'a> {
112    /// Nothing yet.
113    #[default]
114    Absent,
115    /// The value of anything that takes typed text, a select included: what a
116    /// select holds is the `value` of one of [`Field::options`]'s
117    /// [`Choice`]s.
118    ///
119    /// The options are the field's and never this type's, which is what keeps
120    /// a `Chosen { options, value }` variant from existing.
121    /// `makeover-immediate` carries the same single-variant shape.
122    Text(&'a str),
123    /// A checkbox, on or off.
124    On(bool),
125    /// Both ends of a [`FieldKind::Interval`], lower first.
126    ///
127    /// Two values rather than one string with a separator, for
128    /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
129    /// interval submits under two names, so it comes back as two values, and a
130    /// delimiter this crate owned could appear inside either of them.
131    ///
132    /// Either end may be empty while the other stands. "Over 120 BPM" is a
133    /// lower end and no upper one, and it is an answer rather than a
134    /// half-filled form.
135    Between {
136        /// What the lower box holds now.
137        lower: &'a str,
138        /// What the upper box holds now.
139        upper: &'a str,
140    },
141}
142
143impl<'a> Value<'a> {
144    /// The value as text, for the kinds that submit one.
145    const fn as_text(&self) -> &'a str {
146        match self {
147            Self::Text(text) | Self::Between { lower: text, .. } => text,
148            Self::Absent | Self::On(_) => "",
149        }
150    }
151}
152
153impl<'a> Value<'a> {
154    /// The upper end, for the one variant that has one.
155    const fn upper_text(&self) -> &'a str {
156        match self {
157            Self::Between { upper, .. } => upper,
158            Self::Absent | Self::Text(_) | Self::On(_) => "",
159        }
160    }
161}
162
163/// Everything about the field that the description does not carry.
164#[derive(Debug, Clone, Copy, Default)]
165pub struct Filling<'a> {
166    /// What the field holds now.
167    pub value: Value<'a>,
168    /// Markup appended inside the group, after the hint. Not escaped.
169    pub trailing: Option<Markup<'a>>,
170    /// Attributes written onto the control element itself. Not escaped.
171    ///
172    /// [`trailing`](Self::trailing)'s argument at attribute scale: a host knows
173    /// facts about the control that no description layer carries, and until
174    /// this existed the only way to attach one was to stop calling this emitter
175    /// and write a second one. quasi's suggestion source is the first caller —
176    /// a field that owns a list of candidates is a `role="combobox"` pointing
177    /// at the list it owns, and neither half is anything
178    /// [`makeover_layout::Field`] can say.
179    ///
180    /// Written verbatim, so a caller supplies `attr="value"` pairs with no
181    /// leading space and does its own escaping. It is [`Markup`]'s hole in the
182    /// same wall, named the same way so a caller has to state that the contents
183    /// are trusted.
184    ///
185    /// A [`FieldKind::Radio`] drops them, and that is deliberate rather than an
186    /// oversight: a radio group is a set of sibling inputs with no one control
187    /// element, so there is nowhere honest to put an attribute meant for the
188    /// control. The group carries the descriptions for the same reason.
189    pub control_attrs: Option<Markup<'a>>,
190    /// Scopes the `id` attributes to one instance of the form.
191    ///
192    /// The field's `name` is what the value submits under and is the same
193    /// wherever the form appears; its `id` has to be unique in the document,
194    /// and those two facts stop agreeing the moment a form appears twice.
195    /// goingson hits this directly: its new-task and edit-task modals are the
196    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
197    /// `label for` and `aria-describedby` pointing at the right control.
198    ///
199    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
200    /// `name`, which would change what the form submits.
201    pub id_prefix: Option<&'a str>,
202}
203
204impl<'a> Filling<'a> {
205    /// A filling that carries a value and nothing else.
206    #[must_use]
207    pub const fn of(value: Value<'a>) -> Self {
208        Self {
209            value,
210            trailing: None,
211            control_attrs: None,
212            id_prefix: None,
213        }
214    }
215
216    /// The document-unique id for a field of this name.
217    fn id_for(&self, name: &str) -> String {
218        let mut id = String::new();
219        if let Some(prefix) = self.id_prefix {
220            escape_into(prefix, &mut id);
221            id.push('-');
222        }
223        escape_into(name, &mut id);
224        id
225    }
226}
227
228/// Encode the five characters that let a value stop being a value, into a
229/// buffer the caller already has.
230///
231/// The form the emitters use. [`escape`] is this with a `String` allocated
232/// around it, and the allocation is the whole difference: a described screen
233/// escapes once per attribute and once per run of text, so a function that
234/// returns a `String` allocates a few thousand times to produce one page,
235/// where a template engine writes its escaped bytes straight into the output
236/// buffer.
237///
238/// Sound in element text and in a double-quoted attribute alike, which is the
239/// property `textContent`-based escaping cannot have. Both sinks are covered by
240/// one function so that no call site has to choose, here or downstream.
241///
242/// Copies in runs rather than per character. All five encoded characters are
243/// ASCII, so a byte scan cannot land inside a multi-byte character and the
244/// slice between two of them is always a valid `&str`. Text with nothing to
245/// encode — which is most text — is one `push_str` of the whole thing.
246pub fn escape_into(text: &str, out: &mut String) {
247    let mut start = 0;
248    for (index, byte) in text.bytes().enumerate() {
249        let encoded = match byte {
250            b'&' => "&amp;",
251            b'<' => "&lt;",
252            b'>' => "&gt;",
253            b'"' => "&quot;",
254            b'\'' => "&#39;",
255            _ => continue,
256        };
257        out.push_str(&text[start..index]);
258        out.push_str(encoded);
259        start = index + 1;
260    }
261    out.push_str(&text[start..]);
262}
263
264/// Encode the five characters that let a value stop being a value.
265///
266/// [`escape_into`] with a buffer of its own, for the callers that want a value
267/// rather than an append: a caller assembling an attribute out of several
268/// pieces, and everything outside this crate that took this function before the
269/// buffer-writing form existed. Emitting into a buffer you already hold is the
270/// cheaper path and the one this crate's own emitters take.
271#[must_use]
272pub fn escape(text: &str) -> String {
273    let mut out = String::with_capacity(text.len());
274    escape_into(text, &mut out);
275    out
276}
277
278/// The `type` an input takes for a kind.
279///
280/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
281const fn input_type(kind: FieldKind) -> &'static str {
282    match kind {
283        FieldKind::Secret => "password",
284        FieldKind::Number => "number",
285        FieldKind::Checkbox => "checkbox",
286        FieldKind::File => "file",
287        FieldKind::Hidden => "hidden",
288        // Not decoration. Each of these changes the keyboard a touch device
289        // offers and turns on the platform's own validation, which is why the
290        // description names them apart from text rather than letting the app
291        // pass an HTML type through.
292        FieldKind::Email => "email",
293        FieldKind::Url => "url",
294        FieldKind::Tel => "tel",
295        // The same argument, and it buys more here than anywhere else in this
296        // list: a native picker as well as the keyboard and the validation.
297        // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
298        // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
299        FieldKind::Date => "date",
300        FieldKind::DateTime => "datetime-local",
301        FieldKind::Radio => "radio",
302        // The clearest case in this list that a kind is not decoration: a
303        // number and a range submit the same value and are different controls,
304        // and the browser is the one drawing the difference.
305        FieldKind::Range => "range",
306        // Select and Textarea are not inputs at all; they never reach here.
307        // Radio is one, but it is emitted once per option by `radio_html` and
308        // so does not reach here either.
309        FieldKind::Text | FieldKind::Select | FieldKind::Textarea | FieldKind::Rich => "text",
310        // A kind added to the description since this renderer was built. Text
311        // accepts any value the others would, so it degrades rather than
312        // dropping the field.
313        _ => "text",
314    }
315}
316
317/// The attributes every visible control carries, error state included.
318///
319/// `aria-invalid` is the whole reason the error state is readable at all: the
320/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
321/// than on a class, so a control rendered already-invalid without it is styled
322/// as if nothing were wrong. goingson's runtime validation path sets the
323/// attribute and its initial render does not, which is exactly the drift one
324/// emitter removes.
325/// `id` and `name` arrive separately because they are not the same fact. The
326/// name is what submits and is fixed by the description; the id has to be
327/// unique in the document and so carries [`Filling::id_prefix`] when a form
328/// appears more than once.
329/// The `accept` attribute, from the description's accept list.
330///
331/// The list is comma-joined because that is the
332/// attribute's own format, and each entry writes itself: a family is its
333/// wildcard media type, a media type is itself, a suffix is itself with its
334/// leading dot. Nothing is normalised on the way through -- `.tar.gz` is two
335/// dots and the browser is fine with it.
336///
337/// An empty list emits no attribute at all, which is the browser's own "any
338/// file" and is what the description means by listing nothing. Emitting
339/// `accept=""` instead would be a filter that matches nothing on some browsers
340/// and everything on others.
341///
342/// It is a filter and not a guarantee, on the browser's side as much as here:
343/// the picker keeps an "All Files" escape and the user may take it. Whoever
344/// validated still validates.
345fn push_accept(out: &mut String, field: &Field<'_>) {
346    if field.accept.is_empty() {
347        return;
348    }
349    out.push_str(" accept=\"");
350    for (index, one) in field.accept.iter().enumerate() {
351        if index > 0 {
352            out.push(',');
353        }
354        escape_into(one.as_str(), out);
355    }
356    out.push('"');
357}
358
359/// The extent and the granularity, as the browser spells them.
360///
361/// Its own function because an interval writes them onto both of its ends: they
362/// describe the axis rather than either end of it, which is what
363/// [`FieldKind::Interval`] says and what the six audiofiles filter axes are.
364fn push_bounds(out: &mut String, field: &Field<'_>) {
365    if let Some(min) = field.min {
366        out.push_str(" min=\"");
367        escape_into(min, out);
368        out.push('"');
369    }
370    if let Some(max) = field.max {
371        out.push_str(" max=\"");
372        escape_into(max, out);
373        out.push('"');
374    }
375    // The browser's own default is `step="1"`, which turns a 0-to-1 threshold
376    // into a two-position control. That is the granularity the description
377    // means when it says nothing, so this is emitted only when an app has said
378    // otherwise rather than defaulted here.
379    //
380    // A range takes its granularity from its curve as of makeover-layout
381    // 0.32.0, and every other kind keeps `Field::step`. See the crate header on
382    // what this renderer can and cannot do with a curve.
383    let step = if field.kind == FieldKind::Range {
384        field.curve.step()
385    } else {
386        field.step
387    };
388    if let Some(step) = step {
389        out.push_str(" step=\"");
390        escape_into(step, out);
391        out.push('"');
392    }
393}
394
395fn push_control_attributes(
396    out: &mut String,
397    field: &Field<'_>,
398    filling: &Filling<'_>,
399    id: &str,
400    name: &str,
401) {
402    let _ = write!(out, " id=\"{id}\" name=\"");
403    escape_into(name, out);
404    out.push('"');
405    if field.required {
406        out.push_str(" required");
407    }
408    // makeover-layout 0.11.0's constraints. The description carries the rule and
409    // this emits the browser's idiom for it, which is the model `required` has
410    // been using since before the crate wrote down that it carried none.
411    // Enforcement is still whoever validated's, and arrives back as `error`.
412    if let Some(limit) = field.max_length {
413        let _ = write!(out, " maxlength=\"{limit}\"");
414    }
415    push_bounds(out, field);
416    // The description asks for the wall-clock value to be submitted as the
417    // moment it names, and in a browser that conversion is script's: `<input
418    // type="datetime-local">` submits what the user typed and nothing in HTML
419    // turns it into an instant. So this emits the mark and quasi-webview's
420    // `instant.js` does the converting -- the same division as `data-clock`,
421    // where the markup says what to do and the shipped script is what a browser
422    // knows that a description cannot.
423    //
424    // Only DateTime. A date and a time are each half a moment and cannot name
425    // one on their own, so the flag is ignored there rather than emitting a
426    // mark nothing can honour.
427    if field.as_instant && matches!(field.kind, FieldKind::DateTime) {
428        out.push_str(" data-instant=\"true\"");
429    }
430    if field.invalid() {
431        out.push_str(" aria-invalid=\"true\"");
432    }
433
434    push_described_by(out, field, id);
435
436    // Last, so that a host attaching a fact of its own can see everything this
437    // emitter decided and cannot be overwritten by it. Duplicate attributes are
438    // the caller's to avoid: HTML takes the first of a repeated pair, so an
439    // attribute spelled here as well as there keeps this crate's answer.
440    if let Some(Markup(attrs)) = filling.control_attrs {
441        out.push(' ');
442        out.push_str(attrs);
443    }
444}
445
446/// The `aria-describedby` naming whatever of the hint and the error exist.
447///
448/// Both associations, in the order they are useful: the standing help, then
449/// what is currently wrong. goingson's runtime path points describedby at the
450/// error alone and drops the hint association it never made in the first place;
451/// naming both here means the hint survives an error appearing.
452///
453/// Its own function because a radio group carries it on the group rather than
454/// on a control, and one reading of "what describes this field" is the point.
455fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
456    let unit = unit_of(field).is_some();
457    if field.hint.is_none() && field.error.is_none() && field.note.is_none() && !unit {
458        return;
459    }
460    let mut written = false;
461    out.push_str(" aria-describedby=\"");
462    if field.hint.is_some() {
463        let _ = write!(out, "{id}-hint");
464        written = true;
465    }
466    // The unit before the error and after the hint, which is the order they are
467    // useful in: what the number is measured in is standing context like the
468    // hint, and what is wrong with it now comes last.
469    if unit {
470        if written {
471            out.push(' ');
472        }
473        let _ = write!(out, "{id}-unit");
474        written = true;
475    }
476    // The note after the unit and before the error, matching the order the
477    // three are drawn in and the order they are useful in: what the answer
478    // costs is context, and what is wrong with it now still comes last.
479    if field.note.is_some() {
480        if written {
481            out.push(' ');
482        }
483        let _ = write!(out, "{id}-note");
484        written = true;
485    }
486    if field.error.is_some() {
487        if written {
488            out.push(' ');
489        }
490        let _ = write!(out, "{id}-error");
491    }
492    out.push('"');
493}
494
495/// The unit to draw beside this field's value, if there is one to draw.
496///
497/// Two conditions rather than one: the field has to carry a unit and its kind
498/// has to be one that means anything by it. `FieldKind::measurable` is the
499/// description answering the second, so this renderer keeps no list of its own
500/// of which kinds are quantities.
501fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
502    field.unit.filter(|_| field.kind.measurable())
503}
504
505/// Whether the field's control is a set of elements rather than one.
506///
507/// A DOM concern rather than a description one, which is why it is decided here
508/// and not in `makeover-layout`: `for` and `id` are an HTML association and
509/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
510/// points at nothing, because no single element carries the group's id, so the
511/// association has to invert — the label takes an id and the group names itself
512/// with `aria-labelledby`.
513const fn is_group_control(kind: FieldKind) -> bool {
514    matches!(kind, FieldKind::Radio | FieldKind::Interval)
515}
516
517/// An interval: two number boxes inside one labelled group.
518///
519/// The markup MNW's discover sidebar writes by hand -- a `role="group"` with
520/// `aria-labelledby` pointing at the question, holding `min_price` and
521/// `max_price` -- which is HTML saying by hand exactly what
522/// [`FieldKind::Interval`] now says in the description. So this emits what that
523/// page already proved is right, rather than inventing a shape.
524///
525/// The group carries the error state and the descriptions, for
526/// [`push_radio`]'s reason: what is wrong is the answer, and marking one box
527/// invalid would name the wrong half of a fault that belongs to both ends.
528///
529/// # Both boxes take the same extent
530///
531/// [`Field::min`], [`Field::max`] and [`Field::step`] describe the axis rather
532/// than either end, so [`push_bounds`] writes them onto both. The crossing rule
533/// is not emitted, because the description does not carry it and the browser
534/// has no attribute for it: an upper end below the lower one is a refusal
535/// whoever validated hands back as [`Field::error`], which lands on the group.
536///
537/// # Which end is which, in words
538///
539/// `aria-label`, because the description states direction structurally -- the
540/// lower end's name is [`Field::name`] and the upper one's is
541/// [`Field::upper_name`] -- and never in words. Words for the ends are the
542/// host's, the same way a slider's readout is, and a page with visible Min and
543/// Max captions supplies them through [`Filling::trailing`] rather than having
544/// this crate own two strings of English.
545fn push_interval(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
546    let id = filling.id_for(field.name);
547
548    out.push_str("<div class=\"");
549    push_class(out, "form-interval", opts);
550    let _ = write!(out, "\" role=\"group\" aria-labelledby=\"{id}-label\"");
551    if field.invalid() {
552        out.push_str(" aria-invalid=\"true\"");
553    }
554    push_described_by(out, field, &id);
555    out.push('>');
556
557    // An interval with no upper name has one end that can be submitted, which
558    // is what the description said and is drawn honestly rather than repaired:
559    // `Field::interval` is what makes it unsayable, and inventing a name here
560    // would submit a parameter no handler is reading.
561    let ends: [(&str, &str, &str); 2] = [
562        ("lower", field.name, filling.value.as_text()),
563        (
564            "upper",
565            field.upper_name.unwrap_or(""),
566            filling.value.upper_text(),
567        ),
568    ];
569    for (end, name, value) in ends {
570        if name.is_empty() {
571            continue;
572        }
573        out.push_str("<input type=\"number\" class=\"");
574        push_class(out, "field", opts);
575        let _ = write!(out, "\" id=\"{id}-{end}\" name=\"");
576        escape_into(name, out);
577        let _ = write!(out, "\" aria-label=\"{end}\"");
578        if field.required {
579            out.push_str(" required");
580        }
581        push_bounds(out, field);
582        if let Some(text) = field.placeholder {
583            out.push_str(" placeholder=\"");
584            escape_into(text, out);
585            out.push('"');
586        }
587        out.push_str(" value=\"");
588        escape_into(value, out);
589        out.push_str("\">");
590    }
591
592    out.push_str("</div>");
593}
594
595/// A radio group: the options as sibling inputs sharing one `name`.
596///
597/// The group carries the error state and the descriptions, and the inputs carry
598/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
599/// down: marking a single input invalid would say the wrong thing, since what
600/// is wrong is the answer to the question and not one of the alternatives.
601///
602/// Ids are numbered rather than built from the option values, which can hold
603/// anything a `&str` can — spaces and quotes included — and would otherwise
604/// have to be slugged into something unique by a rule this crate would then own.
605///
606/// `required` lands on every input, which is how HTML says a group is
607/// compulsory: the constraint is satisfied when any one of them is checked.
608fn push_radio(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
609    let id = filling.id_for(field.name);
610    let value = filling.value.as_text();
611    let name = escape(field.name);
612
613    out.push_str("<div class=\"");
614    push_class(out, "form-radio-group", opts);
615    let _ = write!(out, "\" role=\"radiogroup\" aria-labelledby=\"{id}-label\"");
616    if field.invalid() {
617        out.push_str(" aria-invalid=\"true\"");
618    }
619    push_described_by(out, field, &id);
620    out.push('>');
621
622    // A group described with no options emits an empty group, for the reason
623    // `Field::options` gives: an app whose option list has not loaded has
624    // exactly that, and an empty group says so on screen rather than in a log.
625    for (index, opt) in field.options.iter().enumerate() {
626        out.push_str("<label class=\"");
627        push_class(out, "form-radio-label", opts);
628        let _ = write!(
629            out,
630            "\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" value=\""
631        );
632        escape_into(opt.value, out);
633        out.push('"');
634        if opt.value == value {
635            out.push_str(" checked");
636        }
637        if field.required {
638            out.push_str(" required");
639        }
640        // A radio group has room a `<select>` does not, so the reason gets its
641        // own element beside the label rather than being run into it. The class
642        // is what a stylesheet mutes; the text is there either way, which is
643        // the half that matters — the finding was a greyed control with its
644        // explanation behind a hover.
645        if opt.unavailable.is_some() {
646            out.push_str(" disabled");
647        }
648        out.push_str("><span>");
649        escape_into(opt.label, out);
650        out.push_str("</span>");
651        // What picking it means, on the line under the label. `5e21dcfc`, and
652        // the same treatment the reason gets one line down: a radio group has
653        // room, so the sentence sits in its own element rather than being run
654        // into the label the way a `<select>`'s has to be.
655        //
656        // Before the reason, which is the order the two read in: what this
657        // option *is* comes ahead of why it cannot be picked, and an option
658        // carrying both has said two things rather than one long one.
659        if let Some(detail) = opt.detail {
660            out.push_str("<span class=\"");
661            push_class(out, "form-option-detail", opts);
662            out.push_str("\">");
663            escape_into(detail, out);
664            out.push_str("</span>");
665        }
666        if let Some(reason) = opt.unavailable {
667            out.push_str("<span class=\"");
668            push_class(out, "form-option-reason", opts);
669            out.push_str("\">");
670            escape_into(reason, out);
671            out.push_str("</span>");
672        }
673        out.push_str("</label>");
674    }
675
676    out.push_str("</div>");
677}
678
679/// The options of a select: the unanswered instruction, an unmatched current
680/// value carried as its own, then the options themselves.
681///
682/// A select handed a value no option carries renders with nothing selected, the
683/// browser falls back to the first option, and the next save writes a value
684/// nobody chose. goingson hit exactly that with a backup-retention default of
685/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
686/// here so the second app gets it without hitting the bug first.
687fn push_options(out: &mut String, field: &Field<'_>, options: &[Choice<'_>], value: &str) {
688    // The unanswered state, which HTML has no attribute for: `placeholder` is
689    // not a `<select>` attribute, and the idiom is an empty option that cannot
690    // be chosen back. `disabled` is what stops it being re-selected once the
691    // user has answered, and `selected` is what puts it in the closed control
692    // while the value is empty; together they read as an instruction rather
693    // than as an option.
694    //
695    // `required` keeps working through it rather than around it: the option's
696    // value is empty, so a required select with this showing is invalid, which
697    // is the true report on a question nobody has answered.
698    //
699    // Emitted only while the value is empty, so it does not sit in the open
700    // list once the field is answered. A non-empty value no option carries is a
701    // wrong answer rather than an absent one and takes the stray-option path
702    // below.
703    if value.is_empty()
704        && let Some(text) = field.placeholder
705    {
706        out.push_str("<option value=\"\" disabled selected>");
707        escape_into(text, out);
708        out.push_str("</option>");
709    }
710    if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
711        // The one place an escaped value is worth keeping: it is written twice,
712        // as the option's value and as its text.
713        let escaped = escape(value);
714        let _ = write!(
715            out,
716            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
717        );
718    }
719    for opt in options {
720        out.push_str("<option value=\"");
721        escape_into(opt.value, out);
722        out.push('"');
723        if opt.value == value {
724            out.push_str(" selected");
725        }
726        // `disabled` is what the browser reads, and it says nothing about why.
727        // The reason goes in the option's own text, because a `<select>` gives
728        // its options no room for anything else: no title attribute the
729        // keyboard reaches, no second line, no element inside. So the row reads
730        // "Multi-sample: Drop a second sample onto the keyboard." and is the
731        // one place the precondition can be both attached to its option and
732        // read without a pointer.
733        if opt.unavailable.is_some() {
734            out.push_str(" disabled");
735        }
736        out.push('>');
737        escape_into(opt.label, out);
738        // Both extra strings run into the row's text, for the reason above:
739        // this is the one control with nowhere else to put either of them.
740        // `5e21dcfc` did not invent that rule, it met it.
741        if let Some(detail) = opt.detail {
742            out.push_str(": ");
743            escape_into(detail, out);
744        }
745        if let Some(reason) = opt.unavailable {
746            out.push_str(": ");
747            escape_into(reason, out);
748        }
749        out.push_str("</option>");
750    }
751}
752
753/// The themes, as one `<optgroup>` per variant with a contrast mark per row.
754///
755/// # The grouping comes out of the order, not out of a group list
756///
757/// [`makeover_layout::Field::themes`] arrives sorted by variant and then by
758/// measured contrast, and the run of one variant is the group. So this walks
759/// the list once and opens a new `<optgroup>` whenever the variant changes,
760/// which is the whole of the grouping logic and cannot disagree with the order
761/// the way a separately-carried group list could.
762///
763/// A theme whose variant equals its predecessor's never opens a group, so a
764/// list that arrived unsorted would emit repeated groups rather than silently
765/// merging distant rows. That is the honest report on a description that broke
766/// its own contract, and it is visible on screen rather than in a log.
767///
768/// # The follow row is not in a group
769///
770/// It names no theme and sits in no variant, so it is emitted first and bare.
771/// Grouping it under a heading would be inventing a fourth variant for one row.
772///
773/// # The badge is text, because a `<select>` has nowhere else to put it
774///
775/// A `<select>`'s options take no elements, no second line and no title the
776/// keyboard reaches, which is [`push_options`]' finding about
777/// [`Choice::unavailable`] met a second time. So the tier rides in the option's
778/// own text, in brackets after the name, and it is
779/// [`makeover_layout::Contrast::badge`]'s spelling rather than one invented
780/// here — three renderers picking their own is one picker reading three ways.
781fn push_theme_options(out: &mut String, field: &Field<'_>, value: &str) {
782    if let Some(follow) = field.follows {
783        out.push_str("<option value=\"");
784        escape_into(follow.value, out);
785        out.push('"');
786        if follow.value == value {
787            out.push_str(" selected");
788        }
789        out.push('>');
790        escape_into(follow.label, out);
791        out.push_str("</option>");
792    }
793
794    // A stored id naming a theme that is no longer installed. `push_options`'
795    // reasoning applies unchanged: a value no row carries is a wrong answer
796    // rather than an absent one, and dropping it would silently show the user
797    // a different theme than the one their config names.
798    let known = field.themes.iter().any(|theme| theme.id == value)
799        || field.follows.is_some_and(|follow| follow.value == value);
800    if !value.is_empty() && !known {
801        let escaped = escape(value);
802        let _ = write!(
803            out,
804            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
805        );
806    }
807
808    let mut open: Option<ThemeVariant> = None;
809    for theme in field.themes {
810        if open != Some(theme.variant) {
811            if open.is_some() {
812                out.push_str("</optgroup>");
813            }
814            out.push_str("<optgroup label=\"");
815            escape_into(theme.variant.heading(), out);
816            out.push_str("\" data-variant=\"");
817            out.push_str(theme.variant.as_str());
818            out.push_str("\">");
819            open = Some(theme.variant);
820        }
821
822        out.push_str("<option value=\"");
823        escape_into(theme.id, out);
824        out.push_str("\" data-contrast=\"");
825        out.push_str(theme.contrast.as_str());
826        out.push('"');
827        if theme.id == value {
828            out.push_str(" selected");
829        }
830        out.push('>');
831        escape_into(theme.name, out);
832        out.push_str(" (");
833        out.push_str(theme.contrast.badge());
834        out.push(')');
835        out.push_str("</option>");
836    }
837    if open.is_some() {
838        out.push_str("</optgroup>");
839    }
840}
841
842/// The control itself, without its label, hint or error.
843fn push_control(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
844    // Emitted before anything else is computed: a radio group carries its
845    // descriptions on the group rather than on a control, so none of the
846    // attributes below belong to it.
847    if matches!(field.kind, FieldKind::Radio) {
848        push_radio(out, field, filling, opts);
849        return;
850    }
851    // The same split one kind along: an interval is two inputs and one
852    // question, so the group carries the error and the descriptions and the
853    // boxes carry what submits.
854    if matches!(field.kind, FieldKind::Interval) {
855        push_interval(out, field, filling, opts);
856        return;
857    }
858
859    let id = filling.id_for(field.name);
860    let placeholder = |out: &mut String| {
861        if let Some(text) = field.placeholder {
862            out.push_str(" placeholder=\"");
863            escape_into(text, out);
864            out.push('"');
865        }
866    };
867
868    match field.kind {
869        // Both multi-line kinds are a `<textarea>`, and the markdown one says so
870        // in an attribute rather than in a class: what the value *is* is not a
871        // styling hook, and a progressive enhancement looking for editors to
872        // upgrade needs a selector that survives `Emit`'s class prefixing.
873        // Without the mark, a described editor is a plain box and the four
874        // hand-written MNW editors have nothing to convert onto.
875        //
876        // `data-format` and not `data-value`: this names the shape of the
877        // value, and `facet` already spends `data-facet-value` on carrying an
878        // actual one. Two attributes a letter apart meaning opposite things is
879        // how a renderer's own vocabulary starts drifting.
880        kind if kind.multiline() => {
881            let rich = matches!(kind, FieldKind::Rich);
882            if rich {
883                push_editor_open(out, opts);
884            }
885            out.push_str("<textarea class=\"");
886            push_class(out, "field", opts);
887            out.push('"');
888            if rich {
889                out.push_str(" data-format=\"markdown\"");
890            }
891            push_control_attributes(out, field, filling, &id, field.name);
892            placeholder(out);
893            out.push('>');
894            escape_into(filling.value.as_text(), out);
895            out.push_str("</textarea>");
896            if rich {
897                push_editor_close(out, opts);
898            }
899        }
900        FieldKind::Select => {
901            out.push_str("<select class=\"");
902            push_class(out, "field", opts);
903            out.push('"');
904            push_control_attributes(out, field, filling, &id, field.name);
905            out.push('>');
906            // A select described with no options emits an empty select, which
907            // says so on screen rather than in a log. That is the description's
908            // own position on `Field::options`, not a fallback invented here.
909            push_options(out, field, field.options, filling.value.as_text());
910            out.push_str("</select>");
911        }
912        // The one place this renderer emits `<optgroup>`, and it emits it
913        // because the description finally says there is a group. The measured
914        // history is the argument: `optgroup` appears at one live site in the
915        // whole tree, and the two apps that had grouped theme pickers lost the
916        // grouping the moment they were described, because `Choice` is a value
917        // and a label and a group is neither.
918        FieldKind::Theme => {
919            out.push_str("<select class=\"");
920            push_class(out, "field", opts);
921            out.push('"');
922            push_control_attributes(out, field, filling, &id, field.name);
923            out.push('>');
924            push_theme_options(out, field, filling.value.as_text());
925            out.push_str("</select>");
926        }
927        FieldKind::Checkbox => {
928            out.push_str("<label class=\"");
929            push_class(out, "form-checkbox-label", opts);
930            out.push_str("\"><input type=\"checkbox\"");
931            push_control_attributes(out, field, filling, &id, field.name);
932            if matches!(filling.value, Value::On(true)) {
933                out.push_str(" checked");
934            }
935            out.push_str("><span>");
936            escape_into(field.label, out);
937            out.push_str("</span></label>");
938        }
939        // A secret never carries its value into the markup. `FieldKind::secret`
940        // is documented as a value that must not be round-tripped through
941        // anything that might persist it, and the DOM is such a thing: it is
942        // read by every extension on the page and is the first thing a crash
943        // reporter serialises. Neither app pre-fills one today, so this costs
944        // nothing and closes the door before something does.
945        FieldKind::Secret => {
946            out.push_str("<input type=\"password\" class=\"");
947            push_class(out, "field", opts);
948            out.push('"');
949            push_control_attributes(out, field, filling, &id, field.name);
950            placeholder(out);
951            out.push('>');
952        }
953        // A file input carries no value, and this is the browser's rule rather
954        // than a preference: setting one from markup is refused, because a page
955        // that could preselect a path could read a file the user never offered.
956        // Nothing upstream needs to know, which is why the exception is here.
957        FieldKind::File => {
958            out.push_str("<input type=\"file\" class=\"");
959            push_class(out, "field", opts);
960            out.push('"');
961            push_control_attributes(out, field, filling, &id, field.name);
962            push_accept(out, field);
963            if field.multiple {
964                out.push_str(" multiple");
965            }
966            out.push('>');
967        }
968        kind => {
969            let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
970            push_class(out, "field", opts);
971            out.push('"');
972            push_control_attributes(out, field, filling, &id, field.name);
973            placeholder(out);
974            out.push_str(" value=\"");
975            escape_into(filling.value.as_text(), out);
976            out.push_str("\">");
977        }
978    }
979}
980
981/// The chrome a markdown field gets and a plain textarea does not: the two
982/// modes, and the pane a preview lands in.
983///
984/// # Why this is the one field with markup around it
985///
986/// [`FieldKind::Rich`]'s own doc says the mark buys a renderer permission to
987/// offer a preview or a syntax pass, and that a renderer with neither draws a
988/// textarea. A renderer taking the permission and emitting the same box as
989/// [`FieldKind::Textarea`] leaves an app converting onto the member with less
990/// than it had written by hand: MNW's `partial-item-text-editor.js` has a
991/// Write/Preview pair and a pane behind it, and describing the field without
992/// this would delete both. So the pair is here, on `facet`'s argument one
993/// field down -- the markup it replaces is not markup an app is keeping.
994///
995/// # Nothing here renders markdown, and that is where the sanitising stays
996///
997/// The pane arrives empty and this crate never turns a value into markup.
998/// Converting markdown is the host's, which is where the sanitiser already is:
999/// MNW renders through `docengine` over ammonia and holds an allowlist beside
1000/// it. A converter here would move that guarantee into a crate with no view of
1001/// the host's content-security posture, and `Rich`'s doc is explicit that a
1002/// host with its own sanitiser still owns it. What this emits is a hook, and
1003/// whatever fills it fills it with markup it has already made safe.
1004///
1005/// # The direction the enhancement runs
1006///
1007/// [`crate::stylesheet`]'s rule for a showing region, and for its reason: a
1008/// control rendered into a document with no script is a control that looks live
1009/// and answers nothing. Nothing is hidden here and no control is shown until
1010/// whatever binds the editor sets `data-ready` on the wrapper, so a reader with
1011/// no script gets the textarea alone and a reader with script gets the modes. A bound editor says which mode it is in with
1012/// `data-mode`, and [`editor_rules`] reads that.
1013fn push_editor_open(out: &mut String, opts: &Emit) {
1014    // The mark sits on the wrapper as well as on the control, saying one thing
1015    // about two: this control's value is markdown, and this editor edits
1016    // markdown. The rules gate on the wrapper and they are attribute rules
1017    // rather than class rules for `data-format`'s own reason -- the gate has to
1018    // survive `Emit`'s class prefixing, because the enhancement selects on it
1019    // too.
1020    out.push_str("<div data-format=\"markdown\"><div class=\"");
1021    push_class(out, "form-editor-modes", opts);
1022    out.push_str("\">");
1023    push_mode(out, "write", "Write", true, opts);
1024    push_mode(out, "preview", "Preview", false, opts);
1025    out.push_str("</div>");
1026}
1027
1028/// One of the two modes, as a segment of the pair.
1029///
1030/// [`crate::option_class`] for [`Selector::Segmented`] rather than a name of
1031/// its own: a Write/Preview pair is a segmented control, and spelling it as one
1032/// gets it the depth, the focus ring and the chosen state every described
1033/// selector gets, from rules that already exist. The words are written here for
1034/// the reason `facet`'s exclude button writes its own: a description carrying
1035/// them would be choosing them for the terminal as well.
1036fn push_mode(out: &mut String, mode: &str, label: &str, chosen: bool, opts: &Emit) {
1037    out.push_str("<button type=\"button\" class=\"");
1038    push_class(out, crate::option_class(Selector::Segmented), opts);
1039    if chosen {
1040        // The sheet keys the held-in segment on the class and a screen reader
1041        // reads the attribute. Both, because they are two readings of one fact,
1042        // which is the arrangement a facet value already has.
1043        out.push_str(" chosen");
1044    }
1045    let _ = write!(
1046        out,
1047        "\" data-editor-mode=\"{mode}\" aria-pressed=\"{chosen}\">{label}</button>"
1048    );
1049}
1050
1051/// The preview pane, and the wrapper closing over both halves.
1052fn push_editor_close(out: &mut String, opts: &Emit) {
1053    out.push_str("<div class=\"");
1054    push_class(out, "form-editor-preview", opts);
1055    // `data-editor-preview` and not an id: a form appears twice in a document
1056    // often enough that `Filling::id_prefix` exists for it, and a binder holding
1057    // the control can reach this without either of them being unique.
1058    out.push_str("\" data-editor-preview></div></div>");
1059}
1060
1061/// The rules the markdown editor's chrome needs.
1062///
1063/// The one place this module writes CSS. The class names [`field_html`] emits
1064/// are goingson's and are deliberately unruled -- `.form-group`, `.form-label`,
1065/// `.form-hint` and `.form-error` are the app's own, and phase A emits only what
1066/// it can generate from the description -- but the two names here have no app
1067/// counterpart to keep, because the chrome did not exist before the member did.
1068///
1069/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
1070/// off a plain textarea, and every rule that hides content is gated on
1071/// `data-ready` as well, which is what keeps them out of a document with no
1072/// script.
1073pub(crate) fn editor_rules(opts: &Emit) -> String {
1074    let mut css = String::new();
1075    let modes = class("form-editor-modes", opts);
1076    let preview = class("form-editor-preview", opts);
1077    let field = class("field", opts);
1078
1079    // Hidden until something binds the editor, which is the whole argument in
1080    // `push_editor_open`.
1081    let _ = writeln!(
1082        css,
1083        "[data-format=\"markdown\"] > .{modes} {{\n    display: none;\n}}"
1084    );
1085    // Block, and nothing about how the two segments sit in it. A button is
1086    // inline already, so they make a row without this crate saying so, and
1087    // saying so is where a gap would follow -- a magnitude, and
1088    // `makeover-geometry`'s.
1089    let _ = writeln!(
1090        css,
1091        "[data-format=\"markdown\"][data-ready] > .{modes} {{\n    display: block;\n}}"
1092    );
1093
1094    // The pane is empty until the host fills it, so it is out of flow in every
1095    // state but the one where a bound editor is showing it. An empty box under
1096    // the control is chrome claiming a preview nobody rendered.
1097    let _ = writeln!(
1098        css,
1099        "[data-format=\"markdown\"] > .{preview} {{\n    display: none;\n}}"
1100    );
1101    let _ = writeln!(
1102        css,
1103        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
1104         {{\n    display: block;\n}}"
1105    );
1106    // One at a time. The source and the preview are the same content read two
1107    // ways, and a field showing both answers its own question twice.
1108    let _ = writeln!(
1109        css,
1110        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
1111         {{\n    display: none;\n}}"
1112    );
1113
1114    // The pane stands where the control stood, so it reads as the surface the
1115    // control was: `.field` is a well, and this is the well it stands in for.
1116    // Nothing about size -- how tall a preview is is the app's, the way the
1117    // height of a track is.
1118    let _ = write!(
1119        css,
1120        "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
1121        crate::depth_declarations(Depth::Well)
1122    );
1123
1124    css
1125}
1126
1127/// The rule a field's unit needs.
1128///
1129/// [`suggestion_rules`]' precedent and its argument: `.form-group`,
1130/// `.form-label`, `.form-hint` and `.form-error` are the apps' own names and
1131/// stay unruled here, and this one has no app counterpart to keep because
1132/// nothing emitted it before `Field::unit` existed.
1133///
1134/// One declaration, and it is the whole look. A unit is a fact about the number
1135/// beside it rather than a second thing to read, so it takes the muted content
1136/// intent -- the same reading `.figure-caption` and `.track-tick` take, and for
1137/// the same reason.
1138///
1139/// Nothing about placement or spacing. Where the span sits relative to the
1140/// control is the app's layout, exactly as `.form-hint`'s is, and a margin
1141/// asserted here would be this crate deciding a magnitude that belongs to
1142/// `makeover-geometry`.
1143/// The rules a field's note needs.
1144///
1145/// [`unit_rules`]' precedent and its argument: `.form-hint` and `.form-error`
1146/// are the apps' own names and stay unruled here, and this one has no app
1147/// counterpart to keep because nothing emitted it before [`Field::note`]
1148/// existed.
1149///
1150/// Colour only, and the tones are the four a badge carries. The bare class is
1151/// `content` rather than `content-muted`: a note is a consequence the user is
1152/// meant to read before answering, so muting it by default would be this crate
1153/// deciding it does not matter.
1154pub(crate) fn note_rules(opts: &Emit) -> String {
1155    let note = class("form-note", opts);
1156    let mut css = String::new();
1157    let _ = writeln!(css, ".{note} {{\n    color: var(--content);\n}}");
1158    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1159        let _ = writeln!(
1160            css,
1161            ".{note}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
1162            tone.token()
1163        );
1164    }
1165    css
1166}
1167
1168pub(crate) fn unit_rules(opts: &Emit) -> String {
1169    let unit = class("form-unit", opts);
1170    let mut css = String::new();
1171    let _ = writeln!(css, ".{unit} {{\n    color: var(--content-muted);\n}}");
1172    css
1173}
1174
1175/// The rules an option's second line needs.
1176///
1177/// [`unit_rules`]' argument: rule what has no app counterpart to keep. An
1178/// unruled second line renders identically to the label it sits under, which is
1179/// a worse default than the hand-written markup it replaces.
1180///
1181/// Colour only, and muted, which is the same reading `.form-unit` and
1182/// `.form-suggestion-detail` take: the line orients the label rather than
1183/// competing with it. Nothing about placement or spacing, for `unit_rules`'
1184/// reason — a magnitude asserted here belongs to `makeover-geometry`.
1185pub(crate) fn option_detail_rules(opts: &Emit) -> String {
1186    let detail = class("form-option-detail", opts);
1187    let mut css = String::new();
1188    let _ = writeln!(css, ".{detail} {{\n    color: var(--content-muted);\n}}");
1189    css
1190}
1191
1192/// The rules a field's suggestion list needs.
1193///
1194/// [`editor_rules`]' precedent and its argument: the class names this module's
1195/// markup emits are the apps' own and stay unruled, and these three have no app
1196/// counterpart to keep because the list did not exist before the member did.
1197/// The markup is `quasi-webview`'s rather than this crate's — a suggestion
1198/// source is a route, which no description layer carries — and the look is
1199/// still this crate's, because a renderer inventing how a list of candidates
1200/// reads is the drift the vocabulary check exists to catch.
1201///
1202/// # In flow, and not floating
1203///
1204/// An absolutely positioned list needs a positioned ancestor, and the only
1205/// candidate is `.form-group`, which is the app's class and deliberately
1206/// unruled here. So the list stands under the control and moves what is below
1207/// it. An app that wants it over the form positions the group itself, which is
1208/// one declaration and is the app's call about its own layout.
1209///
1210/// `:empty` is what takes it away, so a route that answers with no candidates
1211/// leaves no box behind. It is a content question rather than a whitespace one
1212/// only because the emitter writes no whitespace inside the container, which is
1213/// stated in `quasi-webview`'s own test.
1214///
1215/// # Nothing about size
1216///
1217/// No height, no scroll ceiling, no padding. How tall a list of candidates gets
1218/// to be before it scrolls is a magnitude, and magnitudes are
1219/// `makeover-geometry`'s, exactly as the preview pane's height is.
1220pub(crate) fn suggestion_rules(opts: &Emit) -> String {
1221    let list = class("form-suggestions", opts);
1222    let entry = class("form-suggestion", opts);
1223    let detail = class("form-suggestion-detail", opts);
1224    let mut css = String::new();
1225
1226    let _ = writeln!(css, ".{list}:empty {{\n    display: none;\n}}");
1227    // Over what it covers, which is what a list of candidates is even in flow:
1228    // it is answering the box above it and goes away when the answer is taken.
1229    css.push_str(&crate::depth_rule(&list, Depth::Overlay));
1230    // An entry answers a click, so it gets every state one implies.
1231    css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
1232    // The keyboard's highlight and the pointer's are the same surface. They are
1233    // the same fact told two ways, and a list where arrowing and hovering look
1234    // different is a list that has two current entries.
1235    //
1236    // Keyed on `aria-selected` rather than on a class, for the reason
1237    // `aria-invalid` carries the error state: it is what a screen reader hears,
1238    // so a look keyed on it cannot drift from what is announced. A `.current`
1239    // class would also be a name apps already spell for their own reasons --
1240    // the MNW server has one -- and unlayered app CSS beats this layer in
1241    // silence.
1242    let _ = writeln!(
1243        css,
1244        ".{entry}[aria-selected=\"true\"] {{\n    background: var(--hover-surface);\n}}"
1245    );
1246    // The second line, muted rather than disabled. `1fcf2e9b` replaced the
1247    // unavailable reason this rule used to draw: a candidate carries no
1248    // `unavailable`, and what sits beside the label now is what tells one row
1249    // from another that reads the same. Disabled would say the row cannot be
1250    // picked, which is the opposite of what the detail is for.
1251    let _ = writeln!(css, ".{detail} {{\n    color: var(--content-muted);\n}}");
1252
1253    css
1254}
1255
1256/// One field, as the group the app drops into its form.
1257///
1258/// The shape is goingson's, down to the class names, so adoption there deletes
1259/// `renderFormField` rather than restyling anything. That is also why the class
1260/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
1261/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
1262/// emits only what it can generate from the description. Whether they should
1263/// move into the description is the next question this raises, not one it
1264/// answers.
1265///
1266/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
1267/// nothing drawn, which is what [`FieldKind::visible`] means.
1268///
1269/// The error marks the group as well as the control. That is
1270/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
1271/// cannot find the group from the message, so the group has to be told.
1272///
1273/// ```
1274/// use makeover_layout::{Field, FieldKind};
1275/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
1276///
1277/// let field = Field::new(FieldKind::Text, "title", "Title");
1278/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
1279///
1280/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
1281/// assert!(html.contains(r#"value="Ship it""#));
1282/// ```
1283#[must_use]
1284pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
1285    let mut html = String::new();
1286    field_html_into(field, filling, opts, &mut html);
1287    html
1288}
1289
1290/// One field, written into a buffer the caller already has.
1291///
1292/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
1293/// these, so a host building one should hold a single buffer and append each
1294/// field into it rather than take a `String` per field and concatenate.
1295pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
1296    let id = filling.id_for(field.name);
1297
1298    if !field.kind.visible() {
1299        // Name only, no id: a hidden field is never pointed at by a label or a
1300        // description, so the one attribute it needs is the one that submits.
1301        out.push_str("<input type=\"hidden\" name=\"");
1302        escape_into(field.name, out);
1303        out.push_str("\" value=\"");
1304        escape_into(filling.value.as_text(), out);
1305        out.push_str("\">");
1306        return;
1307    }
1308
1309    out.push_str("<div class=\"");
1310    push_class(out, "form-group", opts);
1311    if field.invalid() {
1312        out.push_str(" has-error");
1313    }
1314    if field.extended {
1315        // The disclosure that hides these is a property of the form, not of the
1316        // field, so the field is marked and the app opens or closes the group.
1317        out.push_str("\" data-extended=\"true");
1318    }
1319    out.push_str("\">");
1320
1321    // A checkbox labels itself, on the right of the box. Both apps special-case
1322    // this inline today, which is the tell that it belongs in the description;
1323    // `FieldKind::labels_itself` is where it went.
1324    if !field.kind.labels_itself() {
1325        out.push_str("<label class=\"");
1326        push_class(out, "form-label", opts);
1327        // A group control is named *by* its label rather than pointing at it,
1328        // so the two carry opposite halves of the association. See
1329        // `is_group_control`.
1330        if is_group_control(field.kind) {
1331            let _ = write!(out, "\" id=\"{id}-label\">");
1332        } else {
1333            let _ = write!(out, "\" for=\"{id}\">");
1334        }
1335        escape_into(field.label, out);
1336        out.push_str("</label>");
1337    }
1338
1339    push_control(out, field, filling, opts);
1340
1341    // Adjacent text, because HTML has no unit attribute and inventing one would
1342    // be markup nothing reads. Pointed at by `aria-describedby` so it is not
1343    // decoration a screen reader skips: the number and what it is measured in
1344    // are one fact, and reading the first without the second is reading it
1345    // wrong.
1346    if let Some(unit) = unit_of(field) {
1347        out.push_str("<span class=\"");
1348        push_class(out, "form-unit", opts);
1349        let _ = write!(out, "\" id=\"{id}-unit\">");
1350        escape_into(unit, out);
1351        out.push_str("</span>");
1352    }
1353
1354    if let Some(hint) = field.hint {
1355        out.push_str("<div class=\"");
1356        push_class(out, "form-hint", opts);
1357        let _ = write!(out, "\" id=\"{id}-hint\">");
1358        escape_into(hint, out);
1359        out.push_str("</div>");
1360    }
1361    // A consequence of the answer, between the standing help and the failure.
1362    // The tone rides on `data-tone` -- the same attribute every other toned
1363    // thing in this crate takes -- and it also picks the live region: Warning
1364    // and Danger are assertive, which is quasi-webview's own reading at
1365    // `node.rs:1403` and is honoured here rather than restated differently.
1366    if let Some((tone, note)) = field.note {
1367        out.push_str("<div class=\"");
1368        push_class(out, "form-note", opts);
1369        let assertive = matches!(tone, Tone::Warning | Tone::Danger);
1370        let _ = write!(
1371            out,
1372            "\" id=\"{id}-note\" role=\"{}\"",
1373            if assertive { "alert" } else { "status" }
1374        );
1375        // Neutral is the bare class rather than a variant, matching every
1376        // other toned component here: it is the absence of a status.
1377        if tone != Tone::Neutral {
1378            let _ = write!(out, " data-tone=\"{}\"", tone.token());
1379        }
1380        out.push('>');
1381        escape_into(note, out);
1382        out.push_str("</div>");
1383    }
1384    if let Some(Markup(markup)) = filling.trailing {
1385        out.push_str(markup);
1386    }
1387    if let Some(error) = field.error {
1388        out.push_str("<div class=\"");
1389        push_class(out, "form-error", opts);
1390        let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
1391        escape_into(error, out);
1392        out.push_str("</div>");
1393    }
1394
1395    out.push_str("</div>");
1396}
1397
1398#[cfg(test)]
1399mod tests {
1400    use super::*;
1401    use makeover_layout::{Accepted, Curve, Family};
1402
1403    fn field(kind: FieldKind) -> Field<'static> {
1404        Field::new(kind, "title", "Title")
1405    }
1406
1407    #[test]
1408    fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
1409        // The payload from goingson's own CHRONIC-XSS regression test.
1410        let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
1411        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1412        // The payload survives as text, which is the point: it is inert
1413        // because the quote that would have closed the attribute is encoded,
1414        // not because the words were filtered.
1415        assert!(!html.contains("\" onfocus"), "{html}");
1416        assert!(
1417            html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
1418            "{html}"
1419        );
1420    }
1421
1422    /// The seam quasi's suggestion source needs: a host's own attributes land
1423    /// on the control, unescaped, and after everything this crate decided.
1424    #[test]
1425    fn a_host_can_write_its_own_attributes_onto_the_control() {
1426        let mut filling = Filling::of(Value::Text("ru"));
1427        filling.control_attrs = Some(Markup(
1428            r#"role="combobox" aria-expanded="false" aria-controls="title-suggestions""#,
1429        ));
1430        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1431        assert!(html.contains(r#"role="combobox""#), "{html}");
1432        assert!(
1433            html.contains(r#"aria-controls="title-suggestions""#),
1434            "{html}"
1435        );
1436        // After the id, which is what "last" buys: a host can read what this
1437        // emitter wrote and cannot be overwritten by it.
1438        let id = html.find(r#"id="title""#).expect("id");
1439        let role = html.find(r#"role="combobox""#).expect("role");
1440        assert!(id < role, "{html}");
1441    }
1442
1443    /// A radio group has no one control element, so there is nowhere honest to
1444    /// put an attribute meant for the control. Documented on the member.
1445    #[test]
1446    fn a_radio_group_drops_control_attributes() {
1447        let mut f = field(FieldKind::Radio);
1448        let options = [Choice::new("a", "A")];
1449        f.options = &options;
1450        let filling = Filling {
1451            control_attrs: Some(Markup(r#"data-host="1""#)),
1452            ..Filling::default()
1453        };
1454        let html = field_html(&f, &filling, &Emit::default());
1455        assert!(!html.contains("data-host"), "{html}");
1456    }
1457
1458    #[test]
1459    fn a_label_cannot_open_a_tag() {
1460        let mut f = field(FieldKind::Text);
1461        f.label = "<script>alert(1)</script>";
1462        let html = field_html(&f, &Filling::default(), &Emit::default());
1463        assert!(!html.contains("<script>"), "{html}");
1464        assert!(html.contains("&lt;script&gt;"), "{html}");
1465    }
1466
1467    #[test]
1468    fn every_escaped_sink_is_covered_by_the_one_escaper() {
1469        assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
1470        // The character `textContent` serialization leaves alone, which is why
1471        // the app needs two escapers and this needs one.
1472        assert!(escape("\"").contains("&quot;"));
1473    }
1474
1475    /// The streaming escaper is the one the emitters call and [`escape`] is a
1476    /// buffer around it, so the two cannot be allowed to drift. It copies in
1477    /// runs between the encoded characters, which is where a multi-byte
1478    /// character would break it if the scan were not restricted to ASCII.
1479    #[test]
1480    fn the_streaming_escaper_appends_what_the_returning_one_returns() {
1481        for text in [
1482            "",
1483            "plain",
1484            "&<>\"'",
1485            "&&&",
1486            "a & b",
1487            "trailing&",
1488            "&leading",
1489            "é世 & <b>naïve</b> \u{1f600}",
1490        ] {
1491            let mut out = String::from("kept: ");
1492            escape_into(text, &mut out);
1493            assert_eq!(out, format!("kept: {}", escape(text)), "{text:?}");
1494        }
1495    }
1496
1497    /// Same obligation one layer up: a form is a run of fields appended into one
1498    /// buffer, and the two ways to get one have to agree byte for byte.
1499    #[test]
1500    fn a_streamed_field_is_the_field_the_other_form_returns() {
1501        let kinds = [
1502            FieldKind::Text,
1503            FieldKind::Secret,
1504            FieldKind::Number,
1505            FieldKind::Checkbox,
1506            FieldKind::Radio,
1507            FieldKind::Select,
1508            FieldKind::Textarea,
1509            FieldKind::File,
1510            FieldKind::Hidden,
1511        ];
1512        let choices = [Choice::plain("one"), Choice::plain("two")];
1513        let opts = Emit {
1514            class_prefix: "mk-",
1515            ..Emit::default()
1516        };
1517        for kind in kinds {
1518            let described = Field {
1519                hint: Some("a hint"),
1520                error: Some("wrong <here>"),
1521                placeholder: Some("x\" y"),
1522                options: &choices,
1523                required: true,
1524                max_length: Some(40),
1525                min: Some("1"),
1526                max: Some("9"),
1527                extended: true,
1528                ..Field::new(kind, "the & name", "The <label>")
1529            };
1530            let filling = Filling {
1531                value: Value::Text("one"),
1532                trailing: Some(Markup("<i>t</i>")),
1533                control_attrs: Some(Markup(r#"data-host="1""#)),
1534                id_prefix: Some("modal"),
1535            };
1536            let mut streamed = String::new();
1537            field_html_into(&described, &filling, &opts, &mut streamed);
1538            assert_eq!(
1539                streamed,
1540                field_html(&described, &filling, &opts),
1541                "{kind:?}"
1542            );
1543
1544            // And the bare field, where every optional half is absent.
1545            let plain = Field::new(kind, "name", "Label");
1546            let mut streamed = String::new();
1547            field_html_into(&plain, &Filling::default(), &opts, &mut streamed);
1548            assert_eq!(
1549                streamed,
1550                field_html(&plain, &Filling::default(), &opts),
1551                "{kind:?}"
1552            );
1553        }
1554    }
1555
1556    #[test]
1557    fn markup_is_the_only_way_past_the_escaping() {
1558        let filling = Filling {
1559            trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
1560            ..Filling::default()
1561        };
1562        let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1563        assert!(
1564            html.contains("<div class=\"recurrence-config\"></div>"),
1565            "{html}"
1566        );
1567    }
1568
1569    #[test]
1570    fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
1571        let mut f = field(FieldKind::Text);
1572        f.error = Some("Required");
1573        let opts = Emit::default();
1574        let html = field_html(&f, &Filling::default(), &opts);
1575        assert!(html.contains("aria-invalid=\"true\""), "{html}");
1576        // The selector the CSS side emits for exactly this state.
1577        assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
1578        // And the group is marked too, which a renderer without descendant
1579        // selectors depends on.
1580        assert!(html.contains("has-error"), "{html}");
1581    }
1582
1583    #[test]
1584    fn a_valid_field_claims_nothing_about_being_invalid() {
1585        let html = field_html(
1586            &field(FieldKind::Text),
1587            &Filling::default(),
1588            &Emit::default(),
1589        );
1590        assert!(!html.contains("aria-invalid"), "{html}");
1591        assert!(!html.contains("has-error"), "{html}");
1592    }
1593
1594    #[test]
1595    fn a_note_sits_between_the_hint_and_the_error_and_carries_its_tone() {
1596        let mut f = field(FieldKind::Text);
1597        f.hint = Some("Keep it short");
1598        f.note = Some((Tone::Warning, "Re-encoding drops embedded BWF"));
1599        f.error = Some("Required");
1600        let html = field_html(&f, &Filling::default(), &Emit::default());
1601
1602        // All three associated, in the order they are drawn.
1603        assert!(
1604            html.contains(r#"aria-describedby="title-hint title-note title-error""#),
1605            "{html}"
1606        );
1607        assert!(
1608            html.contains(r#"id="title-note" role="alert" data-tone="warning""#),
1609            "{html}"
1610        );
1611        // And in that order in the document, so the reading order matches.
1612        let hint = html.find("title-hint").unwrap();
1613        let note = html.rfind("title-note").unwrap();
1614        let err = html.rfind("title-error").unwrap();
1615        assert!(hint < note && note < err, "{html}");
1616    }
1617
1618    #[test]
1619    fn a_quiet_note_is_polite_and_wears_no_tone_attribute() {
1620        // Neutral is the bare class, matching every other toned component
1621        // here, and only Warning and Danger interrupt.
1622        let mut f = field(FieldKind::Text);
1623        f.note = Some((Tone::Info, "This is what that setting implies"));
1624        let html = field_html(&f, &Filling::default(), &Emit::default());
1625        assert!(html.contains(r#"role="status" data-tone="info""#), "{html}");
1626
1627        f.note = Some((Tone::Neutral, "An ordinary fact"));
1628        let html = field_html(&f, &Filling::default(), &Emit::default());
1629        assert!(html.contains(r#"id="title-note" role="status">"#), "{html}");
1630        assert!(!html.contains("data-tone"), "{html}");
1631    }
1632
1633    #[test]
1634    fn a_note_does_not_mark_the_group_invalid() {
1635        // `Field::invalid` stays `error.is_some()`, and the renderer's
1636        // `has-error` follows it rather than any message being present.
1637        let mut f = field(FieldKind::Text);
1638        f.note = Some((Tone::Danger, "This cannot be undone"));
1639        let html = field_html(&f, &Filling::default(), &Emit::default());
1640        assert!(!html.contains("has-error"), "{html}");
1641        assert!(!html.contains(r#"aria-invalid="true""#), "{html}");
1642    }
1643
1644    #[test]
1645    fn the_hint_survives_an_error_arriving() {
1646        let mut f = field(FieldKind::Text);
1647        f.hint = Some("Keep it short");
1648        f.error = Some("Required");
1649        let html = field_html(&f, &Filling::default(), &Emit::default());
1650        assert!(
1651            html.contains("aria-describedby=\"title-hint title-error\""),
1652            "{html}"
1653        );
1654    }
1655
1656    #[test]
1657    fn a_secret_never_carries_its_value_into_the_markup() {
1658        let filling = Filling::of(Value::Text("hunter2"));
1659        let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
1660        assert!(!html.contains("hunter2"), "{html}");
1661        assert!(html.contains("type=\"password\""), "{html}");
1662    }
1663
1664    #[test]
1665    fn a_hidden_field_is_the_input_and_nothing_else() {
1666        let filling = Filling::of(Value::Text("42"));
1667        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1668        assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
1669    }
1670
1671    #[test]
1672    fn a_checkbox_labels_itself_and_takes_no_separate_label() {
1673        let html = field_html(
1674            &field(FieldKind::Checkbox),
1675            &Filling::of(Value::On(true)),
1676            &Emit::default(),
1677        );
1678        assert!(!html.contains("form-label"), "{html}");
1679        assert!(html.contains("checked"), "{html}");
1680        assert!(html.contains("<span>Title</span>"), "{html}");
1681    }
1682
1683    #[test]
1684    fn a_select_keeps_a_value_no_option_carries() {
1685        let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
1686        let f = Field::select("title", "Title", &options);
1687        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1688        assert!(html.contains("data-unmatched=\"true\""), "{html}");
1689        // Selected, so the next save round-trips it rather than writing the
1690        // first option over the top of it.
1691        assert!(html.contains("<option value=\"10\" selected"), "{html}");
1692    }
1693
1694    #[test]
1695    fn a_select_with_no_options_emits_an_empty_select() {
1696        // The description says a select with no options is sayable, because an
1697        // app whose option list has not loaded has exactly that. Emitting the
1698        // empty select reports it on screen rather than in a log.
1699        let f = Field::select("title", "Title", &[]);
1700        let html = field_html(&f, &Filling::default(), &Emit::default());
1701        assert!(html.contains("<select"), "{html}");
1702        assert!(!html.contains("<option"), "{html}");
1703    }
1704
1705    #[test]
1706    fn an_unanswered_select_shows_its_ghost_text_and_cannot_be_chosen_back() {
1707        let options = [Choice::new("sp404", "SP-404")];
1708        let f = Field {
1709            placeholder: Some("Select device..."),
1710            ..Field::select("device", "Conform for device", &options)
1711        };
1712        let html = field_html(&f, &Filling::default(), &Emit::default());
1713
1714        assert!(
1715            html.contains("<option value=\"\" disabled selected>Select device...</option>"),
1716            "{html}"
1717        );
1718        // First, so the closed control reads it rather than the first real
1719        // option.
1720        assert!(
1721            html.find("Select device...") < html.find("SP-404"),
1722            "{html}"
1723        );
1724    }
1725
1726    #[test]
1727    fn an_answered_select_drops_the_ghost_text() {
1728        // It is an instruction about an empty field, so it has nothing to say
1729        // once the field is answered, and leaving it in the list is one dead
1730        // row every time the control is opened afterwards.
1731        let options = [Choice::new("sp404", "SP-404")];
1732        let f = Field {
1733            placeholder: Some("Select device..."),
1734            ..Field::select("device", "Conform for device", &options)
1735        };
1736        let html = field_html(&f, &Filling::of(Value::Text("sp404")), &Emit::default());
1737        assert!(!html.contains("Select device..."), "{html}");
1738    }
1739
1740    #[test]
1741    fn a_wrong_answer_is_kept_and_is_not_the_ghost_text() {
1742        // The two paths through `push_options` meet here. An unmatched value is
1743        // an answer that is wrong and stays visible as itself; only the empty
1744        // value is unanswered.
1745        let options = [Choice::plain("1"), Choice::plain("7")];
1746        let f = Field {
1747            placeholder: Some("Pick one"),
1748            ..Field::select("retention", "Keep backups for", &options)
1749        };
1750        let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1751        assert!(html.contains("data-unmatched=\"true\""), "{html}");
1752        assert!(!html.contains("Pick one"), "{html}");
1753    }
1754
1755    #[test]
1756    fn a_range_is_a_range_input_and_carries_its_extent() {
1757        let f = Field {
1758            curve: Curve::Linear { step: Some("0.01") },
1759            ..Field::range("review", "Review above", "0", "1")
1760        };
1761        let html = field_html(&f, &Filling::of(Value::Text("0.72")), &Emit::default());
1762        assert!(html.contains("type=\"range\""), "{html}");
1763        assert!(html.contains("min=\"0\""), "{html}");
1764        assert!(html.contains("max=\"1\""), "{html}");
1765        // Without it the browser steps by 1 and a 0-to-1 question becomes a
1766        // two-position control.
1767        assert!(html.contains("step=\"0.01\""), "{html}");
1768    }
1769
1770    #[test]
1771    fn a_range_reads_its_granularity_off_the_curve_and_not_off_field_step() {
1772        // The 0.32.0 narrowing, at the renderer. `Field::step` on a range is a
1773        // site that has not been moved over, and emitting it would make the
1774        // control step by a number the curve never agreed to.
1775        let f = Field {
1776            step: Some("99"),
1777            ..Field::range("review", "Review above", "0", "1")
1778        };
1779        let html = field_html(&f, &Filling::of(Value::Text("0.5")), &Emit::default());
1780        assert!(!html.contains("step="), "{html}");
1781    }
1782
1783    #[test]
1784    fn a_unit_is_adjacent_text_and_the_control_points_at_it() {
1785        // Not decoration: the number and what it is measured in are one fact,
1786        // so the association is what makes this worth emitting at all.
1787        let f = Field {
1788            unit: Some("dBFS"),
1789            ..Field::range("threshold", "Threshold", "-96", "-20")
1790        };
1791        let html = field_html(&f, &Filling::of(Value::Text("-40")), &Emit::default());
1792        assert!(html.contains(r#"id="threshold-unit""#), "{html}");
1793        assert!(html.contains(">dBFS</span>"), "{html}");
1794        assert!(
1795            html.contains(r#"aria-describedby="threshold-unit""#),
1796            "{html}"
1797        );
1798        // The label is the question's name and keeps no unit in it.
1799        assert!(html.contains(">Threshold</label>"), "{html}");
1800    }
1801
1802    #[test]
1803    fn a_unit_takes_its_place_between_the_hint_and_the_error() {
1804        let f = Field {
1805            unit: Some("ms"),
1806            hint: Some("How long the fade runs."),
1807            error: Some("Too long."),
1808            ..Field::new(FieldKind::Number, "fade", "Fade")
1809        };
1810        let html = field_html(&f, &Filling::of(Value::Text("50")), &Emit::default());
1811        assert!(
1812            html.contains(r#"aria-describedby="fade-hint fade-unit fade-error""#),
1813            "{html}"
1814        );
1815    }
1816
1817    #[test]
1818    fn a_unit_on_a_kind_that_is_not_a_quantity_is_ignored() {
1819        // Sayable and ignored, the way `options` is on a kind that offers none.
1820        // The renderer asks the description which kinds are measurable rather
1821        // than keeping its own list.
1822        let f = Field {
1823            unit: Some("s"),
1824            ..Field::new(FieldKind::Text, "name", "Name")
1825        };
1826        let html = field_html(&f, &Filling::of(Value::Text("kick")), &Emit::default());
1827        assert!(!html.contains("name-unit"), "{html}");
1828        assert!(!html.contains("aria-describedby"), "{html}");
1829    }
1830
1831    #[test]
1832    fn a_unit_cannot_break_out_of_the_span_it_sits_in() {
1833        let f = Field {
1834            unit: Some("</span><script>"),
1835            ..Field::new(FieldKind::Number, "n", "N")
1836        };
1837        let html = field_html(&f, &Filling::of(Value::Text("1")), &Emit::default());
1838        assert!(!html.contains("<script>"), "{html}");
1839        assert!(html.contains("&lt;script&gt;"), "{html}");
1840    }
1841
1842    #[test]
1843    fn a_constant_ratio_curve_is_answered_with_a_linear_track() {
1844        // The decided answer, not a shortfall: HTML has no logarithmic range
1845        // input, so the browser draws the extent linearly. The value it submits
1846        // is still a value in the field's own units, which is what every
1847        // handler on this path reads. See the crate header.
1848        let f = Field {
1849            curve: Curve::Logarithmic {
1850                step: Some("0.001"),
1851            },
1852            ..Field::range("attack", "Attack", "0.001", "5")
1853        };
1854        let html = field_html(&f, &Filling::of(Value::Text("0.005")), &Emit::default());
1855        assert!(html.contains("type=\"range\""), "{html}");
1856        assert!(html.contains("min=\"0.001\""), "{html}");
1857        assert!(html.contains("max=\"5\""), "{html}");
1858        assert!(html.contains("step=\"0.001\""), "{html}");
1859    }
1860
1861    #[test]
1862    fn a_number_with_bounds_is_still_typed_into() {
1863        // The distinction the kind exists for, at the renderer where getting it
1864        // wrong is most visible: goingson's `min="1"` duration must not come
1865        // back as a slider.
1866        let f = Field {
1867            min: Some("1"),
1868            ..Field::new(FieldKind::Number, "minutes", "Minutes")
1869        };
1870        let html = field_html(&f, &Filling::of(Value::Text("30")), &Emit::default());
1871        assert!(html.contains("type=\"number\""), "{html}");
1872        assert!(!html.contains("type=\"range\""), "{html}");
1873        // And nothing invents a step for it.
1874        assert!(!html.contains("step="), "{html}");
1875    }
1876
1877    #[test]
1878    fn an_unavailable_option_is_disabled_and_says_why() {
1879        let options = [
1880            Choice::new("chromatic", "Chromatic"),
1881            Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1882        ];
1883        let f = Field::radio("mode", "Mode", &options);
1884        let html = field_html(&f, &Filling::of(Value::Text("chromatic")), &Emit::default());
1885
1886        assert!(html.contains(" disabled"), "{html}");
1887        assert!(html.contains("Drop a second sample."), "{html}");
1888        // The option is still offered: dropping it is what costs the user the
1889        // knowledge that the mode exists.
1890        assert!(html.contains("value=\"multi\""), "{html}");
1891        // And the reason is its own element, not run into the label.
1892        assert!(html.contains("form-option-reason"), "{html}");
1893    }
1894
1895    #[test]
1896    fn an_unavailable_select_option_carries_its_reason_in_its_text() {
1897        // A `<select>` gives an option no room for a second element, so the
1898        // reason has to be in the text or be unreadable without a pointer.
1899        let options = [Choice::new("multi", "Multi-sample").unless("Drop a second sample.")];
1900        let f = Field::select("mode", "Mode", &options);
1901        let html = field_html(&f, &Filling::default(), &Emit::default());
1902        assert!(
1903            html.contains(">Multi-sample: Drop a second sample.</option>"),
1904            "{html}"
1905        );
1906        assert!(html.contains("disabled"), "{html}");
1907    }
1908
1909    #[test]
1910    fn an_option_can_say_what_picking_it_means() {
1911        // makeover-layout 0.39.0. A radio group has room, so the line gets its
1912        // own element under the label, and it is muted rather than unruled: an
1913        // unruled second line renders identically to the label above it, which
1914        // is a worse default than the markup this replaces.
1915        let options = [
1916            Choice::new("16", "Basic").detailing("$16/mo. Fits text, blogs, newsletters."),
1917            Choice::new("24", "Small Files"),
1918        ];
1919        let f = Field::radio("tier", "Content tier", &options);
1920        let html = field_html(&f, &Filling::default(), &Emit::default());
1921
1922        assert!(html.contains("form-option-detail"), "{html}");
1923        assert!(
1924            html.contains(">$16/mo. Fits text, blogs, newsletters.</span>"),
1925            "{html}"
1926        );
1927        // One option carries it and the other does not, so the class appears
1928        // once rather than on every label.
1929        assert_eq!(html.matches("form-option-detail").count(), 1, "{html}");
1930        assert!(
1931            option_detail_rules(&Emit::default()).contains("var(--content-muted)"),
1932            "the line orients the label rather than competing with it"
1933        );
1934    }
1935
1936    #[test]
1937    fn an_option_reads_what_it_is_before_why_it_cannot_be_picked() {
1938        // Two different sentences, drawn in the order they read in. A tier that
1939        // is sold out is still a tier the reader is owed a description of.
1940        let options = [Choice::new("24", "Small Files")
1941            .detailing("$24/mo. Fits audio, plugins, binaries.")
1942            .unless("Sold out while the founder window is open.")];
1943        let f = Field::radio("tier", "Content tier", &options);
1944        let html = field_html(&f, &Filling::default(), &Emit::default());
1945
1946        let detail = html.find("form-option-detail").expect("the detail");
1947        let reason = html.find("form-option-reason").expect("the reason");
1948        assert!(detail < reason, "{html}");
1949        assert!(html.contains(" disabled"), "{html}");
1950
1951        // A `<select>` has room for neither element, so both run into the
1952        // row's own text in the same order.
1953        let f = Field::select("tier", "Content tier", &options);
1954        let html = field_html(&f, &Filling::default(), &Emit::default());
1955        assert!(
1956            html.contains(concat!(
1957                ">Small Files: $24/mo. Fits audio, plugins, binaries.",
1958                ": Sold out while the founder window is open.</option>"
1959            )),
1960            "{html}"
1961        );
1962    }
1963
1964    #[test]
1965    fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
1966        // The association inverts, and getting it wrong is silent: a
1967        // `<label for>` aimed at a group points at no element, so the group
1968        // simply has no accessible name and nothing reports that.
1969        let options = [Choice::plain("copy"), Choice::plain("reference")];
1970        let f = Field::radio("storage", "Storage style", &options);
1971        let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
1972
1973        assert!(html.contains("id=\"storage-label\""), "{html}");
1974        assert!(!html.contains("for=\"storage\""), "{html}");
1975        assert!(html.contains("role=\"radiogroup\""), "{html}");
1976        assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
1977    }
1978
1979    #[test]
1980    fn an_interval_is_one_labelled_group_holding_both_ends() {
1981        // The markup MNW's discover sidebar writes by hand, which is the
1982        // measurement that decided the member: `role="group"` naming the
1983        // question, two number boxes under it.
1984        let f = Field::interval("min_price", "max_price", "Price");
1985        let html = field_html(
1986            &f,
1987            &Filling::of(Value::Between {
1988                lower: "5",
1989                upper: "40",
1990            }),
1991            &Emit::default(),
1992        );
1993
1994        assert!(html.contains("role=\"group\""), "{html}");
1995        assert!(
1996            html.contains("aria-labelledby=\"min_price-label\""),
1997            "{html}"
1998        );
1999        assert!(html.contains("id=\"min_price-label\""), "{html}");
2000        assert!(!html.contains("for=\"min_price\""), "{html}");
2001        assert!(html.contains("name=\"min_price\""), "{html}");
2002        assert!(html.contains("name=\"max_price\""), "{html}");
2003        assert!(html.contains("value=\"5\""), "{html}");
2004        assert!(html.contains("value=\"40\""), "{html}");
2005        assert_eq!(html.matches("type=\"number\"").count(), 2, "{html}");
2006    }
2007
2008    #[test]
2009    fn both_ends_of_an_interval_take_the_whole_extent() {
2010        // The extent describes the axis rather than either end of it, so a
2011        // browser refuses the same values in both boxes.
2012        let f = Field {
2013            min: Some("0"),
2014            max: Some("300"),
2015            step: Some("1"),
2016            ..Field::interval("bpm_min", "bpm_max", "BPM")
2017        };
2018        let html = field_html(&f, &Filling::default(), &Emit::default());
2019
2020        assert_eq!(html.matches("min=\"0\"").count(), 2, "{html}");
2021        assert_eq!(html.matches("max=\"300\"").count(), 2, "{html}");
2022        assert_eq!(html.matches("step=\"1\"").count(), 2, "{html}");
2023        // Neither box holds anything, which is the open interval rather than an
2024        // empty form: no filter on this axis at all.
2025        assert_eq!(html.matches("value=\"\"").count(), 2, "{html}");
2026    }
2027
2028    #[test]
2029    fn an_interval_carries_the_fault_on_the_group_and_not_on_one_end() {
2030        // A crossed interval is wrong about the answer, and the answer is the
2031        // pair. This is the half two `Number` fields could not say.
2032        let f = Field {
2033            error: Some("The high end is below the low one."),
2034            hint: Some("Leave an end empty for no bound."),
2035            ..Field::interval("bpm_min", "bpm_max", "BPM")
2036        };
2037        let html = field_html(&f, &Filling::default(), &Emit::default());
2038
2039        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
2040        let group = html.find("role=\"group\"").expect("group");
2041        let invalid = html.find("aria-invalid").expect("invalid");
2042        let first_input = html.find("<input").expect("input");
2043        assert!(invalid > group && invalid < first_input, "{html}");
2044        assert!(
2045            html.contains("aria-describedby=\"bpm_min-hint bpm_min-error\""),
2046            "{html}"
2047        );
2048    }
2049
2050    #[test]
2051    fn an_interval_with_one_end_named_draws_one_box() {
2052        // Drawn as described rather than repaired. Inventing a name for the
2053        // upper end would submit a parameter no handler reads, and
2054        // `Field::interval` is what makes the omission unsayable at the source.
2055        let f = Field::new(FieldKind::Interval, "bpm_min", "BPM");
2056        let html = field_html(&f, &Filling::default(), &Emit::default());
2057
2058        assert_eq!(html.matches("<input").count(), 1, "{html}");
2059        assert!(html.contains("name=\"bpm_min\""), "{html}");
2060    }
2061
2062    #[test]
2063    fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
2064        // One `name` is what makes them one answer rather than three; distinct
2065        // ids are what keep each `<label>` wrapping its own input.
2066        let options = [
2067            Choice::plain("copy"),
2068            Choice::plain("reference"),
2069            Choice::plain("link"),
2070        ];
2071        let f = Field::radio("storage", "Storage style", &options);
2072        let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
2073
2074        assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
2075        assert_eq!(html.matches(" checked").count(), 1, "{html}");
2076        assert!(
2077            html.contains("value=\"reference\" checked"),
2078            "the checked one is the one held: {html}"
2079        );
2080        for index in 0..3 {
2081            assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
2082        }
2083    }
2084
2085    #[test]
2086    fn a_radio_group_carries_the_error_rather_than_any_one_option() {
2087        // What is wrong is the answer, not one of the alternatives, so marking
2088        // a single input invalid would say something false. Same reading
2089        // `Field::invalid` gives one level up.
2090        let options = [Choice::plain("copy"), Choice::plain("reference")];
2091        let f = Field {
2092            error: Some("Pick one."),
2093            hint: Some("Cannot be changed later."),
2094            ..Field::radio("storage", "Storage style", &options)
2095        };
2096        let html = field_html(&f, &Filling::default(), &Emit::default());
2097
2098        assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
2099        assert!(
2100            html.contains("aria-describedby=\"storage-hint storage-error\""),
2101            "{html}"
2102        );
2103        // The group is the element that carries them, so they land before the
2104        // first option rather than on it.
2105        let group = html.find("role=\"radiogroup\"").expect("group");
2106        let first = html.find("type=\"radio\"").expect("an option");
2107        assert!(group < first, "{html}");
2108    }
2109
2110    #[test]
2111    fn a_compulsory_radio_group_marks_every_option() {
2112        // How HTML says a group is compulsory: the constraint reads as
2113        // satisfied when any one of them is checked.
2114        let options = [Choice::plain("copy"), Choice::plain("reference")];
2115        let f = Field {
2116            required: true,
2117            ..Field::radio("storage", "Storage style", &options)
2118        };
2119        let html = field_html(&f, &Filling::default(), &Emit::default());
2120        assert_eq!(html.matches(" required").count(), 2, "{html}");
2121    }
2122
2123    #[test]
2124    fn a_radio_option_cannot_break_out_of_its_attribute() {
2125        // Values are `&str` and carry whatever the app put in them. The ids are
2126        // numbered rather than derived from the value for the same reason.
2127        let hostile = [Choice::new(
2128            "x\" onclick=alert(1) data-x=\"",
2129            "<script>alert(1)</script>",
2130        )];
2131        let f = Field::radio("storage", "Storage style", &hostile);
2132        let html = field_html(&f, &Filling::default(), &Emit::default());
2133
2134        // The payload survives as text; what must not survive is the quote
2135        // that would end the attribute and let the rest of it become markup.
2136        assert!(html.contains("value=\"x&quot; onclick=alert(1)"), "{html}");
2137        assert!(!html.contains("<script>"), "{html}");
2138        assert!(html.contains("id=\"storage-0\""), "{html}");
2139    }
2140
2141    #[test]
2142    fn a_radio_group_with_no_options_emits_an_empty_group() {
2143        // Same position the select takes, and the description's own.
2144        let f = Field::radio("storage", "Storage style", &[]);
2145        let html = field_html(&f, &Filling::default(), &Emit::default());
2146        assert!(html.contains("role=\"radiogroup\""), "{html}");
2147        assert!(!html.contains("type=\"radio\""), "{html}");
2148    }
2149
2150    #[test]
2151    fn a_placeholder_comes_off_the_description_and_is_escaped() {
2152        // It arrived in `Filling` until makeover-layout 0.8.0 and was never
2153        // covered here; it is a value in an attribute like any other.
2154        let f = Field {
2155            placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
2156            ..field(FieldKind::Text)
2157        };
2158        let html = field_html(&f, &Filling::default(), &Emit::default());
2159        assert!(html.contains("placeholder=\""), "{html}");
2160        assert!(!html.contains("\" onfocus"), "{html}");
2161    }
2162
2163    #[test]
2164    fn a_select_marks_the_option_that_matches() {
2165        let options = [Choice::plain("1"), Choice::plain("3")];
2166        let f = Field::select("title", "Title", &options);
2167        let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
2168        assert!(
2169            html.contains("<option value=\"3\" selected>3</option>"),
2170            "{html}"
2171        );
2172        assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
2173        assert!(!html.contains("data-unmatched"), "{html}");
2174    }
2175
2176    #[test]
2177    fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
2178        let filling = Filling::of(Value::Text("two\nlines"));
2179        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
2180        assert!(html.contains(">two\nlines</textarea>"), "{html}");
2181    }
2182
2183    #[test]
2184    fn a_markdown_field_is_a_textarea_that_says_what_its_value_is() {
2185        // The mark is the whole difference. Without it a described editor is a
2186        // plain box, and an enhancement looking for editors to upgrade has
2187        // nothing to find -- which is the state MNW's four hand-written section
2188        // editors would have had to keep living in.
2189        let filling = Filling::of(Value::Text("# Heading"));
2190        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
2191        assert!(html.contains("<textarea"), "{html}");
2192        assert!(html.contains(r#"data-format="markdown""#), "{html}");
2193        assert!(html.contains("># Heading</textarea>"), "{html}");
2194
2195        // A plain textarea claims nothing about its value, so the marker has to
2196        // be absent rather than present-and-different.
2197        let plain = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
2198        assert!(!plain.contains("data-format"), "{plain}");
2199
2200        // And it is not an input: the catch-all in `input_type` would have
2201        // degraded it to a single-line text box, which is the wrong shape for
2202        // markdown rather than a lossless fallback.
2203        assert!(!html.contains("<input"), "{html}");
2204    }
2205
2206    #[test]
2207    fn a_markdown_field_gets_the_preview_the_member_permits() {
2208        // The mark on its own is what 0.50.0 shipped, and nothing read it. What
2209        // a conversion needs is the pair MNW's `partial-item-text-editor.js`
2210        // already draws, so describing the field is not a way to lose it.
2211        let filling = Filling::of(Value::Text("# Heading"));
2212        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
2213        assert!(html.contains("data-editor-mode=\"write\""), "{html}");
2214        assert!(html.contains("data-editor-mode=\"preview\""), "{html}");
2215        assert!(html.contains("data-editor-preview"), "{html}");
2216        // Write is the mode a fresh editor is in, and the segment says so twice
2217        // because the sheet reads one and a screen reader reads the other.
2218        assert!(
2219            html.contains(
2220                "class=\"segment chosen\" data-editor-mode=\"write\" aria-pressed=\"true\""
2221            ),
2222            "{html}"
2223        );
2224        assert!(
2225            html.contains("data-editor-mode=\"preview\" aria-pressed=\"false\""),
2226            "{html}"
2227        );
2228        // The value is still the textarea's, and still text rather than an
2229        // attribute. The chrome sits around the control, not in place of it.
2230        assert!(html.contains("># Heading</textarea>"), "{html}");
2231    }
2232
2233    #[test]
2234    fn a_plain_textarea_gets_no_editor_chrome() {
2235        let filling = Filling::of(Value::Text("plain"));
2236        let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
2237        assert!(!html.contains("data-editor-mode"), "{html}");
2238        assert!(!html.contains("data-editor-preview"), "{html}");
2239        assert!(!html.contains("segment"), "{html}");
2240    }
2241
2242    #[test]
2243    fn nothing_the_editor_emits_renders_the_value_as_markup() {
2244        // The whole of this crate's half of the sanitising question: the pane is
2245        // empty, so no value reaches markup through it, and the host's own
2246        // renderer keeps the guarantee it already has.
2247        let filling = Filling::of(Value::Text("<img src=x onerror=alert(1)>"));
2248        let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
2249        assert!(html.contains("data-editor-preview></div>"), "{html}");
2250        assert!(!html.contains("<img"), "{html}");
2251        assert!(
2252            html.contains("&lt;img src=x onerror=alert(1)&gt;"),
2253            "{html}"
2254        );
2255    }
2256
2257    #[test]
2258    fn the_editor_rules_gate_on_the_attribute_and_on_a_binding() {
2259        let css = editor_rules(&Emit::default());
2260        // Behind the attribute, which is the reason the mark is an attribute:
2261        // a class-keyed gate would be prefixed away from the enhancement that
2262        // selects on it.
2263        for line in css.lines().filter(|line| line.contains('{')) {
2264            assert!(line.contains("[data-format=\"markdown\"]"), "{line}");
2265        }
2266        // Nothing is hidden and no control appears until something binds the
2267        // editor. A reader with no script gets the textarea alone.
2268        assert!(
2269            css.contains(
2270                "[data-format=\"markdown\"] > .form-editor-modes {\n    display: none;\n}"
2271            )
2272        );
2273        assert!(css.contains(
2274            "[data-format=\"markdown\"][data-ready] > .form-editor-modes {\n    display: block;\n}"
2275        ));
2276        assert!(css.contains(
2277            "[data-ready][data-mode=\"preview\"] > .form-editor-preview {\n    display: block;\n}"
2278        ));
2279        assert!(
2280            css.contains("[data-ready][data-mode=\"preview\"] > .field {\n    display: none;\n}")
2281        );
2282        // No magnitude, the line this crate holds everywhere else.
2283        assert!(!css.contains("px"), "{css}");
2284        assert!(!css.contains("rem"), "{css}");
2285    }
2286
2287    /// The prefix reaches the chrome as well, and the gate deliberately does
2288    /// not: an app assembling the sheet with its own prefix still has the
2289    /// selector an enhancement finds the editors by.
2290    #[test]
2291    fn the_editor_chrome_is_prefixed_and_its_gate_is_not() {
2292        let opts = Emit {
2293            class_prefix: "mk-",
2294            ..Emit::default()
2295        };
2296        let html = field_html(&field(FieldKind::Rich), &Filling::default(), &opts);
2297        assert!(html.contains("class=\"mk-form-editor-modes\""), "{html}");
2298        assert!(html.contains("class=\"mk-form-editor-preview\""), "{html}");
2299        assert!(html.contains("class=\"mk-segment chosen\""), "{html}");
2300        assert!(html.contains("data-format=\"markdown\""), "{html}");
2301
2302        let css = editor_rules(&opts);
2303        assert!(css.contains(".mk-form-editor-modes"), "{css}");
2304        assert!(css.contains("[data-format=\"markdown\"]"), "{css}");
2305    }
2306
2307    /// Every class the editor puts in markup is one the generated sheet rules,
2308    /// which is `FACET_CLASSES`' obligation without a list to keep: these two
2309    /// have rules, so the vocabulary seal picks them up from the sheet itself.
2310    #[test]
2311    fn the_editor_classes_are_in_the_vocabulary() {
2312        let opts = Emit::default();
2313        let names = crate::vocabulary::names(&opts);
2314        for name in ["form-editor-modes", "form-editor-preview", "segment"] {
2315            assert!(names.contains(name), "{name} is not in the vocabulary");
2316        }
2317    }
2318
2319    #[test]
2320    fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
2321        let opts = Emit {
2322            class_prefix: "mk-",
2323            ..Emit::default()
2324        };
2325        let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
2326        assert!(html.contains("class=\"mk-form-group\""), "{html}");
2327        assert!(html.contains("class=\"mk-field\""), "{html}");
2328    }
2329
2330    #[test]
2331    fn a_datetime_asking_for_an_instant_is_marked_for_the_script_that_converts_it() {
2332        let mut f = field(FieldKind::DateTime);
2333        f.as_instant = true;
2334        let html = field_html(&f, &Filling::default(), &Emit::default());
2335        assert!(html.contains("data-instant=\"true\""), "{html}");
2336        // The control is unchanged: the flag says what is submitted, not what
2337        // is drawn.
2338        assert!(html.contains("type=\"datetime-local\""), "{html}");
2339    }
2340
2341    #[test]
2342    fn only_a_datetime_can_name_a_moment_so_only_a_datetime_is_marked() {
2343        for kind in [FieldKind::Date, FieldKind::Text, FieldKind::Number] {
2344            let mut f = field(kind);
2345            f.as_instant = true;
2346            let html = field_html(&f, &Filling::default(), &Emit::default());
2347            assert!(!html.contains("data-instant"), "{kind:?}: {html}");
2348        }
2349    }
2350
2351    #[test]
2352    fn a_datetime_that_did_not_ask_carries_no_mark() {
2353        let html = field_html(
2354            &field(FieldKind::DateTime),
2355            &Filling::default(),
2356            &Emit::default(),
2357        );
2358        assert!(!html.contains("data-instant"), "{html}");
2359    }
2360
2361    #[test]
2362    fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
2363        let mut f = field(FieldKind::Text);
2364        f.extended = true;
2365        let html = field_html(&f, &Filling::default(), &Emit::default());
2366        assert!(html.contains("data-extended=\"true\""), "{html}");
2367    }
2368
2369    /// The prefix scopes the id and leaves the name alone. Prefixing the name
2370    /// too would change what the form submits, which is the failure this pair
2371    /// of assertions exists to catch rather than describe.
2372    #[test]
2373    fn the_id_prefix_scopes_the_id_and_never_the_name() {
2374        let mut f = field(FieldKind::Text);
2375        f.hint = Some("Keep it short");
2376        f.error = Some("Required");
2377        let filling = Filling {
2378            id_prefix: Some("form-modal-task-edit"),
2379            ..Filling::default()
2380        };
2381        let html = field_html(&f, &filling, &Emit::default());
2382
2383        assert!(
2384            html.contains(r#"id="form-modal-task-edit-title""#),
2385            "{html}"
2386        );
2387        assert!(html.contains(r#"name="title""#), "{html}");
2388        assert!(
2389            !html.contains(r#"name="form-modal-task-edit-title""#),
2390            "{html}"
2391        );
2392
2393        // The label and both associations follow the id, or they point at
2394        // nothing once the same form is on screen twice.
2395        assert!(
2396            html.contains(r#"for="form-modal-task-edit-title""#),
2397            "{html}"
2398        );
2399        assert!(
2400            html.contains(
2401                r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
2402            ),
2403            "{html}"
2404        );
2405        assert!(
2406            html.contains(r#"id="form-modal-task-edit-title-hint""#),
2407            "{html}"
2408        );
2409    }
2410
2411    #[test]
2412    fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
2413        let filling = Filling {
2414            value: Value::Text("42"),
2415            id_prefix: Some("scoped"),
2416            ..Filling::default()
2417        };
2418        let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
2419        assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
2420    }
2421
2422    /// These three exist so a touch keyboard and the platform's validation
2423    /// arrive with the field. Emitting text for any of them is the regression
2424    /// the variants were added to prevent, so the type is asserted directly.
2425    #[test]
2426    fn a_constraint_becomes_the_browsers_own_attribute() {
2427        // makeover-layout 0.11.0's model: the description carries the rule and
2428        // each renderer emits its host's idiom for it. Enforcement is still
2429        // whoever validated's, and arrives back as `error`.
2430        let html = field_html(
2431            &Field {
2432                max_length: Some(100),
2433                min: Some("1"),
2434                max: Some("240"),
2435                required: true,
2436                ..Field::new(FieldKind::Number, "minutes", "Minutes")
2437            },
2438            &Filling::default(),
2439            &Emit::default(),
2440        );
2441        assert!(html.contains(r#"maxlength="100""#));
2442        assert!(html.contains(r#"min="1""#));
2443        assert!(html.contains(r#"max="240""#));
2444        assert!(html.contains(" required"));
2445    }
2446
2447    #[test]
2448    fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
2449        // The bound is text because it is only a number for some of the kinds
2450        // that take one; goingson's own sites are a duration and a datetime.
2451        let html = field_html(
2452            &Field {
2453                min: Some("2026-08-09T14:30"),
2454                ..Field::new(FieldKind::Text, "starts", "Starts")
2455            },
2456            &Filling::default(),
2457            &Emit::default(),
2458        );
2459        assert!(html.contains(r#"min="2026-08-09T14:30""#));
2460    }
2461
2462    #[test]
2463    fn a_file_field_is_a_file_input() {
2464        // `844b5ae0`. A field that takes any file emits no `accept` at all,
2465        // which is the browser's own "any file". `accept=""` is a filter that
2466        // means nothing on one browser and everything on another.
2467        let html = field_html(
2468            &Field::new(FieldKind::File, "attachment", "Attachment"),
2469            &Filling::default(),
2470            &Emit::default(),
2471        );
2472        assert!(html.contains(r#"type="file""#));
2473        assert!(!html.contains("accept="));
2474        assert!(!html.contains("multiple"));
2475        // And it never carries a value: a file input's value is not settable
2476        // from markup, and the browser refuses one that tries.
2477        assert!(!html.contains("value="));
2478    }
2479
2480    #[test]
2481    fn an_accept_list_is_comma_joined_in_the_attributes_own_format() {
2482        // `f7261a5a`, makeover-layout 0.31.0. Each entry writes itself: a
2483        // family is its wildcard, a media type is itself, a suffix keeps its
2484        // leading dot and however many more it has.
2485        const MIXED: &[Accepted<'_>] = &[
2486            Accepted::Family(Family::Image),
2487            Accepted::Type("text/csv"),
2488            Accepted::Suffix(".tar.gz"),
2489        ];
2490        let html = field_html(
2491            &Field {
2492                multiple: true,
2493                ..Field::upload("drop", "Drop files", MIXED)
2494            },
2495            &Filling::default(),
2496            &Emit::default(),
2497        );
2498        assert!(
2499            html.contains(r#"accept="image/*,text/csv,.tar.gz""#),
2500            "{html}"
2501        );
2502        assert!(html.contains(" multiple"), "{html}");
2503    }
2504
2505    #[test]
2506    fn an_accept_entry_cannot_end_the_attribute_it_sits_in() {
2507        // The list reaches an attribute value, so it is escaped like every
2508        // other string that does. Nothing in the tree writes a quote into one;
2509        // that it cannot is the point.
2510        const HOSTILE: &[Accepted<'_>] = &[Accepted::Type(r#"image/x" onload="x"#)];
2511        let html = field_html(
2512            &Field::upload("cover", "Cover", HOSTILE),
2513            &Filling::default(),
2514            &Emit::default(),
2515        );
2516        assert!(!html.contains(r#"onload="x"#), "{html}");
2517    }
2518
2519    #[test]
2520    fn the_typed_text_kinds_keep_their_input_type() {
2521        for (kind, expected) in [
2522            (FieldKind::Email, "email"),
2523            (FieldKind::Url, "url"),
2524            (FieldKind::Tel, "tel"),
2525            (FieldKind::Date, "date"),
2526            (FieldKind::DateTime, "datetime-local"),
2527        ] {
2528            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
2529            assert!(
2530                html.contains(&format!(r#"type="{expected}""#)),
2531                "{kind:?} emitted {html}"
2532            );
2533        }
2534    }
2535
2536    #[test]
2537    fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
2538        // The regression this closes: described as text with a hint reading
2539        // "YYYY-MM-DD", which loses the picker, the platform's validation and
2540        // the touch keyboard, and asks prose to do all three.
2541        for kind in [FieldKind::Date, FieldKind::DateTime] {
2542            let html = field_html(&field(kind), &Filling::default(), &Emit::default());
2543            assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
2544        }
2545    }
2546
2547    #[test]
2548    fn no_prefix_leaves_the_id_as_the_name() {
2549        let html = field_html(
2550            &field(FieldKind::Text),
2551            &Filling::default(),
2552            &Emit::default(),
2553        );
2554        assert!(html.contains(r#"id="title" name="title""#), "{html}");
2555    }
2556
2557    /// Two variants and two tiers, which is the smallest list that can show
2558    /// where a group opens and that two badges differ.
2559    const THEMES: &[makeover_layout::ThemeChoice<'_>] = &[
2560        makeover_layout::ThemeChoice::new(
2561            "goingson",
2562            "GoingsOn",
2563            ThemeVariant::Light,
2564            makeover_layout::Contrast::High,
2565        ),
2566        makeover_layout::ThemeChoice::new(
2567            "ayu-light",
2568            "Ayu Light",
2569            ThemeVariant::Light,
2570            makeover_layout::Contrast::Low,
2571        ),
2572        makeover_layout::ThemeChoice::new(
2573            "carbonfox",
2574            "Carbonfox",
2575            ThemeVariant::Dark,
2576            makeover_layout::Contrast::High,
2577        ),
2578    ];
2579
2580    #[test]
2581    fn a_theme_picker_opens_one_optgroup_per_variant() {
2582        let f = Field::theme("theme", "Theme", THEMES);
2583        let html = field_html(&f, &Filling::default(), &Emit::default());
2584
2585        assert_eq!(html.matches("<optgroup").count(), 2, "{html}");
2586        assert_eq!(html.matches("</optgroup>").count(), 2, "{html}");
2587        assert!(
2588            html.contains(r#"<optgroup label="Light" data-variant="light">"#),
2589            "{html}"
2590        );
2591        assert!(
2592            html.contains(r#"<optgroup label="Dark" data-variant="dark">"#),
2593            "{html}"
2594        );
2595        // The two light themes share one group: a new group opens on a change
2596        // of variant and on nothing else.
2597        assert!(
2598            html.find("Ayu Light") < html.find("<optgroup label=\"Dark\""),
2599            "{html}"
2600        );
2601    }
2602
2603    #[test]
2604    fn every_theme_carries_its_measured_tier() {
2605        // The fact the three hand-written pickers lost. It rides in the text
2606        // because a `<select>`'s options take no elements, and in an attribute
2607        // because a stylesheet cannot read text.
2608        let f = Field::theme("theme", "Theme", THEMES);
2609        let html = field_html(&f, &Filling::default(), &Emit::default());
2610
2611        assert!(html.contains(r#"data-contrast="high""#), "{html}");
2612        assert!(html.contains(r#"data-contrast="low""#), "{html}");
2613        assert!(html.contains("GoingsOn (AA)"), "{html}");
2614        assert!(html.contains("Ayu Light (low)"), "{html}");
2615    }
2616
2617    #[test]
2618    fn the_follow_row_is_first_and_sits_in_no_group() {
2619        // It names no theme and belongs to no variant, so grouping it would be
2620        // inventing a fourth variant for one row.
2621        let f = Field::theme("theme", "Theme", THEMES)
2622            .following(Choice::new("system", "Follow System"));
2623        let html = field_html(&f, &Filling::default(), &Emit::default());
2624
2625        let follow = html.find("Follow System").expect("the row was offered");
2626        assert!(follow < html.find("<optgroup").expect("groups"), "{html}");
2627    }
2628
2629    #[test]
2630    fn the_stored_theme_is_the_selected_one() {
2631        let f = Field::theme("theme", "Theme", THEMES)
2632            .following(Choice::new("system", "Follow System"));
2633
2634        let named = field_html(&f, &Filling::of(Value::Text("carbonfox")), &Emit::default());
2635        assert!(
2636            named.contains(r#"value="carbonfox" data-contrast="high" selected"#),
2637            "{named}"
2638        );
2639        assert!(!named.contains(r#"value="system" selected"#), "{named}");
2640
2641        let following = field_html(&f, &Filling::of(Value::Text("system")), &Emit::default());
2642        assert!(
2643            following.contains(r#"value="system" selected"#),
2644            "{following}"
2645        );
2646    }
2647
2648    #[test]
2649    fn a_theme_that_is_no_longer_installed_keeps_its_value() {
2650        // `push_options`' rule, met again: a value no row carries is a wrong
2651        // answer rather than an absent one, and dropping it would save a
2652        // different theme over the user's on the next write.
2653        let f = Field::theme("theme", "Theme", THEMES);
2654        let html = field_html(
2655            &f,
2656            &Filling::of(Value::Text("deleted-theme")),
2657            &Emit::default(),
2658        );
2659        assert!(html.contains(r#"data-unmatched="true""#), "{html}");
2660        assert!(
2661            html.contains(r#"<option value="deleted-theme" selected"#),
2662            "{html}"
2663        );
2664    }
2665
2666    #[test]
2667    fn the_follow_row_is_not_a_stray_value() {
2668        // The near-miss: `system` is carried by no `ThemeChoice`, so a check
2669        // that only walked the theme list would emit a duplicate unmatched row
2670        // beside the real one.
2671        let f = Field::theme("theme", "Theme", THEMES)
2672            .following(Choice::new("system", "Follow System"));
2673        let html = field_html(&f, &Filling::of(Value::Text("system")), &Emit::default());
2674        assert!(!html.contains("data-unmatched"), "{html}");
2675    }
2676
2677    #[test]
2678    fn a_machine_with_no_themes_still_gets_a_picker() {
2679        // `Field::themes`' own position: an app whose theme directories hold
2680        // nothing has exactly this, and the empty control says so on screen.
2681        let f =
2682            Field::theme("theme", "Theme", &[]).following(Choice::new("system", "Follow System"));
2683        let html = field_html(&f, &Filling::default(), &Emit::default());
2684        assert!(html.contains("<select"), "{html}");
2685        assert!(!html.contains("<optgroup"), "{html}");
2686        assert!(html.contains("Follow System"), "{html}");
2687    }
2688}