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::{
41    Choice, Depth, Field, FieldKind, Intent as _, Selector, ThemeVariant, Tone, Value,
42};
43use std::fmt::Write as _;
44
45/// Every class this module can put in markup.
46///
47/// [`crate::facet::FACET_CLASSES`]' obligation, and the module where it was
48/// missing longest. Every one of these is ruled by the generated sheet, the
49/// group's four through `group_rules`; the list is written down anyway,
50/// because it is what `crate::corpus` holds the emitters against and what the
51/// vocabulary test holds the sheet against.
52///
53/// What goes wrong without it: an app checking its stylesheet against
54/// [`crate::vocabulary::names`] concludes that its live `.form-group` and
55/// `.form-label` rules match nothing and are safe to delete.
56pub const FIELD_CLASSES: &[&str] = &[
57    "field",
58    "form-checkbox-label",
59    "form-checklist",
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/// Everything about the field that the description does not carry.
106#[derive(Debug, Clone, Copy, Default)]
107pub struct Filling<'a> {
108    /// What the field holds now.
109    pub value: Value<'a>,
110    /// Markup appended inside the group, after the hint. Not escaped.
111    pub trailing: Option<Markup<'a>>,
112    /// Attributes written onto the control element itself. Not escaped.
113    ///
114    /// [`trailing`](Self::trailing)'s argument at attribute scale: a host knows
115    /// facts about the control that no description layer carries, and until
116    /// this existed the only way to attach one was to stop calling this emitter
117    /// and write a second one. quasi's suggestion source is the first caller ,
118    /// a field that owns a list of candidates is a `role="combobox"` pointing
119    /// at the list it owns, and neither half is anything
120    /// [`makeover_layout::Field`] can say.
121    ///
122    /// Written verbatim, so a caller supplies `attr="value"` pairs with no
123    /// leading space and does its own escaping. It is [`Markup`]'s hole in the
124    /// same wall, named the same way so a caller has to state that the contents
125    /// are trusted.
126    ///
127    /// A [`FieldKind::Radio`] drops them, and that is deliberate rather than an
128    /// oversight: a radio group is a set of sibling inputs with no one control
129    /// element, so there is nowhere honest to put an attribute meant for the
130    /// control. The group carries the descriptions for the same reason.
131    pub control_attrs: Option<Markup<'a>>,
132    /// Scopes the `id` attributes to one instance of the form.
133    ///
134    /// The field's `name` is what the value submits under and is the same
135    /// wherever the form appears; its `id` has to be unique in the document,
136    /// and those two facts stop agreeing the moment a form appears twice.
137    /// goingson hits this directly: its new-task and edit-task modals are the
138    /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
139    /// `label for` and `aria-describedby` pointing at the right control.
140    ///
141    /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
142    /// `name`, which would change what the form submits.
143    pub id_prefix: Option<&'a str>,
144}
145
146impl<'a> Filling<'a> {
147    /// A filling that carries a value and nothing else.
148    #[must_use]
149    pub const fn of(value: Value<'a>) -> Self {
150        Self {
151            value,
152            trailing: None,
153            control_attrs: None,
154            id_prefix: None,
155        }
156    }
157
158    /// The document-unique id for a field of this name.
159    ///
160    /// One token whatever the name holds. An id is referenced from
161    /// `aria-describedby` and `aria-labelledby`, which are space-separated
162    /// lists, so a field named `first name` referenced as `first name-hint`
163    /// pointed at two ids that do not exist and its hint was never announced.
164    /// Whitespace becomes `-`; nothing else in an id needs changing.
165    fn id_for(&self, name: &str) -> String {
166        let mut id = String::new();
167        if let Some(prefix) = self.id_prefix {
168            escape_into(&tokenised(prefix), &mut id);
169            id.push('-');
170        }
171        escape_into(&tokenised(name), &mut id);
172        id
173    }
174}
175
176/// `raw` with every run of whitespace replaced by one `-`, so it is one IDREF.
177fn tokenised(raw: &str) -> std::borrow::Cow<'_, str> {
178    if !raw.contains(char::is_whitespace) {
179        return std::borrow::Cow::Borrowed(raw);
180    }
181    std::borrow::Cow::Owned(raw.split_whitespace().collect::<Vec<_>>().join("-"))
182}
183
184/// Encode the five characters that let a value stop being a value, into a
185/// buffer the caller already has.
186///
187/// The form the emitters use. [`escape`] is this with a `String` allocated
188/// around it, and the allocation is the whole difference: a described screen
189/// escapes once per attribute and once per run of text, so a function that
190/// returns a `String` allocates a few thousand times to produce one page,
191/// where a template engine writes its escaped bytes straight into the output
192/// buffer.
193///
194/// Sound in element text and in a double-quoted attribute alike, which is the
195/// property `textContent`-based escaping cannot have. Both sinks are covered by
196/// one function so that no call site has to choose, here or downstream.
197///
198/// Copies in runs rather than per character. All five encoded characters are
199/// ASCII, so a byte scan cannot land inside a multi-byte character and the
200/// slice between two of them is always a valid `&str`. Text with nothing to
201/// encode, which is most text, is one `push_str` of the whole thing.
202pub fn escape_into(text: &str, out: &mut String) {
203    let mut start = 0;
204    for (index, byte) in text.bytes().enumerate() {
205        let encoded = match byte {
206            b'&' => "&amp;",
207            b'<' => "&lt;",
208            b'>' => "&gt;",
209            b'"' => "&quot;",
210            b'\'' => "&#39;",
211            _ => continue,
212        };
213        out.push_str(&text[start..index]);
214        out.push_str(encoded);
215        start = index + 1;
216    }
217    out.push_str(&text[start..]);
218}
219
220/// Encode the five characters that let a value stop being a value.
221///
222/// [`escape_into`] with a buffer of its own, for the callers that want a value
223/// rather than an append: a caller assembling an attribute out of several
224/// pieces, and everything outside this crate that took this function before the
225/// buffer-writing form existed. Emitting into a buffer you already hold is the
226/// cheaper path and the one this crate's own emitters take.
227#[must_use]
228pub fn escape(text: &str) -> String {
229    let mut out = String::with_capacity(text.len());
230    escape_into(text, &mut out);
231    out
232}
233
234/// The `type` an input takes for a kind.
235///
236/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
237const fn input_type(kind: FieldKind) -> &'static str {
238    match kind {
239        FieldKind::Secret => "password",
240        FieldKind::Number => "number",
241        FieldKind::Checkbox => "checkbox",
242        FieldKind::File => "file",
243        FieldKind::Hidden => "hidden",
244        // Not decoration. Each of these changes the keyboard a touch device
245        // offers and turns on the platform's own validation, which is why the
246        // description names them apart from text rather than letting the app
247        // pass an HTML type through.
248        FieldKind::Email => "email",
249        FieldKind::Url => "url",
250        FieldKind::Tel => "tel",
251        // The same argument, and it buys more here than anywhere else in this
252        // list: a native picker as well as the keyboard and the validation.
253        // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
254        // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
255        FieldKind::Date => "date",
256        FieldKind::DateTime => "datetime-local",
257        FieldKind::Radio => "radio",
258        // The clearest case in this list that a kind is not decoration: a
259        // number and a range submit the same value and are different controls,
260        // and the browser is the one drawing the difference.
261        FieldKind::Range => "range",
262        // Select and Textarea are not inputs at all; they never reach here.
263        // Radio is one, but it is emitted once per option by `radio_html` and
264        // so does not reach here either.
265        FieldKind::Text | FieldKind::Select | FieldKind::Textarea | FieldKind::Rich => "text",
266        // A kind added to the description since this renderer was built. Text
267        // accepts any value the others would, so it degrades rather than
268        // dropping the field.
269        _ => "text",
270    }
271}
272
273/// The attributes every visible control carries, error state included.
274///
275/// `aria-invalid` is the whole reason the error state is readable at all: the
276/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
277/// than on a class, so a control rendered already-invalid without it is styled
278/// as if nothing were wrong. goingson's runtime validation path sets the
279/// attribute and its initial render does not, which is exactly the drift one
280/// emitter removes.
281/// `id` and `name` arrive separately because they are not the same fact. The
282/// name is what submits and is fixed by the description; the id has to be
283/// unique in the document and so carries [`Filling::id_prefix`] when a form
284/// appears more than once.
285/// The `accept` attribute, from the description's accept list.
286///
287/// The list is comma-joined because that is the
288/// attribute's own format, and each entry writes itself: a family is its
289/// wildcard media type, a media type is itself, a suffix is itself with its
290/// leading dot. Nothing is normalised on the way through, `.tar.gz` is two
291/// dots and the browser is fine with it.
292///
293/// An empty list emits no attribute at all, which is the browser's own "any
294/// file" and is what the description means by listing nothing. Emitting
295/// `accept=""` instead would be a filter that matches nothing on some browsers
296/// and everything on others.
297///
298/// It is a filter and not a guarantee, on the browser's side as much as here:
299/// the picker keeps an "All Files" escape and the user may take it. Whoever
300/// validated still validates.
301fn push_accept(out: &mut String, field: &Field<'_>) {
302    if field.accept.is_empty() {
303        return;
304    }
305    out.push_str(" accept=\"");
306    for (index, one) in field.accept.iter().enumerate() {
307        if index > 0 {
308            out.push(',');
309        }
310        escape_into(one.as_str(), out);
311    }
312    out.push('"');
313}
314
315/// The extent and the granularity, as the browser spells them.
316///
317/// Its own function because an interval writes them onto both of its ends: they
318/// describe the axis rather than either end of it, which is what
319/// [`FieldKind::Interval`] says and what the six audiofiles filter axes are.
320fn push_bounds(out: &mut String, field: &Field<'_>) {
321    if let Some(min) = field.min {
322        out.push_str(" min=\"");
323        escape_into(min, out);
324        out.push('"');
325    }
326    if let Some(max) = field.max {
327        out.push_str(" max=\"");
328        escape_into(max, out);
329        out.push('"');
330    }
331    // The browser's own default is `step="1"`, which turns a 0-to-1 threshold
332    // into a two-position control. That is the granularity the description
333    // means when it says nothing, so this is emitted only when an app has said
334    // otherwise rather than defaulted here.
335    //
336    // A range takes its granularity from its curve as of makeover-layout
337    // 0.32.0, and every other kind keeps `Field::step`. See the crate header on
338    // what this renderer can and cannot do with a curve.
339    let step = if field.kind == FieldKind::Range {
340        field.curve.step()
341    } else {
342        field.step
343    };
344    if let Some(step) = step {
345        out.push_str(" step=\"");
346        escape_into(step, out);
347        out.push('"');
348    }
349}
350
351fn push_control_attributes(
352    out: &mut String,
353    field: &Field<'_>,
354    filling: &Filling<'_>,
355    id: &str,
356    name: &str,
357) {
358    let _ = write!(out, " id=\"{id}\" name=\"");
359    escape_into(name, out);
360    out.push('"');
361    if field.required {
362        out.push_str(" required");
363    }
364    // makeover-layout 0.11.0's constraints. The description carries the rule and
365    // this emits the browser's idiom for it, which is the model `required` has
366    // been using since before the crate wrote down that it carried none.
367    // Enforcement is still whoever validated's, and arrives back as `error`.
368    if let Some(limit) = field.max_length {
369        let _ = write!(out, " maxlength=\"{limit}\"");
370    }
371    push_bounds(out, field);
372    // The description asks for the wall-clock value to be submitted as the
373    // moment it names, and in a browser that conversion is script's: `<input
374    // type="datetime-local">` submits what the user typed and nothing in HTML
375    // turns it into an instant. So this emits the mark and quasi-webview's
376    // `instant.js` does the converting, the same division as `data-clock`,
377    // where the markup says what to do and the shipped script is what a browser
378    // knows that a description cannot.
379    //
380    // Only DateTime. A date and a time are each half a moment and cannot name
381    // one on their own, so the flag is ignored there rather than emitting a
382    // mark nothing can honour.
383    if field.as_instant && matches!(field.kind, FieldKind::DateTime) {
384        out.push_str(" data-instant=\"true\"");
385    }
386    if field.invalid() {
387        out.push_str(" aria-invalid=\"true\"");
388    }
389
390    push_described_by(out, field, id);
391
392    // Last, so that a host attaching a fact of its own can see everything this
393    // emitter decided and cannot be overwritten by it. Duplicate attributes are
394    // the caller's to avoid: HTML takes the first of a repeated pair, so an
395    // attribute spelled here as well as there keeps this crate's answer.
396    if let Some(Markup(attrs)) = filling.control_attrs {
397        out.push(' ');
398        out.push_str(attrs);
399    }
400}
401
402/// The `aria-describedby` naming whatever of the hint and the error exist.
403///
404/// Both associations, in the order they are useful: the standing help, then
405/// what is currently wrong. goingson's runtime path points describedby at the
406/// error alone and drops the hint association it never made in the first place;
407/// naming both here means the hint survives an error appearing.
408///
409/// Its own function because a radio group carries it on the group rather than
410/// on a control, and one reading of "what describes this field" is the point.
411fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
412    let unit = field.shown_unit().is_some();
413    if field.hint.is_none() && field.error.is_none() && field.note.is_none() && !unit {
414        return;
415    }
416    let mut written = false;
417    out.push_str(" aria-describedby=\"");
418    if field.hint.is_some() {
419        let _ = write!(out, "{id}-hint");
420        written = true;
421    }
422    // The unit before the error and after the hint, which is the order they are
423    // useful in: what the number is measured in is standing context like the
424    // hint, and what is wrong with it now comes last.
425    if unit {
426        if written {
427            out.push(' ');
428        }
429        let _ = write!(out, "{id}-unit");
430        written = true;
431    }
432    // The note after the unit and before the error, matching the order the
433    // three are drawn in and the order they are useful in: what the answer
434    // costs is context, and what is wrong with it now still comes last.
435    if field.note.is_some() {
436        if written {
437            out.push(' ');
438        }
439        let _ = write!(out, "{id}-note");
440        written = true;
441    }
442    if field.error.is_some() {
443        if written {
444            out.push(' ');
445        }
446        let _ = write!(out, "{id}-error");
447    }
448    out.push('"');
449}
450
451/// Whether the field's control is a set of elements rather than one.
452///
453/// A DOM concern rather than a description one, which is why it is decided here
454/// and not in `makeover-layout`: `for` and `id` are an HTML association and
455/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
456/// points at nothing, because no single element carries the group's id, so the
457/// association has to invert, the label takes an id and the group names itself
458/// with `aria-labelledby`.
459const fn is_group_control(kind: FieldKind) -> bool {
460    matches!(
461        kind,
462        FieldKind::Radio | FieldKind::Checklist | FieldKind::Interval
463    )
464}
465
466/// An interval: two number boxes inside one labelled group.
467///
468/// The markup MNW's discover sidebar writes by hand, a `role="group"` with
469/// `aria-labelledby` pointing at the question, holding `min_price` and
470/// `max_price`, which is HTML saying by hand exactly what
471/// [`FieldKind::Interval`] now says in the description. So this emits what that
472/// page already proved is right, rather than inventing a shape.
473///
474/// The group carries the error state and the descriptions, for
475/// [`push_radio`]'s reason: what is wrong is the answer, and marking one box
476/// invalid would name the wrong half of a fault that belongs to both ends.
477///
478/// # Both boxes take the same extent
479///
480/// [`Field::min`], [`Field::max`] and [`Field::step`] describe the axis rather
481/// than either end, so [`push_bounds`] writes them onto both. The crossing rule
482/// is not emitted, because the description does not carry it and the browser
483/// has no attribute for it: an upper end below the lower one is a refusal
484/// whoever validated hands back as [`Field::error`], which lands on the group.
485///
486/// # Which end is which, in words
487///
488/// `aria-label`, because the description states direction structurally, the
489/// lower end's name is [`Field::name`] and the upper one's is
490/// [`Field::upper_name`], and never in words. Words for the ends are the
491/// host's, the same way a slider's readout is, and a page with visible Min and
492/// Max captions supplies them through [`Filling::trailing`] rather than having
493/// this crate own two strings of English.
494fn push_interval(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
495    let id = filling.id_for(field.name);
496
497    out.push_str("<div class=\"");
498    push_class(out, "form-interval", opts);
499    let _ = write!(out, "\" role=\"group\" aria-labelledby=\"{id}-label\"");
500    if field.invalid() {
501        out.push_str(" aria-invalid=\"true\"");
502    }
503    push_described_by(out, field, &id);
504    out.push('>');
505
506    // An interval with no upper name has one end that can be submitted, which
507    // is what the description said and is drawn honestly rather than repaired:
508    // `Field::interval` is what makes it unsayable, and inventing a name here
509    // would submit a parameter no handler is reading.
510    let ends: [(&str, &str, &str, &str); 2] = [
511        (
512            "lower",
513            opts.lower_label,
514            field.name,
515            filling.value.as_text(),
516        ),
517        (
518            "upper",
519            opts.upper_label,
520            field.upper_name.unwrap_or(""),
521            filling.value.upper_text(),
522        ),
523    ];
524    for (end, said, name, value) in ends {
525        if name.is_empty() {
526            continue;
527        }
528        out.push_str("<input type=\"number\" class=\"");
529        push_class(out, "field", opts);
530        let _ = write!(out, "\" id=\"{id}-{end}\" name=\"");
531        escape_into(name, out);
532        out.push_str("\" aria-label=\"");
533        escape_into(said, out);
534        out.push('"');
535        if field.required {
536            out.push_str(" required");
537        }
538        push_bounds(out, field);
539        if let Some(text) = field.placeholder {
540            out.push_str(" placeholder=\"");
541            escape_into(text, out);
542            out.push('"');
543        }
544        out.push_str(" value=\"");
545        escape_into(value, out);
546        out.push_str("\">");
547    }
548
549    out.push_str("</div>");
550}
551
552/// A radio group: the options as sibling inputs sharing one `name`.
553///
554/// The group carries the error state and the descriptions, and the inputs carry
555/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
556/// down: marking a single input invalid would say the wrong thing, since what
557/// is wrong is the answer to the question and not one of the alternatives.
558///
559/// Ids are numbered rather than built from the option values, which can hold
560/// anything a `&str` can, spaces and quotes included, and would otherwise
561/// have to be slugged into something unique by a rule this crate would then own.
562///
563/// `required` lands on every input, which is how HTML says a group is
564/// compulsory: the constraint is satisfied when any one of them is checked.
565///
566/// # A checklist is the same markup with checkboxes
567///
568/// [`FieldKind::Checklist`] shares all of the above, and two things differ.
569/// An option is ticked by [`Choice::chosen`] alone: a set is not one value, so
570/// there is nothing for the field's value to be compared with. And `required`
571/// is not written, because on a checkbox it demands *that* box, so a required
572/// checklist would refuse every answer that left any option unticked. What a
573/// compulsory set means stays with whoever validated.
574///
575/// A radio option is marked by `chosen` too, or by carrying the field's value,
576/// which is [`Choice::chosen`]'s rule for every renderer.
577fn push_choice_group(
578    out: &mut String,
579    field: &Field<'_>,
580    filling: &Filling<'_>,
581    opts: &Emit,
582    mut placed: Option<&mut Vec<core::ops::Range<usize>>>,
583) {
584    let id = filling.id_for(field.name);
585    let value = filling.value.as_text();
586    let name = escape(field.name);
587    let several = field.kind.takes_several();
588    let (group_class, role, label_class, input) = if several {
589        ("form-checklist", "group", "form-checkbox-label", "checkbox")
590    } else {
591        (
592            "form-radio-group",
593            "radiogroup",
594            "form-radio-label",
595            "radio",
596        )
597    };
598
599    out.push_str("<div class=\"");
600    push_class(out, group_class, opts);
601    let _ = write!(out, "\" role=\"{role}\" aria-labelledby=\"{id}-label\"");
602    if field.invalid() {
603        out.push_str(" aria-invalid=\"true\"");
604    }
605    push_described_by(out, field, &id);
606    out.push('>');
607
608    // A group described with no options emits an empty group, for the reason
609    // `Field::options` gives: an app whose option list has not loaded has
610    // exactly that, and an empty group says so on screen rather than in a log.
611    for (index, opt) in field.options.iter().enumerate() {
612        let at = out.len();
613        out.push_str("<label class=\"");
614        push_class(out, label_class, opts);
615        let _ = write!(
616            out,
617            "\"><input type=\"{input}\" id=\"{id}-{index}\" name=\"{name}\" value=\""
618        );
619        escape_into(opt.value, out);
620        out.push('"');
621        if opt.chosen || (!several && opt.value == value) {
622            out.push_str(" checked");
623        }
624        if field.required && !several {
625            out.push_str(" required");
626        }
627        // A radio group has room a `<select>` does not, so the reason gets its
628        // own element beside the label rather than being run into it. The class
629        // is what a stylesheet mutes; the text is there either way, which is
630        // the half that matters, the finding was a greyed control with its
631        // explanation behind a hover.
632        if opt.unavailable.is_some() {
633            out.push_str(" disabled");
634        }
635        out.push_str("><span>");
636        escape_into(opt.label, out);
637        out.push_str("</span>");
638        // What picking it means, on the line under the label. `5e21dcfc`, and
639        // the same treatment the reason gets one line down: a radio group has
640        // room, so the sentence sits in its own element rather than being run
641        // into the label the way a `<select>`'s has to be.
642        //
643        // Before the reason, which is the order the two read in: what this
644        // option *is* comes ahead of why it cannot be picked, and an option
645        // carrying both has said two things rather than one long one.
646        if let Some(detail) = opt.detail {
647            out.push_str("<span class=\"");
648            push_class(out, "form-option-detail", opts);
649            out.push_str("\">");
650            escape_into(detail, out);
651            out.push_str("</span>");
652        }
653        if let Some(reason) = opt.unavailable {
654            out.push_str("<span class=\"");
655            push_class(out, "form-option-reason", opts);
656            out.push_str("\">");
657            escape_into(reason, out);
658            out.push_str("</span>");
659        }
660        out.push_str("</label>");
661        if let Some(placed) = placed.as_deref_mut() {
662            placed.push(at..out.len());
663        }
664    }
665
666    out.push_str("</div>");
667}
668
669/// The options of a select: the unanswered instruction, an unmatched current
670/// value carried as its own, then the options themselves.
671///
672/// An option is marked either by [`Choice::chosen`] or by carrying the field's
673/// current value; the stray-option and placeholder paths below key on the value
674/// alone, so a list that marks itself has an empty value and reaches neither.
675///
676/// A select handed a value no option carries renders with nothing selected, the
677/// browser falls back to the first option, and the next save writes a value
678/// nobody chose. goingson hit exactly that with a backup-retention default of
679/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
680/// here so the second app gets it without hitting the bug first.
681fn push_options(
682    out: &mut String,
683    field: &Field<'_>,
684    options: &[Choice<'_>],
685    value: &Value<'_>,
686    mut placed: Option<&mut Vec<core::ops::Range<usize>>>,
687) {
688    // Whether the field stated a value at all, which is what decides who owns
689    // the marking. `Value::Absent` is a description that never set one, and it
690    // is NOT the same as a field holding the empty string: an empty value is an
691    // answer ("Any action", "All time") and matches the option carrying it.
692    //
693    // Collapsing the two is what `as_text` does, and doing it here cost a real
694    // bug. A select that marks its own options and offers an empty-valued one
695    // got two options marked: the chosen one said so, and the empty one matched
696    // a value that was never set. Everything downstream keys on this
697    // distinction, so it is read once and passed down.
698    let stated = match value {
699        Value::Absent => None,
700        other => Some(other.as_text()),
701    };
702    let marked_by_hand = options.iter().any(|opt| opt.chosen);
703    let value = stated.unwrap_or_default();
704    // The unanswered state, which HTML has no attribute for: `placeholder` is
705    // not a `<select>` attribute, and the idiom is an empty option that cannot
706    // be chosen back. `disabled` is what stops it being re-selected once the
707    // user has answered, and `selected` is what puts it in the closed control
708    // while the value is empty; together they read as an instruction rather
709    // than as an option.
710    //
711    // `required` keeps working through it rather than around it: the option's
712    // value is empty, so a required select with this showing is invalid, which
713    // is the true report on a question nobody has answered.
714    //
715    // Emitted only while the value is empty, so it does not sit in the open
716    // list once the field is answered. A non-empty value no option carries is a
717    // wrong answer rather than an absent one and takes the stray-option path
718    // below.
719    //
720    // Skipped where the description marks its own options: the instruction
721    // would be a second `selected`, and a list that says which option is the
722    // answer has already said the question is answered.
723    if value.is_empty()
724        && !marked_by_hand
725        && let Some(text) = field.placeholder
726    {
727        out.push_str("<option value=\"\" disabled selected>");
728        escape_into(text, out);
729        out.push_str("</option>");
730    }
731    // Only for a value the field actually stated. A description that marks its
732    // own options has no value for this to be unmatched against, and inventing
733    // an option there would put a sentinel in the list, which is exactly what
734    // kept a self-marking select off the residual seam, since a staged value
735    // matches nothing and the stray got baked in.
736    if stated.is_some() && !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
737        // The one place an escaped value is worth keeping: it is written twice,
738        // as the option's value and as its text.
739        let escaped = escape(value);
740        let _ = write!(
741            out,
742            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
743        );
744    }
745    for opt in options {
746        let at = out.len();
747        out.push_str("<option value=\"");
748        escape_into(opt.value, out);
749        out.push('"');
750        // Two ways an option is the marked one, and a description uses one of
751        // them: the option says so itself, or the field's value names it. See
752        // [`makeover_layout::Choice::chosen`] for why both exist and why this
753        // crate cannot refuse the pair, a caller that sets both gets both
754        // marked, and quasi-declare is where that is caught.
755        //
756        // "Uses one of them" is now enforced rather than hoped for, because the
757        // two are not symmetrical. Value-matching is skipped where no value was
758        // stated, so a self-marking list is read only through `chosen`. Without
759        // that, an option carrying the empty value matches an unset field and
760        // is marked alongside the one the description chose, two `selected`
761        // attributes, which HTML resolves to whichever is last in tree order
762        // rather than to the one that was meant.
763        //
764        // A stated value still marks by value as it always did, so a list that
765        // sets both still gets both, and quasi-declare is still where that is
766        // caught.
767        if opt.chosen || (stated.is_some() && opt.value == value) {
768            out.push_str(" selected");
769        }
770        // `disabled` is what the browser reads, and it says nothing about why.
771        // The reason goes in the option's own text, because a `<select>` gives
772        // its options no room for anything else: no title attribute the
773        // keyboard reaches, no second line, no element inside. So the row reads
774        // "Multi-sample: Drop a second sample onto the keyboard." and is the
775        // one place the precondition can be both attached to its option and
776        // read without a pointer.
777        if opt.unavailable.is_some() {
778            out.push_str(" disabled");
779        }
780        out.push('>');
781        escape_into(opt.label, out);
782        // Both extra strings run into the row's text, for the reason above:
783        // this is the one control with nowhere else to put either of them.
784        // `5e21dcfc` did not invent that rule, it met it.
785        if let Some(detail) = opt.detail {
786            out.push_str(": ");
787            escape_into(detail, out);
788        }
789        if let Some(reason) = opt.unavailable {
790            out.push_str(": ");
791            escape_into(reason, out);
792        }
793        out.push_str("</option>");
794        if let Some(placed) = placed.as_deref_mut() {
795            placed.push(at..out.len());
796        }
797    }
798}
799
800/// The themes, as one `<optgroup>` per variant with a contrast mark per row.
801///
802/// # The grouping comes out of the order, not out of a group list
803///
804/// [`makeover_layout::Field::themes`] arrives sorted by variant and then by
805/// measured contrast, and the run of one variant is the group. So this walks
806/// the list once and opens a new `<optgroup>` whenever the variant changes,
807/// which is the whole of the grouping logic and cannot disagree with the order
808/// the way a separately-carried group list could.
809///
810/// A theme whose variant equals its predecessor's never opens a group, so a
811/// list that arrived unsorted would emit repeated groups rather than silently
812/// merging distant rows. That is the honest report on a description that broke
813/// its own contract, and it is visible on screen rather than in a log.
814///
815/// # The follow row is not in a group
816///
817/// It names no theme and sits in no variant, so it is emitted first and bare.
818/// Grouping it under a heading would be inventing a fourth variant for one row.
819///
820/// # The badge is text, because a `<select>` has nowhere else to put it
821///
822/// A `<select>`'s options take no elements, no second line and no title the
823/// keyboard reaches, which is [`push_options`]' finding about
824/// [`Choice::unavailable`] met a second time. So the tier rides in the option's
825/// own text, in brackets after the name, and it is
826/// [`makeover_layout::Contrast::badge`]'s spelling rather than one invented
827/// here, three renderers picking their own is one picker reading three ways.
828fn push_theme_options(out: &mut String, field: &Field<'_>, value: &str) {
829    if let Some(follow) = field.follows {
830        out.push_str("<option value=\"");
831        escape_into(follow.value, out);
832        out.push('"');
833        if follow.value == value {
834            out.push_str(" selected");
835        }
836        out.push('>');
837        escape_into(follow.label, out);
838        out.push_str("</option>");
839    }
840
841    // A stored id naming a theme that is no longer installed. `push_options`'
842    // reasoning applies unchanged: a value no row carries is a wrong answer
843    // rather than an absent one, and dropping it would silently show the user
844    // a different theme than the one their config names.
845    let known = field.themes.iter().any(|theme| theme.id == value)
846        || field.follows.is_some_and(|follow| follow.value == value);
847    if !value.is_empty() && !known {
848        let escaped = escape(value);
849        let _ = write!(
850            out,
851            "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
852        );
853    }
854
855    let mut open: Option<ThemeVariant> = None;
856    for theme in field.themes {
857        if open != Some(theme.variant) {
858            if open.is_some() {
859                out.push_str("</optgroup>");
860            }
861            out.push_str("<optgroup label=\"");
862            escape_into(theme.variant.heading(), out);
863            out.push_str("\" data-variant=\"");
864            out.push_str(theme.variant.as_str());
865            out.push_str("\">");
866            open = Some(theme.variant);
867        }
868
869        out.push_str("<option value=\"");
870        escape_into(theme.id, out);
871        out.push_str("\" data-contrast=\"");
872        out.push_str(theme.contrast.as_str());
873        out.push('"');
874        if theme.id == value {
875            out.push_str(" selected");
876        }
877        out.push('>');
878        escape_into(theme.name, out);
879        out.push_str(" (");
880        out.push_str(theme.contrast.badge());
881        out.push(')');
882        out.push_str("</option>");
883    }
884    if open.is_some() {
885        out.push_str("</optgroup>");
886    }
887}
888
889/// The control itself, without its label, hint or error.
890fn push_control(
891    out: &mut String,
892    field: &Field<'_>,
893    filling: &Filling<'_>,
894    opts: &Emit,
895    placed: Option<&mut Vec<core::ops::Range<usize>>>,
896) {
897    // Emitted before anything else is computed: a radio group carries its
898    // descriptions on the group rather than on a control, so none of the
899    // attributes below belong to it. A checklist is the same group of
900    // checkboxes, for the same reason.
901    if matches!(field.kind, FieldKind::Radio | FieldKind::Checklist) {
902        push_choice_group(out, field, filling, opts, placed);
903        return;
904    }
905    // The same split one kind along: an interval is two inputs and one
906    // question, so the group carries the error and the descriptions and the
907    // boxes carry what submits.
908    if matches!(field.kind, FieldKind::Interval) {
909        push_interval(out, field, filling, opts);
910        return;
911    }
912
913    let id = filling.id_for(field.name);
914    let placeholder = |out: &mut String| {
915        if let Some(text) = field.placeholder {
916            out.push_str(" placeholder=\"");
917            escape_into(text, out);
918            out.push('"');
919        }
920    };
921
922    match field.kind {
923        // Both multi-line kinds are a `<textarea>`, and the markdown one says so
924        // in an attribute rather than in a class: what the value *is* is not a
925        // styling hook, and a progressive enhancement looking for editors to
926        // upgrade needs a selector that survives `Emit`'s class prefixing.
927        // Without the mark, a described editor is a plain box and the four
928        // hand-written MNW editors have nothing to convert onto.
929        //
930        // `data-format` and not `data-value`: this names the shape of the
931        // value, and `facet` already spends `data-facet-value` on carrying an
932        // actual one. Two attributes a letter apart meaning opposite things is
933        // how a renderer's own vocabulary starts drifting.
934        kind if kind.multiline() => {
935            let rich = matches!(kind, FieldKind::Rich);
936            if rich {
937                push_editor_open(out, opts);
938            }
939            out.push_str("<textarea class=\"");
940            push_class(out, "field", opts);
941            out.push('"');
942            if rich {
943                out.push_str(" data-format=\"markdown\"");
944            }
945            push_control_attributes(out, field, filling, &id, field.name);
946            placeholder(out);
947            out.push('>');
948            escape_into(filling.value.as_text(), out);
949            out.push_str("</textarea>");
950            if rich {
951                push_editor_close(out, opts);
952            }
953        }
954        FieldKind::Select => {
955            out.push_str("<select class=\"");
956            push_class(out, "field", opts);
957            out.push('"');
958            push_control_attributes(out, field, filling, &id, field.name);
959            out.push('>');
960            // A select described with no options emits an empty select, which
961            // says so on screen rather than in a log. That is the description's
962            // own position on `Field::options`, not a fallback invented here.
963            push_options(out, field, field.options, &filling.value, placed);
964            out.push_str("</select>");
965        }
966        // The one place this renderer emits `<optgroup>`, and it emits it
967        // because the description finally says there is a group. The measured
968        // history is the argument: `optgroup` appears at one live site in the
969        // whole tree, and the two apps that had grouped theme pickers lost the
970        // grouping the moment they were described, because `Choice` is a value
971        // and a label and a group is neither.
972        FieldKind::Theme => {
973            out.push_str("<select class=\"");
974            push_class(out, "field", opts);
975            out.push('"');
976            push_control_attributes(out, field, filling, &id, field.name);
977            out.push('>');
978            push_theme_options(out, field, filling.value.as_text());
979            out.push_str("</select>");
980        }
981        FieldKind::Checkbox => {
982            out.push_str("<label class=\"");
983            push_class(out, "form-checkbox-label", opts);
984            out.push_str("\"><input type=\"checkbox\"");
985            push_control_attributes(out, field, filling, &id, field.name);
986            if matches!(filling.value, Value::On(true)) {
987                out.push_str(" checked");
988            }
989            out.push_str("><span>");
990            escape_into(field.label, out);
991            push_required_marker(out, field, opts);
992            out.push_str("</span></label>");
993        }
994        // A secret never carries its value into the markup. `FieldKind::secret`
995        // is documented as a value that must not be round-tripped through
996        // anything that might persist it, and the DOM is such a thing: it is
997        // read by every extension on the page and is the first thing a crash
998        // reporter serialises. Neither app pre-fills one today, so this costs
999        // nothing and closes the door before something does.
1000        FieldKind::Secret => {
1001            out.push_str("<input type=\"password\" class=\"");
1002            push_class(out, "field", opts);
1003            out.push('"');
1004            push_control_attributes(out, field, filling, &id, field.name);
1005            placeholder(out);
1006            out.push('>');
1007        }
1008        // A file input carries no value, and this is the browser's rule rather
1009        // than a preference: setting one from markup is refused, because a page
1010        // that could preselect a path could read a file the user never offered.
1011        // Nothing upstream needs to know, which is why the exception is here.
1012        FieldKind::File => {
1013            out.push_str("<input type=\"file\" class=\"");
1014            push_class(out, "field", opts);
1015            out.push('"');
1016            push_control_attributes(out, field, filling, &id, field.name);
1017            push_accept(out, field);
1018            if field.multiple {
1019                out.push_str(" multiple");
1020            }
1021            out.push('>');
1022        }
1023        kind => {
1024            let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
1025            push_class(out, "field", opts);
1026            out.push('"');
1027            push_control_attributes(out, field, filling, &id, field.name);
1028            placeholder(out);
1029            out.push_str(" value=\"");
1030            escape_into(filling.value.as_text(), out);
1031            out.push_str("\">");
1032        }
1033    }
1034}
1035
1036/// The chrome a markdown field gets and a plain textarea does not: the two
1037/// modes, and the pane a preview lands in.
1038///
1039/// # Why this is the one field with markup around it
1040///
1041/// [`FieldKind::Rich`]'s own doc says the mark buys a renderer permission to
1042/// offer a preview or a syntax pass, and that a renderer with neither draws a
1043/// textarea. A renderer taking the permission and emitting the same box as
1044/// [`FieldKind::Textarea`] leaves an app converting onto the member with less
1045/// than it had written by hand: MNW's `partial-item-text-editor.js` has a
1046/// Write/Preview pair and a pane behind it, and describing the field without
1047/// this would delete both. So the pair is here, on `facet`'s argument one
1048/// field down, the markup it replaces is not markup an app is keeping.
1049///
1050/// # Nothing here renders markdown, and that is where the sanitising stays
1051///
1052/// The pane arrives empty and this crate never turns a value into markup.
1053/// Converting markdown is the host's, which is where the sanitiser already is:
1054/// MNW renders through `docengine` over ammonia and holds an allowlist beside
1055/// it. A converter here would move that guarantee into a crate with no view of
1056/// the host's content-security posture, and `Rich`'s doc is explicit that a
1057/// host with its own sanitiser still owns it. What this emits is a hook, and
1058/// whatever fills it fills it with markup it has already made safe.
1059///
1060/// # The direction the enhancement runs
1061///
1062/// [`crate::stylesheet`]'s rule for a showing region, and for its reason: a
1063/// control rendered into a document with no script is a control that looks live
1064/// and answers nothing. Nothing is hidden here and no control is shown until
1065/// whatever binds the editor sets `data-ready` on the wrapper, so a reader with
1066/// no script gets the textarea alone and a reader with script gets the modes. A bound editor says which mode it is in with
1067/// `data-mode`, and [`editor_rules`] reads that.
1068fn push_editor_open(out: &mut String, opts: &Emit) {
1069    // The mark sits on the wrapper as well as on the control, saying one thing
1070    // about two: this control's value is markdown, and this editor edits
1071    // markdown. The rules gate on the wrapper and they are attribute rules
1072    // rather than class rules for `data-format`'s own reason, the gate has to
1073    // survive `Emit`'s class prefixing, because the enhancement selects on it
1074    // too.
1075    out.push_str("<div data-format=\"markdown\"><div class=\"");
1076    push_class(out, "form-editor-modes", opts);
1077    out.push_str("\">");
1078    push_mode(out, "write", opts.write_label, true, opts);
1079    push_mode(out, "preview", opts.preview_label, false, opts);
1080    out.push_str("</div>");
1081}
1082
1083/// One of the two modes, as a segment of the pair.
1084///
1085/// [`crate::option_class`] for [`Selector::Segmented`] rather than a name of
1086/// its own: a Write/Preview pair is a segmented control, and spelling it as one
1087/// gets it the depth, the focus ring and the chosen state every described
1088/// selector gets, from rules that already exist. The words come from [`Emit`]:
1089/// a description carrying them would be choosing them for the terminal as
1090/// well, and this crate choosing them would be choosing a language.
1091fn push_mode(out: &mut String, mode: &str, label: &str, chosen: bool, opts: &Emit) {
1092    out.push_str("<button type=\"button\" class=\"");
1093    push_class(out, crate::option_class(Selector::Segmented), opts);
1094    if chosen {
1095        // The sheet keys the held-in segment on the class and a screen reader
1096        // reads the attribute. Both, because they are two readings of one fact,
1097        // which is the arrangement a facet value already has.
1098        out.push_str(" chosen");
1099    }
1100    let _ = write!(
1101        out,
1102        "\" data-editor-mode=\"{mode}\" aria-pressed=\"{chosen}\">"
1103    );
1104    escape_into(label, out);
1105    out.push_str("</button>");
1106}
1107
1108/// The preview pane, and the wrapper closing over both halves.
1109fn push_editor_close(out: &mut String, opts: &Emit) {
1110    out.push_str("<div class=\"");
1111    push_class(out, "form-editor-preview", opts);
1112    // `data-editor-preview` and not an id: a form appears twice in a document
1113    // often enough that `Filling::id_prefix` exists for it, and a binder holding
1114    // the control can reach this without either of them being unique.
1115    out.push_str("\" data-editor-preview></div></div>");
1116}
1117
1118/// The rules the markdown editor's chrome needs.
1119///
1120/// The one place this module writes CSS. The class names [`field_html`] emits
1121/// are goingson's and are deliberately unruled, `.form-group`, `.form-label`,
1122/// `.form-hint` and `.form-error` are the app's own, and phase A emits only what
1123/// it can generate from the description, but the two names here have no app
1124/// counterpart to keep, because the chrome did not exist before the member did.
1125///
1126/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
1127/// off a plain textarea, and every rule that hides content is gated on
1128/// `data-ready` as well, which is what keeps them out of a document with no
1129/// script.
1130pub(crate) fn editor_rules(opts: &Emit) -> String {
1131    let mut css = String::new();
1132    let modes = class("form-editor-modes", opts);
1133    let preview = class("form-editor-preview", opts);
1134    let field = class("field", opts);
1135
1136    // Hidden until something binds the editor, which is the whole argument in
1137    // `push_editor_open`.
1138    let _ = writeln!(
1139        css,
1140        "[data-format=\"markdown\"] > .{modes} {{\n    display: none;\n}}"
1141    );
1142    // Block, and nothing about how the two segments sit in it. A button is
1143    // inline already, so they make a row without this crate saying so, and
1144    // saying so is where a gap would follow, a magnitude, and
1145    // `makeover-geometry`'s.
1146    let _ = writeln!(
1147        css,
1148        "[data-format=\"markdown\"][data-ready] > .{modes} {{\n    display: block;\n}}"
1149    );
1150
1151    // The pane is empty until the host fills it, so it is out of flow in every
1152    // state but the one where a bound editor is showing it. An empty box under
1153    // the control is chrome claiming a preview nobody rendered.
1154    let _ = writeln!(
1155        css,
1156        "[data-format=\"markdown\"] > .{preview} {{\n    display: none;\n}}"
1157    );
1158    let _ = writeln!(
1159        css,
1160        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
1161         {{\n    display: block;\n}}"
1162    );
1163    // One at a time. The source and the preview are the same content read two
1164    // ways, and a field showing both answers its own question twice.
1165    let _ = writeln!(
1166        css,
1167        "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
1168         {{\n    display: none;\n}}"
1169    );
1170
1171    // The pane stands where the control stood, so it reads as the surface the
1172    // control was: `.field` is a well, and this is the well it stands in for.
1173    // Nothing about size, how tall a preview is is the app's, the way the
1174    // height of a track is.
1175    let _ = write!(
1176        css,
1177        "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
1178        crate::depth_declarations(Depth::Well)
1179    );
1180
1181    css
1182}
1183
1184/// The rules a field's group needs: its label, its hint, its message, and the
1185/// arrangement of the controls that answer one question.
1186///
1187/// These were the apps' names from phase A, left unruled so that adoption would
1188/// delete goingson's `renderFormField` rather than restyle anything. Adoption
1189/// happened and the argument went with it: a described form in an app that had
1190/// never written the rules drew its label as body text and its error as a plain
1191/// sentence, and MNW was that app. wiki `look-restoration`: the renderer owns
1192/// the look.
1193///
1194/// The values are the ones goingson shipped, less the group's own margin. A
1195/// form spaces its groups with a gap, so a margin here would space them twice;
1196/// an app laying groups out in normal flow keeps a margin of its own. The radio,
1197/// checkbox, reason and interval rules came from quasi-webview's arrangement
1198/// sheet unchanged, where they styled names this crate emits.
1199///
1200/// `visible` is the message's state rather than decoration. goingson's scripts
1201/// raise and lower it on a message that stays in the document, and this crate
1202/// writes it on every message it emits, so a lowered message is hidden and a
1203/// written one shows.
1204///
1205/// `has-error` tones the label. The control already carries the danger edge
1206/// through `aria-invalid`; the label is what a reader scanning a long form reads
1207/// first, and it is the part of the group that says which question failed.
1208pub(crate) fn group_rules(opts: &Emit) -> String {
1209    let group = class("form-group", opts);
1210    let label = class("form-label", opts);
1211    let hint = class("form-hint", opts);
1212    let error = class("form-error", opts);
1213    let radios = class("form-radio-group", opts);
1214    let checklist = class("form-checklist", opts);
1215    let radio = class("form-radio-label", opts);
1216    let checkbox = class("form-checkbox-label", opts);
1217    let reason = class("form-option-reason", opts);
1218    let detail = class("form-option-detail", opts);
1219    let interval = class("form-interval", opts);
1220    let danger = Tone::Danger.token();
1221    let mut css = String::new();
1222
1223    let _ = writeln!(
1224        css,
1225        ".{label} {{\n    display: block;\n    margin-block-end: var(--gap-bound);\n    color: var(--content);\n    font-weight: bold;\n}}"
1226    );
1227    let _ = writeln!(
1228        css,
1229        ".{group}.has-error > .{label} {{\n    color: var(--{danger});\n}}"
1230    );
1231    let _ = writeln!(
1232        css,
1233        ".{hint} {{\n    margin-block-start: var(--gap-bound);\n    color: var(--content-secondary);\n    font-size: var(--text-note);\n}}"
1234    );
1235    let _ = writeln!(
1236        css,
1237        ".{error} {{\n    margin-block-start: var(--gap-bound);\n    color: var(--{danger});\n    font-weight: bold;\n}}"
1238    );
1239    let _ = writeln!(css, ".{error}:not(.visible) {{\n    display: none;\n}}");
1240
1241    // A radio group is a stack of labelled choices, and a choice may say why:
1242    // the box beside its label rather than centred over it. A checklist is the
1243    // same stack with a box that stays ticked.
1244    let _ = writeln!(
1245        css,
1246        ".{radios},\n.{checklist} {{\n    display: flex;\n    flex-direction: column;\n    gap: var(--gap-peer);\n}}"
1247    );
1248    let _ = writeln!(
1249        css,
1250        ".{radio},\n.{checkbox} {{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: baseline;\n    gap: var(--gap-bound);\n}}"
1251    );
1252    // An option's second line sits under its label rather than running along
1253    // it. `push_choice_group` says why it is its own element: a radio group has
1254    // room, so the sentence does not have to be run into the label.
1255    //
1256    // `display: block` was that same intent and it never worked. The label is a
1257    // flex row and an outer `display` on a flex item is ignored, so the detail
1258    // laid out as another item on the label's line: MNW's project wizard drew
1259    // "Audio Upload and stream audio files." where the Askama form it replaced
1260    // drew the sentence underneath. The row wraps and both spans take a whole
1261    // line of it, which is what actually puts them under the label.
1262    //
1263    // Both spans, because an unavailable option's reason is the same shape as a
1264    // detail and was failing the same way. MNW carried both rules in its own
1265    // sheet, pointing here.
1266    let _ = writeln!(css, ".{reason},\n.{detail} {{\n    flex-basis: 100%;\n}}");
1267    let _ = writeln!(
1268        css,
1269        ".{interval} {{\n    display: flex;\n    align-items: center;\n    gap: var(--gap-bound);\n}}"
1270    );
1271    css
1272}
1273
1274/// The rule a field's unit needs.
1275///
1276/// Nothing emitted a unit before `Field::unit` existed, so there was no app
1277/// rule to keep.
1278///
1279/// One declaration, and it is the whole look. A unit is a fact about the number
1280/// beside it rather than a second thing to read, so it takes the muted content
1281/// intent, the same reading `.figure-caption` and `.track-tick` take, and for
1282/// the same reason.
1283///
1284/// And where it sits, which the first version left to the flow and got wrong. A
1285/// control fills its group's width, so the span after it wrapped onto a line of
1286/// its own and "min" hung under the box it measures. A group carrying a unit is
1287/// two columns instead: the control and its unit share the first row's line,
1288/// and the label, the hint, the note and the message span both. The control's
1289/// track is `auto`, so it is as wide as the control and the unit reads straight
1290/// after the number; the spare room goes to the unit's track, where it is
1291/// empty. The other way round put "min" at the far edge of the pane.
1292/// The rules a field's note needs.
1293///
1294/// Nothing emitted a note before [`Field::note`] existed, so there was no app
1295/// rule to keep.
1296///
1297/// Colour only, and the tones are the four a badge carries. The bare class is
1298/// `content` rather than `content-muted`: a note is a consequence the user is
1299/// meant to read before answering, so muting it by default would be this crate
1300/// deciding it does not matter.
1301pub(crate) fn note_rules(opts: &Emit) -> String {
1302    let note = class("form-note", opts);
1303    let mut css = String::new();
1304    let _ = writeln!(css, ".{note} {{\n    color: var(--content);\n}}");
1305    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1306        let _ = writeln!(
1307            css,
1308            ".{note}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
1309            tone.token()
1310        );
1311    }
1312    css
1313}
1314
1315/// The mark a compulsory field's label carries, where it carries one.
1316///
1317/// [`Emit::required_marker`](crate::Emit::required_marker) holds the copy and
1318/// the reasoning; what is decided here is that the mark rides *inside* the
1319/// label, after its text, which is where both sibling renderers put it.
1320///
1321/// Wrapped rather than run into the text, for one reason: the control beside it
1322/// already carries the `required` attribute, so a screen reader that also read
1323/// this would say the same thing twice. `aria-hidden` keeps the mark to the
1324/// eye, which is the channel that was missing.
1325///
1326/// Unclassed, and that is deliberate. Every name in [`FIELD_CLASSES`] is owed a
1327/// rule by the generated sheet, and there is no rule here worth writing: the
1328/// mark is part of the label's own line, in the label's own colour, at the
1329/// label's own weight. A class would be a hook for a look this crate has no
1330/// opinion about, and the space before it is a literal for the same reason the
1331/// terminal's is, a gap inside a run of text is not a magnitude
1332/// `makeover-geometry` has any business naming.
1333fn push_required_marker(out: &mut String, field: &Field<'_>, opts: &Emit) {
1334    if !field.required || opts.required_marker.is_empty() {
1335        return;
1336    }
1337    out.push_str(" <span aria-hidden=\"true\">");
1338    escape_into(opts.required_marker, out);
1339    out.push_str("</span>");
1340}
1341
1342pub(crate) fn unit_rules(opts: &Emit) -> String {
1343    let unit = class("form-unit", opts);
1344    let group = class("form-group", opts);
1345    let mut css = String::new();
1346    let _ = writeln!(css, ".{unit} {{\n    color: var(--content-muted);\n}}");
1347    let _ = writeln!(
1348        css,
1349        ".{group}:has(> .{unit}) {{\n    display: grid;\n    grid-template-columns: auto minmax(0, 1fr);\n    column-gap: var(--gap-bound);\n    align-items: center;\n}}"
1350    );
1351    let _ = writeln!(
1352        css,
1353        ".{group}:has(> .{unit}) > :not(.{unit}, input, select, textarea) {{\n    grid-column: 1 / -1;\n}}"
1354    );
1355    css
1356}
1357
1358/// The rules an option's second line needs.
1359///
1360/// [`unit_rules`]' argument: rule what has no app counterpart to keep. An
1361/// unruled second line renders identically to the label it sits under, which is
1362/// a worse default than the hand-written markup it replaces.
1363///
1364/// Colour only, and muted, which is the same reading `.form-unit` and
1365/// `.form-suggestion-detail` take: the line orients the label rather than
1366/// competing with it. Nothing about placement or spacing, for `unit_rules`'
1367/// reason, a magnitude asserted here belongs to `makeover-geometry`.
1368pub(crate) fn option_detail_rules(opts: &Emit) -> String {
1369    let detail = class("form-option-detail", opts);
1370    let mut css = String::new();
1371    let _ = writeln!(css, ".{detail} {{\n    color: var(--content-muted);\n}}");
1372    css
1373}
1374
1375/// The rules a field's suggestion list needs.
1376///
1377/// [`editor_rules`]' precedent and its argument: the class names this module's
1378/// markup emits are the apps' own and stay unruled, and these three have no app
1379/// counterpart to keep because the list did not exist before the member did.
1380/// The markup is `quasi-webview`'s rather than this crate's, a suggestion
1381/// source is a route, which no description layer carries, and the look is
1382/// still this crate's, because a renderer inventing how a list of candidates
1383/// reads is the drift the vocabulary check exists to catch.
1384///
1385/// # In flow, and not floating
1386///
1387/// An absolutely positioned list needs a positioned ancestor, and the only
1388/// candidate is `.form-group`, which is the app's class and deliberately
1389/// unruled here. So the list stands under the control and moves what is below
1390/// it. An app that wants it over the form positions the group itself, which is
1391/// one declaration and is the app's call about its own layout.
1392///
1393/// `:empty` is what takes it away, so a route that answers with no candidates
1394/// leaves no box behind. It is a content question rather than a whitespace one
1395/// only because the emitter writes no whitespace inside the container, which is
1396/// stated in `quasi-webview`'s own test.
1397///
1398/// # Nothing about size
1399///
1400/// No height, no scroll ceiling, no padding. How tall a list of candidates gets
1401/// to be before it scrolls is a magnitude, and magnitudes are
1402/// `makeover-geometry`'s, exactly as the preview pane's height is.
1403pub(crate) fn suggestion_rules(opts: &Emit) -> String {
1404    let list = class("form-suggestions", opts);
1405    let entry = class("form-suggestion", opts);
1406    let detail = class("form-suggestion-detail", opts);
1407    let mut css = String::new();
1408
1409    let _ = writeln!(css, ".{list}:empty {{\n    display: none;\n}}");
1410    // Over what it covers, which is what a list of candidates is even in flow:
1411    // it is answering the box above it and goes away when the answer is taken.
1412    css.push_str(&crate::depth_rule(&list, Depth::Overlay));
1413    // An entry answers a click, so it gets every state one implies.
1414    css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
1415    // The keyboard's highlight and the pointer's are the same surface. They are
1416    // the same fact told two ways, and a list where arrowing and hovering look
1417    // different is a list that has two current entries.
1418    //
1419    // Keyed on `aria-selected` rather than on a class, for the reason
1420    // `aria-invalid` carries the error state: it is what a screen reader hears,
1421    // so a look keyed on it cannot drift from what is announced. A `.current`
1422    // class would also be a name apps already spell for their own reasons:
1423    // the MNW server has one, and unlayered app CSS beats this layer in
1424    // silence.
1425    let _ = writeln!(
1426        css,
1427        ".{entry}[aria-selected=\"true\"] {{\n    background: var(--hover-surface);\n}}"
1428    );
1429    // The second line, muted rather than disabled. A candidate carries no
1430    // `unavailable`, and what sits beside the label now is what tells one row
1431    // from another that reads the same. Disabled would say the row cannot be
1432    // picked, which is the opposite of what the detail is for.
1433    let _ = writeln!(css, ".{detail} {{\n    color: var(--content-muted);\n}}");
1434
1435    css
1436}
1437
1438/// One field, as the group the app drops into its form.
1439///
1440/// The shape is goingson's, down to the class names, so adoption there deletes
1441/// `renderFormField` rather than restyling anything. That is also why the class
1442/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
1443/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
1444/// emits only what it can generate from the description. Whether they should
1445/// move into the description is the next question this raises, not one it
1446/// answers.
1447///
1448/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
1449/// nothing drawn, which is what [`FieldKind::visible`] means.
1450///
1451/// The error marks the group as well as the control. That is
1452/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
1453/// cannot find the group from the message, so the group has to be told.
1454///
1455/// ```
1456/// use makeover_layout::{Field, FieldKind, Value};
1457/// use makeover_webview::{Emit, form::{Filling, field_html}};
1458///
1459/// let field = Field::new(FieldKind::Text, "title", "Title");
1460/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
1461///
1462/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
1463/// assert!(html.contains(r#"value="Ship it""#));
1464/// ```
1465#[must_use]
1466pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
1467    let mut html = String::new();
1468    field_html_into(field, filling, opts, &mut html);
1469    html
1470}
1471
1472/// One field, written into a buffer the caller already has.
1473///
1474/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
1475/// these, so a host building one should hold a single buffer and append each
1476/// field into it rather than take a `String` per field and concatenate.
1477pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
1478    emit_field(field, filling, opts, out, None);
1479}
1480
1481/// One field, saying where each of its options landed.
1482///
1483/// Byte-identical to [`field_html_into`], and it appends one entry to `placed`
1484/// per option, in order: the offsets in `out` between which that option was
1485/// written. A select's option is its `<option>`; a radio group's or a
1486/// checklist's is its `<label>`, which holds the input. Nothing is appended for
1487/// a field that offers no options.
1488///
1489/// Same reason as [`crate::list::cells_html_placed`]: a caller compiling a
1490/// described screen into a template has to know which bytes one option
1491/// produced, and two options with the same label are the same bytes.
1492pub fn field_html_placed(
1493    field: &Field<'_>,
1494    filling: &Filling<'_>,
1495    opts: &Emit,
1496    out: &mut String,
1497    placed: &mut Vec<core::ops::Range<usize>>,
1498) {
1499    emit_field(field, filling, opts, out, Some(placed));
1500}
1501
1502fn emit_field(
1503    field: &Field<'_>,
1504    filling: &Filling<'_>,
1505    opts: &Emit,
1506    out: &mut String,
1507    placed: Option<&mut Vec<core::ops::Range<usize>>>,
1508) {
1509    let id = filling.id_for(field.name);
1510
1511    if !field.kind.visible() {
1512        // Name only, no id: a hidden field is never pointed at by a label or a
1513        // description, so the one attribute it needs is the one that submits.
1514        out.push_str("<input type=\"hidden\" name=\"");
1515        escape_into(field.name, out);
1516        out.push_str("\" value=\"");
1517        escape_into(filling.value.as_text(), out);
1518        out.push_str("\">");
1519        return;
1520    }
1521
1522    out.push_str("<div class=\"");
1523    push_class(out, "form-group", opts);
1524    if field.invalid() {
1525        out.push_str(" has-error");
1526    }
1527    if field.extended {
1528        // The disclosure that hides these is a property of the form, not of the
1529        // field, so the field is marked and the app opens or closes the group.
1530        out.push_str("\" data-extended=\"true");
1531    }
1532    out.push_str("\">");
1533
1534    // A checkbox labels itself, on the right of the box. Both apps special-case
1535    // this inline today, which is the tell that it belongs in the description;
1536    // `FieldKind::labels_itself` is where it went.
1537    if !field.kind.labels_itself() {
1538        out.push_str("<label class=\"");
1539        push_class(out, "form-label", opts);
1540        // A group control is named *by* its label rather than pointing at it,
1541        // so the two carry opposite halves of the association. See
1542        // `is_group_control`.
1543        if is_group_control(field.kind) {
1544            let _ = write!(out, "\" id=\"{id}-label\">");
1545        } else {
1546            let _ = write!(out, "\" for=\"{id}\">");
1547        }
1548        escape_into(field.label, out);
1549        push_required_marker(out, field, opts);
1550        out.push_str("</label>");
1551    }
1552
1553    push_control(out, field, filling, opts, placed);
1554
1555    // Adjacent text, because HTML has no unit attribute and inventing one would
1556    // be markup nothing reads. Pointed at by `aria-describedby` so it is not
1557    // decoration a screen reader skips: the number and what it is measured in
1558    // are one fact, and reading the first without the second is reading it
1559    // wrong.
1560    if let Some(unit) = field.shown_unit() {
1561        out.push_str("<span class=\"");
1562        push_class(out, "form-unit", opts);
1563        let _ = write!(out, "\" id=\"{id}-unit\">");
1564        escape_into(unit, out);
1565        out.push_str("</span>");
1566    }
1567
1568    if let Some(hint) = field.hint {
1569        out.push_str("<div class=\"");
1570        push_class(out, "form-hint", opts);
1571        let _ = write!(out, "\" id=\"{id}-hint\">");
1572        escape_into(hint, out);
1573        out.push_str("</div>");
1574    }
1575    // A consequence of the answer, between the standing help and the failure.
1576    // The tone rides on `data-tone`, the same attribute every other toned
1577    // thing in this crate takes, and it also picks the live region: Warning
1578    // and Danger are assertive, which is quasi-webview's own reading at
1579    // `node.rs:1403` and is honoured here rather than restated differently.
1580    if let Some((tone, note)) = field.note {
1581        out.push_str("<div class=\"");
1582        push_class(out, "form-note", opts);
1583        let assertive = matches!(tone, Tone::Warning | Tone::Danger);
1584        let _ = write!(
1585            out,
1586            "\" id=\"{id}-note\" role=\"{}\"",
1587            if assertive { "alert" } else { "status" }
1588        );
1589        // Neutral is the bare class rather than a variant, matching every
1590        // other toned component here: it is the absence of a status.
1591        if tone != Tone::Neutral {
1592            let _ = write!(out, " data-tone=\"{}\"", tone.token());
1593        }
1594        out.push('>');
1595        escape_into(note, out);
1596        out.push_str("</div>");
1597    }
1598    if let Some(Markup(markup)) = filling.trailing {
1599        out.push_str(markup);
1600    }
1601    if let Some(error) = field.error {
1602        out.push_str("<div class=\"");
1603        push_class(out, "form-error", opts);
1604        let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
1605        escape_into(error, out);
1606        out.push_str("</div>");
1607    }
1608
1609    out.push_str("</div>");
1610}
1611
1612#[cfg(test)]
1613mod tests;