makeover_webview/form.rs
1//! Phase B, the forms half: the escaper, the field classes and the rules a
2//! described field's markup is drawn with.
3//!
4//! The field markup itself is drawn by the quasi hosts (`quasi-webview` for
5//! this renderer), which own the vocabulary member. What stays here is what
6//! every caller writing HTML needs and what the generated stylesheet has to
7//! agree with: [`escape`] and [`escape_into`], [`Markup`] and [`Filling`], the
8//! class lists, and the rules behind them.
9//!
10//! # Why one escaper is enough
11//!
12//! goingson carries four escapers and 543 call sites that must pick between
13//! them, because `escapeHtml` is built on `textContent` serialization and
14//! **`textContent` refuses to encode `"`**. That is what makes it unsound in an
15//! attribute, and it is the whole reason the choice exists. Its `escape.js`
16//! records the finding as the CHRONIC-XSS seal, and its test suite has a gate
17//! keeping the unsafe one off the namespace.
18//!
19//! [`escape`] here is not built on that, so it encodes the quote along with
20//! everything else, which makes one function sound in both sinks. The four-way
21//! choice does not move into Rust: it disappears. A caller hands an unescaped
22//! value to the output only through [`Markup`], which it has to name.
23//!
24//! # What the description does not carry
25//!
26//! One thing: the **current value**, which arrives in [`Filling`]. A webview
27//! reads it back out of the DOM, an immediate-mode renderer writes through a
28//! `&mut`, and a terminal keeps an edit buffer; a description carrying it would
29//! have to carry a way to write it back, at which point it is a form model.
30
31use crate::{Emit, class};
32use makeover_layout::{Depth, Intent as _, Tone, Value};
33use std::fmt::Write as _;
34
35/// Every class a field's markup can carry.
36///
37/// [`crate::facet::FACET_CLASSES`]' obligation. Every one of these is ruled by
38/// the generated sheet, the group's four through `group_rules`; the list is
39/// written down anyway, because it is what the hosts' markup is held against
40/// and what the vocabulary test holds the sheet against.
41///
42/// What goes wrong without it: an app checking its stylesheet against
43/// [`crate::vocabulary::names`] concludes that its live `.form-group` and
44/// `.form-label` rules match nothing and are safe to delete.
45pub const FIELD_CLASSES: &[&str] = &[
46 "field",
47 "form-checkbox-label",
48 "form-checklist",
49 "form-editor-modes",
50 "form-editor-preview",
51 "form-error",
52 "form-group",
53 "form-hint",
54 "form-interval",
55 "form-label",
56 "form-note",
57 "form-option-detail",
58 "form-option-reason",
59 "form-radio-group",
60 "form-radio-label",
61 "form-unit",
62];
63
64// `form-suggestions`, `form-suggestion` and `form-suggestion-detail` are
65// deliberately absent: [`suggestion_rules`] writes their look and
66// `quasi-webview` writes their markup, because a suggestion source is a route
67// and no description layer carries one. They reach the vocabulary through the
68// generated sheet, which is where a name this crate rules but does not emit
69// belongs.
70
71/// The state classes a field carries, which take no prefix.
72///
73/// `chosen` and `latched`'s convention, stated in
74/// [`crate::vocabulary::vocabulary`]: a state qualifies a prefixed component
75/// (`.mk-form-group.has-error`) rather than standing on its own, so a prefix
76/// moves the thing and not its state.
77///
78/// `has-error` marks the group and `visible` marks the message: a renderer
79/// with no descendant selectors cannot find the group from the message, so
80/// both are told.
81pub const FIELD_STATE_CLASSES: &[&str] = &["has-error", "visible"];
82
83/// A string that is already markup, and is emitted without escaping.
84///
85/// The one hole in the escaping, and it has to be named to be used. goingson
86/// has two live callers that need it, both passing a recurrence-config block
87/// built elsewhere, and both would otherwise have their markup rendered as
88/// visible angle brackets. A caller constructing this is stating that the
89/// contents are trusted; nothing here can check that for them.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct Markup<'a>(pub &'a str);
92
93/// Everything about the field that the description does not carry.
94#[derive(Debug, Clone, Copy, Default)]
95pub struct Filling<'a> {
96 /// What the field holds now.
97 pub value: Value<'a>,
98 /// Markup appended inside the group, after the hint. Not escaped.
99 pub trailing: Option<Markup<'a>>,
100 /// Attributes written onto the control element itself. Not escaped.
101 ///
102 /// [`trailing`](Self::trailing)'s argument at attribute scale: a host knows
103 /// facts about the control that no description layer carries. quasi's
104 /// suggestion source is the first caller: a field that owns a list of
105 /// candidates is a `role="combobox"` pointing at the list it owns, and
106 /// neither half is anything the described field can say.
107 ///
108 /// Written verbatim, so a caller supplies `attr="value"` pairs with no
109 /// leading space and does its own escaping. It is [`Markup`]'s hole in the
110 /// same wall, named the same way so a caller has to state that the contents
111 /// are trusted.
112 ///
113 /// A radio group drops them, and that is deliberate rather than an
114 /// oversight: a radio group is a set of sibling inputs with no one control
115 /// element, so there is nowhere honest to put an attribute meant for the
116 /// control. The group carries the descriptions for the same reason.
117 pub control_attrs: Option<Markup<'a>>,
118 /// Scopes the `id` attributes to one instance of the form.
119 ///
120 /// The field's `name` is what the value submits under and is the same
121 /// wherever the form appears; its `id` has to be unique in the document,
122 /// and those two facts stop agreeing the moment a form appears twice.
123 /// goingson hits this directly: its new-task and edit-task modals are the
124 /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
125 /// `label for` and `aria-describedby` pointing at the right control.
126 ///
127 /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
128 /// `name`, which would change what the form submits.
129 pub id_prefix: Option<&'a str>,
130}
131
132impl<'a> Filling<'a> {
133 /// A filling that carries a value and nothing else.
134 #[must_use]
135 pub const fn of(value: Value<'a>) -> Self {
136 Self {
137 value,
138 trailing: None,
139 control_attrs: None,
140 id_prefix: None,
141 }
142 }
143}
144
145/// Encode the five characters that let a value stop being a value, into a
146/// buffer the caller already has.
147///
148/// The form an emitter uses. [`escape`] is this with a `String` allocated
149/// around it, and the allocation is the whole difference: a described screen
150/// escapes once per attribute and once per run of text, so a function that
151/// returns a `String` allocates a few thousand times to produce one page,
152/// where a template engine writes its escaped bytes straight into the output
153/// buffer.
154///
155/// Sound in element text and in a double-quoted attribute alike, which is the
156/// property `textContent`-based escaping cannot have. Both sinks are covered by
157/// one function so that no call site has to choose, here or downstream.
158///
159/// Copies in runs rather than per character. All five encoded characters are
160/// ASCII, so a byte scan cannot land inside a multi-byte character and the
161/// slice between two of them is always a valid `&str`. Text with nothing to
162/// encode, which is most text, is one `push_str` of the whole thing.
163pub fn escape_into(text: &str, out: &mut String) {
164 let mut start = 0;
165 for (index, byte) in text.bytes().enumerate() {
166 let encoded = match byte {
167 b'&' => "&",
168 b'<' => "<",
169 b'>' => ">",
170 b'"' => """,
171 b'\'' => "'",
172 _ => continue,
173 };
174 out.push_str(&text[start..index]);
175 out.push_str(encoded);
176 start = index + 1;
177 }
178 out.push_str(&text[start..]);
179}
180
181/// Encode the five characters that let a value stop being a value.
182///
183/// [`escape_into`] with a buffer of its own, for the callers that want a value
184/// rather than an append: a caller assembling an attribute out of several
185/// pieces, and everything outside this crate that took this function before the
186/// buffer-writing form existed. Emitting into a buffer you already hold is the
187/// cheaper path and the one the hosts' emitters take.
188#[must_use]
189pub fn escape(text: &str) -> String {
190 let mut out = String::with_capacity(text.len());
191 escape_into(text, &mut out);
192 out
193}
194
195/// The rules the markdown editor's chrome needs.
196///
197/// The two names here have no app counterpart to keep, because the chrome did
198/// not exist before the member did. The markup is a Write/Preview pair of
199/// segments and an empty preview pane, drawn by the hosts; converting markdown
200/// stays the host's, where its sanitiser already is.
201///
202/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
203/// off a plain textarea, and every rule that hides content is gated on
204/// `data-ready` as well, which is what keeps them out of a document with no
205/// script.
206pub(crate) fn editor_rules(opts: &Emit) -> String {
207 let mut css = String::new();
208 let modes = class("form-editor-modes", opts);
209 let preview = class("form-editor-preview", opts);
210 let field = class("field", opts);
211
212 // Hidden until something binds the editor: a control rendered into a
213 // document with no script looks live and answers nothing, so a reader with
214 // no script gets the textarea alone.
215 let _ = writeln!(
216 css,
217 "[data-format=\"markdown\"] > .{modes} {{\n display: none;\n}}"
218 );
219 // Block, and nothing about how the two segments sit in it. A button is
220 // inline already, so they make a row without this crate saying so, and
221 // saying so is where a gap would follow, a magnitude, and
222 // `makeover-geometry`'s.
223 let _ = writeln!(
224 css,
225 "[data-format=\"markdown\"][data-ready] > .{modes} {{\n display: block;\n}}"
226 );
227
228 // The pane is empty until the host fills it, so it is out of flow in every
229 // state but the one where a bound editor is showing it. An empty box under
230 // the control is chrome claiming a preview nobody rendered.
231 let _ = writeln!(
232 css,
233 "[data-format=\"markdown\"] > .{preview} {{\n display: none;\n}}"
234 );
235 let _ = writeln!(
236 css,
237 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
238 {{\n display: block;\n}}"
239 );
240 // One at a time. The source and the preview are the same content read two
241 // ways, and a field showing both answers its own question twice.
242 let _ = writeln!(
243 css,
244 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
245 {{\n display: none;\n}}"
246 );
247
248 // The pane stands where the control stood, so it reads as the surface the
249 // control was: `.field` is a well, and this is the well it stands in for.
250 // Nothing about size, how tall a preview is is the app's, the way the
251 // height of a track is.
252 let _ = write!(
253 css,
254 "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
255 crate::depth_declarations(Depth::Well)
256 );
257
258 css
259}
260
261/// The rules a field's group needs: its label, its hint, its message, and the
262/// arrangement of the controls that answer one question.
263///
264/// These were the apps' names from phase A, left unruled so that adoption would
265/// delete goingson's `renderFormField` rather than restyle anything. Adoption
266/// happened and the argument went with it: a described form in an app that had
267/// never written the rules drew its label as body text and its error as a plain
268/// sentence, and MNW was that app. wiki `look-restoration`: the renderer owns
269/// the look.
270///
271/// The values are the ones goingson shipped, less the group's own margin. A
272/// form spaces its groups with a gap, so a margin here would space them twice;
273/// an app laying groups out in normal flow keeps a margin of its own. The radio,
274/// checkbox, reason and interval rules came from quasi-webview's arrangement
275/// sheet unchanged, where they styled names this crate emits.
276///
277/// `visible` is the message's state rather than decoration. goingson's scripts
278/// raise and lower it on a message that stays in the document, and this crate
279/// writes it on every message it emits, so a lowered message is hidden and a
280/// written one shows.
281///
282/// `has-error` draws a danger edge down the group's leading side. The control
283/// already carries the danger edge through `aria-invalid`; the group's edge is
284/// what a reader scanning a long form finds first, and it says which question
285/// failed without colouring a word of it. The label and the message keep
286/// content ink: a status colour is a fill and an edge, never the colour of
287/// words a reader has to read (wiki `quasi-vocabulary-findings`).
288pub(crate) fn group_rules(opts: &Emit) -> String {
289 let group = class("form-group", opts);
290 let label = class("form-label", opts);
291 let hint = class("form-hint", opts);
292 let error = class("form-error", opts);
293 let radios = class("form-radio-group", opts);
294 let checklist = class("form-checklist", opts);
295 let radio = class("form-radio-label", opts);
296 let checkbox = class("form-checkbox-label", opts);
297 let reason = class("form-option-reason", opts);
298 let interval = class("form-interval", opts);
299 let danger = Tone::Danger.token();
300 let mut css = String::new();
301
302 let _ = writeln!(
303 css,
304 ".{label} {{\n display: block;\n margin-block-end: var(--gap-bound);\n color: var(--content);\n font-weight: bold;\n}}"
305 );
306 let _ = writeln!(
307 css,
308 ".{group}.has-error {{\n border-inline-start: {} solid var(--{danger});\n \
309 padding-inline-start: var(--step-snug);\n}}",
310 opts.focus_width
311 );
312 let _ = writeln!(
313 css,
314 ".{hint} {{\n margin-block-start: var(--gap-bound);\n max-inline-size: var(--measure-reading, 42rem);\n color: var(--content-secondary);\n font-size: var(--text-note);\n}}"
315 );
316 let _ = writeln!(
317 css,
318 ".{error} {{\n margin-block-start: var(--gap-bound);\n color: var(--content);\n font-weight: bold;\n}}"
319 );
320 let _ = writeln!(css, ".{error}:not(.visible) {{\n display: none;\n}}");
321
322 // A radio group is a stack of labelled choices, and a choice may say why:
323 // the box beside its label rather than centred over it. A checklist is the
324 // same stack with a box that stays ticked.
325 let _ = writeln!(
326 css,
327 ".{radios},\n.{checklist} {{\n display: flex;\n flex-direction: column;\n gap: var(--gap-peer);\n}}"
328 );
329 // Two tracks: the box, and everything it labels. A label that wraps
330 // wraps in its own track beside the box, where a wrapping flex row left the
331 // box alone on the line above its words, and the box sits on the label's
332 // first line rather than above it.
333 let _ = writeln!(
334 css,
335 ".{radio},\n.{checkbox} {{\n display: grid;\n grid-template-columns: auto 1fr;\n \
336 align-items: baseline;\n column-gap: var(--gap-bound);\n}}\n\
337 .{radio} > :not(input),\n.{checkbox} > :not(input),\n.{reason} {{\n grid-column: 2;\n min-width: 0;\n}}"
338 );
339 // An option's second line, and an unavailable option's reason, sit under
340 // its label in the label's track: the second track above holds every child
341 // but the box, each on a row of its own.
342 let _ = writeln!(
343 css,
344 ".{interval} {{\n display: flex;\n align-items: center;\n gap: var(--gap-bound);\n}}"
345 );
346 css
347}
348
349/// The rules a field's note needs.
350///
351/// Nothing emitted a note before the described field could carry one, so
352/// there was no app rule to keep.
353///
354/// The tones are the four a badge carries, drawn as a leading edge the way a
355/// toned sentence draws one; the words keep content ink. The bare class is
356/// `content` rather than `content-muted`: a note is a consequence the user is
357/// meant to read before answering, so muting it by default would be this crate
358/// deciding it does not matter.
359pub(crate) fn note_rules(opts: &Emit) -> String {
360 let note = class("form-note", opts);
361 let mut css = String::new();
362 let _ = writeln!(css, ".{note} {{\n color: var(--content);\n}}");
363 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
364 let _ = writeln!(
365 css,
366 ".{note}[data-tone=\"{0}\"] {{\n border-inline-start: {1} solid var(--{0});\n \
367 padding-inline-start: var(--step-snug);\n}}",
368 tone.token(),
369 opts.focus_width
370 );
371 }
372 css
373}
374
375/// The rule a field's unit needs.
376///
377/// Nothing emitted a unit before the described field could carry one, so
378/// there was no app rule to keep.
379///
380/// One declaration, and it is the whole look. A unit is a fact about the number
381/// beside it rather than a second thing to read, so it takes the muted content
382/// intent, the same reading `.figure-caption` and `.track-tick` take, and for
383/// the same reason.
384///
385/// And where it sits, which the first version left to the flow and got wrong. A
386/// control fills its group's width, so the span after it wrapped onto a line of
387/// its own and "min" hung under the box it measures. A group carrying a unit is
388/// two columns instead: the control and its unit share the first row's line,
389/// and the label, the hint, the note and the message span both. The control's
390/// track is `auto`, so it is as wide as the control and the unit reads straight
391/// after the number; the spare room goes to the unit's track, where it is
392/// empty. The other way round put "min" at the far edge of the pane.
393pub(crate) fn unit_rules(opts: &Emit) -> String {
394 let unit = class("form-unit", opts);
395 let group = class("form-group", opts);
396 let mut css = String::new();
397 let _ = writeln!(css, ".{unit} {{\n color: var(--content-muted);\n}}");
398 let _ = writeln!(
399 css,
400 ".{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}}"
401 );
402 let _ = writeln!(
403 css,
404 ".{group}:has(> .{unit}) > :not(.{unit}, input, select, textarea) {{\n grid-column: 1 / -1;\n}}"
405 );
406 css
407}
408
409/// The rules an option's second line needs.
410///
411/// [`unit_rules`]' argument: rule what has no app counterpart to keep. An
412/// unruled second line renders identically to the label it sits under, which is
413/// a worse default than the hand-written markup it replaces.
414///
415/// Colour only, and muted, which is the same reading `.form-unit` and
416/// `.form-suggestion-detail` take: the line orients the label rather than
417/// competing with it. Nothing about placement or spacing, for `unit_rules`'
418/// reason, a magnitude asserted here belongs to `makeover-geometry`.
419pub(crate) fn option_detail_rules(opts: &Emit) -> String {
420 let detail = class("form-option-detail", opts);
421 let mut css = String::new();
422 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
423 css
424}
425
426/// The rules a field's suggestion list needs.
427///
428/// [`editor_rules`]' precedent and its argument: these three have no app
429/// counterpart to keep because the list did not exist before the member did.
430/// The markup is `quasi-webview`'s, a suggestion source is a route, which no
431/// description layer carries, and the look is
432/// still this crate's, because a renderer inventing how a list of candidates
433/// reads is the drift the vocabulary check exists to catch.
434///
435/// # In flow, and not floating
436///
437/// An absolutely positioned list needs a positioned ancestor, and the only
438/// candidate is `.form-group`, which is the app's class and deliberately
439/// unruled here. So the list stands under the control and moves what is below
440/// it. An app that wants it over the form positions the group itself, which is
441/// one declaration and is the app's call about its own layout.
442///
443/// `:empty` is what takes it away, so a route that answers with no candidates
444/// leaves no box behind. It is a content question rather than a whitespace one
445/// only because the emitter writes no whitespace inside the container, which is
446/// stated in `quasi-webview`'s own test.
447///
448/// # Placement, and nothing about size
449///
450/// One candidate to a line, its detail at the line's end. Without it the
451/// entries are bare anchors and run together as one paragraph: MNW's discover
452/// search drew "Blue HourProjectKickItem". Spacing comes from the geometry
453/// tokens every other form rule uses, so no magnitude is asserted here.
454///
455/// No height and no scroll ceiling. How tall a list of candidates gets to be
456/// before it scrolls is a magnitude, and magnitudes are `makeover-geometry`'s,
457/// exactly as the preview pane's height is.
458pub(crate) fn suggestion_rules(opts: &Emit) -> String {
459 let list = class("form-suggestions", opts);
460 let entry = class("form-suggestion", opts);
461 let detail = class("form-suggestion-detail", opts);
462 let mut css = String::new();
463
464 let _ = writeln!(css, ".{list}:empty {{\n display: none;\n}}");
465 let _ = writeln!(
466 css,
467 ".{list} {{\n display: flex;\n flex-direction: column;\n}}"
468 );
469 let _ = writeln!(
470 css,
471 ".{entry} {{\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: var(--gap-group);\n padding: var(--gap-bound) var(--gap-peer);\n color: inherit;\n text-decoration: none;\n}}"
472 );
473 // Over what it covers, which is what a list of candidates is even in flow:
474 // it is answering the box above it and goes away when the answer is taken.
475 css.push_str(&crate::depth_rule(&list, Depth::Overlay));
476 // An entry answers a click, so it gets every state one implies.
477 css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
478 // The keyboard's highlight and the pointer's are the same surface. They are
479 // the same fact told two ways, and a list where arrowing and hovering look
480 // different is a list that has two current entries.
481 //
482 // Keyed on `aria-selected` rather than on a class, for the reason
483 // `aria-invalid` carries the error state: it is what a screen reader hears,
484 // so a look keyed on it cannot drift from what is announced. A `.current`
485 // class would also be a name apps already spell for their own reasons:
486 // the MNW server has one, and unlayered app CSS beats this layer in
487 // silence.
488 let _ = writeln!(
489 css,
490 ".{entry}[aria-selected=\"true\"] {{\n background: var(--hover-surface);\n}}"
491 );
492 // The second line, muted rather than disabled. A candidate carries no
493 // `unavailable`, and what sits beside the label now is what tells one row
494 // from another that reads the same. Disabled would say the row cannot be
495 // picked, which is the opposite of what the detail is for.
496 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
497
498 css
499}
500
501#[cfg(test)]
502mod tests;