Skip to main content

makeover_webview/
form.rs

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