Skip to main content

sunday_slate/web/
form.rs

1use super::is_htmx;
2use crate::{AppError, AppState};
3use askama::Template;
4use axum::Form;
5use axum::extract::{FromRequest, FromRequestParts, Request};
6use axum::response::{Html, IntoResponse, Response};
7use garde::Report;
8use serde::de::DeserializeOwned;
9use std::collections::HashMap;
10
11/// Maps field names to ordered error messages, built from a `garde::Report`.
12#[derive(Debug, Default, Clone)]
13pub struct FormErrors(HashMap<String, Vec<String>>);
14
15impl From<&Report> for FormErrors {
16    fn from(value: &Report) -> Self {
17        let mut map: HashMap<String, Vec<String>> = HashMap::new();
18        for (path, err) in value.iter() {
19            let field = path.to_string();
20            map.entry(field)
21                .or_default()
22                .push(err.message().to_string());
23        }
24        Self(map)
25    }
26}
27
28impl FormErrors {
29    /// Return the error messages for the named field, or an empty slice
30    /// if the field has no errors.
31    pub fn field(&self, name: &str) -> &[String] {
32        self.0.get(name).map(Vec::as_slice).unwrap_or(&[])
33    }
34
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    /// Build a one-field, one-message error set (for checks garde can't express,
40    /// e.g. a database uniqueness rule).
41    pub fn single(field: &str, message: &str) -> Self {
42        let mut map: HashMap<String, Vec<String>> = HashMap::new();
43        map.insert(field.to_string(), vec![message.to_string()]);
44        Self(map)
45    }
46}
47
48pub trait FormView: Template {
49    fn render_form(&self) -> Result<String, askama::Error>;
50}
51
52pub fn form_response(htmx: bool, view: &impl FormView) -> Result<Response, AppError> {
53    let html = if htmx {
54        view.render_form()?
55    } else {
56        view.render()?
57    };
58    Ok(Html(html).into_response())
59}
60
61#[macro_export]
62macro_rules! form_view {
63    ($t:ty) => {
64        impl $crate::web::FormView for $t {
65            fn render_form(&self) -> ::std::result::Result<String, ::askama::Error> {
66                self.as_form().render()
67            }
68        }
69    };
70}
71
72pub trait FormInput: DeserializeOwned + garde::Validate<Context = ()> + Send {
73    type View: FormView;
74    /// Request context the error view needs beyond the input itself, such
75    /// as the route's team. `()` when the input alone fills the view.
76    type Ctx: FromRequestParts<AppState> + Send;
77    fn normalize(&mut self) {}
78    fn to_view(&self, ctx: Self::Ctx, errors: FormErrors) -> Self::View; // owns the prefill (and which fields to omit)
79}
80
81pub struct Valid<T>(pub T);
82
83impl<T: FormInput> FromRequest<AppState> for Valid<T> {
84    type Rejection = Response;
85    async fn from_request(req: Request, state: &AppState) -> Result<Self, Response> {
86        let (mut parts, body) = req.into_parts();
87        let htmx = is_htmx(&parts.headers);
88        let ctx = T::Ctx::from_request_parts(&mut parts, state)
89            .await
90            .map_err(IntoResponse::into_response)?;
91        let Form(mut input) = Form::<T>::from_request(Request::from_parts(parts, body), state)
92            .await
93            .map_err(IntoResponse::into_response)?;
94        input.normalize();
95        if let Err(report) = input.validate() {
96            let view = input.to_view(ctx, FormErrors::from(&report));
97            return Err(form_response(htmx, &view).map_err(IntoResponse::into_response)?);
98        }
99        Ok(Valid(input))
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::auth::password::Password;
107    use garde::Validate;
108
109    #[test]
110    fn form_errors_from_single_field() {
111        #[derive(Validate)]
112        struct F {
113            #[garde(email)]
114            email: String,
115        }
116        let f = F {
117            email: "not-an-email".to_string(),
118        };
119        let Err(report) = f.validate() else {
120            panic!("expected error")
121        };
122        let fe = FormErrors::from(&report);
123        assert!(!fe.is_empty());
124        let msgs = fe.field("email");
125        assert_eq!(msgs.len(), 1);
126        assert!(msgs[0].contains("not a valid email"));
127    }
128
129    #[test]
130    fn form_errors_keys_are_flat_with_transparent() {
131        #[derive(Validate)]
132        struct F {
133            #[garde(dive)]
134            password: Password,
135        }
136        let f = F {
137            password: Password("sh ort".to_string()),
138        };
139        let Err(report) = f.validate() else {
140            panic!("expected error")
141        };
142        let fe = FormErrors::from(&report);
143        assert!(fe.field("password.0").is_empty());
144        assert!(!fe.field("password").is_empty());
145        let msgs = fe.field("password");
146        assert!(msgs.iter().any(|m| m.contains("length")));
147        assert!(msgs.iter().any(|m| m.contains("spaces")));
148    }
149}