//! Phase B, the forms half: [`makeover_layout::Field`] rendered to HTML. //! //! # Why this emits strings //! //! Both webview apps build their markup as strings and hand it to `innerHTML`: //! goingson's `renderFormField` returns a template literal that fifteen call //! sites interpolate into larger literals, and Balanced Breakfast's builds //! nodes but appends them into the same string-built forms. Returning nodes //! would rewrite the surrounding templates as well, which makes it a migration //! rather than an adoption. So: strings, and the escaping comes with them. //! //! # Why one escaper is enough here //! //! goingson carries four escapers and 543 call sites that must pick between //! them, because `escapeHtml` is built on `textContent` serialization and //! **`textContent` refuses to encode `"`**. That is what makes it unsound in an //! attribute, and it is the whole reason the choice exists. Its `escape.js` //! records the finding as the CHRONIC-XSS seal, and its test suite has a gate //! keeping the unsafe one off the namespace. //! //! [`escape`] here is not built on that, so it encodes the quote along with //! everything else, which makes one function sound in both sinks. The four-way //! choice does not move into Rust: it disappears. Nothing in this module hands //! an unescaped value to the output except through [`Markup`], which a caller //! has to name. //! //! # What the description does not carry //! //! [`Field`] describes the field and not its contents, so three things arrive //! from the renderer side in [`Filling`]: the current value, the options of a //! select, and the placeholder. The first two are genuinely renderer state. The //! third is user-facing text and belongs with `label` and `hint` in //! makeover-layout; it lives here because that crate is published and adding a //! field to `Field` is a breaking change, not because this is its home. use crate::{Emit, class}; use makeover_layout::{Field, FieldKind}; use std::fmt::Write as _; /// A string that is already markup, and is emitted without escaping. /// /// The one hole in the escaping, and it has to be named to be used. goingson /// has two live callers that need it, both passing a recurrence-config block /// built elsewhere, and both would otherwise have their markup rendered as /// visible angle brackets. A caller constructing this is stating that the /// contents are trusted; nothing here can check that for them. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Markup<'a>(pub &'a str); /// One option of a select. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Choice<'a> { /// What is submitted. pub value: &'a str, /// What is read. pub label: &'a str, } impl<'a> Choice<'a> { /// An option whose submitted value is also its label. #[must_use] pub const fn plain(value: &'a str) -> Self { Self { value, label: value, } } } /// What the field currently holds. /// /// An enum rather than a bag of optional fields, on the same reasoning /// [`makeover_layout::Depth`] is one: a select with no options and a checkbox /// with a string value are both unsayable here, where a struct would let them /// be said and then have to cope. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Value<'a> { /// Nothing yet. #[default] Absent, /// The value of anything that takes typed text. Text(&'a str), /// The options of a select, and which of them is current. Chosen { /// Every option, in the order they are offered. options: &'a [Choice<'a>], /// The current value. Matched against each option's `value`. value: &'a str, }, /// A checkbox, on or off. On(bool), } impl<'a> Value<'a> { /// The value as text, for the kinds that submit one. const fn as_text(&self) -> &'a str { match self { Self::Text(text) | Self::Chosen { value: text, .. } => text, Self::Absent | Self::On(_) => "", } } } /// Everything about the field that the description does not carry. #[derive(Debug, Clone, Copy, Default)] pub struct Filling<'a> { /// What the field holds now. pub value: Value<'a>, /// Ghost text shown while the field is empty. pub placeholder: Option<&'a str>, /// Markup appended inside the group, after the hint. Not escaped. pub trailing: Option>, /// Scopes the `id` attributes to one instance of the form. /// /// The field's `name` is what the value submits under and is the same /// wherever the form appears; its `id` has to be unique in the document, /// and those two facts stop agreeing the moment a form appears twice. /// goingson hits this directly: its new-task and edit-task modals are the /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep /// `label for` and `aria-describedby` pointing at the right control. /// /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to /// `name`, which would change what the form submits. pub id_prefix: Option<&'a str>, } impl<'a> Filling<'a> { /// A filling that carries a value and nothing else. #[must_use] pub const fn of(value: Value<'a>) -> Self { Self { value, placeholder: None, trailing: None, id_prefix: None, } } /// The document-unique id for a field of this name. fn id_for(&self, name: &str) -> String { match self.id_prefix { Some(prefix) => format!("{}-{}", escape(prefix), escape(name)), None => escape(name), } } } /// Encode the five characters that let a value stop being a value. /// /// Sound in element text and in a double-quoted attribute alike, which is the /// property `textContent`-based escaping cannot have. Both sinks are covered by /// one function so that no call site has to choose, here or downstream. #[must_use] pub fn escape(text: &str) -> String { let mut out = String::with_capacity(text.len()); for ch in text.chars() { match ch { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), other => out.push(other), } } out } /// The `type` an input takes for a kind. /// /// [`FieldKind::Secret`] is `password`, which both apps already map by hand. const fn input_type(kind: FieldKind) -> &'static str { match kind { FieldKind::Secret => "password", FieldKind::Number => "number", FieldKind::Checkbox => "checkbox", FieldKind::Hidden => "hidden", // Select and Textarea are not inputs at all; they never reach here. FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text", } } /// The attributes every visible control carries, error state included. /// /// `aria-invalid` is the whole reason the error state is readable at all: the /// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather /// than on a class, so a control rendered already-invalid without it is styled /// as if nothing were wrong. goingson's runtime validation path sets the /// attribute and its initial render does not, which is exactly the drift one /// emitter removes. /// `id` and `name` arrive separately because they are not the same fact. The /// name is what submits and is fixed by the description; the id has to be /// unique in the document and so carries [`Filling::id_prefix`] when a form /// appears more than once. fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String { let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name)); if field.required { attrs.push_str(" required"); } if field.invalid() { attrs.push_str(" aria-invalid=\"true\""); } // Both associations, in the order they are useful: the standing help, then // what is currently wrong. goingson's runtime path points describedby at // the error alone and drops the hint association it never made in the first // place; naming both here means the hint survives an error appearing. let mut described = Vec::new(); if field.hint.is_some() { described.push(format!("{id}-hint")); } if field.error.is_some() { described.push(format!("{id}-error")); } if !described.is_empty() { let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" ")); } attrs } /// The options of a select, with an unmatched current value carried as its own. /// /// A select handed a value no option carries renders with nothing selected, the /// browser falls back to the first option, and the next save writes a value /// nobody chose. goingson hit exactly that with a backup-retention default of /// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is /// here so the second app gets it without hitting the bug first. fn options_html(options: &[Choice<'_>], value: &str) -> String { let mut html = String::new(); if !value.is_empty() && !options.iter().any(|opt| opt.value == value) { let escaped = escape(value); let _ = write!( html, "" ); } for opt in options { let selected = if opt.value == value { " selected" } else { "" }; let _ = write!( html, "", escape(opt.value), escape(opt.label) ); } html } /// The control itself, without its label, hint or error. fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String { let id = filling.id_for(field.name); let attrs = control_attributes(field, &id, field.name); let field_class = class("field", opts); let placeholder = filling.placeholder.map_or_else(String::new, |text| { format!(" placeholder=\"{}\"", escape(text)) }); match field.kind { FieldKind::Textarea => format!( "", escape(filling.value.as_text()) ), FieldKind::Select => { let options = match filling.value { Value::Chosen { options, value } => options_html(options, value), // Described as a select and filled as something else. Emitting // an empty select says so on screen rather than in a log. _ => String::new(), }; format!("") } FieldKind::Checkbox => { let checked = if matches!(filling.value, Value::On(true)) { " checked" } else { "" }; format!( "", class("form-checkbox-label", opts), escape(field.label) ) } // A secret never carries its value into the markup. `FieldKind::secret` // is documented as a value that must not be round-tripped through // anything that might persist it, and the DOM is such a thing: it is // read by every extension on the page and is the first thing a crash // reporter serialises. Neither app pre-fills one today, so this costs // nothing and closes the door before something does. FieldKind::Secret => format!( "" ), kind => format!( "", input_type(kind), escape(filling.value.as_text()) ), } } /// One field, as the group the app drops into its form. /// /// The shape is goingson's, down to the class names, so adoption there deletes /// `renderFormField` rather than restyling anything. That is also why the class /// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`, /// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately /// emits only what it can generate from the description. Whether they should /// move into the description is the next question this raises, not one it /// answers. /// /// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and /// nothing drawn, which is what [`FieldKind::visible`] means. /// /// The error marks the group as well as the control. That is /// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors /// cannot find the group from the message, so the group has to be told. /// /// ``` /// use makeover_layout::{Field, FieldKind}; /// use makeover_webview::{Emit, form::{Filling, Value, field_html}}; /// /// let field = Field::new(FieldKind::Text, "title", "Title"); /// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default()); /// /// assert!(html.contains(r#""#)); /// assert!(html.contains(r#"value="Ship it""#)); /// ``` #[must_use] pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String { let id = filling.id_for(field.name); if !field.kind.visible() { // Name only, no id: a hidden field is never pointed at by a label or a // description, so the one attribute it needs is the one that submits. return format!( "", escape(field.name), escape(filling.value.as_text()) ); } let mut html = format!("
"); // A checkbox labels itself, on the right of the box. Both apps special-case // this inline today, which is the tell that it belongs in the description; // `FieldKind::labels_itself` is where it went. if !field.kind.labels_itself() { let _ = write!( html, "", class("form-label", opts), escape(field.label) ); } html.push_str(&control_html(field, filling, opts)); if let Some(hint) = field.hint { let _ = write!( html, "
{}
", class("form-hint", opts), escape(hint) ); } if let Some(Markup(markup)) = filling.trailing { html.push_str(markup); } if let Some(error) = field.error { let _ = write!( html, "
{}
", class("form-error", opts), escape(error) ); } html.push_str("
"); html } #[cfg(test)] mod tests { use super::*; fn field(kind: FieldKind) -> Field<'static> { Field::new(kind, "title", "Title") } #[test] fn a_value_cannot_break_out_of_the_attribute_it_sits_in() { // The payload from goingson's own CHRONIC-XSS regression test. let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\"")); let html = field_html(&field(FieldKind::Text), &filling, &Emit::default()); // The payload survives as text, which is the point: it is inert // because the quote that would have closed the attribute is encoded, // not because the words were filtered. assert!(!html.contains("\" onfocus"), "{html}"); assert!( html.contains("value=\"x" onfocus=alert(1) autofocus="\""), "{html}" ); } #[test] fn a_label_cannot_open_a_tag() { let mut f = field(FieldKind::Text); f.label = ""; let html = field_html(&f, &Filling::default(), &Emit::default()); assert!(!html.contains("