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