Skip to main content

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