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