Skip to main content

max / makeover-webview

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