Skip to main content

makeover_webview/
form.rs

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