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