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` tones the label. The control already carries the danger edge
283/// through `aria-invalid`; the label is what a reader scanning a long form reads
284/// first, and it is the part of the group that says which question failed.
285pub(crate) fn group_rules(opts: &Emit) -> String {
286 let group = class("form-group", opts);
287 let label = class("form-label", opts);
288 let hint = class("form-hint", opts);
289 let error = class("form-error", opts);
290 let radios = class("form-radio-group", opts);
291 let checklist = class("form-checklist", opts);
292 let radio = class("form-radio-label", opts);
293 let checkbox = class("form-checkbox-label", opts);
294 let reason = class("form-option-reason", opts);
295 let interval = class("form-interval", opts);
296 let danger = Tone::Danger.token();
297 let mut css = String::new();
298
299 let _ = writeln!(
300 css,
301 ".{label} {{\n display: block;\n margin-block-end: var(--gap-bound);\n color: var(--content);\n font-weight: bold;\n}}"
302 );
303 let _ = writeln!(
304 css,
305 ".{group}.has-error > .{label} {{\n color: var(--{danger});\n}}"
306 );
307 let _ = writeln!(
308 css,
309 ".{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}}"
310 );
311 let _ = writeln!(
312 css,
313 ".{error} {{\n margin-block-start: var(--gap-bound);\n color: var(--{danger});\n font-weight: bold;\n}}"
314 );
315 let _ = writeln!(css, ".{error}:not(.visible) {{\n display: none;\n}}");
316
317 // A radio group is a stack of labelled choices, and a choice may say why:
318 // the box beside its label rather than centred over it. A checklist is the
319 // same stack with a box that stays ticked.
320 let _ = writeln!(
321 css,
322 ".{radios},\n.{checklist} {{\n display: flex;\n flex-direction: column;\n gap: var(--gap-peer);\n}}"
323 );
324 // Two tracks: the box, and everything it labels. A label that wraps
325 // wraps in its own track beside the box, where a wrapping flex row left the
326 // box alone on the line above its words, and the box sits on the label's
327 // first line rather than above it.
328 let _ = writeln!(
329 css,
330 ".{radio},\n.{checkbox} {{\n display: grid;\n grid-template-columns: auto 1fr;\n \
331 align-items: baseline;\n column-gap: var(--gap-bound);\n}}\n\
332 .{radio} > :not(input),\n.{checkbox} > :not(input),\n.{reason} {{\n grid-column: 2;\n min-width: 0;\n}}"
333 );
334 // An option's second line, and an unavailable option's reason, sit under
335 // its label in the label's track: the second track above holds every child
336 // but the box, each on a row of its own.
337 let _ = writeln!(
338 css,
339 ".{interval} {{\n display: flex;\n align-items: center;\n gap: var(--gap-bound);\n}}"
340 );
341 css
342}
343
344/// The rules a field's note needs.
345///
346/// Nothing emitted a note before the described field could carry one, so
347/// there was no app rule to keep.
348///
349/// Colour only, and the tones are the four a badge carries. The bare class is
350/// `content` rather than `content-muted`: a note is a consequence the user is
351/// meant to read before answering, so muting it by default would be this crate
352/// deciding it does not matter.
353pub(crate) fn note_rules(opts: &Emit) -> String {
354 let note = class("form-note", opts);
355 let mut css = String::new();
356 let _ = writeln!(css, ".{note} {{\n color: var(--content);\n}}");
357 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
358 let _ = writeln!(
359 css,
360 ".{note}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
361 tone.token()
362 );
363 }
364 css
365}
366
367/// The rule a field's unit needs.
368///
369/// Nothing emitted a unit before the described field could carry one, so
370/// there was no app rule to keep.
371///
372/// One declaration, and it is the whole look. A unit is a fact about the number
373/// beside it rather than a second thing to read, so it takes the muted content
374/// intent, the same reading `.figure-caption` and `.track-tick` take, and for
375/// the same reason.
376///
377/// And where it sits, which the first version left to the flow and got wrong. A
378/// control fills its group's width, so the span after it wrapped onto a line of
379/// its own and "min" hung under the box it measures. A group carrying a unit is
380/// two columns instead: the control and its unit share the first row's line,
381/// and the label, the hint, the note and the message span both. The control's
382/// track is `auto`, so it is as wide as the control and the unit reads straight
383/// after the number; the spare room goes to the unit's track, where it is
384/// empty. The other way round put "min" at the far edge of the pane.
385pub(crate) fn unit_rules(opts: &Emit) -> String {
386 let unit = class("form-unit", opts);
387 let group = class("form-group", opts);
388 let mut css = String::new();
389 let _ = writeln!(css, ".{unit} {{\n color: var(--content-muted);\n}}");
390 let _ = writeln!(
391 css,
392 ".{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}}"
393 );
394 let _ = writeln!(
395 css,
396 ".{group}:has(> .{unit}) > :not(.{unit}, input, select, textarea) {{\n grid-column: 1 / -1;\n}}"
397 );
398 css
399}
400
401/// The rules an option's second line needs.
402///
403/// [`unit_rules`]' argument: rule what has no app counterpart to keep. An
404/// unruled second line renders identically to the label it sits under, which is
405/// a worse default than the hand-written markup it replaces.
406///
407/// Colour only, and muted, which is the same reading `.form-unit` and
408/// `.form-suggestion-detail` take: the line orients the label rather than
409/// competing with it. Nothing about placement or spacing, for `unit_rules`'
410/// reason, a magnitude asserted here belongs to `makeover-geometry`.
411pub(crate) fn option_detail_rules(opts: &Emit) -> String {
412 let detail = class("form-option-detail", opts);
413 let mut css = String::new();
414 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
415 css
416}
417
418/// The rules a field's suggestion list needs.
419///
420/// [`editor_rules`]' precedent and its argument: these three have no app
421/// counterpart to keep because the list did not exist before the member did.
422/// The markup is `quasi-webview`'s, a suggestion source is a route, which no
423/// description layer carries, and the look is
424/// still this crate's, because a renderer inventing how a list of candidates
425/// reads is the drift the vocabulary check exists to catch.
426///
427/// # In flow, and not floating
428///
429/// An absolutely positioned list needs a positioned ancestor, and the only
430/// candidate is `.form-group`, which is the app's class and deliberately
431/// unruled here. So the list stands under the control and moves what is below
432/// it. An app that wants it over the form positions the group itself, which is
433/// one declaration and is the app's call about its own layout.
434///
435/// `:empty` is what takes it away, so a route that answers with no candidates
436/// leaves no box behind. It is a content question rather than a whitespace one
437/// only because the emitter writes no whitespace inside the container, which is
438/// stated in `quasi-webview`'s own test.
439///
440/// # Placement, and nothing about size
441///
442/// One candidate to a line, its detail at the line's end. Without it the
443/// entries are bare anchors and run together as one paragraph: MNW's discover
444/// search drew "Blue HourProjectKickItem". Spacing comes from the geometry
445/// tokens every other form rule uses, so no magnitude is asserted here.
446///
447/// No height and no scroll ceiling. How tall a list of candidates gets to be
448/// before it scrolls is a magnitude, and magnitudes are `makeover-geometry`'s,
449/// exactly as the preview pane's height is.
450pub(crate) fn suggestion_rules(opts: &Emit) -> String {
451 let list = class("form-suggestions", opts);
452 let entry = class("form-suggestion", opts);
453 let detail = class("form-suggestion-detail", opts);
454 let mut css = String::new();
455
456 let _ = writeln!(css, ".{list}:empty {{\n display: none;\n}}");
457 let _ = writeln!(
458 css,
459 ".{list} {{\n display: flex;\n flex-direction: column;\n}}"
460 );
461 let _ = writeln!(
462 css,
463 ".{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}}"
464 );
465 // Over what it covers, which is what a list of candidates is even in flow:
466 // it is answering the box above it and goes away when the answer is taken.
467 css.push_str(&crate::depth_rule(&list, Depth::Overlay));
468 // An entry answers a click, so it gets every state one implies.
469 css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
470 // The keyboard's highlight and the pointer's are the same surface. They are
471 // the same fact told two ways, and a list where arrowing and hovering look
472 // different is a list that has two current entries.
473 //
474 // Keyed on `aria-selected` rather than on a class, for the reason
475 // `aria-invalid` carries the error state: it is what a screen reader hears,
476 // so a look keyed on it cannot drift from what is announced. A `.current`
477 // class would also be a name apps already spell for their own reasons:
478 // the MNW server has one, and unlayered app CSS beats this layer in
479 // silence.
480 let _ = writeln!(
481 css,
482 ".{entry}[aria-selected=\"true\"] {{\n background: var(--hover-surface);\n}}"
483 );
484 // The second line, muted rather than disabled. A candidate carries no
485 // `unavailable`, and what sits beside the label now is what tells one row
486 // from another that reads the same. Disabled would say the row cannot be
487 // picked, which is the opposite of what the detail is for.
488 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
489
490 css
491}
492
493#[cfg(test)]
494mod tests;