Skip to main content

max / makeover-webview

23.4 KB · 607 lines History Blame Raw
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 //! [`Field`] describes the field and not its contents, so three things arrive
30 //! from the renderer side in [`Filling`]: the current value, the options of a
31 //! select, and the placeholder. The first two are genuinely renderer state. The
32 //! third is user-facing text and belongs with `label` and `hint` in
33 //! makeover-layout; it lives here because that crate is published and adding a
34 //! field to `Field` is a breaking change, not because this is its home.
35
36 use crate::{Emit, class};
37 use makeover_layout::{Field, FieldKind};
38 use std::fmt::Write as _;
39
40 /// A string that is already markup, and is emitted without escaping.
41 ///
42 /// The one hole in the escaping, and it has to be named to be used. goingson
43 /// has two live callers that need it, both passing a recurrence-config block
44 /// built elsewhere, and both would otherwise have their markup rendered as
45 /// visible angle brackets. A caller constructing this is stating that the
46 /// contents are trusted; nothing here can check that for them.
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub struct Markup<'a>(pub &'a str);
49
50 /// One option of a select.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub struct Choice<'a> {
53 /// What is submitted.
54 pub value: &'a str,
55 /// What is read.
56 pub label: &'a str,
57 }
58
59 impl<'a> Choice<'a> {
60 /// An option whose submitted value is also its label.
61 #[must_use]
62 pub const fn plain(value: &'a str) -> Self {
63 Self {
64 value,
65 label: value,
66 }
67 }
68 }
69
70 /// What the field currently holds.
71 ///
72 /// An enum rather than a bag of optional fields, on the same reasoning
73 /// [`makeover_layout::Depth`] is one: a select with no options and a checkbox
74 /// with a string value are both unsayable here, where a struct would let them
75 /// be said and then have to cope.
76 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77 pub enum Value<'a> {
78 /// Nothing yet.
79 #[default]
80 Absent,
81 /// The value of anything that takes typed text.
82 Text(&'a str),
83 /// The options of a select, and which of them is current.
84 Chosen {
85 /// Every option, in the order they are offered.
86 options: &'a [Choice<'a>],
87 /// The current value. Matched against each option's `value`.
88 value: &'a str,
89 },
90 /// A checkbox, on or off.
91 On(bool),
92 }
93
94 impl<'a> Value<'a> {
95 /// The value as text, for the kinds that submit one.
96 const fn as_text(&self) -> &'a str {
97 match self {
98 Self::Text(text) | Self::Chosen { value: text, .. } => text,
99 Self::Absent | Self::On(_) => "",
100 }
101 }
102 }
103
104 /// Everything about the field that the description does not carry.
105 #[derive(Debug, Clone, Copy, Default)]
106 pub struct Filling<'a> {
107 /// What the field holds now.
108 pub value: Value<'a>,
109 /// Ghost text shown while the field is empty.
110 pub placeholder: Option<&'a str>,
111 /// Markup appended inside the group, after the hint. Not escaped.
112 pub trailing: Option<Markup<'a>>,
113 /// Scopes the `id` attributes to one instance of the form.
114 ///
115 /// The field's `name` is what the value submits under and is the same
116 /// wherever the form appears; its `id` has to be unique in the document,
117 /// and those two facts stop agreeing the moment a form appears twice.
118 /// goingson hits this directly: its new-task and edit-task modals are the
119 /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
120 /// `label for` and `aria-describedby` pointing at the right control.
121 ///
122 /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
123 /// `name`, which would change what the form submits.
124 pub id_prefix: Option<&'a str>,
125 }
126
127 impl<'a> Filling<'a> {
128 /// A filling that carries a value and nothing else.
129 #[must_use]
130 pub const fn of(value: Value<'a>) -> Self {
131 Self {
132 value,
133 placeholder: None,
134 trailing: None,
135 id_prefix: None,
136 }
137 }
138
139 /// The document-unique id for a field of this name.
140 fn id_for(&self, name: &str) -> String {
141 match self.id_prefix {
142 Some(prefix) => format!("{}-{}", escape(prefix), escape(name)),
143 None => escape(name),
144 }
145 }
146 }
147
148 /// Encode the five characters that let a value stop being a value.
149 ///
150 /// Sound in element text and in a double-quoted attribute alike, which is the
151 /// property `textContent`-based escaping cannot have. Both sinks are covered by
152 /// one function so that no call site has to choose, here or downstream.
153 #[must_use]
154 pub fn escape(text: &str) -> String {
155 let mut out = String::with_capacity(text.len());
156 for ch in text.chars() {
157 match ch {
158 '&' => out.push_str("&amp;"),
159 '<' => out.push_str("&lt;"),
160 '>' => out.push_str("&gt;"),
161 '"' => out.push_str("&quot;"),
162 '\'' => out.push_str("&#39;"),
163 other => out.push(other),
164 }
165 }
166 out
167 }
168
169 /// The `type` an input takes for a kind.
170 ///
171 /// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
172 const fn input_type(kind: FieldKind) -> &'static str {
173 match kind {
174 FieldKind::Secret => "password",
175 FieldKind::Number => "number",
176 FieldKind::Checkbox => "checkbox",
177 FieldKind::Hidden => "hidden",
178 // Select and Textarea are not inputs at all; they never reach here.
179 FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
180 }
181 }
182
183 /// The attributes every visible control carries, error state included.
184 ///
185 /// `aria-invalid` is the whole reason the error state is readable at all: the
186 /// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
187 /// than on a class, so a control rendered already-invalid without it is styled
188 /// as if nothing were wrong. goingson's runtime validation path sets the
189 /// attribute and its initial render does not, which is exactly the drift one
190 /// emitter removes.
191 /// `id` and `name` arrive separately because they are not the same fact. The
192 /// name is what submits and is fixed by the description; the id has to be
193 /// unique in the document and so carries [`Filling::id_prefix`] when a form
194 /// appears more than once.
195 fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
196 let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
197 if field.required {
198 attrs.push_str(" required");
199 }
200 if field.invalid() {
201 attrs.push_str(" aria-invalid=\"true\"");
202 }
203
204 // Both associations, in the order they are useful: the standing help, then
205 // what is currently wrong. goingson's runtime path points describedby at
206 // the error alone and drops the hint association it never made in the first
207 // place; naming both here means the hint survives an error appearing.
208 let mut described = Vec::new();
209 if field.hint.is_some() {
210 described.push(format!("{id}-hint"));
211 }
212 if field.error.is_some() {
213 described.push(format!("{id}-error"));
214 }
215 if !described.is_empty() {
216 let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" "));
217 }
218 attrs
219 }
220
221 /// The options of a select, with an unmatched current value carried as its own.
222 ///
223 /// A select handed a value no option carries renders with nothing selected, the
224 /// browser falls back to the first option, and the next save writes a value
225 /// nobody chose. goingson hit exactly that with a backup-retention default of
226 /// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
227 /// here so the second app gets it without hitting the bug first.
228 fn options_html(options: &[Choice<'_>], value: &str) -> String {
229 let mut html = String::new();
230 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
231 let escaped = escape(value);
232 let _ = write!(
233 html,
234 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
235 );
236 }
237 for opt in options {
238 let selected = if opt.value == value { " selected" } else { "" };
239 let _ = write!(
240 html,
241 "<option value=\"{}\"{selected}>{}</option>",
242 escape(opt.value),
243 escape(opt.label)
244 );
245 }
246 html
247 }
248
249 /// The control itself, without its label, hint or error.
250 fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
251 let id = filling.id_for(field.name);
252 let attrs = control_attributes(field, &id, field.name);
253 let field_class = class("field", opts);
254 let placeholder = filling.placeholder.map_or_else(String::new, |text| {
255 format!(" placeholder=\"{}\"", escape(text))
256 });
257
258 match field.kind {
259 FieldKind::Textarea => format!(
260 "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
261 escape(filling.value.as_text())
262 ),
263 FieldKind::Select => {
264 let options = match filling.value {
265 Value::Chosen { options, value } => options_html(options, value),
266 // Described as a select and filled as something else. Emitting
267 // an empty select says so on screen rather than in a log.
268 _ => String::new(),
269 };
270 format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
271 }
272 FieldKind::Checkbox => {
273 let checked = if matches!(filling.value, Value::On(true)) {
274 " checked"
275 } else {
276 ""
277 };
278 format!(
279 "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
280 class("form-checkbox-label", opts),
281 escape(field.label)
282 )
283 }
284 // A secret never carries its value into the markup. `FieldKind::secret`
285 // is documented as a value that must not be round-tripped through
286 // anything that might persist it, and the DOM is such a thing: it is
287 // read by every extension on the page and is the first thing a crash
288 // reporter serialises. Neither app pre-fills one today, so this costs
289 // nothing and closes the door before something does.
290 FieldKind::Secret => format!(
291 "<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>"
292 ),
293 kind => format!(
294 "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
295 input_type(kind),
296 escape(filling.value.as_text())
297 ),
298 }
299 }
300
301 /// One field, as the group the app drops into its form.
302 ///
303 /// The shape is goingson's, down to the class names, so adoption there deletes
304 /// `renderFormField` rather than restyling anything. That is also why the class
305 /// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
306 /// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
307 /// emits only what it can generate from the description. Whether they should
308 /// move into the description is the next question this raises, not one it
309 /// answers.
310 ///
311 /// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
312 /// nothing drawn, which is what [`FieldKind::visible`] means.
313 ///
314 /// The error marks the group as well as the control. That is
315 /// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
316 /// cannot find the group from the message, so the group has to be told.
317 ///
318 /// ```
319 /// use makeover_layout::{Field, FieldKind};
320 /// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
321 ///
322 /// let field = Field::new(FieldKind::Text, "title", "Title");
323 /// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
324 ///
325 /// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
326 /// assert!(html.contains(r#"value="Ship it""#));
327 /// ```
328 #[must_use]
329 pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
330 let id = filling.id_for(field.name);
331
332 if !field.kind.visible() {
333 // Name only, no id: a hidden field is never pointed at by a label or a
334 // description, so the one attribute it needs is the one that submits.
335 return format!(
336 "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
337 escape(field.name),
338 escape(filling.value.as_text())
339 );
340 }
341
342 let mut html = format!("<div class=\"{}", class("form-group", opts));
343 if field.invalid() {
344 html.push_str(" has-error");
345 }
346 if field.extended {
347 // The disclosure that hides these is a property of the form, not of the
348 // field, so the field is marked and the app opens or closes the group.
349 html.push_str("\" data-extended=\"true");
350 }
351 html.push_str("\">");
352
353 // A checkbox labels itself, on the right of the box. Both apps special-case
354 // this inline today, which is the tell that it belongs in the description;
355 // `FieldKind::labels_itself` is where it went.
356 if !field.kind.labels_itself() {
357 let _ = write!(
358 html,
359 "<label class=\"{}\" for=\"{id}\">{}</label>",
360 class("form-label", opts),
361 escape(field.label)
362 );
363 }
364
365 html.push_str(&control_html(field, filling, opts));
366
367 if let Some(hint) = field.hint {
368 let _ = write!(
369 html,
370 "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
371 class("form-hint", opts),
372 escape(hint)
373 );
374 }
375 if let Some(Markup(markup)) = filling.trailing {
376 html.push_str(markup);
377 }
378 if let Some(error) = field.error {
379 let _ = write!(
380 html,
381 "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
382 class("form-error", opts),
383 escape(error)
384 );
385 }
386
387 html.push_str("</div>");
388 html
389 }
390
391 #[cfg(test)]
392 mod tests {
393 use super::*;
394
395 fn field(kind: FieldKind) -> Field<'static> {
396 Field::new(kind, "title", "Title")
397 }
398
399 #[test]
400 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
401 // The payload from goingson's own CHRONIC-XSS regression test.
402 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
403 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
404 // The payload survives as text, which is the point: it is inert
405 // because the quote that would have closed the attribute is encoded,
406 // not because the words were filtered.
407 assert!(!html.contains("\" onfocus"), "{html}");
408 assert!(
409 html.contains("value=\"x&quot; onfocus=alert(1) autofocus=&quot;\""),
410 "{html}"
411 );
412 }
413
414 #[test]
415 fn a_label_cannot_open_a_tag() {
416 let mut f = field(FieldKind::Text);
417 f.label = "<script>alert(1)</script>";
418 let html = field_html(&f, &Filling::default(), &Emit::default());
419 assert!(!html.contains("<script>"), "{html}");
420 assert!(html.contains("&lt;script&gt;"), "{html}");
421 }
422
423 #[test]
424 fn every_escaped_sink_is_covered_by_the_one_escaper() {
425 assert_eq!(escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#39;");
426 // The character `textContent` serialization leaves alone, which is why
427 // the app needs two escapers and this needs one.
428 assert!(escape("\"").contains("&quot;"));
429 }
430
431 #[test]
432 fn markup_is_the_only_way_past_the_escaping() {
433 let filling = Filling {
434 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
435 ..Filling::default()
436 };
437 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
438 assert!(html.contains("<div class=\"recurrence-config\"></div>"), "{html}");
439 }
440
441 #[test]
442 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
443 let mut f = field(FieldKind::Text);
444 f.error = Some("Required");
445 let opts = Emit::default();
446 let html = field_html(&f, &Filling::default(), &opts);
447 assert!(html.contains("aria-invalid=\"true\""), "{html}");
448 // The selector the CSS side emits for exactly this state.
449 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
450 // And the group is marked too, which a renderer without descendant
451 // selectors depends on.
452 assert!(html.contains("has-error"), "{html}");
453 }
454
455 #[test]
456 fn a_valid_field_claims_nothing_about_being_invalid() {
457 let html = field_html(&field(FieldKind::Text), &Filling::default(), &Emit::default());
458 assert!(!html.contains("aria-invalid"), "{html}");
459 assert!(!html.contains("has-error"), "{html}");
460 }
461
462 #[test]
463 fn the_hint_survives_an_error_arriving() {
464 let mut f = field(FieldKind::Text);
465 f.hint = Some("Keep it short");
466 f.error = Some("Required");
467 let html = field_html(&f, &Filling::default(), &Emit::default());
468 assert!(
469 html.contains("aria-describedby=\"title-hint title-error\""),
470 "{html}"
471 );
472 }
473
474 #[test]
475 fn a_secret_never_carries_its_value_into_the_markup() {
476 let filling = Filling::of(Value::Text("hunter2"));
477 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
478 assert!(!html.contains("hunter2"), "{html}");
479 assert!(html.contains("type=\"password\""), "{html}");
480 }
481
482 #[test]
483 fn a_hidden_field_is_the_input_and_nothing_else() {
484 let filling = Filling::of(Value::Text("42"));
485 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
486 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
487 }
488
489 #[test]
490 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
491 let html = field_html(
492 &field(FieldKind::Checkbox),
493 &Filling::of(Value::On(true)),
494 &Emit::default(),
495 );
496 assert!(!html.contains("form-label"), "{html}");
497 assert!(html.contains("checked"), "{html}");
498 assert!(html.contains("<span>Title</span>"), "{html}");
499 }
500
501 #[test]
502 fn a_select_keeps_a_value_no_option_carries() {
503 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
504 let filling = Filling::of(Value::Chosen {
505 options: &options,
506 value: "10",
507 });
508 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
509 assert!(html.contains("data-unmatched=\"true\""), "{html}");
510 // Selected, so the next save round-trips it rather than writing the
511 // first option over the top of it.
512 assert!(html.contains("<option value=\"10\" selected"), "{html}");
513 }
514
515 #[test]
516 fn a_select_marks_the_option_that_matches() {
517 let options = [Choice::plain("1"), Choice::plain("3")];
518 let filling = Filling::of(Value::Chosen {
519 options: &options,
520 value: "3",
521 });
522 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
523 assert!(html.contains("<option value=\"3\" selected>3</option>"), "{html}");
524 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
525 assert!(!html.contains("data-unmatched"), "{html}");
526 }
527
528 #[test]
529 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
530 let filling = Filling::of(Value::Text("two\nlines"));
531 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
532 assert!(html.contains(">two\nlines</textarea>"), "{html}");
533 }
534
535 #[test]
536 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
537 let opts = Emit {
538 class_prefix: "mk-",
539 ..Emit::default()
540 };
541 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
542 assert!(html.contains("class=\"mk-form-group\""), "{html}");
543 assert!(html.contains("class=\"mk-field\""), "{html}");
544 }
545
546 #[test]
547 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
548 let mut f = field(FieldKind::Text);
549 f.extended = true;
550 let html = field_html(&f, &Filling::default(), &Emit::default());
551 assert!(html.contains("data-extended=\"true\""), "{html}");
552 }
553
554 /// The prefix scopes the id and leaves the name alone. Prefixing the name
555 /// too would change what the form submits, which is the failure this pair
556 /// of assertions exists to catch rather than describe.
557 #[test]
558 fn the_id_prefix_scopes_the_id_and_never_the_name() {
559 let mut f = field(FieldKind::Text);
560 f.hint = Some("Keep it short");
561 f.error = Some("Required");
562 let filling = Filling {
563 id_prefix: Some("form-modal-task-edit"),
564 ..Filling::default()
565 };
566 let html = field_html(&f, &filling, &Emit::default());
567
568 assert!(html.contains(r#"id="form-modal-task-edit-title""#), "{html}");
569 assert!(html.contains(r#"name="title""#), "{html}");
570 assert!(!html.contains(r#"name="form-modal-task-edit-title""#), "{html}");
571
572 // The label and both associations follow the id, or they point at
573 // nothing once the same form is on screen twice.
574 assert!(
575 html.contains(r#"for="form-modal-task-edit-title""#),
576 "{html}"
577 );
578 assert!(
579 html.contains(
580 r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
581 ),
582 "{html}"
583 );
584 assert!(
585 html.contains(r#"id="form-modal-task-edit-title-hint""#),
586 "{html}"
587 );
588 }
589
590 #[test]
591 fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
592 let filling = Filling {
593 value: Value::Text("42"),
594 id_prefix: Some("scoped"),
595 ..Filling::default()
596 };
597 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
598 assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
599 }
600
601 #[test]
602 fn no_prefix_leaves_the_id_as_the_name() {
603 let html = field_html(&field(FieldKind::Text), &Filling::default(), &Emit::default());
604 assert!(html.contains(r#"id="title" name="title""#), "{html}");
605 }
606 }
607