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}
114
115impl<'a> Filling<'a> {
116 #[must_use]
118 pub const fn of(value: Value<'a>) -> Self {
119 Self {
120 value,
121 placeholder: None,
122 trailing: None,
123 }
124 }
125}
126
127#[must_use]
133pub fn escape(text: &str) -> String {
134 let mut out = String::with_capacity(text.len());
135 for ch in text.chars() {
136 match ch {
137 '&' => out.push_str("&"),
138 '<' => out.push_str("<"),
139 '>' => out.push_str(">"),
140 '"' => out.push_str("""),
141 '\'' => out.push_str("'"),
142 other => out.push(other),
143 }
144 }
145 out
146}
147
148const fn input_type(kind: FieldKind) -> &'static str {
152 match kind {
153 FieldKind::Secret => "password",
154 FieldKind::Number => "number",
155 FieldKind::Checkbox => "checkbox",
156 FieldKind::Hidden => "hidden",
157 FieldKind::Text | FieldKind::Select | FieldKind::Textarea => "text",
159 }
160}
161
162fn control_attributes(field: &Field<'_>, id: &str) -> String {
171 let mut attrs = format!(" id=\"{0}\" name=\"{0}\"", escape(id));
172 if field.required {
173 attrs.push_str(" required");
174 }
175 if field.invalid() {
176 attrs.push_str(" aria-invalid=\"true\"");
177 }
178
179 let mut described = Vec::new();
184 if field.hint.is_some() {
185 described.push(format!("{}-hint", escape(id)));
186 }
187 if field.error.is_some() {
188 described.push(format!("{}-error", escape(id)));
189 }
190 if !described.is_empty() {
191 let _ = write!(attrs, " aria-describedby=\"{}\"", described.join(" "));
192 }
193 attrs
194}
195
196fn options_html(options: &[Choice<'_>], value: &str) -> String {
204 let mut html = String::new();
205 if !value.is_empty() && !options.iter().any(|opt| opt.value == value) {
206 let escaped = escape(value);
207 let _ = write!(
208 html,
209 "<option value=\"{escaped}\" selected data-unmatched=\"true\">{escaped}</option>"
210 );
211 }
212 for opt in options {
213 let selected = if opt.value == value { " selected" } else { "" };
214 let _ = write!(
215 html,
216 "<option value=\"{}\"{selected}>{}</option>",
217 escape(opt.value),
218 escape(opt.label)
219 );
220 }
221 html
222}
223
224fn control_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
226 let id = field.name;
227 let attrs = control_attributes(field, id);
228 let field_class = class("field", opts);
229 let placeholder = filling.placeholder.map_or_else(String::new, |text| {
230 format!(" placeholder=\"{}\"", escape(text))
231 });
232
233 match field.kind {
234 FieldKind::Textarea => format!(
235 "<textarea class=\"{field_class}\"{attrs}{placeholder}>{}</textarea>",
236 escape(filling.value.as_text())
237 ),
238 FieldKind::Select => {
239 let options = match filling.value {
240 Value::Chosen { options, value } => options_html(options, value),
241 _ => String::new(),
244 };
245 format!("<select class=\"{field_class}\"{attrs}>{options}</select>")
246 }
247 FieldKind::Checkbox => {
248 let checked = if matches!(filling.value, Value::On(true)) {
249 " checked"
250 } else {
251 ""
252 };
253 format!(
254 "<label class=\"{}\"><input type=\"checkbox\"{attrs}{checked}><span>{}</span></label>",
255 class("form-checkbox-label", opts),
256 escape(field.label)
257 )
258 }
259 FieldKind::Secret => format!(
266 "<input type=\"password\" class=\"{field_class}\"{attrs}{placeholder}>"
267 ),
268 kind => format!(
269 "<input type=\"{}\" class=\"{field_class}\"{attrs}{placeholder} value=\"{}\">",
270 input_type(kind),
271 escape(filling.value.as_text())
272 ),
273 }
274}
275
276#[must_use]
304pub fn field_html(field: &Field<'_>, filling: &Filling<'_>, opts: &Emit) -> String {
305 let id = escape(field.name);
306
307 if !field.kind.visible() {
308 return format!(
309 "<input type=\"hidden\" name=\"{id}\" value=\"{}\">",
310 escape(filling.value.as_text())
311 );
312 }
313
314 let mut html = format!("<div class=\"{}", class("form-group", opts));
315 if field.invalid() {
316 html.push_str(" has-error");
317 }
318 if field.extended {
319 html.push_str("\" data-extended=\"true");
322 }
323 html.push_str("\">");
324
325 if !field.kind.labels_itself() {
329 let _ = write!(
330 html,
331 "<label class=\"{}\" for=\"{id}\">{}</label>",
332 class("form-label", opts),
333 escape(field.label)
334 );
335 }
336
337 html.push_str(&control_html(field, filling, opts));
338
339 if let Some(hint) = field.hint {
340 let _ = write!(
341 html,
342 "<div class=\"{}\" id=\"{id}-hint\">{}</div>",
343 class("form-hint", opts),
344 escape(hint)
345 );
346 }
347 if let Some(Markup(markup)) = filling.trailing {
348 html.push_str(markup);
349 }
350 if let Some(error) = field.error {
351 let _ = write!(
352 html,
353 "<div class=\"{} visible\" id=\"{id}-error\" role=\"alert\">{}</div>",
354 class("form-error", opts),
355 escape(error)
356 );
357 }
358
359 html.push_str("</div>");
360 html
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 fn field(kind: FieldKind) -> Field<'static> {
368 Field::new(kind, "title", "Title")
369 }
370
371 #[test]
372 fn a_value_cannot_break_out_of_the_attribute_it_sits_in() {
373 let filling = Filling::of(Value::Text("x\" onfocus=alert(1) autofocus=\""));
375 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
376 assert!(!html.contains("\" onfocus"), "{html}");
380 assert!(
381 html.contains("value=\"x" onfocus=alert(1) autofocus="\""),
382 "{html}"
383 );
384 }
385
386 #[test]
387 fn a_label_cannot_open_a_tag() {
388 let mut f = field(FieldKind::Text);
389 f.label = "<script>alert(1)</script>";
390 let html = field_html(&f, &Filling::default(), &Emit::default());
391 assert!(!html.contains("<script>"), "{html}");
392 assert!(html.contains("<script>"), "{html}");
393 }
394
395 #[test]
396 fn every_escaped_sink_is_covered_by_the_one_escaper() {
397 assert_eq!(escape("&<>\"'"), "&<>"'");
398 assert!(escape("\"").contains("""));
401 }
402
403 #[test]
404 fn markup_is_the_only_way_past_the_escaping() {
405 let filling = Filling {
406 trailing: Some(Markup("<div class=\"recurrence-config\"></div>")),
407 ..Filling::default()
408 };
409 let html = field_html(&field(FieldKind::Text), &filling, &Emit::default());
410 assert!(html.contains("<div class=\"recurrence-config\"></div>"), "{html}");
411 }
412
413 #[test]
414 fn an_invalid_field_carries_the_attribute_its_own_stylesheet_keys_on() {
415 let mut f = field(FieldKind::Text);
416 f.error = Some("Required");
417 let opts = Emit::default();
418 let html = field_html(&f, &Filling::default(), &opts);
419 assert!(html.contains("aria-invalid=\"true\""), "{html}");
420 assert!(crate::stylesheet(&opts).contains("[aria-invalid=\"true\"]"));
422 assert!(html.contains("has-error"), "{html}");
425 }
426
427 #[test]
428 fn a_valid_field_claims_nothing_about_being_invalid() {
429 let html = field_html(&field(FieldKind::Text), &Filling::default(), &Emit::default());
430 assert!(!html.contains("aria-invalid"), "{html}");
431 assert!(!html.contains("has-error"), "{html}");
432 }
433
434 #[test]
435 fn the_hint_survives_an_error_arriving() {
436 let mut f = field(FieldKind::Text);
437 f.hint = Some("Keep it short");
438 f.error = Some("Required");
439 let html = field_html(&f, &Filling::default(), &Emit::default());
440 assert!(
441 html.contains("aria-describedby=\"title-hint title-error\""),
442 "{html}"
443 );
444 }
445
446 #[test]
447 fn a_secret_never_carries_its_value_into_the_markup() {
448 let filling = Filling::of(Value::Text("hunter2"));
449 let html = field_html(&field(FieldKind::Secret), &filling, &Emit::default());
450 assert!(!html.contains("hunter2"), "{html}");
451 assert!(html.contains("type=\"password\""), "{html}");
452 }
453
454 #[test]
455 fn a_hidden_field_is_the_input_and_nothing_else() {
456 let filling = Filling::of(Value::Text("42"));
457 let html = field_html(&field(FieldKind::Hidden), &filling, &Emit::default());
458 assert_eq!(html, "<input type=\"hidden\" name=\"title\" value=\"42\">");
459 }
460
461 #[test]
462 fn a_checkbox_labels_itself_and_takes_no_separate_label() {
463 let html = field_html(
464 &field(FieldKind::Checkbox),
465 &Filling::of(Value::On(true)),
466 &Emit::default(),
467 );
468 assert!(!html.contains("form-label"), "{html}");
469 assert!(html.contains("checked"), "{html}");
470 assert!(html.contains("<span>Title</span>"), "{html}");
471 }
472
473 #[test]
474 fn a_select_keeps_a_value_no_option_carries() {
475 let options = [Choice::plain("1"), Choice::plain("3"), Choice::plain("7")];
476 let filling = Filling::of(Value::Chosen {
477 options: &options,
478 value: "10",
479 });
480 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
481 assert!(html.contains("data-unmatched=\"true\""), "{html}");
482 assert!(html.contains("<option value=\"10\" selected"), "{html}");
485 }
486
487 #[test]
488 fn a_select_marks_the_option_that_matches() {
489 let options = [Choice::plain("1"), Choice::plain("3")];
490 let filling = Filling::of(Value::Chosen {
491 options: &options,
492 value: "3",
493 });
494 let html = field_html(&field(FieldKind::Select), &filling, &Emit::default());
495 assert!(html.contains("<option value=\"3\" selected>3</option>"), "{html}");
496 assert!(html.contains("<option value=\"1\">1</option>"), "{html}");
497 assert!(!html.contains("data-unmatched"), "{html}");
498 }
499
500 #[test]
501 fn a_textarea_carries_its_value_as_text_and_not_as_an_attribute() {
502 let filling = Filling::of(Value::Text("two\nlines"));
503 let html = field_html(&field(FieldKind::Textarea), &filling, &Emit::default());
504 assert!(html.contains(">two\nlines</textarea>"), "{html}");
505 }
506
507 #[test]
508 fn the_class_prefix_reaches_the_markup_as_well_as_the_stylesheet() {
509 let opts = Emit {
510 class_prefix: "mk-",
511 ..Emit::default()
512 };
513 let html = field_html(&field(FieldKind::Text), &Filling::default(), &opts);
514 assert!(html.contains("class=\"mk-form-group\""), "{html}");
515 assert!(html.contains("class=\"mk-field\""), "{html}");
516 }
517
518 #[test]
519 fn an_extended_field_says_so_and_leaves_the_disclosure_to_the_form() {
520 let mut f = field(FieldKind::Text);
521 f.extended = true;
522 let html = field_html(&f, &Filling::default(), &Emit::default());
523 assert!(html.contains("data-extended=\"true\""), "{html}");
524 }
525}