Skip to main content

serenade_form/
transformer.rs

1//! View ↔ model transformers for form fields.
2
3use crate::FormError;
4use crate::kind::ChoiceOptions;
5
6/// Converts between the HTML view string and the model string stored on the field.
7///
8/// # Examples
9///
10/// ```
11/// use serenade_form::{BoolToStringTransformer, DataTransformer};
12///
13/// let t = BoolToStringTransformer::default();
14/// assert_eq!(t.reverse_transform("1").unwrap(), "1");
15/// assert_eq!(t.reverse_transform("").unwrap(), "0");
16/// assert_eq!(t.transform("1").unwrap(), "1");
17/// ```
18pub trait DataTransformer: Send + Sync {
19    /// Model value → view string used in HTML.
20    ///
21    /// # Errors
22    ///
23    /// Returns [`FormError::Transform`] when the model value cannot be shown.
24    fn transform(&self, model: &str) -> Result<String, FormError>;
25
26    /// Submitted view string → model value stored on the field.
27    ///
28    /// # Errors
29    ///
30    /// Returns [`FormError::Transform`] when the view value is invalid.
31    fn reverse_transform(&self, view: &str) -> Result<String, FormError>;
32}
33
34/// Maps truthy/falsy view strings to normalized `"1"` / `"0"` model values.
35#[derive(Debug, Clone, Copy, Default)]
36pub struct BoolToStringTransformer;
37
38impl DataTransformer for BoolToStringTransformer {
39    fn transform(&self, model: &str) -> Result<String, FormError> {
40        Ok(if is_truthy(model) {
41            String::from("1")
42        } else {
43            String::new()
44        })
45    }
46
47    fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
48        Ok(if is_truthy(view) {
49            String::from("1")
50        } else {
51            String::from("0")
52        })
53    }
54}
55
56/// Parses and normalizes signed 64-bit integers as decimal strings.
57#[derive(Debug, Clone, Copy, Default)]
58pub struct I64ToStringTransformer;
59
60impl DataTransformer for I64ToStringTransformer {
61    fn transform(&self, model: &str) -> Result<String, FormError> {
62        if model.is_empty() {
63            return Ok(String::new());
64        }
65        model
66            .parse::<i64>()
67            .map(|n| n.to_string())
68            .map_err(|_| FormError::Transform(String::from("invalid i64 model value")))
69    }
70
71    fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
72        if view.is_empty() {
73            return Ok(String::new());
74        }
75        view.parse::<i64>()
76            .map(|n| n.to_string())
77            .map_err(|_| FormError::Transform(String::from("invalid i64 view value")))
78    }
79}
80
81/// Ensures submitted values are members of a [`ChoiceOptions`] list.
82#[derive(Debug, Clone)]
83pub struct ChoiceToValueTransformer {
84    options: ChoiceOptions,
85}
86
87impl ChoiceToValueTransformer {
88    /// Builds a transformer from choice options.
89    #[must_use]
90    pub const fn new(options: ChoiceOptions) -> Self {
91        Self { options }
92    }
93}
94
95impl DataTransformer for ChoiceToValueTransformer {
96    fn transform(&self, model: &str) -> Result<String, FormError> {
97        if model.is_empty() {
98            return Ok(String::new());
99        }
100        if self.options.multiple {
101            let mut out = Vec::new();
102            for part in split_multi(model) {
103                if !self.is_allowed(part) {
104                    return Err(FormError::Transform(format!(
105                        "choice value {part:?} is not allowed"
106                    )));
107                }
108                out.push(part.to_owned());
109            }
110            return Ok(join_multi(&out));
111        }
112        if self.is_allowed(model) {
113            Ok(model.to_owned())
114        } else {
115            Err(FormError::Transform(format!(
116                "choice value {model:?} is not allowed"
117            )))
118        }
119    }
120
121    fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
122        self.transform(view)
123    }
124}
125
126impl ChoiceToValueTransformer {
127    fn is_allowed(&self, value: &str) -> bool {
128        self.options.choices.iter().any(|c| c.value == value)
129    }
130}
131
132fn is_truthy(value: &str) -> bool {
133    matches!(
134        value.trim().to_ascii_lowercase().as_str(),
135        "1" | "true" | "on" | "yes"
136    )
137}
138
139/// Splits a multi-value model/view string on ASCII whitespace.
140#[must_use]
141pub fn split_multi(value: &str) -> Vec<&str> {
142    value.split_whitespace().filter(|s| !s.is_empty()).collect()
143}
144
145/// Joins multi-values with a single space (stable round-trip for choice multi).
146#[must_use]
147pub fn join_multi(values: &[String]) -> String {
148    values.join(" ")
149}