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