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