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