1use std::fmt::Write as _;
4
5use serenade_validator::ConstraintViolationList;
6
7use crate::form::Field;
8use crate::kind::{ChoiceOptions, FieldConfig};
9use crate::transformer::split_multi;
10use crate::{Form, FormError, escape_attr, escape_html};
11
12#[must_use]
16pub fn form_label(field: &Field) -> String {
17 if matches!(field.config(), FieldConfig::Hidden(_)) {
18 return String::new();
19 }
20 if matches!(
21 field.config(),
22 FieldConfig::Choice(ChoiceOptions { expanded: true, .. })
23 ) {
24 return String::new();
25 }
26 let id = escape_attr(field.name());
27 let label = escape_html(field.name());
28 format!(r#"<label for="{id}">{label}</label>"#)
29}
30
31pub fn form_widget(field: &Field) -> Result<String, FormError> {
37 let id = escape_attr(field.name());
38 let name = escape_attr(field.name());
39 let view = view_value(field)?;
40 let value = escape_attr(&view);
41 let html = match field.config() {
42 FieldConfig::Textarea(options) => {
43 let rows = options
44 .rows
45 .map_or(String::new(), |r| format!(r#" rows="{r}""#));
46 let placeholder = placeholder_attr(options.placeholder.as_deref());
47 format!(
48 r#"<textarea id="{id}" name="{name}"{rows}{placeholder}>{text}</textarea>"#,
49 text = escape_html(&view),
50 )
51 }
52 FieldConfig::Hidden(_) => {
53 format!(r#"<input type="hidden" id="{id}" name="{name}" value="{value}" />"#)
54 }
55 FieldConfig::Password(options) => {
56 let placeholder = placeholder_attr(options.placeholder.as_deref());
57 format!(
58 r#"<input type="password" id="{id}" name="{name}" value="{value}"{placeholder} />"#
59 )
60 }
61 FieldConfig::Checkbox(options) => {
62 let checked = if field.value() == options.checked_value
63 || matches!(field.value(), "1" | "true")
64 {
65 " checked"
66 } else {
67 ""
68 };
69 let checked_value = escape_attr(&options.checked_value);
70 format!(
71 r#"<input type="checkbox" id="{id}" name="{name}" value="{checked_value}"{checked} />"#
72 )
73 }
74 FieldConfig::Choice(options) => render_choice_widget(field, options, &id, &name),
75 FieldConfig::Number(options) => {
76 let min = options
77 .min
78 .map_or(String::new(), |m| format!(r#" min="{m}""#));
79 let max = options
80 .max
81 .map_or(String::new(), |m| format!(r#" max="{m}""#));
82 let step = options
83 .step
84 .map_or(String::new(), |s| format!(r#" step="{s}""#));
85 format!(
86 r#"<input type="number" id="{id}" name="{name}" value="{value}"{min}{max}{step} />"#
87 )
88 }
89 FieldConfig::File(options) => {
90 let accept = options.accept.as_deref().map_or(String::new(), |a| {
91 format!(r#" accept="{}""#, escape_attr(a))
92 });
93 format!(r#"<input type="file" id="{id}" name="{name}"{accept} />"#)
94 }
95 FieldConfig::Text(options) => {
96 let placeholder = placeholder_attr(options.placeholder.as_deref());
97 format!(r#"<input type="text" id="{id}" name="{name}" value="{value}"{placeholder} />"#)
98 }
99 };
100 Ok(html)
101}
102
103#[must_use]
105pub fn form_errors(field: &Field, violations: &ConstraintViolationList) -> String {
106 let messages: Vec<&str> = violations
107 .as_slice()
108 .iter()
109 .filter(|v| v.property_path == field.name())
110 .map(|v| v.message.as_str())
111 .collect();
112 if messages.is_empty() {
113 return String::new();
114 }
115 let mut html = String::from(r#"<ul class="form-errors">"#);
116 for message in messages {
117 let _ = write!(html, "<li>{}</li>", escape_html(message));
118 }
119 html.push_str("</ul>");
120 html
121}
122
123pub fn form_row(field: &Field, violations: &ConstraintViolationList) -> Result<String, FormError> {
129 let label = form_label(field);
130 let widget = form_widget(field)?;
131 let errors = form_errors(field, violations);
132 Ok(format!(
133 r#"<div class="form-row">{label}{widget}{errors}</div>"#
134 ))
135}
136
137pub fn form_csrf(form: &Form) -> Result<String, FormError> {
143 form.csrf_html()
144}
145
146fn view_value(field: &Field) -> Result<String, FormError> {
147 field
148 .transformer
149 .as_ref()
150 .map_or_else(|| Ok(field.value.clone()), |t| t.transform(&field.value))
151}
152
153fn placeholder_attr(placeholder: Option<&str>) -> String {
154 placeholder.map_or(String::new(), |p| {
155 format!(r#" placeholder="{}""#, escape_attr(p))
156 })
157}
158
159fn render_choice_widget(field: &Field, options: &ChoiceOptions, id: &str, name: &str) -> String {
160 let selected = split_multi(field.value());
161 let legend = escape_html(field.name());
162 if options.expanded {
163 let mut html = format!(r"<fieldset><legend>{legend}</legend>");
164 for (i, choice) in options.choices.iter().enumerate() {
165 let input_id = format!("{id}_{i}");
166 let checked = if selected.contains(&choice.value.as_str()) {
167 " checked"
168 } else {
169 ""
170 };
171 let input_type = if options.multiple {
172 "checkbox"
173 } else {
174 "radio"
175 };
176 let _ = write!(
177 html,
178 r#"<label for="{input_id}"><input type="{input_type}" id="{input_id}" name="{name}" value="{value}"{checked} />{choice_label}</label>"#,
179 value = escape_attr(&choice.value),
180 choice_label = escape_html(&choice.label),
181 );
182 }
183 html.push_str("</fieldset>");
184 return html;
185 }
186 let multiple = if options.multiple { " multiple" } else { "" };
187 let mut html = format!(r#"<select id="{id}" name="{name}"{multiple}>"#);
188 for choice in &options.choices {
189 let is_selected = selected.contains(&choice.value.as_str());
190 let selected_attr = if is_selected { " selected" } else { "" };
191 let _ = write!(
192 html,
193 r#"<option value="{value}"{selected_attr}>{label}</option>"#,
194 value = escape_attr(&choice.value),
195 label = escape_html(&choice.label),
196 );
197 }
198 html.push_str("</select>");
199 html
200}