Skip to main content

max / makeover-webview

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