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'&' => "&",
249 b'<' => "<",
250 b'>' => ">",
251 b'"' => """,
252 b'\'' => "'",
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(
622 out: &mut String,
623 field: &Field<'_>,
624 filling: &Filling<'_>,
625 opts: &Emit,
626 mut placed: Option<&mut Vec<core::ops::Range<usize>>>,
627) {
628 let id = filling.id_for(field.name);
629 let value = filling.value.as_text();
630 let name = escape(field.name);
631 let several = field.kind.takes_several();
632 let (group_class, role, label_class, input) = if several {
633 ("form-checklist", "group", "form-checkbox-label", "checkbox")
634 } else {
635 (
636 "form-radio-group",
637 "radiogroup",
638 "form-radio-label",
639 "radio",
640 )
641 };
642
643 out.push_str("<div class=\"");
644 push_class(out, group_class, opts);
645 let _ = write!(out, "\" role=\"{role}\" aria-labelledby=\"{id}-label\"");
646 if field.invalid() {
647 out.push_str(" aria-invalid=\"true\"");
648 }
649 push_described_by(out, field, &id);
650 out.push('>');
651
652 // A group described with no options emits an empty group, for the reason
653 // `Field::options` gives: an app whose option list has not loaded has
654 // exactly that, and an empty group says so on screen rather than in a log.
655 for (index, opt) in field.options.iter().enumerate() {
656 let at = out.len();
657 out.push_str("<label class=\"");
658 push_class(out, label_class, opts);
659 let _ = write!(
660 out,
661 "\"><input type=\"{input}\" id=\"{id}-{index}\" name=\"{name}\" value=\""
662 );
663 escape_into(opt.value, out);
664 out.push('"');
665 if opt.chosen || (!several && opt.value == value) {
666 out.push_str(" checked");
667 }
668 if field.required && !several {
669 out.push_str(" required");
670 }
671 // A radio group has room a `<select>` does not, so the reason gets its
672 // own element beside the label rather than being run into it. The class
673 // is what a stylesheet mutes; the text is there either way, which is
674 // the half that matters — the finding was a greyed control with its
675 // explanation behind a hover.
676 if opt.unavailable.is_some() {
677 out.push_str(" disabled");
678 }
679 out.push_str("><span>");
680 escape_into(opt.label, out);
681 out.push_str("</span>");
682 // What picking it means, on the line under the label. `5e21dcfc`, and
683 // the same treatment the reason gets one line down: a radio group has
684 // room, so the sentence sits in its own element rather than being run
685 // into the label the way a `<select>`'s has to be.
686 //
687 // Before the reason, which is the order the two read in: what this
688 // option *is* comes ahead of why it cannot be picked, and an option
689 // carrying both has said two things rather than one long one.
690 if let Some(detail) = opt.detail {
691 out.push_str("<span class=\"");
692 push_class(out, "form-option-detail", opts);
693 out.push_str("\">");
694 escape_into(detail, out);
695 out.push_str("</span>");
696 }
697 if let Some(reason) = opt.unavailable {
698 out.push_str("<span class=\"");
699 push_class(out, "form-option-reason", opts);
700 out.push_str("\">");
701 escape_into(reason, out);
702 out.push_str("</span>");
703 }
704 out.push_str("</label>");
705 if let Some(placed) = placed.as_deref_mut() {
706 placed.push(at..out.len());
707 }
708 }
709
710 out.push_str("</div>");
711}
712
713/// The options of a select: the unanswered instruction, an unmatched current
714/// value carried as its own, then the options themselves.
715///
716/// An option is marked either by [`Choice::chosen`] or by carrying the field's
717/// current value; the stray-option and placeholder paths below key on the value
718/// alone, so a list that marks itself has an empty value and reaches neither.
719///
720/// A select handed a value no option carries renders with nothing selected, the
721/// browser falls back to the first option, and the next save writes a value
722/// nobody chose. goingson hit exactly that with a backup-retention default of
723/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
724/// here so the second app gets it without hitting the bug first.
725fn push_options(
726 out: &mut String,
727 field: &Field<'_>,
728 options: &[Choice<'_>],
729 value: &Value<'_>,
730 mut placed: Option<&mut Vec<core::ops::Range<usize>>>,
731) {
732 // Whether the field stated a value at all, which is what decides who owns
733 // the marking. `Value::Absent` is a description that never set one, and it
734 // is NOT the same as a field holding the empty string: an empty value is an
735 // answer ("Any action", "All time") and matches the option carrying it.
736 //
737 // Collapsing the two is what `as_text` does, and doing it here cost a real
738 // bug. A select that marks its own options and offers an empty-valued one
739 // got two options marked: the chosen one said so, and the empty one matched
740 // a value that was never set. Everything downstream keys on this
741 // distinction, so it is read once and passed down.
742 let stated = match value {
743 Value::Absent => None,
744 other => Some(other.as_text()),
745 };
746 let marked_by_hand = options.iter().any(|opt| opt.chosen);
747 let value = stated.unwrap_or_default();
748 // The unanswered state, which HTML has no attribute for: `placeholder` is
749 // not a `<select>` attribute, and the idiom is an empty option that cannot
750 // be chosen back. `disabled` is what stops it being re-selected once the
751 // user has answered, and `selected` is what puts it in the closed control
752 // while the value is empty; together they read as an instruction rather
753 // than as an option.
754 //
755 // `required` keeps working through it rather than around it: the option's
756 // value is empty, so a required select with this showing is invalid, which
757 // is the true report on a question nobody has answered.
758 //
759 // Emitted only while the value is empty, so it does not sit in the open
760 // list once the field is answered. A non-empty value no option carries is a
761 // wrong answer rather than an absent one and takes the stray-option path
762 // below.
763 //
764 // Skipped where the description marks its own options: the instruction
765 // would be a second `selected`, and a list that says which option is the
766 // answer has already said the question is answered.
767 if value.is_empty()
768 && !marked_by_hand
769 && let Some(text) = field.placeholder
770 {
771 out.push_str("<option value=\"\" disabled selected>");
772 escape_into(text, out);
773 out.push_str("</option>");
774 }
775 // Only for a value the field actually stated. A description that marks its
776 // own options has no value for this to be unmatched against, and inventing
777 // an option there would put a sentinel in the list -- which is exactly what
778 // kept a self-marking select off the residual seam, since a staged value
779 // matches nothing and the stray got baked in.
780 if stated.is_some() && !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
781 // The one place an escaped value is worth keeping: it is written twice,
782 // as the option's value and as its text.
783 let escaped = escape(value);
784 let _ = write!(
785 out,
786 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
787 );
788 }
789 for opt in options {
790 let at = out.len();
791 out.push_str("<option value=\"");
792 escape_into(opt.value, out);
793 out.push('"');
794 // Two ways an option is the marked one, and a description uses one of
795 // them: the option says so itself, or the field's value names it. See
796 // [`makeover_layout::Choice::chosen`] for why both exist and why this
797 // crate cannot refuse the pair -- a caller that sets both gets both
798 // marked, and quasi-declare is where that is caught.
799 //
800 // "Uses one of them" is now enforced rather than hoped for, because the
801 // two are not symmetrical. Value-matching is skipped where no value was
802 // stated, so a self-marking list is read only through `chosen`. Without
803 // that, an option carrying the empty value matches an unset field and
804 // is marked alongside the one the description chose -- two `selected`
805 // attributes, which HTML resolves to whichever is last in tree order
806 // rather than to the one that was meant.
807 //
808 // A stated value still marks by value as it always did, so a list that
809 // sets both still gets both, and quasi-declare is still where that is
810 // caught.
811 if opt.chosen || (stated.is_some() && opt.value == value) {
812 out.push_str(" selected");
813 }
814 // `disabled` is what the browser reads, and it says nothing about why.
815 // The reason goes in the option's own text, because a `<select>` gives
816 // its options no room for anything else: no title attribute the
817 // keyboard reaches, no second line, no element inside. So the row reads
818 // "Multi-sample: Drop a second sample onto the keyboard." and is the
819 // one place the precondition can be both attached to its option and
820 // read without a pointer.
821 if opt.unavailable.is_some() {
822 out.push_str(" disabled");
823 }
824 out.push('>');
825 escape_into(opt.label, out);
826 // Both extra strings run into the row's text, for the reason above:
827 // this is the one control with nowhere else to put either of them.
828 // `5e21dcfc` did not invent that rule, it met it.
829 if let Some(detail) = opt.detail {
830 out.push_str(": ");
831 escape_into(detail, out);
832 }
833 if let Some(reason) = opt.unavailable {
834 out.push_str(": ");
835 escape_into(reason, out);
836 }
837 out.push_str("</option>");
838 if let Some(placed) = placed.as_deref_mut() {
839 placed.push(at..out.len());
840 }
841 }
842}
843
844/// The themes, as one `<optgroup>` per variant with a contrast mark per row.
845///
846/// # The grouping comes out of the order, not out of a group list
847///
848/// [`makeover_layout::Field::themes`] arrives sorted by variant and then by
849/// measured contrast, and the run of one variant is the group. So this walks
850/// the list once and opens a new `<optgroup>` whenever the variant changes,
851/// which is the whole of the grouping logic and cannot disagree with the order
852/// the way a separately-carried group list could.
853///
854/// A theme whose variant equals its predecessor's never opens a group, so a
855/// list that arrived unsorted would emit repeated groups rather than silently
856/// merging distant rows. That is the honest report on a description that broke
857/// its own contract, and it is visible on screen rather than in a log.
858///
859/// # The follow row is not in a group
860///
861/// It names no theme and sits in no variant, so it is emitted first and bare.
862/// Grouping it under a heading would be inventing a fourth variant for one row.
863///
864/// # The badge is text, because a `<select>` has nowhere else to put it
865///
866/// A `<select>`'s options take no elements, no second line and no title the
867/// keyboard reaches, which is [`push_options`]' finding about
868/// [`Choice::unavailable`] met a second time. So the tier rides in the option's
869/// own text, in brackets after the name, and it is
870/// [`makeover_layout::Contrast::badge`]'s spelling rather than one invented
871/// here — three renderers picking their own is one picker reading three ways.
872fn push_theme_options(out: &mut String, field: &Field<'_>, value: &str) {
873 if let Some(follow) = field.follows {
874 out.push_str("<option value=\"");
875 escape_into(follow.value, out);
876 out.push('"');
877 if follow.value == value {
878 out.push_str(" selected");
879 }
880 out.push('>');
881 escape_into(follow.label, out);
882 out.push_str("</option>");
883 }
884
885 // A stored id naming a theme that is no longer installed. `push_options`'
886 // reasoning applies unchanged: a value no row carries is a wrong answer
887 // rather than an absent one, and dropping it would silently show the user
888 // a different theme than the one their config names.
889 let known = field.themes.iter().any(|theme| theme.id == value)
890 || field.follows.is_some_and(|follow| follow.value == value);
891 if !value.is_empty() && !known {
892 let escaped = escape(value);
893 let _ = write!(
894 out,
895 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
896 );
897 }
898
899 let mut open: Option<ThemeVariant> = None;
900 for theme in field.themes {
901 if open != Some(theme.variant) {
902 if open.is_some() {
903 out.push_str("</optgroup>");
904 }
905 out.push_str("<optgroup label=\"");
906 escape_into(theme.variant.heading(), out);
907 out.push_str("\" data-variant=\"");
908 out.push_str(theme.variant.as_str());
909 out.push_str("\">");
910 open = Some(theme.variant);
911 }
912
913 out.push_str("<option value=\"");
914 escape_into(theme.id, out);
915 out.push_str("\" data-contrast=\"");
916 out.push_str(theme.contrast.as_str());
917 out.push('"');
918 if theme.id == value {
919 out.push_str(" selected");
920 }
921 out.push('>');
922 escape_into(theme.name, out);
923 out.push_str(" (");
924 out.push_str(theme.contrast.badge());
925 out.push(')');
926 out.push_str("</option>");
927 }
928 if open.is_some() {
929 out.push_str("</optgroup>");
930 }
931}
932
933/// The control itself, without its label, hint or error.
934fn push_control(
935 out: &mut String,
936 field: &Field<'_>,
937 filling: &Filling<'_>,
938 opts: &Emit,
939 placed: Option<&mut Vec<core::ops::Range<usize>>>,
940) {
941 // Emitted before anything else is computed: a radio group carries its
942 // descriptions on the group rather than on a control, so none of the
943 // attributes below belong to it. A checklist is the same group of
944 // checkboxes, for the same reason.
945 if matches!(field.kind, FieldKind::Radio | FieldKind::Checklist) {
946 push_choice_group(out, field, filling, opts, placed);
947 return;
948 }
949 // The same split one kind along: an interval is two inputs and one
950 // question, so the group carries the error and the descriptions and the
951 // boxes carry what submits.
952 if matches!(field.kind, FieldKind::Interval) {
953 push_interval(out, field, filling, opts);
954 return;
955 }
956
957 let id = filling.id_for(field.name);
958 let placeholder = |out: &mut String| {
959 if let Some(text) = field.placeholder {
960 out.push_str(" placeholder=\"");
961 escape_into(text, out);
962 out.push('"');
963 }
964 };
965
966 match field.kind {
967 // Both multi-line kinds are a `<textarea>`, and the markdown one says so
968 // in an attribute rather than in a class: what the value *is* is not a
969 // styling hook, and a progressive enhancement looking for editors to
970 // upgrade needs a selector that survives `Emit`'s class prefixing.
971 // Without the mark, a described editor is a plain box and the four
972 // hand-written MNW editors have nothing to convert onto.
973 //
974 // `data-format` and not `data-value`: this names the shape of the
975 // value, and `facet` already spends `data-facet-value` on carrying an
976 // actual one. Two attributes a letter apart meaning opposite things is
977 // how a renderer's own vocabulary starts drifting.
978 kind if kind.multiline() => {
979 let rich = matches!(kind, FieldKind::Rich);
980 if rich {
981 push_editor_open(out, opts);
982 }
983 out.push_str("<textarea class=\"");
984 push_class(out, "field", opts);
985 out.push('"');
986 if rich {
987 out.push_str(" data-format=\"markdown\"");
988 }
989 push_control_attributes(out, field, filling, &id, field.name);
990 placeholder(out);
991 out.push('>');
992 escape_into(filling.value.as_text(), out);
993 out.push_str("</textarea>");
994 if rich {
995 push_editor_close(out, opts);
996 }
997 }
998 FieldKind::Select => {
999 out.push_str("<select class=\"");
1000 push_class(out, "field", opts);
1001 out.push('"');
1002 push_control_attributes(out, field, filling, &id, field.name);
1003 out.push('>');
1004 // A select described with no options emits an empty select, which
1005 // says so on screen rather than in a log. That is the description's
1006 // own position on `Field::options`, not a fallback invented here.
1007 push_options(out, field, field.options, &filling.value, placed);
1008 out.push_str("</select>");
1009 }
1010 // The one place this renderer emits `<optgroup>`, and it emits it
1011 // because the description finally says there is a group. The measured
1012 // history is the argument: `optgroup` appears at one live site in the
1013 // whole tree, and the two apps that had grouped theme pickers lost the
1014 // grouping the moment they were described, because `Choice` is a value
1015 // and a label and a group is neither.
1016 FieldKind::Theme => {
1017 out.push_str("<select class=\"");
1018 push_class(out, "field", opts);
1019 out.push('"');
1020 push_control_attributes(out, field, filling, &id, field.name);
1021 out.push('>');
1022 push_theme_options(out, field, filling.value.as_text());
1023 out.push_str("</select>");
1024 }
1025 FieldKind::Checkbox => {
1026 out.push_str("<label class=\"");
1027 push_class(out, "form-checkbox-label", opts);
1028 out.push_str("\"><input type=\"checkbox\"");
1029 push_control_attributes(out, field, filling, &id, field.name);
1030 if matches!(filling.value, Value::On(true)) {
1031 out.push_str(" checked");
1032 }
1033 out.push_str("><span>");
1034 escape_into(field.label, out);
1035 push_required_marker(out, field, opts);
1036 out.push_str("</span></label>");
1037 }
1038 // A secret never carries its value into the markup. `FieldKind::secret`
1039 // is documented as a value that must not be round-tripped through
1040 // anything that might persist it, and the DOM is such a thing: it is
1041 // read by every extension on the page and is the first thing a crash
1042 // reporter serialises. Neither app pre-fills one today, so this costs
1043 // nothing and closes the door before something does.
1044 FieldKind::Secret => {
1045 out.push_str("<input type=\"password\" class=\"");
1046 push_class(out, "field", opts);
1047 out.push('"');
1048 push_control_attributes(out, field, filling, &id, field.name);
1049 placeholder(out);
1050 out.push('>');
1051 }
1052 // A file input carries no value, and this is the browser's rule rather
1053 // than a preference: setting one from markup is refused, because a page
1054 // that could preselect a path could read a file the user never offered.
1055 // Nothing upstream needs to know, which is why the exception is here.
1056 FieldKind::File => {
1057 out.push_str("<input type=\"file\" class=\"");
1058 push_class(out, "field", opts);
1059 out.push('"');
1060 push_control_attributes(out, field, filling, &id, field.name);
1061 push_accept(out, field);
1062 if field.multiple {
1063 out.push_str(" multiple");
1064 }
1065 out.push('>');
1066 }
1067 kind => {
1068 let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
1069 push_class(out, "field", opts);
1070 out.push('"');
1071 push_control_attributes(out, field, filling, &id, field.name);
1072 placeholder(out);
1073 out.push_str(" value=\"");
1074 escape_into(filling.value.as_text(), out);
1075 out.push_str("\">");
1076 }
1077 }
1078}
1079
1080/// The chrome a markdown field gets and a plain textarea does not: the two
1081/// modes, and the pane a preview lands in.
1082///
1083/// # Why this is the one field with markup around it
1084///
1085/// [`FieldKind::Rich`]'s own doc says the mark buys a renderer permission to
1086/// offer a preview or a syntax pass, and that a renderer with neither draws a
1087/// textarea. A renderer taking the permission and emitting the same box as
1088/// [`FieldKind::Textarea`] leaves an app converting onto the member with less
1089/// than it had written by hand: MNW's `partial-item-text-editor.js` has a
1090/// Write/Preview pair and a pane behind it, and describing the field without
1091/// this would delete both. So the pair is here, on `facet`'s argument one
1092/// field down -- the markup it replaces is not markup an app is keeping.
1093///
1094/// # Nothing here renders markdown, and that is where the sanitising stays
1095///
1096/// The pane arrives empty and this crate never turns a value into markup.
1097/// Converting markdown is the host's, which is where the sanitiser already is:
1098/// MNW renders through `docengine` over ammonia and holds an allowlist beside
1099/// it. A converter here would move that guarantee into a crate with no view of
1100/// the host's content-security posture, and `Rich`'s doc is explicit that a
1101/// host with its own sanitiser still owns it. What this emits is a hook, and
1102/// whatever fills it fills it with markup it has already made safe.
1103///
1104/// # The direction the enhancement runs
1105///
1106/// [`crate::stylesheet`]'s rule for a showing region, and for its reason: a
1107/// control rendered into a document with no script is a control that looks live
1108/// and answers nothing. Nothing is hidden here and no control is shown until
1109/// whatever binds the editor sets `data-ready` on the wrapper, so a reader with
1110/// no script gets the textarea alone and a reader with script gets the modes. A bound editor says which mode it is in with
1111/// `data-mode`, and [`editor_rules`] reads that.
1112fn push_editor_open(out: &mut String, opts: &Emit) {
1113 // The mark sits on the wrapper as well as on the control, saying one thing
1114 // about two: this control's value is markdown, and this editor edits
1115 // markdown. The rules gate on the wrapper and they are attribute rules
1116 // rather than class rules for `data-format`'s own reason -- the gate has to
1117 // survive `Emit`'s class prefixing, because the enhancement selects on it
1118 // too.
1119 out.push_str("<div data-format=\"markdown\"><div class=\"");
1120 push_class(out, "form-editor-modes", opts);
1121 out.push_str("\">");
1122 push_mode(out, "write", "Write", true, opts);
1123 push_mode(out, "preview", "Preview", false, opts);
1124 out.push_str("</div>");
1125}
1126
1127/// One of the two modes, as a segment of the pair.
1128///
1129/// [`crate::option_class`] for [`Selector::Segmented`] rather than a name of
1130/// its own: a Write/Preview pair is a segmented control, and spelling it as one
1131/// gets it the depth, the focus ring and the chosen state every described
1132/// selector gets, from rules that already exist. The words are written here for
1133/// the reason `facet`'s exclude button writes its own: a description carrying
1134/// them would be choosing them for the terminal as well.
1135fn push_mode(out: &mut String, mode: &str, label: &str, chosen: bool, opts: &Emit) {
1136 out.push_str("<button type=\"button\" class=\"");
1137 push_class(out, crate::option_class(Selector::Segmented), opts);
1138 if chosen {
1139 // The sheet keys the held-in segment on the class and a screen reader
1140 // reads the attribute. Both, because they are two readings of one fact,
1141 // which is the arrangement a facet value already has.
1142 out.push_str(" chosen");
1143 }
1144 let _ = write!(
1145 out,
1146 "\" data-editor-mode=\"{mode}\" aria-pressed=\"{chosen}\">{label}</button>"
1147 );
1148}
1149
1150/// The preview pane, and the wrapper closing over both halves.
1151fn push_editor_close(out: &mut String, opts: &Emit) {
1152 out.push_str("<div class=\"");
1153 push_class(out, "form-editor-preview", opts);
1154 // `data-editor-preview` and not an id: a form appears twice in a document
1155 // often enough that `Filling::id_prefix` exists for it, and a binder holding
1156 // the control can reach this without either of them being unique.
1157 out.push_str("\" data-editor-preview></div></div>");
1158}
1159
1160/// The rules the markdown editor's chrome needs.
1161///
1162/// The one place this module writes CSS. The class names [`field_html`] emits
1163/// are goingson's and are deliberately unruled -- `.form-group`, `.form-label`,
1164/// `.form-hint` and `.form-error` are the app's own, and phase A emits only what
1165/// it can generate from the description -- but the two names here have no app
1166/// counterpart to keep, because the chrome did not exist before the member did.
1167///
1168/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
1169/// off a plain textarea, and every rule that hides content is gated on
1170/// `data-ready` as well, which is what keeps them out of a document with no
1171/// script.
1172pub(crate) fn editor_rules(opts: &Emit) -> String {
1173 let mut css = String::new();
1174 let modes = class("form-editor-modes", opts);
1175 let preview = class("form-editor-preview", opts);
1176 let field = class("field", opts);
1177
1178 // Hidden until something binds the editor, which is the whole argument in
1179 // `push_editor_open`.
1180 let _ = writeln!(
1181 css,
1182 "[data-format=\"markdown\"] > .{modes} {{\n display: none;\n}}"
1183 );
1184 // Block, and nothing about how the two segments sit in it. A button is
1185 // inline already, so they make a row without this crate saying so, and
1186 // saying so is where a gap would follow -- a magnitude, and
1187 // `makeover-geometry`'s.
1188 let _ = writeln!(
1189 css,
1190 "[data-format=\"markdown\"][data-ready] > .{modes} {{\n display: block;\n}}"
1191 );
1192
1193 // The pane is empty until the host fills it, so it is out of flow in every
1194 // state but the one where a bound editor is showing it. An empty box under
1195 // the control is chrome claiming a preview nobody rendered.
1196 let _ = writeln!(
1197 css,
1198 "[data-format=\"markdown\"] > .{preview} {{\n display: none;\n}}"
1199 );
1200 let _ = writeln!(
1201 css,
1202 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
1203 {{\n display: block;\n}}"
1204 );
1205 // One at a time. The source and the preview are the same content read two
1206 // ways, and a field showing both answers its own question twice.
1207 let _ = writeln!(
1208 css,
1209 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
1210 {{\n display: none;\n}}"
1211 );
1212
1213 // The pane stands where the control stood, so it reads as the surface the
1214 // control was: `.field` is a well, and this is the well it stands in for.
1215 // Nothing about size -- how tall a preview is is the app's, the way the
1216 // height of a track is.
1217 let _ = write!(
1218 css,
1219 "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
1220 crate::depth_declarations(Depth::Well)
1221 );
1222
1223 css
1224}
1225
1226/// The rules a field's group needs: its label, its hint, its message, and the
1227/// arrangement of the controls that answer one question.
1228///
1229/// These were the apps' names from phase A, left unruled so that adoption would
1230/// delete goingson's `renderFormField` rather than restyle anything. Adoption
1231/// happened and the argument went with it: a described form in an app that had
1232/// never written the rules drew its label as body text and its error as a plain
1233/// sentence, and MNW was that app. wiki `look-restoration`: the renderer owns
1234/// the look.
1235///
1236/// The values are the ones goingson shipped, less the group's own margin. A
1237/// form spaces its groups with a gap, so a margin here would space them twice;
1238/// an app laying groups out in normal flow keeps a margin of its own. The radio,
1239/// checkbox, reason and interval rules came from quasi-webview's arrangement
1240/// sheet unchanged, where they styled names this crate emits.
1241///
1242/// `visible` is the message's state rather than decoration. goingson's scripts
1243/// raise and lower it on a message that stays in the document, and this crate
1244/// writes it on every message it emits, so a lowered message is hidden and a
1245/// written one shows.
1246///
1247/// `has-error` tones the label. The control already carries the danger edge
1248/// through `aria-invalid`; the label is what a reader scanning a long form reads
1249/// first, and it is the part of the group that says which question failed.
1250pub(crate) fn group_rules(opts: &Emit) -> String {
1251 let group = class("form-group", opts);
1252 let label = class("form-label", opts);
1253 let hint = class("form-hint", opts);
1254 let error = class("form-error", opts);
1255 let radios = class("form-radio-group", opts);
1256 let checklist = class("form-checklist", opts);
1257 let radio = class("form-radio-label", opts);
1258 let checkbox = class("form-checkbox-label", opts);
1259 let reason = class("form-option-reason", opts);
1260 let detail = class("form-option-detail", opts);
1261 let interval = class("form-interval", opts);
1262 let danger = Tone::Danger.token();
1263 let mut css = String::new();
1264
1265 let _ = writeln!(
1266 css,
1267 ".{label} {{\n display: block;\n margin-block-end: var(--gap-bound);\n color: var(--content);\n font-weight: bold;\n}}"
1268 );
1269 let _ = writeln!(
1270 css,
1271 ".{group}.has-error > .{label} {{\n color: var(--{danger});\n}}"
1272 );
1273 let _ = writeln!(
1274 css,
1275 ".{hint} {{\n margin-block-start: var(--gap-bound);\n color: var(--content-secondary);\n font-size: var(--text-note);\n}}"
1276 );
1277 let _ = writeln!(
1278 css,
1279 ".{error} {{\n margin-block-start: var(--gap-bound);\n color: var(--{danger});\n font-weight: bold;\n}}"
1280 );
1281 let _ = writeln!(css, ".{error}:not(.visible) {{\n display: none;\n}}");
1282
1283 // A radio group is a stack of labelled choices, and a choice may say why:
1284 // the box beside its label rather than centred over it. A checklist is the
1285 // same stack with a box that stays ticked.
1286 let _ = writeln!(
1287 css,
1288 ".{radios},\n.{checklist} {{\n display: flex;\n flex-direction: column;\n gap: var(--gap-peer);\n}}"
1289 );
1290 let _ = writeln!(
1291 css,
1292 ".{radio},\n.{checkbox} {{\n display: flex;\n flex-wrap: wrap;\n align-items: baseline;\n gap: var(--gap-bound);\n}}"
1293 );
1294 // An option's second line sits under its label rather than running along
1295 // it. `push_choice_group` says why it is its own element: a radio group has
1296 // room, so the sentence does not have to be run into the label.
1297 //
1298 // `display: block` was that same intent and it never worked. The label is a
1299 // flex row and an outer `display` on a flex item is ignored, so the detail
1300 // laid out as another item on the label's line: MNW's project wizard drew
1301 // "Audio Upload and stream audio files." where the Askama form it replaced
1302 // drew the sentence underneath. The row wraps and both spans take a whole
1303 // line of it, which is what actually puts them under the label.
1304 //
1305 // Both spans, because an unavailable option's reason is the same shape as a
1306 // detail and was failing the same way. MNW carried both rules in its own
1307 // sheet, pointing here.
1308 let _ = writeln!(css, ".{reason},\n.{detail} {{\n flex-basis: 100%;\n}}");
1309 let _ = writeln!(
1310 css,
1311 ".{interval} {{\n display: flex;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1312 );
1313 css
1314}
1315
1316/// The rule a field's unit needs.
1317///
1318/// Nothing emitted a unit before `Field::unit` existed, so there was no app
1319/// rule to keep.
1320///
1321/// One declaration, and it is the whole look. A unit is a fact about the number
1322/// beside it rather than a second thing to read, so it takes the muted content
1323/// intent -- the same reading `.figure-caption` and `.track-tick` take, and for
1324/// the same reason.
1325///
1326/// Nothing about placement. The span follows the control in the line it shares
1327/// with it.
1328/// The rules a field's note needs.
1329///
1330/// Nothing emitted a note before [`Field::note`] existed, so there was no app
1331/// rule to keep.
1332///
1333/// Colour only, and the tones are the four a badge carries. The bare class is
1334/// `content` rather than `content-muted`: a note is a consequence the user is
1335/// meant to read before answering, so muting it by default would be this crate
1336/// deciding it does not matter.
1337pub(crate) fn note_rules(opts: &Emit) -> String {
1338 let note = class("form-note", opts);
1339 let mut css = String::new();
1340 let _ = writeln!(css, ".{note} {{\n color: var(--content);\n}}");
1341 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1342 let _ = writeln!(
1343 css,
1344 ".{note}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
1345 tone.token()
1346 );
1347 }
1348 css
1349}
1350
1351/// The mark a compulsory field's label carries, where it carries one.
1352///
1353/// [`Emit::required_marker`](crate::Emit::required_marker) holds the copy and
1354/// the reasoning; what is decided here is that the mark rides *inside* the
1355/// label, after its text, which is where both sibling renderers put it.
1356///
1357/// Wrapped rather than run into the text, for one reason: the control beside it
1358/// already carries the `required` attribute, so a screen reader that also read
1359/// this would say the same thing twice. `aria-hidden` keeps the mark to the
1360/// eye, which is the channel that was missing.
1361///
1362/// Unclassed, and that is deliberate. Every name in [`FIELD_CLASSES`] is owed a
1363/// rule by the generated sheet, and there is no rule here worth writing: the
1364/// mark is part of the label's own line, in the label's own colour, at the
1365/// label's own weight. A class would be a hook for a look this crate has no
1366/// opinion about, and the space before it is a literal for the same reason the
1367/// terminal's is -- a gap inside a run of text is not a magnitude
1368/// `makeover-geometry` has any business naming.
1369fn push_required_marker(out: &mut String, field: &Field<'_>, opts: &Emit) {
1370 if !field.required || opts.required_marker.is_empty() {
1371 return;
1372 }
1373 out.push_str(" <span aria-hidden=\"true\">");
1374 escape_into(opts.required_marker, out);
1375 out.push_str("</span>");
1376}
1377
1378pub(crate) fn unit_rules(opts: &Emit) -> String {
1379 let unit = class("form-unit", opts);
1380 let mut css = String::new();
1381 let _ = writeln!(css, ".{unit} {{\n color: var(--content-muted);\n}}");
1382 css
1383}
1384
1385/// The rules an option's second line needs.
1386///
1387/// [`unit_rules`]' argument: rule what has no app counterpart to keep. An
1388/// unruled second line renders identically to the label it sits under, which is
1389/// a worse default than the hand-written markup it replaces.
1390///
1391/// Colour only, and muted, which is the same reading `.form-unit` and
1392/// `.form-suggestion-detail` take: the line orients the label rather than
1393/// competing with it. Nothing about placement or spacing, for `unit_rules`'
1394/// reason — a magnitude asserted here belongs to `makeover-geometry`.
1395pub(crate) fn option_detail_rules(opts: &Emit) -> String {
1396 let detail = class("form-option-detail", opts);
1397 let mut css = String::new();
1398 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
1399 css
1400}
1401
1402/// The rules a field's suggestion list needs.
1403///
1404/// [`editor_rules`]' precedent and its argument: the class names this module's
1405/// markup emits are the apps' own and stay unruled, and these three have no app
1406/// counterpart to keep because the list did not exist before the member did.
1407/// The markup is `quasi-webview`'s rather than this crate's — a suggestion
1408/// source is a route, which no description layer carries — and the look is
1409/// still this crate's, because a renderer inventing how a list of candidates
1410/// reads is the drift the vocabulary check exists to catch.
1411///
1412/// # In flow, and not floating
1413///
1414/// An absolutely positioned list needs a positioned ancestor, and the only
1415/// candidate is `.form-group`, which is the app's class and deliberately
1416/// unruled here. So the list stands under the control and moves what is below
1417/// it. An app that wants it over the form positions the group itself, which is
1418/// one declaration and is the app's call about its own layout.
1419///
1420/// `:empty` is what takes it away, so a route that answers with no candidates
1421/// leaves no box behind. It is a content question rather than a whitespace one
1422/// only because the emitter writes no whitespace inside the container, which is
1423/// stated in `quasi-webview`'s own test.
1424///
1425/// # Nothing about size
1426///
1427/// No height, no scroll ceiling, no padding. How tall a list of candidates gets
1428/// to be before it scrolls is a magnitude, and magnitudes are
1429/// `makeover-geometry`'s, exactly as the preview pane's height is.
1430pub(crate) fn suggestion_rules(opts: &Emit) -> String {
1431 let list = class("form-suggestions", opts);
1432 let entry = class("form-suggestion", opts);
1433 let detail = class("form-suggestion-detail", opts);
1434 let mut css = String::new();
1435
1436 let _ = writeln!(css, ".{list}:empty {{\n display: none;\n}}");
1437 // Over what it covers, which is what a list of candidates is even in flow:
1438 // it is answering the box above it and goes away when the answer is taken.
1439 css.push_str(&crate::depth_rule(&list, Depth::Overlay));
1440 // An entry answers a click, so it gets every state one implies.
1441 css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
1442 // The keyboard's highlight and the pointer's are the same surface. They are
1443 // the same fact told two ways, and a list where arrowing and hovering look
1444 // different is a list that has two current entries.
1445 //
1446 // Keyed on `aria-selected` rather than on a class, for the reason
1447 // `aria-invalid` carries the error state: it is what a screen reader hears,
1448 // so a look keyed on it cannot drift from what is announced. A `.current`
1449 // class would also be a name apps already spell for their own reasons --
1450 // the MNW server has one -- and unlayered app CSS beats this layer in
1451 // silence.
1452 let _ = writeln!(
1453 css,
1454 ".{entry}[aria-selected=\"true\"] {{\n background: var(--hover-surface);\n}}"
1455 );
1456 // The second line, muted rather than disabled. `1fcf2e9b` replaced the
1457 // unavailable reason this rule used to draw: a candidate carries no
1458 // `unavailable`, and what sits beside the label now is what tells one row
1459 // from another that reads the same. Disabled would say the row cannot be
1460 // picked, which is the opposite of what the detail is for.
1461 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
1462
1463 css
1464}
1465
1466/// One field, as the group the app drops into its form.
1467///
1468/// The shape is goingson's, down to the class names, so adoption there deletes
1469/// `renderFormField` rather than restyling anything. That is also why the class
1470/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
1471/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
1472/// emits only what it can generate from the description. Whether they should
1473/// move into the description is the next question this raises, not one it
1474/// answers.
1475///
1476/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
1477/// nothing drawn, which is what [`FieldKind::visible`] means.
1478///
1479/// The error marks the group as well as the control. That is
1480/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
1481/// cannot find the group from the message, so the group has to be told.
1482///
1483/// ```
1484/// use makeover_layout::{Field, FieldKind};
1485/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
1486///
1487/// let field = Field::new(FieldKind::Text, "title", "Title");
1488/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
1489///
1490/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
1491/// assert!(html.contains(r#"value="Ship it""#));
1492/// ```
1493#[must_use]
1494pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
1495 let mut html = String::new();
1496 field_html_into(field, filling, opts, &mut html);
1497 html
1498}
1499
1500/// One field, written into a buffer the caller already has.
1501///
1502/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
1503/// these, so a host building one should hold a single buffer and append each
1504/// field into it rather than take a `String` per field and concatenate.
1505pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
1506 emit_field(field, filling, opts, out, None);
1507}
1508
1509/// One field, saying where each of its options landed.
1510///
1511/// Byte-identical to [`field_html_into`], and it appends one entry to `placed`
1512/// per option, in order: the offsets in `out` between which that option was
1513/// written. A select's option is its `<option>`; a radio group's or a
1514/// checklist's is its `<label>`, which holds the input. Nothing is appended for
1515/// a field that offers no options.
1516///
1517/// Same reason as [`crate::list::cells_html_placed`]: a caller compiling a
1518/// described screen into a template has to know which bytes one option
1519/// produced, and two options with the same label are the same bytes.
1520pub fn field_html_placed(
1521 field: &Field<'_>,
1522 filling: &Filling<'_>,
1523 opts: &Emit,
1524 out: &mut String,
1525 placed: &mut Vec<core::ops::Range<usize>>,
1526) {
1527 emit_field(field, filling, opts, out, Some(placed));
1528}
1529
1530fn emit_field(
1531 field: &Field<'_>,
1532 filling: &Filling<'_>,
1533 opts: &Emit,
1534 out: &mut String,
1535 placed: Option<&mut Vec<core::ops::Range<usize>>>,
1536) {
1537 let id = filling.id_for(field.name);
1538
1539 if !field.kind.visible() {
1540 // Name only, no id: a hidden field is never pointed at by a label or a
1541 // description, so the one attribute it needs is the one that submits.
1542 out.push_str("<input type=\"hidden\" name=\"");
1543 escape_into(field.name, out);
1544 out.push_str("\" value=\"");
1545 escape_into(filling.value.as_text(), out);
1546 out.push_str("\">");
1547 return;
1548 }
1549
1550 out.push_str("<div class=\"");
1551 push_class(out, "form-group", opts);
1552 if field.invalid() {
1553 out.push_str(" has-error");
1554 }
1555 if field.extended {
1556 // The disclosure that hides these is a property of the form, not of the
1557 // field, so the field is marked and the app opens or closes the group.
1558 out.push_str("\" data-extended=\"true");
1559 }
1560 out.push_str("\">");
1561
1562 // A checkbox labels itself, on the right of the box. Both apps special-case
1563 // this inline today, which is the tell that it belongs in the description;
1564 // `FieldKind::labels_itself` is where it went.
1565 if !field.kind.labels_itself() {
1566 out.push_str("<label class=\"");
1567 push_class(out, "form-label", opts);
1568 // A group control is named *by* its label rather than pointing at it,
1569 // so the two carry opposite halves of the association. See
1570 // `is_group_control`.
1571 if is_group_control(field.kind) {
1572 let _ = write!(out, "\" id=\"{id}-label\">");
1573 } else {
1574 let _ = write!(out, "\" for=\"{id}\">");
1575 }
1576 escape_into(field.label, out);
1577 push_required_marker(out, field, opts);
1578 out.push_str("</label>");
1579 }
1580
1581 push_control(out, field, filling, opts, placed);
1582
1583 // Adjacent text, because HTML has no unit attribute and inventing one would
1584 // be markup nothing reads. Pointed at by `aria-describedby` so it is not
1585 // decoration a screen reader skips: the number and what it is measured in
1586 // are one fact, and reading the first without the second is reading it
1587 // wrong.
1588 if let Some(unit) = unit_of(field) {
1589 out.push_str("<span class=\"");
1590 push_class(out, "form-unit", opts);
1591 let _ = write!(out, "\" id=\"{id}-unit\">");
1592 escape_into(unit, out);
1593 out.push_str("</span>");
1594 }
1595
1596 if let Some(hint) = field.hint {
1597 out.push_str("<div class=\"");
1598 push_class(out, "form-hint", opts);
1599 let _ = write!(out, "\" id=\"{id}-hint\">");
1600 escape_into(hint, out);
1601 out.push_str("</div>");
1602 }
1603 // A consequence of the answer, between the standing help and the failure.
1604 // The tone rides on `data-tone` -- the same attribute every other toned
1605 // thing in this crate takes -- and it also picks the live region: Warning
1606 // and Danger are assertive, which is quasi-webview's own reading at
1607 // `node.rs:1403` and is honoured here rather than restated differently.
1608 if let Some((tone, note)) = field.note {
1609 out.push_str("<div class=\"");
1610 push_class(out, "form-note", opts);
1611 let assertive = matches!(tone, Tone::Warning | Tone::Danger);
1612 let _ = write!(
1613 out,
1614 "\" id=\"{id}-note\" role=\"{}\"",
1615 if assertive { "alert" } else { "status" }
1616 );
1617 // Neutral is the bare class rather than a variant, matching every
1618 // other toned component here: it is the absence of a status.
1619 if tone != Tone::Neutral {
1620 let _ = write!(out, " data-tone=\"{}\"", tone.token());
1621 }
1622 out.push('>');
1623 escape_into(note, out);
1624 out.push_str("</div>");
1625 }
1626 if let Some(Markup(markup)) = filling.trailing {
1627 out.push_str(markup);
1628 }
1629 if let Some(error) = field.error {
1630 out.push_str("<div class=\"");
1631 push_class(out, "form-error", opts);
1632 let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
1633 escape_into(error, out);
1634 out.push_str("</div>");
1635 }
1636
1637 out.push_str("</div>");
1638}
1639
1640#[cfg(test)]
1641mod tests;