1use crate::{Emit, class};
37use makeover_layout::{Field, FieldKind};
38use std::fmt::Write as _;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct Markup<'a>(pub &'a str);
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Choice<'a> {
53 pub value: &'a str,
55 pub label: &'a str,
57}
58
59impl<'a> Choice<'a> {
60 #[must_use]
62 pub const fn plain(value: &'a str) -> Self {
63 Self {
64 value,
65 label: value,
66 }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub enum Value<'a> {
78 #[default]
80 Absent,
81 Text(&'a str),
83 Chosen {
85 options: &'a [Choice<'a>],
87 value: &'a str,
89 },
90 On(bool),
92}
93
94impl<'a> Value<'a> {
95 const fn as_text(&self) -> &'a str {
97 match self {
98 Self::Text(text) | Self::Chosen { value: text, .. } => text,
99 Self::Absent | Self::On(_) => "",
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, Default)]
106pub struct Filling<'a> {
107 pub value: Value<'a>,
109 pub placeholder: Option<&'a str>,
111 pub trailing: Option<Markup<'a>>,
113 pub id_prefix: Option<&'a str>,
125}
126
127impl<'a> Filling<'a> {
128 #[must_use]
130 pub const fn of(value: Value<'a>) -> Self {
131 Self {
132 value,
133 placeholder: None,
134 trailing: None,
135 id_prefix: None,
136 }
137 }
138
139 fn id_for(&self, name: &str) -> String {
141 match self.id_prefix {
142 Some(prefix) => format!("{}-{}", escape(prefix), escape(name)),
143 None => escape(name),
144 }
145 }
146}
147
148#[must_use]
154pub fn escape(text: &str) -> String {
155 let mut out = String::with_capacity(text.len());
156 for ch in text.chars() {
157 match ch {
158 '&' => out.push_str("&"),
159 '<' => out.push_str("<"),
160 '>' => out.push_str(">"),
161 '"' => out.push_str("""),
162 '\'' => out.push_str("'"),
163 other => out.push(other),
164 }
165 }
166 out
167}
168
169const fn input_type(kind: FieldKind) -> &'static str {
173 match kind {
174 FieldKind::Secret => "password",
175 FieldKind::Number => "number",
176 FieldKind::Checkbox => "checkbox",
177 FieldKind::Hidden => "hidden",
178 FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
180 }
181}
182
183fn control_attributes(field: &Field<'_>, id: &str, name: &str) -> String {
196 let mut attrs = format!(" id=\"{id}\" name=\"{}\"", escape(name));
197 if field.required {
198 attrs.push_str(" required");
199 }
200 if field.invalid() {
201 attrs.push_str(" aria-invalid=\"true\"");
202 }
203
204 let mut described = Vec::new();
209 if field.hint.is_some() {
210 described.push(format!("{id}-hint"));
211 }
212 if field.error.is_some() {
213 described.push(format!("{id}-error"));
214 }
215 if !described.is_empty() {
216 let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" "));
217 }
218 attrs
219}
220
221fn options_html(options: &[Choice<'_>], value: &str) -> String {
229 let mut html = String::new();
230 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
231 let escaped = escape(value);
232 let _ = write!(
233 html,
234 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
235 );
236 }
237 for opt in options {
238 let selected = if opt.value == value { " selected" } else { "" };
239 let _ = write!(
240 html,
241 "<option value=\"{}\"{selected}>{}</option>",
242 escape(opt.value),
243 escape(opt.label)
244 );
245 }
246 html
247}
248
249fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
251 let id = filling.id_for(field.name);
252 let attrs = control_attributes(field, &id, field.name);
253 let field_class = class("field", opts);
254 let placeholder = filling.placeholder.map_or_else(String::new, |text| {
255 format!(" placeholder=\"{}\"", escape(text))
256 });
257
258 match field.kind {
259 FieldKind::Textarea => format!(
260 "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
261 escape(filling.value.as_text())
262 ),
263 FieldKind::Select => {
264 let options = match filling.value {
265 Value::Chosen { options, value } => options_html(options, value),
266 _ => String::new(),
269 };
270 format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
271 }
272 FieldKind::Checkbox => {
273 let checked = if matches!(filling.value, Value::On(true)) {
274 " checked"
275 } else {
276 ""
277 };
278 format!(
279 "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
280 class("form-checkbox-label", opts),
281 escape(field.label)
282 )
283 }
284 FieldKind::Secret => format!(
291 "<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>"
292 ),
293 kind => format!(
294 "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
295 input_type(kind),
296 escape(filling.value.as_text())
297 ),
298 }
299}
300
301#[must_use]
329pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
330 let id = filling.id_for(field.name);
331
332 if !field.kind.visible() {
333 return format!(
336 "<input type=\"hidden\" name=\"{}\" value=\"{}\">",
337 escape(field.name),
338 escape(filling.value.as_text())
339 );
340 }
341
342 let mut html = format!("<div class=\"{}", class("form-group", opts));
343 if field.invalid() {
344 html.push_str(" has-error");
345 }
346 if field.extended {
347 html.push_str("\" data-extended=\"true");
350 }
351 html.push_str("\">");
352
353 if !field.kind.labels_itself() {
357 let _ = write!(
358 html,
359 "<label class=\"{}\" for=\"{id}\">{}</label>",
360 class("form-label", opts),
361 escape(field.label)
362 );
363 }
364
365 html.push_str(&control_html(field, filling, opts));
366
367 if let Some(hint) = field.hint {
368 let _ = write!(
369 html,
370 "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
371 class("form-hint", opts),
372 escape(hint)
373 );
374 }
375 if let Some(Markup(markup)) = filling.trailing {
376 html.push_str(markup);
377 }
378 if let Some(error) = field.error {
379 let _ = write!(
380 html,
381 "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
382 class("form-error", opts),
383 escape(error)
384 );
385 }
386
387 html.push_str("</div>");
388 html
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 fn field(kind: FieldKind) -> Field<'static> {
396 Field::new(kind, "title", "Title")
397 }
398
399 #[test]
400 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
401 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
403 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
404 assert!(!html.contains("\" onfocus"), "{html}");
408 assert!(
409 html.contains("value=\"x" onfocus=alert(1) autofocus="\""),
410 "{html}"
411 );
412 }
413
414 #[test]
415 fn a_label_cannot_open_a_tag() {
416 let mut f = field(FieldKind::Text);
417 f.label = "<script>alert(1)</script>";
418 let html = field_html(&f, &Filling::default(), &Emit::default());
419 assert!(!html.contains("<script>"), "{html}");
420 assert!(html.contains("<script>"), "{html}");
421 }
422
423 #[test]
424 fn every_escaped_sink_is_covered_by_the_one_escaper() {
425 assert_eq!(escape("&<>\"'"), "&<>"'");
426 assert!(escape("\"").contains("""));
429 }
430
431 #[test]
432 fn markup_is_the_only_way_past_the_escaping() {
433 let filling = Filling {
434 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
435 ..Filling::default()
436 };
437 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
438 assert!(html.contains("<div class=\"recurrence-config\"></div>"), "{html}");
439 }
440
441 #[test]
442 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
443 let mut f = field(FieldKind::Text);
444 f.error = Some("Required");
445 let opts = Emit::default();
446 let html = field_html(&f, &Filling::default(), &opts);
447 assert!(html.contains("aria-invalid=\"true\""), "{html}");
448 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
450 assert!(html.contains("has-error"), "{html}");
453 }
454
455 #[test]
456 fn a_valid_field_claims_nothing_about_being_invalid() {
457 let html = field_html(&field(FieldKind::Text), &Filling::default(), &Emit::default());
458 assert!(!html.contains("aria-invalid"), "{html}");
459 assert!(!html.contains("has-error"), "{html}");
460 }
461
462 #[test]
463 fn the_hint_survives_an_error_arriving() {
464 let mut f = field(FieldKind::Text);
465 f.hint = Some("Keep it short");
466 f.error = Some("Required");
467 let html = field_html(&f, &Filling::default(), &Emit::default());
468 assert!(
469 html.contains("aria-describedby=\"title-hint title-error\""),
470 "{html}"
471 );
472 }
473
474 #[test]
475 fn a_secret_never_carries_its_value_into_the_markup() {
476 let filling = Filling::of(Value::Text("hunter2"));
477 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
478 assert!(!html.contains("hunter2"), "{html}");
479 assert!(html.contains("type=\"password\""), "{html}");
480 }
481
482 #[test]
483 fn a_hidden_field_is_the_input_and_nothing_else() {
484 let filling = Filling::of(Value::Text("42"));
485 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
486 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
487 }
488
489 #[test]
490 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
491 let html = field_html(
492 &field(FieldKind::Checkbox),
493 &Filling::of(Value::On(true)),
494 &Emit::default(),
495 );
496 assert!(!html.contains("form-label"), "{html}");
497 assert!(html.contains("checked"), "{html}");
498 assert!(html.contains("<span>Title</span>"), "{html}");
499 }
500
501 #[test]
502 fn a_select_keeps_a_value_no_option_carries() {
503 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
504 let filling = Filling::of(Value::Chosen {
505 options: &options,
506 value: "10",
507 });
508 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
509 assert!(html.contains("data-unmatched=\"true\""), "{html}");
510 assert!(html.contains("<option value=\"10\" selected"), "{html}");
513 }
514
515 #[test]
516 fn a_select_marks_the_option_that_matches() {
517 let options = [Choice::plain("1"), Choice::plain("3")];
518 let filling = Filling::of(Value::Chosen {
519 options: &options,
520 value: "3",
521 });
522 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
523 assert!(html.contains("<option value=\"3\" selected>3</option>"), "{html}");
524 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
525 assert!(!html.contains("data-unmatched"), "{html}");
526 }
527
528 #[test]
529 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
530 let filling = Filling::of(Value::Text("two\nlines"));
531 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
532 assert!(html.contains(">two\nlines</textarea>"), "{html}");
533 }
534
535 #[test]
536 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
537 let opts = Emit {
538 class_prefix: "mk-",
539 ..Emit::default()
540 };
541 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
542 assert!(html.contains("class=\"mk-form-group\""), "{html}");
543 assert!(html.contains("class=\"mk-field\""), "{html}");
544 }
545
546 #[test]
547 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
548 let mut f = field(FieldKind::Text);
549 f.extended = true;
550 let html = field_html(&f, &Filling::default(), &Emit::default());
551 assert!(html.contains("data-extended=\"true\""), "{html}");
552 }
553
554 #[test]
558 fn the_id_prefix_scopes_the_id_and_never_the_name() {
559 let mut f = field(FieldKind::Text);
560 f.hint = Some("Keep it short");
561 f.error = Some("Required");
562 let filling = Filling {
563 id_prefix: Some("form-modal-task-edit"),
564 ..Filling::default()
565 };
566 let html = field_html(&f, &filling, &Emit::default());
567
568 assert!(html.contains(r#"id="form-modal-task-edit-title""#), "{html}");
569 assert!(html.contains(r#"name="title""#), "{html}");
570 assert!(!html.contains(r#"name="form-modal-task-edit-title""#), "{html}");
571
572 assert!(
575 html.contains(r#"for="form-modal-task-edit-title""#),
576 "{html}"
577 );
578 assert!(
579 html.contains(
580 r#"aria-describedby="form-modal-task-edit-title-hint form-modal-task-edit-title-error""#
581 ),
582 "{html}"
583 );
584 assert!(
585 html.contains(r#"id="form-modal-task-edit-title-hint""#),
586 "{html}"
587 );
588 }
589
590 #[test]
591 fn a_hidden_field_submits_its_bare_name_under_a_prefix() {
592 let filling = Filling {
593 value: Value::Text("42"),
594 id_prefix: Some("scoped"),
595 ..Filling::default()
596 };
597 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
598 assert_eq!(html, r#"<input type="hidden" name="title" value="42">"#);
599 }
600
601 #[test]
602 fn no_prefix_leaves_the_id_as_the_name() {
603 let html = field_html(&field(FieldKind::Text), &Filling::default(), &Emit::default());
604 assert!(html.contains(r#"id="title" name="title""#), "{html}");
605 }
606}