Skip to main content

rustango_cms/forms/
render.rs

1//! Public form renderer.
2//!
3//! Turns a [`schema::Form`](super::schema::Form) into the HTML a visitor fills in. The output is
4//! the contract `form_runtime.js` enhances: pages are `<fieldset
5//! data-rcms-page>` blocks the runtime shows one at a time; with JS off all
6//! pages are visible and the form still submits + server-validates.
7//!
8//! Provenance + per-embed overrides: the form carries a hidden `_form`
9//! (form id), `_embed` (the embedding block's uuid), and a cache-safe
10//! `_csrf` field populated from the double-submit cookie by an inline
11//! script (the rendered HTML may be page-cached, so no per-user token is
12//! baked in). The submit handler reads the `Referer` for the source
13//! page and resolves the embed's override from that page's stream by uuid.
14
15use super::schema::{Field, FieldType, Form};
16
17/// Honeypot field name — a hidden input bots tend to fill.
18pub const HONEYPOT_FIELD: &str = "_hp";
19
20/// Render a whole form to HTML. `embed_id` is the embedding block's uuid
21/// (empty when previewed standalone). `submit_action` is the POST target.
22#[must_use]
23pub fn render_form_html(form: &Form, form_id: i64, embed_id: &str) -> String {
24    let action = format!("/forms/submit/{form_id}");
25    let mut out = String::new();
26    // Standard form styles — opt out per-form to fully replace the look.
27    if form.settings.builtin_css {
28        out.push_str("<link rel=\"stylesheet\" href=\"/forms/forms.css\">\n");
29    }
30    out.push_str("<div class=\"rcms-form-thanks\" role=\"status\" hidden>");
31    out.push_str(&html_escape(form.settings.success_text()));
32    out.push_str("</div>\n");
33    // Forms with file fields submit as multipart (and the runtime fetch-
34    // submits them so the X-CSRF-Token header reaches the CSRF layer).
35    let has_file = form
36        .fields()
37        .any(|f| matches!(f.field_type, FieldType::File));
38    let multipart = if has_file {
39        " enctype=\"multipart/form-data\" data-rcms-multipart"
40    } else {
41        ""
42    };
43    out.push_str(&format!(
44        "<form class=\"rcms-form\" method=\"post\" action=\"{}\" data-rcms-form data-rcms-form-key=\"{}\" data-pages=\"{}\"{multipart} novalidate>\n",
45        html_attr(&action),
46        html_attr(&format!("{form_id}:{embed_id}")),
47        form.pages.len().max(1)
48    ));
49    out.push_str(&format!(
50        "  <input type=\"hidden\" name=\"_form\" value=\"{form_id}\">\n"
51    ));
52    out.push_str(&format!(
53        "  <input type=\"hidden\" name=\"_embed\" value=\"{}\">\n",
54        html_attr(embed_id)
55    ));
56    out.push_str(&format!(
57        "  <input type=\"hidden\" name=\"{}\" value=\"\">\n",
58        rustango::forms::csrf::CSRF_FORM_FIELD
59    ));
60    // Shown by the runtime when the server refused the submission.
61    out.push_str(&format!(
62        "  <div class=\"rcms-form-error\" role=\"alert\" hidden>{}</div>\n",
63        html_escape(form.settings.error_text())
64    ));
65    // Honeypot — off the tab order, and hidden inline so it stays hidden
66    // when a site turns off the built-in form styles.
67    out.push_str(&format!(
68        "  <div class=\"rcms-hp\" aria-hidden=\"true\" style=\"position:absolute;left:-10000px;width:1px;height:1px;overflow:hidden\"><label>Leave blank<input type=\"text\" name=\"{HONEYPOT_FIELD}\" tabindex=\"-1\" autocomplete=\"off\"></label></div>\n"
69    ));
70
71    // Progress (runtime fills it in for multi-page forms).
72    if form.pages.len() > 1 {
73        out.push_str(&format!(
74            "  <div class=\"rcms-form-progress\" data-rcms-progress data-text=\"{}\" hidden></div>\n",
75            html_attr(form.settings.progress_text())
76        ));
77    }
78
79    for (pi, page) in form.pages.iter().enumerate() {
80        out.push_str(&format!(
81            "  <fieldset class=\"rcms-form-page\" data-rcms-page=\"{pi}\">\n"
82        ));
83        if !page.label.is_empty() && form.pages.len() > 1 {
84            out.push_str(&format!(
85                "    <legend>{}</legend>\n",
86                html_escape(&page.label)
87            ));
88        }
89        for section in &page.sections {
90            out.push_str("    <div class=\"rcms-form-section\">\n");
91            if !section.title.is_empty() {
92                out.push_str(&format!(
93                    "      <h3 class=\"rcms-form-section-title\">{}</h3>\n",
94                    html_escape(&section.title)
95                ));
96            }
97            for row in &section.rows {
98                out.push_str("      <div class=\"rcms-form-row\">\n");
99                for col in &row.columns {
100                    out.push_str(&format!(
101                        "        <div class=\"rcms-form-col\" style=\"flex:{} 1 0\">\n",
102                        col.width.clamp(1, 12)
103                    ));
104                    for field in &col.fields {
105                        out.push_str(&render_field(field));
106                    }
107                    out.push_str("        </div>\n");
108                }
109                out.push_str("      </div>\n");
110            }
111            out.push_str("    </div>\n");
112        }
113        out.push_str("  </fieldset>\n");
114    }
115
116    // Navigation — runtime toggles prev/next/submit; no-JS shows submit only.
117    out.push_str("  <div class=\"rcms-form-nav\">\n");
118    out.push_str(&format!(
119        "    <button type=\"button\" class=\"rcms-form-prev\" data-rcms-prev hidden>{}</button>\n",
120        html_escape(form.settings.back_text())
121    ));
122    out.push_str(&format!(
123        "    <button type=\"button\" class=\"rcms-form-next\" data-rcms-next hidden>{}</button>\n",
124        html_escape(form.settings.next_text())
125    ));
126    out.push_str(&format!(
127        "    <button type=\"submit\" class=\"rcms-form-submit\" data-rcms-submit>{}</button>\n",
128        html_escape(form.settings.submit_text())
129    ));
130    out.push_str("  </div>\n");
131
132    out.push_str("</form>\n");
133    // FB-10/FB-14 — the cacheable runtime (csrf-fill, thanks, paging,
134    // conditional logic) enhances every form on the page. Guarded so
135    // multiple embeds load it harmlessly once.
136    out.push_str("<script src=\"/forms/runtime.js\" defer></script>\n");
137    out
138}
139
140fn render_field(f: &Field) -> String {
141    // FB-14 — conditional-logic hooks the runtime reads off each wrapper.
142    let mut wattr = format!(" data-rcms-key=\"{}\"", html_attr(&f.key));
143    if !f.rules.is_empty() {
144        if let Ok(j) = serde_json::to_string(&f.rules) {
145            wattr.push_str(&format!(" data-rcms-rules=\"{}\"", html_attr(&j)));
146        }
147    }
148
149    // Presentational types carry no input.
150    if matches!(f.field_type, FieldType::Static) {
151        return format!(
152            "          <div class=\"rcms-field rcms-field-static\"{wattr}>{}</div>\n",
153            html_escape(&f.content)
154        );
155    }
156    if matches!(f.field_type, FieldType::Richtext) {
157        // Author-controlled rich text, sanitized here because every write
158        // path (builder, publish, MCP, translations) can reach this render
159        // with arbitrary HTML (#756).
160        return format!(
161            "          <div class=\"rcms-field rcms-field-richtext\"{wattr}>{}</div>\n",
162            crate::markdown::sanitize_html(&f.content)
163        );
164    }
165    if matches!(f.field_type, FieldType::Hidden) {
166        return format!(
167            "          <input type=\"hidden\" name=\"{}\" value=\"{}\">\n",
168            html_attr(&f.key),
169            html_attr(&f.default)
170        );
171    }
172
173    let id = format!("rcms-f-{}", html_attr(&f.key));
174    let req = if f.required { " required" } else { "" };
175    let req_star = if f.required {
176        " <span class=\"rcms-req\">*</span>"
177    } else {
178        ""
179    };
180    let ph = if f.placeholder.is_empty() {
181        String::new()
182    } else {
183        format!(" placeholder=\"{}\"", html_attr(&f.placeholder))
184    };
185
186    // FB-13 — native HTML5 length/pattern attrs (client-side validation).
187    let mut vattr = String::new();
188    if let Some(min) = f.min_length {
189        vattr.push_str(&format!(" minlength=\"{min}\""));
190    }
191    if let Some(max) = f.max_length {
192        vattr.push_str(&format!(" maxlength=\"{max}\""));
193    }
194    if !f.pattern.is_empty() {
195        vattr.push_str(&format!(" pattern=\"{}\"", html_attr(&f.pattern)));
196    }
197
198    let control = match f.field_type {
199        FieldType::Textarea => format!(
200            "<textarea id=\"{id}\" name=\"{name}\"{req}{ph}{vattr} rows=\"4\">{val}</textarea>",
201            name = html_attr(&f.key),
202            val = html_escape(&f.default),
203        ),
204        FieldType::Select | FieldType::Multiselect => {
205            let multiple = if matches!(f.field_type, FieldType::Multiselect) {
206                " multiple"
207            } else {
208                ""
209            };
210            let mut s = format!(
211                "<select id=\"{id}\" name=\"{name}\"{req}{multiple}>",
212                name = html_attr(&f.key)
213            );
214            if matches!(f.field_type, FieldType::Select) {
215                // The field's placeholder (translatable) is the prompt.
216                let prompt = if f.placeholder.is_empty() { "—" } else { f.placeholder.as_str() };
217                s.push_str(&format!("<option value=\"\">{}</option>", html_escape(prompt)));
218            }
219            for o in &f.options {
220                s.push_str(&format!(
221                    "<option value=\"{}\">{}</option>",
222                    html_attr(&o.value),
223                    html_escape(if o.label.is_empty() { &o.value } else { &o.label })
224                ));
225            }
226            s.push_str("</select>");
227            s
228        }
229        FieldType::Radio | FieldType::Checkboxes => {
230            let input_type = if matches!(f.field_type, FieldType::Radio) {
231                "radio"
232            } else {
233                "checkbox"
234            };
235            // A required radio group is native (`required` on its inputs);
236            // "at least one box" has no HTML attribute, so the runtime
237            // enforces `data-rcms-required` on a checkbox group.
238            let (group_req, input_req) = match (f.required, f.field_type) {
239                (true, FieldType::Radio) => ("", " required"),
240                (true, _) => (" data-rcms-required aria-required=\"true\"", ""),
241                _ => ("", ""),
242            };
243            let mut s = format!(
244                "<div class=\"rcms-choices\" role=\"group\" aria-label=\"{}\"{group_req}>",
245                html_attr(&f.label)
246            );
247            for o in &f.options {
248                s.push_str(&format!(
249                    "<label class=\"rcms-choice\"><input type=\"{input_type}\" name=\"{name}\" value=\"{val}\"{input_req}> {lbl}</label>",
250                    name = html_attr(&f.key),
251                    val = html_attr(&o.value),
252                    lbl = html_escape(if o.label.is_empty() { &o.value } else { &o.label })
253                ));
254            }
255            s.push_str("</div>");
256            s
257        }
258        FieldType::Checkbox => format!(
259            "<label class=\"rcms-choice\"><input type=\"checkbox\" id=\"{id}\" name=\"{name}\" value=\"yes\"{req}> {lbl}</label>",
260            name = html_attr(&f.key),
261            lbl = html_escape(&f.label)
262        ),
263        FieldType::Rating => {
264            let scale = f.scale.unwrap_or(5).clamp(1, 10);
265            let mut s = format!("<div class=\"rcms-rating\" role=\"radiogroup\" aria-label=\"{}\">", html_attr(&f.label));
266            for i in 1..=scale {
267                s.push_str(&format!(
268                    "<label class=\"rcms-rating-star\"><input type=\"radio\" name=\"{name}\" value=\"{i}\"{req} aria-label=\"{i}\"> <span aria-hidden=\"true\">★</span></label>",
269                    name = html_attr(&f.key)
270                ));
271            }
272            s.push_str("</div>");
273            s
274        }
275        FieldType::File => format!(
276            "<input type=\"file\" id=\"{id}\" name=\"{name}\"{req}{accept}>",
277            name = html_attr(&f.key),
278            accept = if f.accept.is_empty() {
279                String::new()
280            } else {
281                format!(" accept=\"{}\"", html_attr(&f.accept))
282            }
283        ),
284        _ => {
285            // text-shaped + date/time/number map to native input types.
286            let html_type = match f.field_type {
287                FieldType::Email => "email",
288                FieldType::Url => "url",
289                FieldType::Tel => "tel",
290                FieldType::Number => "number",
291                FieldType::Date => "date",
292                FieldType::Datetime => "datetime-local",
293                FieldType::Time => "time",
294                _ => "text",
295            };
296            let mut extra = String::new();
297            if matches!(f.field_type, FieldType::Number) {
298                if let Some(min) = f.min {
299                    extra.push_str(&format!(" min=\"{min}\""));
300                }
301                if let Some(max) = f.max {
302                    extra.push_str(&format!(" max=\"{max}\""));
303                }
304                if let Some(step) = f.step {
305                    extra.push_str(&format!(" step=\"{step}\""));
306                }
307            }
308            format!(
309                "<input type=\"{html_type}\" id=\"{id}\" name=\"{name}\" value=\"{val}\"{req}{ph}{extra}{vattr}>",
310                name = html_attr(&f.key),
311                val = html_attr(&f.default),
312            )
313        }
314    };
315
316    // checkbox renders its own label
317    if matches!(f.field_type, FieldType::Checkbox) {
318        let help = if f.help.is_empty() {
319            String::new()
320        } else {
321            format!(
322                "<small class=\"rcms-help\">{}</small>",
323                html_escape(&f.help)
324            )
325        };
326        return format!("          <div class=\"rcms-field\"{wattr}>{control}{help}</div>\n");
327    }
328
329    let label = if f.label.is_empty() {
330        String::new()
331    } else {
332        format!(
333            "<label for=\"{id}\">{}{req_star}</label>",
334            html_escape(&f.label)
335        )
336    };
337    let help = if f.help.is_empty() {
338        String::new()
339    } else {
340        format!(
341            "<small class=\"rcms-help\">{}</small>",
342            html_escape(&f.help)
343        )
344    };
345    format!("          <div class=\"rcms-field\"{wattr}>{label}{control}{help}</div>\n")
346}
347
348pub(crate) fn html_escape(s: &str) -> String {
349    let mut out = String::with_capacity(s.len());
350    for c in s.chars() {
351        match c {
352            '&' => out.push_str("&amp;"),
353            '<' => out.push_str("&lt;"),
354            '>' => out.push_str("&gt;"),
355            '"' => out.push_str("&quot;"),
356            '\'' => out.push_str("&#39;"),
357            _ => out.push(c),
358        }
359    }
360    out
361}
362
363fn html_attr(s: &str) -> String {
364    html_escape(s)
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use crate::forms::schema::{Choice, Column, Page, Row, Section};
371
372    fn form_with(fields: Vec<Field>) -> Form {
373        Form {
374            pages: vec![Page {
375                id: "p1".into(),
376                label: "Page 1".into(),
377                sections: vec![Section {
378                    id: "s1".into(),
379                    title: String::new(),
380                    rows: vec![Row {
381                        id: "r1".into(),
382                        columns: vec![Column {
383                            id: "c1".into(),
384                            width: 12,
385                            fields,
386                        }],
387                    }],
388                }],
389            }],
390            ..Default::default()
391        }
392    }
393
394    #[test]
395    fn renders_core_inputs_and_hidden_meta() {
396        let form = form_with(vec![
397            Field {
398                id: "f1".into(),
399                key: "name".into(),
400                field_type: FieldType::Text,
401                label: "Name".into(),
402                required: true,
403                ..Default::default()
404            },
405            Field {
406                id: "f2".into(),
407                key: "email".into(),
408                field_type: FieldType::Email,
409                label: "Email".into(),
410                ..Default::default()
411            },
412        ]);
413        let html = render_form_html(&form, 7, "blk-123");
414        assert!(html.contains("action=\"/forms/submit/7\""));
415        assert!(html.contains("name=\"_form\" value=\"7\""));
416        assert!(html.contains("name=\"_embed\" value=\"blk-123\""));
417        assert!(html.contains("name=\"_csrf\" value=\"\""));
418        assert!(html.contains("/forms/runtime.js")); // cacheable runtime
419        assert!(html.contains("name=\"_hp\"")); // honeypot
420        assert!(html.contains("class=\"rcms-form-error\" role=\"alert\" hidden")); // error banner
421        // …hidden inline, so a site without the built-in styles doesn't show it.
422        assert!(html.contains("class=\"rcms-hp\" aria-hidden=\"true\" style=\"position:absolute;left:-10000px"));
423        assert!(html.contains("type=\"email\""));
424        assert!(html.contains("name=\"name\""));
425        assert!(html.contains("required"));
426        assert!(html.contains("data-rcms-page=\"0\""));
427    }
428
429    #[test]
430    fn rich_text_content_is_sanitized_on_render() {
431        // #756 — every write path can store arbitrary HTML here.
432        let form = form_with(vec![Field {
433            id: "f1".into(),
434            field_type: FieldType::Richtext,
435            content: r#"<p>Hi <b>there</b></p><script>alert(1)</script><img src=x onerror=alert(2)>"#.into(),
436            ..Default::default()
437        }]);
438        let html = render_form_html(&form, 7, "");
439        assert!(html.contains("<b>there</b>"), "safe markup survives: {html}");
440        // The form's own `<script src=/forms/runtime.js>` is expected; the
441        // injected one is not.
442        assert!(!html.contains("alert(1)"), "injected script stripped: {html}");
443        assert!(!html.contains("onerror"), "event handler stripped: {html}");
444    }
445
446    #[test]
447    fn sanitize_rich_text_cleans_stored_content() {
448        let mut form = form_with(vec![Field {
449            id: "f1".into(),
450            field_type: FieldType::Richtext,
451            content: "<p>ok</p><script>x()</script>".into(),
452            ..Default::default()
453        }]);
454        form.sanitize_rich_text();
455        let content = &form.fields().next().expect("one field").content;
456        assert_eq!(content, "<p>ok</p>");
457    }
458
459    #[test]
460    fn renders_choice_and_presentational() {
461        let form = form_with(vec![
462            Field {
463                id: "f1".into(),
464                key: "topic".into(),
465                field_type: FieldType::Select,
466                label: "Topic".into(),
467                options: vec![Choice {
468                    value: "a".into(),
469                    label: "Apples".into(),
470                    ..Default::default()
471                }],
472                ..Default::default()
473            },
474            Field {
475                id: "f2".into(),
476                field_type: FieldType::Static,
477                content: "Heading".into(),
478                ..Default::default()
479            },
480        ]);
481        let html = render_form_html(&form, 1, "");
482        assert!(html.contains("<select"));
483        assert!(html.contains("Apples"));
484        assert!(html.contains("rcms-field-static"));
485        assert!(html.contains("Heading"));
486    }
487
488    #[test]
489    fn required_choice_groups_can_be_checked_in_the_browser() {
490        let opts = vec![
491            Choice { value: "a".into(), label: "A".into(), ..Default::default() },
492            Choice { value: "b".into(), label: "B".into(), ..Default::default() },
493        ];
494        let form = form_with(vec![
495            Field { id: "f1".into(), key: "pick".into(), field_type: FieldType::Radio, required: true, options: opts.clone(), ..Default::default() },
496            Field { id: "f2".into(), key: "many".into(), field_type: FieldType::Checkboxes, required: true, options: opts, ..Default::default() },
497            Field { id: "f3".into(), key: "stars".into(), field_type: FieldType::Rating, required: true, ..Default::default() },
498        ]);
499        let html = render_form_html(&form, 1, "");
500        assert!(html.contains(r#"name="pick" value="a" required"#), "{html}");
501        assert!(html.contains(r#"role="group" aria-label="" data-rcms-required"#), "{html}");
502        assert!(!html.contains(r#"name="many" value="a" required"#), "no per-box required: {html}");
503        assert!(html.contains(r#"name="stars" value="1" required"#), "{html}");
504    }
505
506    #[test]
507    fn control_texts_come_from_the_settings() {
508        let mut form = form_with(vec![]);
509        form.pages.push(Page { id: "p2".into(), ..Default::default() });
510        let html = render_form_html(&form, 1, "e1");
511        assert!(html.contains(">Next</button>") && html.contains(">Back</button>"), "defaults: {html}");
512        assert!(html.contains(r#"data-text="Step {n} of {total}""#));
513        assert!(html.contains(r#"data-rcms-form-key="1:e1""#));
514        form.settings.next_label = "Suivant".into();
515        form.settings.back_label = "Retour".into();
516        form.settings.progress_label = "Étape {n} sur {total}".into();
517        form.settings.error_message = "Oups".into();
518        form.settings.success_message = "Merci".into();
519        let html = render_form_html(&form, 1, "e1");
520        for want in [">Suivant</button>", ">Retour</button>", "Étape {n} sur {total}", ">Oups</div>", ">Merci</div>"] {
521            assert!(html.contains(want), "{want}: {html}");
522        }
523    }
524
525    #[test]
526    fn multi_page_emits_progress_and_pages() {
527        let mut form = form_with(vec![Field {
528            id: "f1".into(),
529            key: "a".into(),
530            field_type: FieldType::Text,
531            ..Default::default()
532        }]);
533        form.pages.push(Page {
534            id: "p2".into(),
535            label: "Two".into(),
536            sections: vec![],
537            ..Default::default()
538        });
539        let html = render_form_html(&form, 1, "");
540        assert!(html.contains("data-rcms-progress"));
541        assert!(html.contains("data-rcms-page=\"0\""));
542        assert!(html.contains("data-rcms-page=\"1\""));
543    }
544}