makeover_webview/form.rs
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//! One thing: the **current value**, which arrives in [`Filling`].
30//!
31//! It used to be three. Writing this emitter is what found them, and the other
32//! two turned out not to be renderer state at all — the placeholder is
33//! user-facing text that sits with `label` and `hint`, and a select's options
34//! are needed by every renderer, which is how each of them ends up inventing a
35//! near-miss of the same struct. Both moved down into `makeover-layout` 0.8.0,
36//! `Choice` included, and this crate reads them off [`Field`] now.
37//!
38//! The value stays, and it is not a leftover. A webview reads it back out of
39//! the DOM, an immediate-mode renderer writes through a `&mut`, and a terminal
40//! keeps an edit buffer; a description carrying it would have to carry a way to
41//! write it back, at which point it is a form model.
42
43use crate::{Emit, class, push_class};
44use makeover_layout::{Choice, Depth, Field, FieldKind, Selector};
45use std::fmt::Write as _;
46
47/// Every class this module can put in markup.
48///
49/// [`crate::facet::FACET_CLASSES`]' obligation, and the module where it was
50/// missing longest. Most of these carry no rule and never will: `.form-group`,
51/// `.form-label`, `.form-hint` and `.form-error` are the apps' own names, kept
52/// so adoption deletes goingson's `renderFormField` rather than restyling
53/// anything, and phase A emits only what it can generate from the description.
54/// A class with no rule is invisible to [`crate::vocabulary::vocabulary`],
55/// which reads the generated sheet, so the unruled half of a renderer's
56/// vocabulary can only be written down.
57///
58/// What went wrong without it: an app checking its stylesheet against
59/// [`crate::vocabulary::names`] concluded that its live `.form-group` and
60/// `.form-label` rules matched nothing and were safe to delete. quasi-webview
61/// carried them in a `MAKEOVER_UNLISTED` constant of its own until 0.59.0
62/// rather than let that happen.
63pub const FIELD_CLASSES: &[&str] = &[
64 "field",
65 "form-checkbox-label",
66 "form-editor-modes",
67 "form-editor-preview",
68 "form-error",
69 "form-group",
70 "form-hint",
71 "form-interval",
72 "form-label",
73 "form-option-reason",
74 "form-radio-group",
75 "form-radio-label",
76 "form-unit",
77];
78
79// `form-suggestions`, `form-suggestion` and `form-suggestion-detail` are
80// deliberately absent: [`suggestion_rules`] writes their look and
81// `quasi-webview` writes their markup, because a suggestion source is a route
82// and no description layer carries one. They reach the vocabulary through the
83// generated sheet, which is where a name this crate rules but does not emit
84// belongs.
85
86/// The state classes a field carries, which take no prefix.
87///
88/// `chosen` and `latched`'s convention, stated in
89/// [`crate::vocabulary::vocabulary`]: a state qualifies a prefixed component
90/// (`.mk-form-group.has-error`) rather than standing on its own, so a prefix
91/// moves the thing and not its state.
92///
93/// `has-error` marks the group and `visible` marks the message, which is
94/// [`makeover_layout::Field::invalid`]'s own reasoning: a renderer with no
95/// descendant selectors cannot find the group from the message, so both are
96/// told.
97pub const FIELD_STATE_CLASSES: &[&str] = &["has-error", "visible"];
98
99/// A string that is already markup, and is emitted without escaping.
100///
101/// The one hole in the escaping, and it has to be named to be used. goingson
102/// has two live callers that need it, both passing a recurrence-config block
103/// built elsewhere, and both would otherwise have their markup rendered as
104/// visible angle brackets. A caller constructing this is stating that the
105/// contents are trusted; nothing here can check that for them.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct Markup<'a>(pub &'a str);
108
109/// What the field currently holds.
110///
111/// An enum rather than a bag of optional fields, on the same reasoning
112/// [`makeover_layout::Depth`] is one: a checkbox holding a string is unsayable
113/// here, where a struct would let it be said and then have to cope.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub enum Value<'a> {
116 /// Nothing yet.
117 #[default]
118 Absent,
119 /// The value of anything that takes typed text, a select included: what a
120 /// select holds is the `value` of one of [`Field::options`]'s
121 /// [`Choice`]s.
122 ///
123 /// It carried the options too until makeover-layout 0.8.0 moved them onto
124 /// the field, which collapsed a `Chosen { options, value }` variant into
125 /// this one. `makeover-immediate` arrived at the same single-variant shape
126 /// on its own, from the other direction.
127 Text(&'a str),
128 /// A checkbox, on or off.
129 On(bool),
130 /// Both ends of a [`FieldKind::Interval`], lower first.
131 ///
132 /// Two values rather than one string with a separator, for
133 /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
134 /// interval submits under two names, so it comes back as two values, and a
135 /// delimiter this crate owned could appear inside either of them.
136 ///
137 /// Either end may be empty while the other stands. "Over 120 BPM" is a
138 /// lower end and no upper one, and it is an answer rather than a
139 /// half-filled form.
140 ///
141 /// Added 0.56.0 with makeover-layout 0.34.0.
142 Between {
143 /// What the lower box holds now.
144 lower: &'a str,
145 /// What the upper box holds now.
146 upper: &'a str,
147 },
148}
149
150impl<'a> Value<'a> {
151 /// The value as text, for the kinds that submit one.
152 const fn as_text(&self) -> &'a str {
153 match self {
154 Self::Text(text) | Self::Between { lower: text, .. } => text,
155 Self::Absent | Self::On(_) => "",
156 }
157 }
158}
159
160impl<'a> Value<'a> {
161 /// The upper end, for the one variant that has one.
162 const fn upper_text(&self) -> &'a str {
163 match self {
164 Self::Between { upper, .. } => upper,
165 Self::Absent | Self::Text(_) | Self::On(_) => "",
166 }
167 }
168}
169
170/// Everything about the field that the description does not carry.
171#[derive(Debug, Clone, Copy, Default)]
172pub struct Filling<'a> {
173 /// What the field holds now.
174 pub value: Value<'a>,
175 /// Markup appended inside the group, after the hint. Not escaped.
176 pub trailing: Option<Markup<'a>>,
177 /// Attributes written onto the control element itself. Not escaped.
178 ///
179 /// [`trailing`](Self::trailing)'s argument at attribute scale: a host knows
180 /// facts about the control that no description layer carries, and until
181 /// this existed the only way to attach one was to stop calling this emitter
182 /// and write a second one. quasi's suggestion source is the first caller —
183 /// a field that owns a list of candidates is a `role="combobox"` pointing
184 /// at the list it owns, and neither half is anything
185 /// [`makeover_layout::Field`] can say.
186 ///
187 /// Written verbatim, so a caller supplies `attr="value"` pairs with no
188 /// leading space and does its own escaping. It is [`Markup`]'s hole in the
189 /// same wall, named the same way so a caller has to state that the contents
190 /// are trusted.
191 ///
192 /// A [`FieldKind::Radio`] drops them, and that is deliberate rather than an
193 /// oversight: a radio group is a set of sibling inputs with no one control
194 /// element, so there is nowhere honest to put an attribute meant for the
195 /// control. The group carries the descriptions for the same reason.
196 pub control_attrs: Option<Markup<'a>>,
197 /// Scopes the `id` attributes to one instance of the form.
198 ///
199 /// The field's `name` is what the value submits under and is the same
200 /// wherever the form appears; its `id` has to be unique in the document,
201 /// and those two facts stop agreeing the moment a form appears twice.
202 /// goingson hits this directly: its new-task and edit-task modals are the
203 /// same field set, so it prefixes `form-modal-task-new` or `-edit` to keep
204 /// `label for` and `aria-describedby` pointing at the right control.
205 ///
206 /// Applies to `id`, `for` and the `-hint` / `-error` associations. Never to
207 /// `name`, which would change what the form submits.
208 pub id_prefix: Option<&'a str>,
209}
210
211impl<'a> Filling<'a> {
212 /// A filling that carries a value and nothing else.
213 #[must_use]
214 pub const fn of(value: Value<'a>) -> Self {
215 Self {
216 value,
217 trailing: None,
218 control_attrs: None,
219 id_prefix: None,
220 }
221 }
222
223 /// The document-unique id for a field of this name.
224 fn id_for(&self, name: &str) -> String {
225 let mut id = String::new();
226 if let Some(prefix) = self.id_prefix {
227 escape_into(prefix, &mut id);
228 id.push('-');
229 }
230 escape_into(name, &mut id);
231 id
232 }
233}
234
235/// Encode the five characters that let a value stop being a value, into a
236/// buffer the caller already has.
237///
238/// The form the emitters use. [`escape`] is this with a `String` allocated
239/// around it, and the allocation is the whole difference: a described screen
240/// escapes once per attribute and once per run of text, so a function that
241/// returns a `String` allocates a few thousand times to produce one page, where
242/// a template engine writes its escaped bytes straight into the output buffer.
243/// Measured 2026-08-14 against a real pane, that gap was 85% of a 42x rendering
244/// cost, and this is the half of the fix that lives in this crate.
245///
246/// Sound in element text and in a double-quoted attribute alike, which is the
247/// property `textContent`-based escaping cannot have. Both sinks are covered by
248/// one function so that no call site has to choose, here or downstream.
249///
250/// Copies in runs rather than per character. All five encoded characters are
251/// ASCII, so a byte scan cannot land inside a multi-byte character and the
252/// slice between two of them is always a valid `&str`. Text with nothing to
253/// encode — which is most text — is one `push_str` of the whole thing.
254pub fn escape_into(text: &str, out: &mut String) {
255 let mut start = 0;
256 for (index, byte) in text.bytes().enumerate() {
257 let encoded = match byte {
258 b'&' => "&",
259 b'<' => "<",
260 b'>' => ">",
261 b'"' => """,
262 b'\'' => "'",
263 _ => continue,
264 };
265 out.push_str(&text[start..index]);
266 out.push_str(encoded);
267 start = index + 1;
268 }
269 out.push_str(&text[start..]);
270}
271
272/// Encode the five characters that let a value stop being a value.
273///
274/// [`escape_into`] with a buffer of its own, for the callers that want a value
275/// rather than an append: a caller assembling an attribute out of several
276/// pieces, and everything outside this crate that took this function before the
277/// buffer-writing form existed. Emitting into a buffer you already hold is the
278/// cheaper path and the one this crate's own emitters take.
279#[must_use]
280pub fn escape(text: &str) -> String {
281 let mut out = String::with_capacity(text.len());
282 escape_into(text, &mut out);
283 out
284}
285
286/// The `type` an input takes for a kind.
287///
288/// [`FieldKind::Secret`] is `password`, which both apps already map by hand.
289const fn input_type(kind: FieldKind) -> &'static str {
290 match kind {
291 FieldKind::Secret => "password",
292 FieldKind::Number => "number",
293 FieldKind::Checkbox => "checkbox",
294 FieldKind::File => "file",
295 FieldKind::Hidden => "hidden",
296 // Not decoration. Each of these changes the keyboard a touch device
297 // offers and turns on the platform's own validation, which is why the
298 // description names them apart from text rather than letting the app
299 // pass an HTML type through.
300 FieldKind::Email => "email",
301 FieldKind::Url => "url",
302 FieldKind::Tel => "tel",
303 // The same argument, and it buys more here than anywhere else in this
304 // list: a native picker as well as the keyboard and the validation.
305 // Both submit the format `makeover-layout` names, `DATE_FORMAT` and
306 // `DATETIME_FORMAT`, so honouring it costs this renderer nothing.
307 FieldKind::Date => "date",
308 FieldKind::DateTime => "datetime-local",
309 FieldKind::Radio => "radio",
310 // The clearest case in this list that a kind is not decoration: a
311 // number and a range submit the same value and are different controls,
312 // and the browser is the one drawing the difference.
313 FieldKind::Range => "range",
314 // Select and Textarea are not inputs at all; they never reach here.
315 // Radio is one, but it is emitted once per option by `radio_html` and
316 // so does not reach here either.
317 FieldKind::Text | FieldKind::Select | FieldKind::Textarea | FieldKind::Rich => "text",
318 // A kind added to the description since this renderer was built. Text
319 // accepts any value the others would, so it degrades rather than
320 // dropping the field.
321 _ => "text",
322 }
323}
324
325/// The attributes every visible control carries, error state included.
326///
327/// `aria-invalid` is the whole reason the error state is readable at all: the
328/// generated stylesheet keys the danger ring on `[aria-invalid="true"]` rather
329/// than on a class, so a control rendered already-invalid without it is styled
330/// as if nothing were wrong. goingson's runtime validation path sets the
331/// attribute and its initial render does not, which is exactly the drift one
332/// emitter removes.
333/// `id` and `name` arrive separately because they are not the same fact. The
334/// name is what submits and is fixed by the description; the id has to be
335/// unique in the document and so carries [`Filling::id_prefix`] when a form
336/// appears more than once.
337/// The `accept` attribute, from the description's accept list.
338///
339/// makeover-layout 0.31.0. The list is comma-joined because that is the
340/// attribute's own format, and each entry writes itself: a family is its
341/// wildcard media type, a media type is itself, a suffix is itself with its
342/// leading dot. Nothing is normalised on the way through -- `.tar.gz` is two
343/// dots and the browser is fine with it.
344///
345/// An empty list emits no attribute at all, which is the browser's own "any
346/// file" and is what the description means by listing nothing. Emitting
347/// `accept=""` instead would be a filter that matches nothing on some browsers
348/// and everything on others.
349///
350/// It is a filter and not a guarantee, on the browser's side as much as here:
351/// the picker keeps an "All Files" escape and the user may take it. Whoever
352/// validated still validates.
353fn push_accept(out: &mut String, field: &Field<'_>) {
354 if field.accept.is_empty() {
355 return;
356 }
357 out.push_str(" accept=\"");
358 for (index, one) in field.accept.iter().enumerate() {
359 if index > 0 {
360 out.push(',');
361 }
362 escape_into(one.as_str(), out);
363 }
364 out.push('"');
365}
366
367/// The extent and the granularity, as the browser spells them.
368///
369/// Its own function because an interval writes them onto both of its ends: they
370/// describe the axis rather than either end of it, which is what
371/// [`FieldKind::Interval`] says and what the six audiofiles filter axes are.
372fn push_bounds(out: &mut String, field: &Field<'_>) {
373 if let Some(min) = field.min {
374 out.push_str(" min=\"");
375 escape_into(min, out);
376 out.push('"');
377 }
378 if let Some(max) = field.max {
379 out.push_str(" max=\"");
380 escape_into(max, out);
381 out.push('"');
382 }
383 // The browser's own default is `step="1"`, which turns a 0-to-1 threshold
384 // into a two-position control. That is the granularity the description
385 // means when it says nothing, so this is emitted only when an app has said
386 // otherwise rather than defaulted here.
387 //
388 // A range takes its granularity from its curve as of makeover-layout
389 // 0.32.0, and every other kind keeps `Field::step`. See the crate header on
390 // what this renderer can and cannot do with a curve.
391 let step = if field.kind == FieldKind::Range {
392 field.curve.step()
393 } else {
394 field.step
395 };
396 if let Some(step) = step {
397 out.push_str(" step=\"");
398 escape_into(step, out);
399 out.push('"');
400 }
401}
402
403fn push_control_attributes(
404 out: &mut String,
405 field: &Field<'_>,
406 filling: &Filling<'_>,
407 id: &str,
408 name: &str,
409) {
410 let _ = write!(out, " id=\"{id}\" name=\"");
411 escape_into(name, out);
412 out.push('"');
413 if field.required {
414 out.push_str(" required");
415 }
416 // makeover-layout 0.11.0's constraints. The description carries the rule and
417 // this emits the browser's idiom for it, which is the model `required` has
418 // been using since before the crate wrote down that it carried none.
419 // Enforcement is still whoever validated's, and arrives back as `error`.
420 if let Some(limit) = field.max_length {
421 let _ = write!(out, " maxlength=\"{limit}\"");
422 }
423 push_bounds(out, field);
424 if field.invalid() {
425 out.push_str(" aria-invalid=\"true\"");
426 }
427
428 push_described_by(out, field, id);
429
430 // Last, so that a host attaching a fact of its own can see everything this
431 // emitter decided and cannot be overwritten by it. Duplicate attributes are
432 // the caller's to avoid: HTML takes the first of a repeated pair, so an
433 // attribute spelled here as well as there keeps this crate's answer.
434 if let Some(Markup(attrs)) = filling.control_attrs {
435 out.push(' ');
436 out.push_str(attrs);
437 }
438}
439
440/// The `aria-describedby` naming whatever of the hint and the error exist.
441///
442/// Both associations, in the order they are useful: the standing help, then
443/// what is currently wrong. goingson's runtime path points describedby at the
444/// error alone and drops the hint association it never made in the first place;
445/// naming both here means the hint survives an error appearing.
446///
447/// Its own function because a radio group carries it on the group rather than
448/// on a control, and one reading of "what describes this field" is the point.
449fn push_described_by(out: &mut String, field: &Field<'_>, id: &str) {
450 let unit = unit_of(field).is_some();
451 if field.hint.is_none() && field.error.is_none() && !unit {
452 return;
453 }
454 let mut written = false;
455 out.push_str(" aria-describedby=\"");
456 if field.hint.is_some() {
457 let _ = write!(out, "{id}-hint");
458 written = true;
459 }
460 // The unit before the error and after the hint, which is the order they are
461 // useful in: what the number is measured in is standing context like the
462 // hint, and what is wrong with it now comes last.
463 if unit {
464 if written {
465 out.push(' ');
466 }
467 let _ = write!(out, "{id}-unit");
468 written = true;
469 }
470 if field.error.is_some() {
471 if written {
472 out.push(' ');
473 }
474 let _ = write!(out, "{id}-error");
475 }
476 out.push('"');
477}
478
479/// The unit to draw beside this field's value, if there is one to draw.
480///
481/// Two conditions rather than one: the field has to carry a unit and its kind
482/// has to be one that means anything by it. `FieldKind::measurable` is the
483/// description answering the second, so this renderer keeps no list of its own
484/// of which kinds are quantities.
485fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
486 field.unit.filter(|_| field.kind.measurable())
487}
488
489/// Whether the field's control is a set of elements rather than one.
490///
491/// A DOM concern rather than a description one, which is why it is decided here
492/// and not in `makeover-layout`: `for` and `id` are an HTML association and
493/// egui has no counterpart to get wrong. A `<label for>` aimed at a radio group
494/// points at nothing, because no single element carries the group's id, so the
495/// association has to invert — the label takes an id and the group names itself
496/// with `aria-labelledby`.
497const fn is_group_control(kind: FieldKind) -> bool {
498 matches!(kind, FieldKind::Radio | FieldKind::Interval)
499}
500
501/// An interval: two number boxes inside one labelled group.
502///
503/// The markup MNW's discover sidebar writes by hand -- a `role="group"` with
504/// `aria-labelledby` pointing at the question, holding `min_price` and
505/// `max_price` -- which is HTML saying by hand exactly what
506/// [`FieldKind::Interval`] now says in the description. So this emits what that
507/// page already proved is right, rather than inventing a shape.
508///
509/// The group carries the error state and the descriptions, for
510/// [`push_radio`]'s reason: what is wrong is the answer, and marking one box
511/// invalid would name the wrong half of a fault that belongs to both ends.
512///
513/// # Both boxes take the same extent
514///
515/// [`Field::min`], [`Field::max`] and [`Field::step`] describe the axis rather
516/// than either end, so [`push_bounds`] writes them onto both. The crossing rule
517/// is not emitted, because the description does not carry it and the browser
518/// has no attribute for it: an upper end below the lower one is a refusal
519/// whoever validated hands back as [`Field::error`], which lands on the group.
520///
521/// # Which end is which, in words
522///
523/// `aria-label`, because the description states direction structurally -- the
524/// lower end's name is [`Field::name`] and the upper one's is
525/// [`Field::upper_name`] -- and never in words. Words for the ends are the
526/// host's, the same way a slider's readout is, and a page with visible Min and
527/// Max captions supplies them through [`Filling::trailing`] rather than having
528/// this crate own two strings of English.
529fn push_interval(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
530 let id = filling.id_for(field.name);
531
532 out.push_str("<div class=\"");
533 push_class(out, "form-interval", opts);
534 let _ = write!(out, "\" role=\"group\" aria-labelledby=\"{id}-label\"");
535 if field.invalid() {
536 out.push_str(" aria-invalid=\"true\"");
537 }
538 push_described_by(out, field, &id);
539 out.push('>');
540
541 // An interval with no upper name has one end that can be submitted, which
542 // is what the description said and is drawn honestly rather than repaired:
543 // `Field::interval` is what makes it unsayable, and inventing a name here
544 // would submit a parameter no handler is reading.
545 let ends: [(&str, &str, &str); 2] = [
546 ("lower", field.name, filling.value.as_text()),
547 (
548 "upper",
549 field.upper_name.unwrap_or(""),
550 filling.value.upper_text(),
551 ),
552 ];
553 for (end, name, value) in ends {
554 if name.is_empty() {
555 continue;
556 }
557 out.push_str("<input type=\"number\" class=\"");
558 push_class(out, "field", opts);
559 let _ = write!(out, "\" id=\"{id}-{end}\" name=\"");
560 escape_into(name, out);
561 let _ = write!(out, "\" aria-label=\"{end}\"");
562 if field.required {
563 out.push_str(" required");
564 }
565 push_bounds(out, field);
566 if let Some(text) = field.placeholder {
567 out.push_str(" placeholder=\"");
568 escape_into(text, out);
569 out.push('"');
570 }
571 out.push_str(" value=\"");
572 escape_into(value, out);
573 out.push_str("\">");
574 }
575
576 out.push_str("</div>");
577}
578
579/// A radio group: the options as sibling inputs sharing one `name`.
580///
581/// The group carries the error state and the descriptions, and the inputs carry
582/// what submits. That split is [`Field::invalid`]'s reasoning applied one level
583/// down: marking a single input invalid would say the wrong thing, since what
584/// is wrong is the answer to the question and not one of the alternatives.
585///
586/// Ids are numbered rather than built from the option values, which can hold
587/// anything a `&str` can — spaces and quotes included — and would otherwise
588/// have to be slugged into something unique by a rule this crate would then own.
589///
590/// `required` lands on every input, which is how HTML says a group is
591/// compulsory: the constraint is satisfied when any one of them is checked.
592fn push_radio(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
593 let id = filling.id_for(field.name);
594 let value = filling.value.as_text();
595 let name = escape(field.name);
596
597 out.push_str("<div class=\"");
598 push_class(out, "form-radio-group", opts);
599 let _ = write!(out, "\" role=\"radiogroup\" aria-labelledby=\"{id}-label\"");
600 if field.invalid() {
601 out.push_str(" aria-invalid=\"true\"");
602 }
603 push_described_by(out, field, &id);
604 out.push('>');
605
606 // A group described with no options emits an empty group, for the reason
607 // `Field::options` gives: an app whose option list has not loaded has
608 // exactly that, and an empty group says so on screen rather than in a log.
609 for (index, opt) in field.options.iter().enumerate() {
610 out.push_str("<label class=\"");
611 push_class(out, "form-radio-label", opts);
612 let _ = write!(
613 out,
614 "\"><input type=\"radio\" id=\"{id}-{index}\" name=\"{name}\" value=\""
615 );
616 escape_into(opt.value, out);
617 out.push('"');
618 if opt.value == value {
619 out.push_str(" checked");
620 }
621 if field.required {
622 out.push_str(" required");
623 }
624 // A radio group has room a `<select>` does not, so the reason gets its
625 // own element beside the label rather than being run into it. The class
626 // is what a stylesheet mutes; the text is there either way, which is
627 // the half that matters — the finding was a greyed control with its
628 // explanation behind a hover.
629 if let Some(reason) = opt.unavailable {
630 out.push_str(" disabled");
631 out.push_str("><span>");
632 escape_into(opt.label, out);
633 out.push_str("</span><span class=\"");
634 push_class(out, "form-option-reason", opts);
635 out.push_str("\">");
636 escape_into(reason, out);
637 out.push_str("</span></label>");
638 continue;
639 }
640 out.push_str("><span>");
641 escape_into(opt.label, out);
642 out.push_str("</span></label>");
643 }
644
645 out.push_str("</div>");
646}
647
648/// The options of a select: the unanswered instruction, an unmatched current
649/// value carried as its own, then the options themselves.
650///
651/// A select handed a value no option carries renders with nothing selected, the
652/// browser falls back to the first option, and the next save writes a value
653/// nobody chose. goingson hit exactly that with a backup-retention default of
654/// 10 against a 1/3/7/14/0 list, and grew this stray-option fix locally; it is
655/// here so the second app gets it without hitting the bug first.
656fn push_options(out: &mut String, field: &Field<'_>, options: &[Choice<'_>], value: &str) {
657 // The unanswered state, which HTML has no attribute for: `placeholder` is
658 // not a `<select>` attribute, and the idiom is an empty option that cannot
659 // be chosen back. `disabled` is what stops it being re-selected once the
660 // user has answered, and `selected` is what puts it in the closed control
661 // while the value is empty; together they read as an instruction rather
662 // than as an option.
663 //
664 // `required` keeps working through it rather than around it: the option's
665 // value is empty, so a required select with this showing is invalid, which
666 // is the true report on a question nobody has answered.
667 //
668 // Emitted only while the value is empty, so it does not sit in the open
669 // list once the field is answered. A non-empty value no option carries is a
670 // wrong answer rather than an absent one and takes the stray-option path
671 // below.
672 if value.is_empty()
673 && let Some(text) = field.placeholder
674 {
675 out.push_str("<option value=\"\" disabled selected>");
676 escape_into(text, out);
677 out.push_str("</option>");
678 }
679 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
680 // The one place an escaped value is worth keeping: it is written twice,
681 // as the option's value and as its text.
682 let escaped = escape(value);
683 let _ = write!(
684 out,
685 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
686 );
687 }
688 for opt in options {
689 out.push_str("<option value=\"");
690 escape_into(opt.value, out);
691 out.push('"');
692 if opt.value == value {
693 out.push_str(" selected");
694 }
695 // `disabled` is what the browser reads, and it says nothing about why.
696 // The reason goes in the option's own text, because a `<select>` gives
697 // its options no room for anything else: no title attribute the
698 // keyboard reaches, no second line, no element inside. So the row reads
699 // "Multi-sample: Drop a second sample onto the keyboard." and is the
700 // one place the precondition can be both attached to its option and
701 // read without a pointer.
702 if let Some(reason) = opt.unavailable {
703 out.push_str(" disabled");
704 out.push('>');
705 escape_into(opt.label, out);
706 out.push_str(": ");
707 escape_into(reason, out);
708 out.push_str("</option>");
709 continue;
710 }
711 out.push('>');
712 escape_into(opt.label, out);
713 out.push_str("</option>");
714 }
715}
716
717/// The control itself, without its label, hint or error.
718fn push_control(out: &mut String, field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) {
719 // Emitted before anything else is computed: a radio group carries its
720 // descriptions on the group rather than on a control, so none of the
721 // attributes below belong to it.
722 if matches!(field.kind, FieldKind::Radio) {
723 push_radio(out, field, filling, opts);
724 return;
725 }
726 // The same split one kind along: an interval is two inputs and one
727 // question, so the group carries the error and the descriptions and the
728 // boxes carry what submits.
729 if matches!(field.kind, FieldKind::Interval) {
730 push_interval(out, field, filling, opts);
731 return;
732 }
733
734 let id = filling.id_for(field.name);
735 let placeholder = |out: &mut String| {
736 if let Some(text) = field.placeholder {
737 out.push_str(" placeholder=\"");
738 escape_into(text, out);
739 out.push('"');
740 }
741 };
742
743 match field.kind {
744 // Both multi-line kinds are a `<textarea>`, and the markdown one says so
745 // in an attribute rather than in a class: what the value *is* is not a
746 // styling hook, and a progressive enhancement looking for editors to
747 // upgrade needs a selector that survives `Emit`'s class prefixing.
748 // Without the mark, a described editor is a plain box and the four
749 // hand-written MNW editors have nothing to convert onto.
750 //
751 // `data-format` and not `data-value`: this names the shape of the
752 // value, and `facet` already spends `data-facet-value` on carrying an
753 // actual one. Two attributes a letter apart meaning opposite things is
754 // how a renderer's own vocabulary starts drifting.
755 kind if kind.multiline() => {
756 let rich = matches!(kind, FieldKind::Rich);
757 if rich {
758 push_editor_open(out, opts);
759 }
760 out.push_str("<textarea class=\"");
761 push_class(out, "field", opts);
762 out.push('"');
763 if rich {
764 out.push_str(" data-format=\"markdown\"");
765 }
766 push_control_attributes(out, field, filling, &id, field.name);
767 placeholder(out);
768 out.push('>');
769 escape_into(filling.value.as_text(), out);
770 out.push_str("</textarea>");
771 if rich {
772 push_editor_close(out, opts);
773 }
774 }
775 FieldKind::Select => {
776 out.push_str("<select class=\"");
777 push_class(out, "field", opts);
778 out.push('"');
779 push_control_attributes(out, field, filling, &id, field.name);
780 out.push('>');
781 // A select described with no options emits an empty select, which
782 // says so on screen rather than in a log. That is the description's
783 // own position on `Field::options`, not a fallback invented here.
784 push_options(out, field, field.options, filling.value.as_text());
785 out.push_str("</select>");
786 }
787 FieldKind::Checkbox => {
788 out.push_str("<label class=\"");
789 push_class(out, "form-checkbox-label", opts);
790 out.push_str("\"><input type=\"checkbox\"");
791 push_control_attributes(out, field, filling, &id, field.name);
792 if matches!(filling.value, Value::On(true)) {
793 out.push_str(" checked");
794 }
795 out.push_str("><span>");
796 escape_into(field.label, out);
797 out.push_str("</span></label>");
798 }
799 // A secret never carries its value into the markup. `FieldKind::secret`
800 // is documented as a value that must not be round-tripped through
801 // anything that might persist it, and the DOM is such a thing: it is
802 // read by every extension on the page and is the first thing a crash
803 // reporter serialises. Neither app pre-fills one today, so this costs
804 // nothing and closes the door before something does.
805 FieldKind::Secret => {
806 out.push_str("<input type=\"password\" class=\"");
807 push_class(out, "field", opts);
808 out.push('"');
809 push_control_attributes(out, field, filling, &id, field.name);
810 placeholder(out);
811 out.push('>');
812 }
813 // A file input carries no value, and this is the browser's rule rather
814 // than a preference: setting one from markup is refused, because a page
815 // that could preselect a path could read a file the user never offered.
816 // Nothing upstream needs to know, which is why the exception is here.
817 FieldKind::File => {
818 out.push_str("<input type=\"file\" class=\"");
819 push_class(out, "field", opts);
820 out.push('"');
821 push_control_attributes(out, field, filling, &id, field.name);
822 push_accept(out, field);
823 if field.multiple {
824 out.push_str(" multiple");
825 }
826 out.push('>');
827 }
828 kind => {
829 let _ = write!(out, "<input type=\"{}\" class=\"", input_type(kind));
830 push_class(out, "field", opts);
831 out.push('"');
832 push_control_attributes(out, field, filling, &id, field.name);
833 placeholder(out);
834 out.push_str(" value=\"");
835 escape_into(filling.value.as_text(), out);
836 out.push_str("\">");
837 }
838 }
839}
840
841/// The chrome a markdown field gets and a plain textarea does not: the two
842/// modes, and the pane a preview lands in.
843///
844/// # Why this is the one field with markup around it
845///
846/// [`FieldKind::Rich`]'s own doc says the mark buys a renderer permission to
847/// offer a preview or a syntax pass, and that a renderer with neither draws a
848/// textarea. A renderer taking the permission and emitting the same box as
849/// [`FieldKind::Textarea`] leaves an app converting onto the member with less
850/// than it had written by hand: MNW's `partial-item-text-editor.js` has a
851/// Write/Preview pair and a pane behind it, and describing the field without
852/// this would delete both. So the pair is here, on `facet`'s argument one
853/// field down -- the markup it replaces is not markup an app is keeping.
854///
855/// # Nothing here renders markdown, and that is where the sanitising stays
856///
857/// The pane arrives empty and this crate never turns a value into markup.
858/// Converting markdown is the host's, which is where the sanitiser already is:
859/// MNW renders through `docengine` over ammonia and holds an allowlist beside
860/// it. A converter here would move that guarantee into a crate with no view of
861/// the host's content-security posture, and `Rich`'s doc is explicit that a
862/// host with its own sanitiser still owns it. What this emits is a hook, and
863/// whatever fills it fills it with markup it has already made safe.
864///
865/// # The direction the enhancement runs
866///
867/// [`crate::stylesheet`]'s rule for a showing region, and for its reason: a
868/// control rendered into a document with no script is a control that looks live
869/// and answers nothing. Nothing is hidden here and no control is shown until
870/// whatever binds the editor sets `data-ready` on the wrapper, so a reader with
871/// no script gets the textarea alone -- what 0.50.0 emitted -- and a reader with
872/// script gets the modes. A bound editor says which mode it is in with
873/// `data-mode`, and [`editor_rules`] reads that.
874fn push_editor_open(out: &mut String, opts: &Emit) {
875 // The mark sits on the wrapper as well as on the control, saying one thing
876 // about two: this control's value is markdown, and this editor edits
877 // markdown. The rules gate on the wrapper and they are attribute rules
878 // rather than class rules for `data-format`'s own reason -- the gate has to
879 // survive `Emit`'s class prefixing, because the enhancement selects on it
880 // too.
881 out.push_str("<div data-format=\"markdown\"><div class=\"");
882 push_class(out, "form-editor-modes", opts);
883 out.push_str("\">");
884 push_mode(out, "write", "Write", true, opts);
885 push_mode(out, "preview", "Preview", false, opts);
886 out.push_str("</div>");
887}
888
889/// One of the two modes, as a segment of the pair.
890///
891/// [`crate::option_class`] for [`Selector::Segmented`] rather than a name of
892/// its own: a Write/Preview pair is a segmented control, and spelling it as one
893/// gets it the depth, the focus ring and the chosen state every described
894/// selector gets, from rules that already exist. The words are written here for
895/// the reason `facet`'s exclude button writes its own: a description carrying
896/// them would be choosing them for the terminal as well.
897fn push_mode(out: &mut String, mode: &str, label: &str, chosen: bool, opts: &Emit) {
898 out.push_str("<button type=\"button\" class=\"");
899 push_class(out, crate::option_class(Selector::Segmented), opts);
900 if chosen {
901 // The sheet keys the held-in segment on the class and a screen reader
902 // reads the attribute. Both, because they are two readings of one fact,
903 // which is the arrangement a facet value already has.
904 out.push_str(" chosen");
905 }
906 let _ = write!(
907 out,
908 "\" data-editor-mode=\"{mode}\" aria-pressed=\"{chosen}\">{label}</button>"
909 );
910}
911
912/// The preview pane, and the wrapper closing over both halves.
913fn push_editor_close(out: &mut String, opts: &Emit) {
914 out.push_str("<div class=\"");
915 push_class(out, "form-editor-preview", opts);
916 // `data-editor-preview` and not an id: a form appears twice in a document
917 // often enough that `Filling::id_prefix` exists for it, and a binder holding
918 // the control can reach this without either of them being unique.
919 out.push_str("\" data-editor-preview></div></div>");
920}
921
922/// The rules the markdown editor's chrome needs.
923///
924/// The one place this module writes CSS. The class names [`field_html`] emits
925/// are goingson's and are deliberately unruled -- `.form-group`, `.form-label`,
926/// `.form-hint` and `.form-error` are the app's own, and phase A emits only what
927/// it can generate from the description -- but the two names here have no app
928/// counterpart to keep, because the chrome did not exist before the member did.
929///
930/// Every rule is gated on `[data-format="markdown"]`, which is what keeps them
931/// off a plain textarea, and every rule that hides content is gated on
932/// `data-ready` as well, which is what keeps them out of a document with no
933/// script.
934pub(crate) fn editor_rules(opts: &Emit) -> String {
935 let mut css = String::new();
936 let modes = class("form-editor-modes", opts);
937 let preview = class("form-editor-preview", opts);
938 let field = class("field", opts);
939
940 // Hidden until something binds the editor, which is the whole argument in
941 // `push_editor_open`.
942 let _ = writeln!(
943 css,
944 "[data-format=\"markdown\"] > .{modes} {{\n display: none;\n}}"
945 );
946 // Block, and nothing about how the two segments sit in it. A button is
947 // inline already, so they make a row without this crate saying so, and
948 // saying so is where a gap would follow -- a magnitude, and
949 // `makeover-geometry`'s.
950 let _ = writeln!(
951 css,
952 "[data-format=\"markdown\"][data-ready] > .{modes} {{\n display: block;\n}}"
953 );
954
955 // The pane is empty until the host fills it, so it is out of flow in every
956 // state but the one where a bound editor is showing it. An empty box under
957 // the control is chrome claiming a preview nobody rendered.
958 let _ = writeln!(
959 css,
960 "[data-format=\"markdown\"] > .{preview} {{\n display: none;\n}}"
961 );
962 let _ = writeln!(
963 css,
964 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{preview} \
965 {{\n display: block;\n}}"
966 );
967 // One at a time. The source and the preview are the same content read two
968 // ways, and a field showing both answers its own question twice.
969 let _ = writeln!(
970 css,
971 "[data-format=\"markdown\"][data-ready][data-mode=\"preview\"] > .{field} \
972 {{\n display: none;\n}}"
973 );
974
975 // The pane stands where the control stood, so it reads as the surface the
976 // control was: `.field` is a well, and this is the well it stands in for.
977 // Nothing about size -- how tall a preview is is the app's, the way the
978 // height of a track is.
979 let _ = write!(
980 css,
981 "[data-format=\"markdown\"] > .{preview} {{\n{}}}\n",
982 crate::depth_declarations(Depth::Well)
983 );
984
985 css
986}
987
988/// The rule a field's unit needs.
989///
990/// [`suggestion_rules`]' precedent and its argument: `.form-group`,
991/// `.form-label`, `.form-hint` and `.form-error` are the apps' own names and
992/// stay unruled here, and this one has no app counterpart to keep because
993/// nothing emitted it before `Field::unit` existed.
994///
995/// One declaration, and it is the whole look. A unit is a fact about the number
996/// beside it rather than a second thing to read, so it takes the muted content
997/// intent -- the same reading `.figure-caption` and `.track-tick` take, and for
998/// the same reason.
999///
1000/// Nothing about placement or spacing. Where the span sits relative to the
1001/// control is the app's layout, exactly as `.form-hint`'s is, and a margin
1002/// asserted here would be this crate deciding a magnitude that belongs to
1003/// `makeover-geometry`.
1004pub(crate) fn unit_rules(opts: &Emit) -> String {
1005 let unit = class("form-unit", opts);
1006 let mut css = String::new();
1007 let _ = writeln!(css, ".{unit} {{\n color: var(--content-muted);\n}}");
1008 css
1009}
1010
1011/// The rules a field's suggestion list needs.
1012///
1013/// [`editor_rules`]' precedent and its argument: the class names this module's
1014/// markup emits are the apps' own and stay unruled, and these three have no app
1015/// counterpart to keep because the list did not exist before the member did.
1016/// The markup is `quasi-webview`'s rather than this crate's — a suggestion
1017/// source is a route, which no description layer carries — and the look is
1018/// still this crate's, because a renderer inventing how a list of candidates
1019/// reads is the drift the vocabulary check exists to catch.
1020///
1021/// # In flow, and not floating
1022///
1023/// An absolutely positioned list needs a positioned ancestor, and the only
1024/// candidate is `.form-group`, which is the app's class and deliberately
1025/// unruled here. So the list stands under the control and moves what is below
1026/// it. An app that wants it over the form positions the group itself, which is
1027/// one declaration and is the app's call about its own layout.
1028///
1029/// `:empty` is what takes it away, so a route that answers with no candidates
1030/// leaves no box behind. It is a content question rather than a whitespace one
1031/// only because the emitter writes no whitespace inside the container, which is
1032/// stated in `quasi-webview`'s own test.
1033///
1034/// # Nothing about size
1035///
1036/// No height, no scroll ceiling, no padding. How tall a list of candidates gets
1037/// to be before it scrolls is a magnitude, and magnitudes are
1038/// `makeover-geometry`'s, exactly as the preview pane's height is.
1039pub(crate) fn suggestion_rules(opts: &Emit) -> String {
1040 let list = class("form-suggestions", opts);
1041 let entry = class("form-suggestion", opts);
1042 let detail = class("form-suggestion-detail", opts);
1043 let mut css = String::new();
1044
1045 let _ = writeln!(css, ".{list}:empty {{\n display: none;\n}}");
1046 // Over what it covers, which is what a list of candidates is even in flow:
1047 // it is answering the box above it and goes away when the answer is taken.
1048 css.push_str(&crate::depth_rule(&list, Depth::Overlay));
1049 // An entry answers a click, so it gets every state one implies.
1050 css.push_str(&crate::interactive_rules(&entry, Depth::Flat, opts));
1051 // The keyboard's highlight and the pointer's are the same surface. They are
1052 // the same fact told two ways, and a list where arrowing and hovering look
1053 // different is a list that has two current entries.
1054 //
1055 // Keyed on `aria-selected` rather than on a class, for the reason
1056 // `aria-invalid` carries the error state: it is what a screen reader hears,
1057 // so a look keyed on it cannot drift from what is announced. A `.current`
1058 // class would also be a name apps already spell for their own reasons --
1059 // the MNW server has one -- and unlayered app CSS beats this layer in
1060 // silence.
1061 let _ = writeln!(
1062 css,
1063 ".{entry}[aria-selected=\"true\"] {{\n background: var(--hover-surface);\n}}"
1064 );
1065 // The second line, muted rather than disabled. `1fcf2e9b` replaced the
1066 // unavailable reason this rule used to draw: a candidate carries no
1067 // `unavailable`, and what sits beside the label now is what tells one row
1068 // from another that reads the same. Disabled would say the row cannot be
1069 // picked, which is the opposite of what the detail is for.
1070 let _ = writeln!(css, ".{detail} {{\n color: var(--content-muted);\n}}");
1071
1072 css
1073}
1074
1075/// One field, as the group the app drops into its form.
1076///
1077/// The shape is goingson's, down to the class names, so adoption there deletes
1078/// `renderFormField` rather than restyling anything. That is also why the class
1079/// names are not emitted by [`crate::stylesheet`]: `.form-group`, `.form-label`,
1080/// `.form-hint` and `.form-error` are the apps' own, and phase A deliberately
1081/// emits only what it can generate from the description. Whether they should
1082/// move into the description is the next question this raises, not one it
1083/// answers.
1084///
1085/// A [`FieldKind::Hidden`] field is the input alone: no group, no label, and
1086/// nothing drawn, which is what [`FieldKind::visible`] means.
1087///
1088/// The error marks the group as well as the control. That is
1089/// [`Field::invalid`]'s own reasoning: a renderer with no descendant selectors
1090/// cannot find the group from the message, so the group has to be told.
1091///
1092/// ```
1093/// use makeover_layout::{Field, FieldKind};
1094/// use makeover_webview::{Emit, form::{Filling, Value, field_html}};
1095///
1096/// let field = Field::new(FieldKind::Text, "title", "Title");
1097/// let html = field_html(&field, &Filling::of(Value::Text("Ship it")), &Emit::default());
1098///
1099/// assert!(html.contains(r#"<label class="form-label" for="title">Title</label>"#));
1100/// assert!(html.contains(r#"value="Ship it""#));
1101/// ```
1102#[must_use]
1103pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
1104 let mut html = String::new();
1105 field_html_into(field, filling, opts, &mut html);
1106 html
1107}
1108
1109/// One field, written into a buffer the caller already has.
1110///
1111/// [`field_html`]'s streaming form, byte-identical to it. A form is a run of
1112/// these, so a host building one should hold a single buffer and append each
1113/// field into it rather than take a `String` per field and concatenate.
1114pub fn field_html_into(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit, out: &mut String) {
1115 let id = filling.id_for(field.name);
1116
1117 if !field.kind.visible() {
1118 // Name only, no id: a hidden field is never pointed at by a label or a
1119 // description, so the one attribute it needs is the one that submits.
1120 out.push_str("<input type=\"hidden\" name=\"");
1121 escape_into(field.name, out);
1122 out.push_str("\" value=\"");
1123 escape_into(filling.value.as_text(), out);
1124 out.push_str("\">");
1125 return;
1126 }
1127
1128 out.push_str("<div class=\"");
1129 push_class(out, "form-group", opts);
1130 if field.invalid() {
1131 out.push_str(" has-error");
1132 }
1133 if field.extended {
1134 // The disclosure that hides these is a property of the form, not of the
1135 // field, so the field is marked and the app opens or closes the group.
1136 out.push_str("\" data-extended=\"true");
1137 }
1138 out.push_str("\">");
1139
1140 // A checkbox labels itself, on the right of the box. Both apps special-case
1141 // this inline today, which is the tell that it belongs in the description;
1142 // `FieldKind::labels_itself` is where it went.
1143 if !field.kind.labels_itself() {
1144 out.push_str("<label class=\"");
1145 push_class(out, "form-label", opts);
1146 // A group control is named *by* its label rather than pointing at it,
1147 // so the two carry opposite halves of the association. See
1148 // `is_group_control`.
1149 if is_group_control(field.kind) {
1150 let _ = write!(out, "\" id=\"{id}-label\">");
1151 } else {
1152 let _ = write!(out, "\" for=\"{id}\">");
1153 }
1154 escape_into(field.label, out);
1155 out.push_str("</label>");
1156 }
1157
1158 push_control(out, field, filling, opts);
1159
1160 // Adjacent text, because HTML has no unit attribute and inventing one would
1161 // be markup nothing reads. Pointed at by `aria-describedby` so it is not
1162 // decoration a screen reader skips: the number and what it is measured in
1163 // are one fact, and reading the first without the second is reading it
1164 // wrong.
1165 if let Some(unit) = unit_of(field) {
1166 out.push_str("<span class=\"");
1167 push_class(out, "form-unit", opts);
1168 let _ = write!(out, "\" id=\"{id}-unit\">");
1169 escape_into(unit, out);
1170 out.push_str("</span>");
1171 }
1172
1173 if let Some(hint) = field.hint {
1174 out.push_str("<div class=\"");
1175 push_class(out, "form-hint", opts);
1176 let _ = write!(out, "\" id=\"{id}-hint\">");
1177 escape_into(hint, out);
1178 out.push_str("</div>");
1179 }
1180 if let Some(Markup(markup)) = filling.trailing {
1181 out.push_str(markup);
1182 }
1183 if let Some(error) = field.error {
1184 out.push_str("<div class=\"");
1185 push_class(out, "form-error", opts);
1186 let _ = write!(out, " visible\" id=\"{id}-error\" role=\"alert\">");
1187 escape_into(error, out);
1188 out.push_str("</div>");
1189 }
1190
1191 out.push_str("</div>");
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196 use super::*;
1197 use makeover_layout::{Accepted, Curve, Family};
1198
1199 fn field(kind: FieldKind) -> Field<'static> {
1200 Field::new(kind, "title", "Title")
1201 }
1202
1203 #[test]
1204 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
1205 // The payload from goingson's own CHRONIC-XSS regression test.
1206 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
1207 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1208 // The payload survives as text, which is the point: it is inert
1209 // because the quote that would have closed the attribute is encoded,
1210 // not because the words were filtered.
1211 assert!(!html.contains("\" onfocus"), "{html}");
1212 assert!(
1213 html.contains("value=\"x" onfocus=alert(1) autofocus="\""),
1214 "{html}"
1215 );
1216 }
1217
1218 /// The seam quasi's suggestion source needs: a host's own attributes land
1219 /// on the control, unescaped, and after everything this crate decided.
1220 #[test]
1221 fn a_host_can_write_its_own_attributes_onto_the_control() {
1222 let mut filling = Filling::of(Value::Text("ru"));
1223 filling.control_attrs = Some(Markup(
1224 r#"role="combobox" aria-expanded="false" aria-controls="title-suggestions""#,
1225 ));
1226 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1227 assert!(html.contains(r#"role="combobox""#), "{html}");
1228 assert!(
1229 html.contains(r#"aria-controls="title-suggestions""#),
1230 "{html}"
1231 );
1232 // After the id, which is what "last" buys: a host can read what this
1233 // emitter wrote and cannot be overwritten by it.
1234 let id = html.find(r#"id="title""#).expect("id");
1235 let role = html.find(r#"role="combobox""#).expect("role");
1236 assert!(id < role, "{html}");
1237 }
1238
1239 /// A radio group has no one control element, so there is nowhere honest to
1240 /// put an attribute meant for the control. Documented on the member.
1241 #[test]
1242 fn a_radio_group_drops_control_attributes() {
1243 let mut f = field(FieldKind::Radio);
1244 let options = [Choice::new("a", "A")];
1245 f.options = &options;
1246 let filling = Filling {
1247 control_attrs: Some(Markup(r#"data-host="1""#)),
1248 ..Filling::default()
1249 };
1250 let html = field_html(&f, &filling, &Emit::default());
1251 assert!(!html.contains("data-host"), "{html}");
1252 }
1253
1254 #[test]
1255 fn a_label_cannot_open_a_tag() {
1256 let mut f = field(FieldKind::Text);
1257 f.label = "<script>alert(1)</script>";
1258 let html = field_html(&f, &Filling::default(), &Emit::default());
1259 assert!(!html.contains("<script>"), "{html}");
1260 assert!(html.contains("<script>"), "{html}");
1261 }
1262
1263 #[test]
1264 fn every_escaped_sink_is_covered_by_the_one_escaper() {
1265 assert_eq!(escape("&<>\"'"), "&<>"'");
1266 // The character `textContent` serialization leaves alone, which is why
1267 // the app needs two escapers and this needs one.
1268 assert!(escape("\"").contains("""));
1269 }
1270
1271 /// The streaming escaper is the one the emitters call and [`escape`] is a
1272 /// buffer around it, so the two cannot be allowed to drift. It copies in
1273 /// runs between the encoded characters, which is where a multi-byte
1274 /// character would break it if the scan were not restricted to ASCII.
1275 #[test]
1276 fn the_streaming_escaper_appends_what_the_returning_one_returns() {
1277 for text in [
1278 "",
1279 "plain",
1280 "&<>\"'",
1281 "&&&",
1282 "a & b",
1283 "trailing&",
1284 "&leading",
1285 "é世 & <b>naïve</b> \u{1f600}",
1286 ] {
1287 let mut out = String::from("kept: ");
1288 escape_into(text, &mut out);
1289 assert_eq!(out, format!("kept: {}", escape(text)), "{text:?}");
1290 }
1291 }
1292
1293 /// Same obligation one layer up: a form is a run of fields appended into one
1294 /// buffer, and the two ways to get one have to agree byte for byte.
1295 #[test]
1296 fn a_streamed_field_is_the_field_the_other_form_returns() {
1297 let kinds = [
1298 FieldKind::Text,
1299 FieldKind::Secret,
1300 FieldKind::Number,
1301 FieldKind::Checkbox,
1302 FieldKind::Radio,
1303 FieldKind::Select,
1304 FieldKind::Textarea,
1305 FieldKind::File,
1306 FieldKind::Hidden,
1307 ];
1308 let choices = [Choice::plain("one"), Choice::plain("two")];
1309 let opts = Emit {
1310 class_prefix: "mk-",
1311 ..Emit::default()
1312 };
1313 for kind in kinds {
1314 let described = Field {
1315 hint: Some("a hint"),
1316 error: Some("wrong <here>"),
1317 placeholder: Some("x\" y"),
1318 options: &choices,
1319 required: true,
1320 max_length: Some(40),
1321 min: Some("1"),
1322 max: Some("9"),
1323 extended: true,
1324 ..Field::new(kind, "the & name", "The <label>")
1325 };
1326 let filling = Filling {
1327 value: Value::Text("one"),
1328 trailing: Some(Markup("<i>t</i>")),
1329 control_attrs: Some(Markup(r#"data-host="1""#)),
1330 id_prefix: Some("modal"),
1331 };
1332 let mut streamed = String::new();
1333 field_html_into(&described, &filling, &opts, &mut streamed);
1334 assert_eq!(
1335 streamed,
1336 field_html(&described, &filling, &opts),
1337 "{kind:?}"
1338 );
1339
1340 // And the bare field, where every optional half is absent.
1341 let plain = Field::new(kind, "name", "Label");
1342 let mut streamed = String::new();
1343 field_html_into(&plain, &Filling::default(), &opts, &mut streamed);
1344 assert_eq!(
1345 streamed,
1346 field_html(&plain, &Filling::default(), &opts),
1347 "{kind:?}"
1348 );
1349 }
1350 }
1351
1352 #[test]
1353 fn markup_is_the_only_way_past_the_escaping() {
1354 let filling = Filling {
1355 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
1356 ..Filling::default()
1357 };
1358 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
1359 assert!(
1360 html.contains("<div class=\"recurrence-config\"></div>"),
1361 "{html}"
1362 );
1363 }
1364
1365 #[test]
1366 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
1367 let mut f = field(FieldKind::Text);
1368 f.error = Some("Required");
1369 let opts = Emit::default();
1370 let html = field_html(&f, &Filling::default(), &opts);
1371 assert!(html.contains("aria-invalid=\"true\""), "{html}");
1372 // The selector the CSS side emits for exactly this state.
1373 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
1374 // And the group is marked too, which a renderer without descendant
1375 // selectors depends on.
1376 assert!(html.contains("has-error"), "{html}");
1377 }
1378
1379 #[test]
1380 fn a_valid_field_claims_nothing_about_being_invalid() {
1381 let html = field_html(
1382 &field(FieldKind::Text),
1383 &Filling::default(),
1384 &Emit::default(),
1385 );
1386 assert!(!html.contains("aria-invalid"), "{html}");
1387 assert!(!html.contains("has-error"), "{html}");
1388 }
1389
1390 #[test]
1391 fn the_hint_survives_an_error_arriving() {
1392 let mut f = field(FieldKind::Text);
1393 f.hint = Some("Keep it short");
1394 f.error = Some("Required");
1395 let html = field_html(&f, &Filling::default(), &Emit::default());
1396 assert!(
1397 html.contains("aria-describedby=\"title-hint title-error\""),
1398 "{html}"
1399 );
1400 }
1401
1402 #[test]
1403 fn a_secret_never_carries_its_value_into_the_markup() {
1404 let filling = Filling::of(Value::Text("hunter2"));
1405 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
1406 assert!(!html.contains("hunter2"), "{html}");
1407 assert!(html.contains("type=\"password\""), "{html}");
1408 }
1409
1410 #[test]
1411 fn a_hidden_field_is_the_input_and_nothing_else() {
1412 let filling = Filling::of(Value::Text("42"));
1413 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
1414 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
1415 }
1416
1417 #[test]
1418 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
1419 let html = field_html(
1420 &field(FieldKind::Checkbox),
1421 &Filling::of(Value::On(true)),
1422 &Emit::default(),
1423 );
1424 assert!(!html.contains("form-label"), "{html}");
1425 assert!(html.contains("checked"), "{html}");
1426 assert!(html.contains("<span>Title</span>"), "{html}");
1427 }
1428
1429 #[test]
1430 fn a_select_keeps_a_value_no_option_carries() {
1431 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
1432 let f = Field::select("title", "Title", &options);
1433 let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1434 assert!(html.contains("data-unmatched=\"true\""), "{html}");
1435 // Selected, so the next save round-trips it rather than writing the
1436 // first option over the top of it.
1437 assert!(html.contains("<option value=\"10\" selected"), "{html}");
1438 }
1439
1440 #[test]
1441 fn a_select_with_no_options_emits_an_empty_select() {
1442 // The description says a select with no options is sayable, because an
1443 // app whose option list has not loaded has exactly that. Emitting the
1444 // empty select reports it on screen rather than in a log.
1445 let f = Field::select("title", "Title", &[]);
1446 let html = field_html(&f, &Filling::default(), &Emit::default());
1447 assert!(html.contains("<select"), "{html}");
1448 assert!(!html.contains("<option"), "{html}");
1449 }
1450
1451 #[test]
1452 fn an_unanswered_select_shows_its_ghost_text_and_cannot_be_chosen_back() {
1453 let options = [Choice::new("sp404", "SP-404")];
1454 let f = Field {
1455 placeholder: Some("Select device..."),
1456 ..Field::select("device", "Conform for device", &options)
1457 };
1458 let html = field_html(&f, &Filling::default(), &Emit::default());
1459
1460 assert!(
1461 html.contains("<option value=\"\" disabled selected>Select device...</option>"),
1462 "{html}"
1463 );
1464 // First, so the closed control reads it rather than the first real
1465 // option.
1466 assert!(
1467 html.find("Select device...") < html.find("SP-404"),
1468 "{html}"
1469 );
1470 }
1471
1472 #[test]
1473 fn an_answered_select_drops_the_ghost_text() {
1474 // It is an instruction about an empty field, so it has nothing to say
1475 // once the field is answered, and leaving it in the list is one dead
1476 // row every time the control is opened afterwards.
1477 let options = [Choice::new("sp404", "SP-404")];
1478 let f = Field {
1479 placeholder: Some("Select device..."),
1480 ..Field::select("device", "Conform for device", &options)
1481 };
1482 let html = field_html(&f, &Filling::of(Value::Text("sp404")), &Emit::default());
1483 assert!(!html.contains("Select device..."), "{html}");
1484 }
1485
1486 #[test]
1487 fn a_wrong_answer_is_kept_and_is_not_the_ghost_text() {
1488 // The two paths through `push_options` meet here. An unmatched value is
1489 // an answer that is wrong and stays visible as itself; only the empty
1490 // value is unanswered.
1491 let options = [Choice::plain("1"), Choice::plain("7")];
1492 let f = Field {
1493 placeholder: Some("Pick one"),
1494 ..Field::select("retention", "Keep backups for", &options)
1495 };
1496 let html = field_html(&f, &Filling::of(Value::Text("10")), &Emit::default());
1497 assert!(html.contains("data-unmatched=\"true\""), "{html}");
1498 assert!(!html.contains("Pick one"), "{html}");
1499 }
1500
1501 #[test]
1502 fn a_range_is_a_range_input_and_carries_its_extent() {
1503 let f = Field {
1504 curve: Curve::Linear { step: Some("0.01") },
1505 ..Field::range("review", "Review above", "0", "1")
1506 };
1507 let html = field_html(&f, &Filling::of(Value::Text("0.72")), &Emit::default());
1508 assert!(html.contains("type=\"range\""), "{html}");
1509 assert!(html.contains("min=\"0\""), "{html}");
1510 assert!(html.contains("max=\"1\""), "{html}");
1511 // Without it the browser steps by 1 and a 0-to-1 question becomes a
1512 // two-position control.
1513 assert!(html.contains("step=\"0.01\""), "{html}");
1514 }
1515
1516 #[test]
1517 fn a_range_reads_its_granularity_off_the_curve_and_not_off_field_step() {
1518 // The 0.32.0 narrowing, at the renderer. `Field::step` on a range is a
1519 // site that has not been moved over, and emitting it would make the
1520 // control step by a number the curve never agreed to.
1521 let f = Field {
1522 step: Some("99"),
1523 ..Field::range("review", "Review above", "0", "1")
1524 };
1525 let html = field_html(&f, &Filling::of(Value::Text("0.5")), &Emit::default());
1526 assert!(!html.contains("step="), "{html}");
1527 }
1528
1529 #[test]
1530 fn a_unit_is_adjacent_text_and_the_control_points_at_it() {
1531 // Not decoration: the number and what it is measured in are one fact,
1532 // so the association is what makes this worth emitting at all.
1533 let f = Field {
1534 unit: Some("dBFS"),
1535 ..Field::range("threshold", "Threshold", "-96", "-20")
1536 };
1537 let html = field_html(&f, &Filling::of(Value::Text("-40")), &Emit::default());
1538 assert!(html.contains(r#"id="threshold-unit""#), "{html}");
1539 assert!(html.contains(">dBFS</span>"), "{html}");
1540 assert!(
1541 html.contains(r#"aria-describedby="threshold-unit""#),
1542 "{html}"
1543 );
1544 // The label is the question's name and keeps no unit in it.
1545 assert!(html.contains(">Threshold</label>"), "{html}");
1546 }
1547
1548 #[test]
1549 fn a_unit_takes_its_place_between_the_hint_and_the_error() {
1550 let f = Field {
1551 unit: Some("ms"),
1552 hint: Some("How long the fade runs."),
1553 error: Some("Too long."),
1554 ..Field::new(FieldKind::Number, "fade", "Fade")
1555 };
1556 let html = field_html(&f, &Filling::of(Value::Text("50")), &Emit::default());
1557 assert!(
1558 html.contains(r#"aria-describedby="fade-hint fade-unit fade-error""#),
1559 "{html}"
1560 );
1561 }
1562
1563 #[test]
1564 fn a_unit_on_a_kind_that_is_not_a_quantity_is_ignored() {
1565 // Sayable and ignored, the way `options` is on a kind that offers none.
1566 // The renderer asks the description which kinds are measurable rather
1567 // than keeping its own list.
1568 let f = Field {
1569 unit: Some("s"),
1570 ..Field::new(FieldKind::Text, "name", "Name")
1571 };
1572 let html = field_html(&f, &Filling::of(Value::Text("kick")), &Emit::default());
1573 assert!(!html.contains("name-unit"), "{html}");
1574 assert!(!html.contains("aria-describedby"), "{html}");
1575 }
1576
1577 #[test]
1578 fn a_unit_cannot_break_out_of_the_span_it_sits_in() {
1579 let f = Field {
1580 unit: Some("</span><script>"),
1581 ..Field::new(FieldKind::Number, "n", "N")
1582 };
1583 let html = field_html(&f, &Filling::of(Value::Text("1")), &Emit::default());
1584 assert!(!html.contains("<script>"), "{html}");
1585 assert!(html.contains("<script>"), "{html}");
1586 }
1587
1588 #[test]
1589 fn a_constant_ratio_curve_still_emits_a_linear_track() {
1590 // Honest shortfall rather than a silent one: HTML has no logarithmic
1591 // range input, so the browser draws the extent linearly. The value it
1592 // submits is still a value in the field's own units, which is what
1593 // every handler on this path reads. See the crate header.
1594 let f = Field {
1595 curve: Curve::Logarithmic {
1596 step: Some("0.001"),
1597 },
1598 ..Field::range("attack", "Attack", "0.001", "5")
1599 };
1600 let html = field_html(&f, &Filling::of(Value::Text("0.005")), &Emit::default());
1601 assert!(html.contains("type=\"range\""), "{html}");
1602 assert!(html.contains("min=\"0.001\""), "{html}");
1603 assert!(html.contains("max=\"5\""), "{html}");
1604 assert!(html.contains("step=\"0.001\""), "{html}");
1605 }
1606
1607 #[test]
1608 fn a_number_with_bounds_is_still_typed_into() {
1609 // The distinction the kind exists for, at the renderer where getting it
1610 // wrong is most visible: goingson's `min="1"` duration must not come
1611 // back as a slider.
1612 let f = Field {
1613 min: Some("1"),
1614 ..Field::new(FieldKind::Number, "minutes", "Minutes")
1615 };
1616 let html = field_html(&f, &Filling::of(Value::Text("30")), &Emit::default());
1617 assert!(html.contains("type=\"number\""), "{html}");
1618 assert!(!html.contains("type=\"range\""), "{html}");
1619 // And nothing invents a step for it.
1620 assert!(!html.contains("step="), "{html}");
1621 }
1622
1623 #[test]
1624 fn an_unavailable_option_is_disabled_and_says_why() {
1625 let options = [
1626 Choice::new("chromatic", "Chromatic"),
1627 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1628 ];
1629 let f = Field::radio("mode", "Mode", &options);
1630 let html = field_html(&f, &Filling::of(Value::Text("chromatic")), &Emit::default());
1631
1632 assert!(html.contains(" disabled"), "{html}");
1633 assert!(html.contains("Drop a second sample."), "{html}");
1634 // The option is still offered: dropping it is what costs the user the
1635 // knowledge that the mode exists.
1636 assert!(html.contains("value=\"multi\""), "{html}");
1637 // And the reason is its own element, not run into the label.
1638 assert!(html.contains("form-option-reason"), "{html}");
1639 }
1640
1641 #[test]
1642 fn an_unavailable_select_option_carries_its_reason_in_its_text() {
1643 // A `<select>` gives an option no room for a second element, so the
1644 // reason has to be in the text or be unreadable without a pointer.
1645 let options = [Choice::new("multi", "Multi-sample").unless("Drop a second sample.")];
1646 let f = Field::select("mode", "Mode", &options);
1647 let html = field_html(&f, &Filling::default(), &Emit::default());
1648 assert!(
1649 html.contains(">Multi-sample: Drop a second sample.</option>"),
1650 "{html}"
1651 );
1652 assert!(html.contains("disabled"), "{html}");
1653 }
1654
1655 #[test]
1656 fn a_radio_group_is_named_by_its_label_instead_of_pointing_at_it() {
1657 // The association inverts, and getting it wrong is silent: a
1658 // `<label for>` aimed at a group points at no element, so the group
1659 // simply has no accessible name and nothing reports that.
1660 let options = [Choice::plain("copy"), Choice::plain("reference")];
1661 let f = Field::radio("storage", "Storage style", &options);
1662 let html = field_html(&f, &Filling::of(Value::Text("copy")), &Emit::default());
1663
1664 assert!(html.contains("id=\"storage-label\""), "{html}");
1665 assert!(!html.contains("for=\"storage\""), "{html}");
1666 assert!(html.contains("role=\"radiogroup\""), "{html}");
1667 assert!(html.contains("aria-labelledby=\"storage-label\""), "{html}");
1668 }
1669
1670 #[test]
1671 fn an_interval_is_one_labelled_group_holding_both_ends() {
1672 // The markup MNW's discover sidebar writes by hand, which is the
1673 // measurement that decided the member: `role="group"` naming the
1674 // question, two number boxes under it.
1675 let f = Field::interval("min_price", "max_price", "Price");
1676 let html = field_html(
1677 &f,
1678 &Filling::of(Value::Between {
1679 lower: "5",
1680 upper: "40",
1681 }),
1682 &Emit::default(),
1683 );
1684
1685 assert!(html.contains("role=\"group\""), "{html}");
1686 assert!(
1687 html.contains("aria-labelledby=\"min_price-label\""),
1688 "{html}"
1689 );
1690 assert!(html.contains("id=\"min_price-label\""), "{html}");
1691 assert!(!html.contains("for=\"min_price\""), "{html}");
1692 assert!(html.contains("name=\"min_price\""), "{html}");
1693 assert!(html.contains("name=\"max_price\""), "{html}");
1694 assert!(html.contains("value=\"5\""), "{html}");
1695 assert!(html.contains("value=\"40\""), "{html}");
1696 assert_eq!(html.matches("type=\"number\"").count(), 2, "{html}");
1697 }
1698
1699 #[test]
1700 fn both_ends_of_an_interval_take_the_whole_extent() {
1701 // The extent describes the axis rather than either end of it, so a
1702 // browser refuses the same values in both boxes.
1703 let f = Field {
1704 min: Some("0"),
1705 max: Some("300"),
1706 step: Some("1"),
1707 ..Field::interval("bpm_min", "bpm_max", "BPM")
1708 };
1709 let html = field_html(&f, &Filling::default(), &Emit::default());
1710
1711 assert_eq!(html.matches("min=\"0\"").count(), 2, "{html}");
1712 assert_eq!(html.matches("max=\"300\"").count(), 2, "{html}");
1713 assert_eq!(html.matches("step=\"1\"").count(), 2, "{html}");
1714 // Neither box holds anything, which is the open interval rather than an
1715 // empty form: no filter on this axis at all.
1716 assert_eq!(html.matches("value=\"\"").count(), 2, "{html}");
1717 }
1718
1719 #[test]
1720 fn an_interval_carries_the_fault_on_the_group_and_not_on_one_end() {
1721 // A crossed interval is wrong about the answer, and the answer is the
1722 // pair. This is the half two `Number` fields could not say.
1723 let f = Field {
1724 error: Some("The high end is below the low one."),
1725 hint: Some("Leave an end empty for no bound."),
1726 ..Field::interval("bpm_min", "bpm_max", "BPM")
1727 };
1728 let html = field_html(&f, &Filling::default(), &Emit::default());
1729
1730 assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
1731 let group = html.find("role=\"group\"").expect("group");
1732 let invalid = html.find("aria-invalid").expect("invalid");
1733 let first_input = html.find("<input").expect("input");
1734 assert!(invalid > group && invalid < first_input, "{html}");
1735 assert!(
1736 html.contains("aria-describedby=\"bpm_min-hint bpm_min-error\""),
1737 "{html}"
1738 );
1739 }
1740
1741 #[test]
1742 fn an_interval_with_one_end_named_draws_one_box() {
1743 // Drawn as described rather than repaired. Inventing a name for the
1744 // upper end would submit a parameter no handler reads, and
1745 // `Field::interval` is what makes the omission unsayable at the source.
1746 let f = Field::new(FieldKind::Interval, "bpm_min", "BPM");
1747 let html = field_html(&f, &Filling::default(), &Emit::default());
1748
1749 assert_eq!(html.matches("<input").count(), 1, "{html}");
1750 assert!(html.contains("name=\"bpm_min\""), "{html}");
1751 }
1752
1753 #[test]
1754 fn every_option_shares_the_name_and_only_the_current_one_is_checked() {
1755 // One `name` is what makes them one answer rather than three; distinct
1756 // ids are what keep each `<label>` wrapping its own input.
1757 let options = [
1758 Choice::plain("copy"),
1759 Choice::plain("reference"),
1760 Choice::plain("link"),
1761 ];
1762 let f = Field::radio("storage", "Storage style", &options);
1763 let html = field_html(&f, &Filling::of(Value::Text("reference")), &Emit::default());
1764
1765 assert_eq!(html.matches("name=\"storage\"").count(), 3, "{html}");
1766 assert_eq!(html.matches(" checked").count(), 1, "{html}");
1767 assert!(
1768 html.contains("value=\"reference\" checked"),
1769 "the checked one is the one held: {html}"
1770 );
1771 for index in 0..3 {
1772 assert!(html.contains(&format!("id=\"storage-{index}\"")), "{html}");
1773 }
1774 }
1775
1776 #[test]
1777 fn a_radio_group_carries_the_error_rather_than_any_one_option() {
1778 // What is wrong is the answer, not one of the alternatives, so marking
1779 // a single input invalid would say something false. Same reading
1780 // `Field::invalid` gives one level up.
1781 let options = [Choice::plain("copy"), Choice::plain("reference")];
1782 let f = Field {
1783 error: Some("Pick one."),
1784 hint: Some("Cannot be changed later."),
1785 ..Field::radio("storage", "Storage style", &options)
1786 };
1787 let html = field_html(&f, &Filling::default(), &Emit::default());
1788
1789 assert_eq!(html.matches("aria-invalid=\"true\"").count(), 1, "{html}");
1790 assert!(
1791 html.contains("aria-describedby=\"storage-hint storage-error\""),
1792 "{html}"
1793 );
1794 // The group is the element that carries them, so they land before the
1795 // first option rather than on it.
1796 let group = html.find("role=\"radiogroup\"").expect("group");
1797 let first = html.find("type=\"radio\"").expect("an option");
1798 assert!(group < first, "{html}");
1799 }
1800
1801 #[test]
1802 fn a_compulsory_radio_group_marks_every_option() {
1803 // How HTML says a group is compulsory: the constraint reads as
1804 // satisfied when any one of them is checked.
1805 let options = [Choice::plain("copy"), Choice::plain("reference")];
1806 let f = Field {
1807 required: true,
1808 ..Field::radio("storage", "Storage style", &options)
1809 };
1810 let html = field_html(&f, &Filling::default(), &Emit::default());
1811 assert_eq!(html.matches(" required").count(), 2, "{html}");
1812 }
1813
1814 #[test]
1815 fn a_radio_option_cannot_break_out_of_its_attribute() {
1816 // Values are `&str` and carry whatever the app put in them. The ids are
1817 // numbered rather than derived from the value for the same reason.
1818 let hostile = [Choice::new(
1819 "x\" onclick=alert(1) data-x=\"",
1820 "<script>alert(1)</script>",
1821 )];
1822 let f = Field::radio("storage", "Storage style", &hostile);
1823 let html = field_html(&f, &Filling::default(), &Emit::default());
1824
1825 // The payload survives as text; what must not survive is the quote
1826 // that would end the attribute and let the rest of it become markup.
1827 assert!(html.contains("value=\"x" onclick=alert(1)"), "{html}");
1828 assert!(!html.contains("<script>"), "{html}");
1829 assert!(html.contains("id=\"storage-0\""), "{html}");
1830 }
1831
1832 #[test]
1833 fn a_radio_group_with_no_options_emits_an_empty_group() {
1834 // Same position the select takes, and the description's own.
1835 let f = Field::radio("storage", "Storage style", &[]);
1836 let html = field_html(&f, &Filling::default(), &Emit::default());
1837 assert!(html.contains("role=\"radiogroup\""), "{html}");
1838 assert!(!html.contains("type=\"radio\""), "{html}");
1839 }
1840
1841 #[test]
1842 fn a_placeholder_comes_off_the_description_and_is_escaped() {
1843 // It arrived in `Filling` until makeover-layout 0.8.0 and was never
1844 // covered here; it is a value in an attribute like any other.
1845 let f = Field {
1846 placeholder: Some("x\" onfocus=alert(1) autofocus=\""),
1847 ..field(FieldKind::Text)
1848 };
1849 let html = field_html(&f, &Filling::default(), &Emit::default());
1850 assert!(html.contains("placeholder=\""), "{html}");
1851 assert!(!html.contains("\" onfocus"), "{html}");
1852 }
1853
1854 #[test]
1855 fn a_select_marks_the_option_that_matches() {
1856 let options = [Choice::plain("1"), Choice::plain("3")];
1857 let f = Field::select("title", "Title", &options);
1858 let html = field_html(&f, &Filling::of(Value::Text("3")), &Emit::default());
1859 assert!(
1860 html.contains("<option value=\"3\" selected>3</option>"),
1861 "{html}"
1862 );
1863 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
1864 assert!(!html.contains("data-unmatched"), "{html}");
1865 }
1866
1867 #[test]
1868 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
1869 let filling = Filling::of(Value::Text("two\nlines"));
1870 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1871 assert!(html.contains(">two\nlines</textarea>"), "{html}");
1872 }
1873
1874 #[test]
1875 fn a_markdown_field_is_a_textarea_that_says_what_its_value_is() {
1876 // The mark is the whole difference. Without it a described editor is a
1877 // plain box, and an enhancement looking for editors to upgrade has
1878 // nothing to find -- which is the state MNW's four hand-written section
1879 // editors would have had to keep living in.
1880 let filling = Filling::of(Value::Text("# Heading"));
1881 let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1882 assert!(html.contains("<textarea"), "{html}");
1883 assert!(html.contains(r#"data-format="markdown""#), "{html}");
1884 assert!(html.contains("># Heading</textarea>"), "{html}");
1885
1886 // A plain textarea claims nothing about its value, so the marker has to
1887 // be absent rather than present-and-different.
1888 let plain = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1889 assert!(!plain.contains("data-format"), "{plain}");
1890
1891 // And it is not an input: the catch-all in `input_type` would have
1892 // degraded it to a single-line text box, which is the wrong shape for
1893 // markdown rather than a lossless fallback.
1894 assert!(!html.contains("<input"), "{html}");
1895 }
1896
1897 #[test]
1898 fn a_markdown_field_gets_the_preview_the_member_permits() {
1899 // The mark on its own is what 0.50.0 shipped, and nothing read it. What
1900 // a conversion needs is the pair MNW's `partial-item-text-editor.js`
1901 // already draws, so describing the field is not a way to lose it.
1902 let filling = Filling::of(Value::Text("# Heading"));
1903 let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1904 assert!(html.contains("data-editor-mode=\"write\""), "{html}");
1905 assert!(html.contains("data-editor-mode=\"preview\""), "{html}");
1906 assert!(html.contains("data-editor-preview"), "{html}");
1907 // Write is the mode a fresh editor is in, and the segment says so twice
1908 // because the sheet reads one and a screen reader reads the other.
1909 assert!(
1910 html.contains(
1911 "class=\"segment chosen\" data-editor-mode=\"write\" aria-pressed=\"true\""
1912 ),
1913 "{html}"
1914 );
1915 assert!(
1916 html.contains("data-editor-mode=\"preview\" aria-pressed=\"false\""),
1917 "{html}"
1918 );
1919 // The value is still the textarea's, and still text rather than an
1920 // attribute. The chrome sits around the control, not in place of it.
1921 assert!(html.contains("># Heading</textarea>"), "{html}");
1922 }
1923
1924 #[test]
1925 fn a_plain_textarea_gets_no_editor_chrome() {
1926 let filling = Filling::of(Value::Text("plain"));
1927 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
1928 assert!(!html.contains("data-editor-mode"), "{html}");
1929 assert!(!html.contains("data-editor-preview"), "{html}");
1930 assert!(!html.contains("segment"), "{html}");
1931 }
1932
1933 #[test]
1934 fn nothing_the_editor_emits_renders_the_value_as_markup() {
1935 // The whole of this crate's half of the sanitising question: the pane is
1936 // empty, so no value reaches markup through it, and the host's own
1937 // renderer keeps the guarantee it already has.
1938 let filling = Filling::of(Value::Text("<img src=x onerror=alert(1)>"));
1939 let html = field_html(&field(FieldKind::Rich), &filling, &Emit::default());
1940 assert!(html.contains("data-editor-preview></div>"), "{html}");
1941 assert!(!html.contains("<img"), "{html}");
1942 assert!(
1943 html.contains("<img src=x onerror=alert(1)>"),
1944 "{html}"
1945 );
1946 }
1947
1948 #[test]
1949 fn the_editor_rules_gate_on_the_attribute_and_on_a_binding() {
1950 let css = editor_rules(&Emit::default());
1951 // Behind the attribute, which is the reason the mark is an attribute:
1952 // a class-keyed gate would be prefixed away from the enhancement that
1953 // selects on it.
1954 for line in css.lines().filter(|line| line.contains('{')) {
1955 assert!(line.contains("[data-format=\"markdown\"]"), "{line}");
1956 }
1957 // Nothing is hidden and no control appears until something binds the
1958 // editor. A reader with no script gets the textarea alone.
1959 assert!(
1960 css.contains(
1961 "[data-format=\"markdown\"] > .form-editor-modes {\n display: none;\n}"
1962 )
1963 );
1964 assert!(css.contains(
1965 "[data-format=\"markdown\"][data-ready] > .form-editor-modes {\n display: block;\n}"
1966 ));
1967 assert!(css.contains(
1968 "[data-ready][data-mode=\"preview\"] > .form-editor-preview {\n display: block;\n}"
1969 ));
1970 assert!(
1971 css.contains("[data-ready][data-mode=\"preview\"] > .field {\n display: none;\n}")
1972 );
1973 // No magnitude, the line this crate holds everywhere else.
1974 assert!(!css.contains("px"), "{css}");
1975 assert!(!css.contains("rem"), "{css}");
1976 }
1977
1978 /// The prefix reaches the chrome as well, and the gate deliberately does
1979 /// not: an app assembling the sheet with its own prefix still has the
1980 /// selector an enhancement finds the editors by.
1981 #[test]
1982 fn the_editor_chrome_is_prefixed_and_its_gate_is_not() {
1983 let opts = Emit {
1984 class_prefix: "mk-",
1985 ..Emit::default()
1986 };
1987 let html = field_html(&field(FieldKind::Rich), &Filling::default(), &opts);
1988 assert!(html.contains("class=\"mk-form-editor-modes\""), "{html}");
1989 assert!(html.contains("class=\"mk-form-editor-preview\""), "{html}");
1990 assert!(html.contains("class=\"mk-segment chosen\""), "{html}");
1991 assert!(html.contains("data-format=\"markdown\""), "{html}");
1992
1993 let css = editor_rules(&opts);
1994 assert!(css.contains(".mk-form-editor-modes"), "{css}");
1995 assert!(css.contains("[data-format=\"markdown\"]"), "{css}");
1996 }
1997
1998 /// Every class the editor puts in markup is one the generated sheet rules,
1999 /// which is `FACET_CLASSES`' obligation without a list to keep: these two
2000 /// have rules, so the vocabulary seal picks them up from the sheet itself.
2001 #[test]
2002 fn the_editor_classes_are_in_the_vocabulary() {
2003 let opts = Emit::default();
2004 let names = crate::vocabulary::names(&opts);
2005 for name in ["form-editor-modes", "form-editor-preview", "segment"] {
2006 assert!(names.contains(name), "{name} is not in the vocabulary");
2007 }
2008 }
2009
2010 #[test]
2011 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
2012 let opts = Emit {
2013 class_prefix: "mk-",
2014 ..Emit::default()
2015 };
2016 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
2017 assert!(html.contains("class=\"mk-form-group\""), "{html}");
2018 assert!(html.contains("class=\"mk-field\""), "{html}");
2019 }
2020
2021 #[test]
2022 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
2023 let mut f = field(FieldKind::Text);
2024 f.extended = true;
2025 let html = field_html(&f, &Filling::default(), &Emit::default());
2026 assert!(html.contains("data-extended=\"true\""), "{html}");
2027 }
2028
2029 /// The prefix scopes the id and leaves the name alone. Prefixing the name
2030 /// too would change what the form submits, which is the failure this pair
2031 /// of assertions exists to catch rather than describe.
2032 #[test]
2033 fn the_id_prefix_scopes_the_id_and_never_the_name() {
2034 let mut f = field(FieldKind::Text);
2035 f.hint = Some("Keep it short");
2036 f.error = Some("Required");
2037 let filling = Filling {
2038 id_prefix: Some("form-modal-task-edit"),
2039 ..Filling::default()
2040 };
2041 let html = field_html(&f, &filling, &Emit::default());
2042
2043 assert!(
2044 html.contains(r#"id="form-modal-task-edit-title""#),
2045 "{html}"
2046 );
2047 assert!(html.contains(r#"name="title""#), "{html}");
2048 assert!(
2049 !html.contains(r#"name="form-modal-task-edit-title""#),
2050 "{html}"
2051 );
2052
2053 // The label and both associations follow the id, or they point at
2054 // nothing once the same form is on screen twice.
2055 assert!(
2056 html.contains(r#"for="form-modal-task-edit-title""#),
2057 "{html}"
2058 );
2059 assert!(
2060 html.contains(
2061 r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
2062 ),
2063 "{html}"
2064 );
2065 assert!(
2066 html.contains(r#"id="form-modal-task-edit-title-hint""#),
2067 "{html}"
2068 );
2069 }
2070
2071 #[test]
2072 fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
2073 let filling = Filling {
2074 value: Value::Text("42"),
2075 id_prefix: Some("scoped"),
2076 ..Filling::default()
2077 };
2078 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
2079 assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
2080 }
2081
2082 /// These three exist so a touch keyboard and the platform's validation
2083 /// arrive with the field. Emitting text for any of them is the regression
2084 /// the variants were added to prevent, so the type is asserted directly.
2085 #[test]
2086 fn a_constraint_becomes_the_browsers_own_attribute() {
2087 // makeover-layout 0.11.0's model: the description carries the rule and
2088 // each renderer emits its host's idiom for it. Enforcement is still
2089 // whoever validated's, and arrives back as `error`.
2090 let html = field_html(
2091 &Field {
2092 max_length: Some(100),
2093 min: Some("1"),
2094 max: Some("240"),
2095 required: true,
2096 ..Field::new(FieldKind::Number, "minutes", "Minutes")
2097 },
2098 &Filling::default(),
2099 &Emit::default(),
2100 );
2101 assert!(html.contains(r#"maxlength="100""#));
2102 assert!(html.contains(r#"min="1""#));
2103 assert!(html.contains(r#"max="240""#));
2104 assert!(html.contains(" required"));
2105 }
2106
2107 #[test]
2108 fn a_bound_is_emitted_as_written_and_escaped_like_anything_else() {
2109 // The bound is text because it is only a number for some of the kinds
2110 // that take one; goingson's own sites are a duration and a datetime.
2111 let html = field_html(
2112 &Field {
2113 min: Some("2026-08-09T14:30"),
2114 ..Field::new(FieldKind::Text, "starts", "Starts")
2115 },
2116 &Filling::default(),
2117 &Emit::default(),
2118 );
2119 assert!(html.contains(r#"min="2026-08-09T14:30""#));
2120 }
2121
2122 #[test]
2123 fn a_file_field_is_a_file_input() {
2124 // `844b5ae0`. A field that takes any file emits no `accept` at all,
2125 // which is the browser's own "any file". `accept=""` is a filter that
2126 // means nothing on one browser and everything on another.
2127 let html = field_html(
2128 &Field::new(FieldKind::File, "attachment", "Attachment"),
2129 &Filling::default(),
2130 &Emit::default(),
2131 );
2132 assert!(html.contains(r#"type="file""#));
2133 assert!(!html.contains("accept="));
2134 assert!(!html.contains("multiple"));
2135 // And it never carries a value: a file input's value is not settable
2136 // from markup, and the browser refuses one that tries.
2137 assert!(!html.contains("value="));
2138 }
2139
2140 #[test]
2141 fn an_accept_list_is_comma_joined_in_the_attributes_own_format() {
2142 // `f7261a5a`, makeover-layout 0.31.0. Each entry writes itself: a
2143 // family is its wildcard, a media type is itself, a suffix keeps its
2144 // leading dot and however many more it has.
2145 const MIXED: &[Accepted<'_>] = &[
2146 Accepted::Family(Family::Image),
2147 Accepted::Type("text/csv"),
2148 Accepted::Suffix(".tar.gz"),
2149 ];
2150 let html = field_html(
2151 &Field {
2152 multiple: true,
2153 ..Field::upload("drop", "Drop files", MIXED)
2154 },
2155 &Filling::default(),
2156 &Emit::default(),
2157 );
2158 assert!(
2159 html.contains(r#"accept="image/*,text/csv,.tar.gz""#),
2160 "{html}"
2161 );
2162 assert!(html.contains(" multiple"), "{html}");
2163 }
2164
2165 #[test]
2166 fn an_accept_entry_cannot_end_the_attribute_it_sits_in() {
2167 // The list reaches an attribute value, so it is escaped like every
2168 // other string that does. Nothing in the tree writes a quote into one;
2169 // that it cannot is the point.
2170 const HOSTILE: &[Accepted<'_>] = &[Accepted::Type(r#"image/x" onload="x"#)];
2171 let html = field_html(
2172 &Field::upload("cover", "Cover", HOSTILE),
2173 &Filling::default(),
2174 &Emit::default(),
2175 );
2176 assert!(!html.contains(r#"onload="x"#), "{html}");
2177 }
2178
2179 #[test]
2180 fn the_typed_text_kinds_keep_their_input_type() {
2181 for (kind, expected) in [
2182 (FieldKind::Email, "email"),
2183 (FieldKind::Url, "url"),
2184 (FieldKind::Tel, "tel"),
2185 (FieldKind::Date, "date"),
2186 (FieldKind::DateTime, "datetime-local"),
2187 ] {
2188 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
2189 assert!(
2190 html.contains(&format!(r#"type="{expected}""#)),
2191 "{kind:?} emitted {html}"
2192 );
2193 }
2194 }
2195
2196 #[test]
2197 fn a_temporal_field_is_a_native_control_and_not_a_hinted_text_box() {
2198 // The regression this closes: described as text with a hint reading
2199 // "YYYY-MM-DD", which loses the picker, the platform's validation and
2200 // the touch keyboard, and asks prose to do all three.
2201 for kind in [FieldKind::Date, FieldKind::DateTime] {
2202 let html = field_html(&field(kind), &Filling::default(), &Emit::default());
2203 assert!(!html.contains(r#"type="text""#), "{kind:?} emitted {html}");
2204 }
2205 }
2206
2207 #[test]
2208 fn no_prefix_leaves_the_id_as_the_name() {
2209 let html = field_html(
2210 &field(FieldKind::Text),
2211 &Filling::default(),
2212 &Emit::default(),
2213 );
2214 assert!(html.contains(r#"id="title" name="title""#), "{html}");
2215 }
2216}