Skip to main content

ignite_core/
field.rs

1//! Form fields and table columns, as the panel renders them.
2
3use std::str::FromStr;
4
5use chrono::{NaiveDate, NaiveDateTime};
6
7use crate::form::{FieldErrors, FormInput};
8
9/// The kind of input a form field renders as, and how its value is read.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum FieldKind {
12    /// A single line of text.
13    Text,
14    /// Several lines of text.
15    Textarea,
16    /// A password. The form never shows the stored value.
17    Password,
18    /// A whole number, submitted as text. A resource's integer field is checked as a whole
19    /// number. A profile field accepts decimals as well (see [`Field::check_number`]).
20    Number,
21    /// A decimal number, submitted as text, such as `9.5`. The string is the browser's
22    /// step for the input: `"any"` accepts every value, and `"0.01"` steps by cents.
23    Decimal(&'static str),
24    /// A yes/no value. Read it with [`FormInput::checkbox`](crate::FormInput::checkbox).
25    Checkbox,
26    /// One choice from a list of `(value, label)` pairs.
27    Select(&'static [(&'static str, &'static str)]),
28    /// One choice from options that the resource loads from the database each time its
29    /// form is shown, such as the rows of a related table. See
30    /// [`IgniteResource::options`](crate::IgniteResource::options).
31    Lookup,
32    /// A calendar date, as `YYYY-MM-DD`.
33    Date,
34    /// A date and time, as `YYYY-MM-DDTHH:MM`, with seconds when given.
35    DateTime,
36}
37
38/// One input on a create or edit form.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct Field {
41    /// The form field name. It matches a key of the record.
42    pub name: &'static str,
43    /// The label shown next to the input.
44    pub label: &'static str,
45    /// The input type, and how the value is read.
46    pub kind: FieldKind,
47    /// Whether the form rejects a blank value.
48    pub required: bool,
49}
50
51impl Field {
52    /// Returns the trimmed value of a required field. If it is missing or
53    /// blank, records "<label> is required" in `errors` under the field name
54    /// and returns `None`.
55    pub fn check_required<'a>(
56        &self,
57        form: &'a FormInput,
58        errors: &mut FieldErrors,
59    ) -> Option<&'a str> {
60        check_required(self.name, self.label, form, errors)
61    }
62
63    /// Parses `text` as a whole number of type `T`. If it does not parse, records
64    /// "<label> must be a whole number." in `errors` and returns `None`. Resources and
65    /// profile fields both check numbers this way.
66    pub fn check_whole_number<T: FromStr>(
67        &self,
68        text: &str,
69        errors: &mut FieldErrors,
70    ) -> Option<T> {
71        check_whole_number(self.name, self.label, text, errors)
72    }
73
74    /// Parses `text` as a number, whole or decimal, such as `42` or `42.5`. Values that are
75    /// not finite (`inf`, `NaN`) are refused. If it does not parse, records
76    /// "<label> must be a number." in `errors` and returns `None`.
77    pub fn check_number(&self, text: &str, errors: &mut FieldErrors) -> Option<f64> {
78        check_number(self.name, self.label, text, errors)
79    }
80
81    /// Parses `text` as a decimal number of type `T` (`f32` or `f64`), such as `9.5`. A
82    /// value that is not finite (`inf`, `NaN`, or an `f32` too large) is refused. If it
83    /// does not parse, records "<label> must be a number." in `errors` and returns `None`.
84    pub fn check_decimal<T: FromStr + Into<f64> + Copy>(
85        &self,
86        text: &str,
87        errors: &mut FieldErrors,
88    ) -> Option<T> {
89        check_decimal(self.name, self.label, text, errors)
90    }
91
92    /// Parses `text` as a date and time: `YYYY-MM-DDTHH:MM` as a date-time input sends it,
93    /// or with a space in place of the `T`, and with seconds when given. If it does not
94    /// parse, records "<label> must be a date and time, as YYYY-MM-DD HH:MM." in `errors`
95    /// and returns `None`.
96    pub fn check_datetime(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDateTime> {
97        check_datetime(self.name, self.label, text, errors)
98    }
99
100    /// Checks that `text` is the value of one of `choices`. If it is not, records
101    /// "Choose one of the options." in `errors` and returns false.
102    pub fn check_choice(
103        &self,
104        text: &str,
105        choices: &[(&str, &str)],
106        errors: &mut FieldErrors,
107    ) -> bool {
108        check_choice(self.name, text, choices, errors)
109    }
110
111    /// Parses `text` as a `YYYY-MM-DD` date. If it does not parse, records
112    /// "<label> must be a date, as YYYY-MM-DD." in `errors` and returns `None`.
113    pub fn check_date(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDate> {
114        check_date(self.name, self.label, text, errors)
115    }
116}
117
118// The checks themselves, by field name and label, so a static `Field` and a runtime
119// `FieldDef` run the same code. `name` is the key of the error in `errors`.
120
121/// See [`Field::check_required`].
122pub(crate) fn check_required<'a>(
123    name: &str,
124    label: &str,
125    form: &'a FormInput,
126    errors: &mut FieldErrors,
127) -> Option<&'a str> {
128    match form.get(name).map(str::trim) {
129        Some(value) if !value.is_empty() => Some(value),
130        _ => {
131            errors.insert(name.to_string(), format!("{label} is required."));
132            None
133        }
134    }
135}
136
137/// See [`Field::check_whole_number`].
138pub(crate) fn check_whole_number<T: FromStr>(
139    name: &str,
140    label: &str,
141    text: &str,
142    errors: &mut FieldErrors,
143) -> Option<T> {
144    match text.parse::<T>() {
145        Ok(value) => Some(value),
146        Err(_) => {
147            errors.insert(name.to_string(), format!("{label} must be a whole number."));
148            None
149        }
150    }
151}
152
153/// See [`Field::check_number`].
154pub(crate) fn check_number(
155    name: &str,
156    label: &str,
157    text: &str,
158    errors: &mut FieldErrors,
159) -> Option<f64> {
160    match text.parse::<f64>() {
161        Ok(value) if value.is_finite() => Some(value),
162        _ => {
163            errors.insert(name.to_string(), format!("{label} must be a number."));
164            None
165        }
166    }
167}
168
169/// See [`Field::check_decimal`].
170pub(crate) fn check_decimal<T: FromStr + Into<f64> + Copy>(
171    name: &str,
172    label: &str,
173    text: &str,
174    errors: &mut FieldErrors,
175) -> Option<T> {
176    match text.parse::<T>() {
177        Ok(value) if Into::<f64>::into(value).is_finite() => Some(value),
178        _ => {
179            errors.insert(name.to_string(), format!("{label} must be a number."));
180            None
181        }
182    }
183}
184
185/// See [`Field::check_datetime`].
186pub(crate) fn check_datetime(
187    name: &str,
188    label: &str,
189    text: &str,
190    errors: &mut FieldErrors,
191) -> Option<NaiveDateTime> {
192    const FORMATS: [&str; 4] = [
193        "%Y-%m-%dT%H:%M",
194        "%Y-%m-%dT%H:%M:%S",
195        "%Y-%m-%d %H:%M",
196        "%Y-%m-%d %H:%M:%S",
197    ];
198    let parsed = FORMATS
199        .iter()
200        .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok());
201    if parsed.is_none() {
202        errors.insert(
203            name.to_string(),
204            format!("{label} must be a date and time, as YYYY-MM-DD HH:MM."),
205        );
206    }
207    parsed
208}
209
210/// See [`Field::check_choice`].
211pub(crate) fn check_choice(
212    name: &str,
213    text: &str,
214    choices: &[(&str, &str)],
215    errors: &mut FieldErrors,
216) -> bool {
217    if choices.iter().any(|(value, _)| *value == text) {
218        return true;
219    }
220    errors.insert(name.to_string(), "Choose one of the options.".to_string());
221    false
222}
223
224/// See [`Field::check_date`].
225pub(crate) fn check_date(
226    name: &str,
227    label: &str,
228    text: &str,
229    errors: &mut FieldErrors,
230) -> Option<NaiveDate> {
231    match NaiveDate::parse_from_str(text, "%Y-%m-%d") {
232        Ok(value) => Some(value),
233        Err(_) => {
234            errors.insert(
235                name.to_string(),
236                format!("{label} must be a date, as YYYY-MM-DD."),
237            );
238            None
239        }
240    }
241}
242
243/// One column of the list view.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub struct Column {
246    /// The record key the column shows. It matches a field name.
247    pub key: &'static str,
248    /// The column heading.
249    pub label: &'static str,
250    /// Whether the heading links to a sort by this column.
251    pub sortable: bool,
252    /// Whether the search box matches this column.
253    pub searchable: bool,
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use std::collections::HashMap;
260
261    const TITLE: Field = Field {
262        name: "title",
263        label: "Title",
264        kind: FieldKind::Text,
265        required: true,
266    };
267
268    fn form(pairs: &[(&str, &str)]) -> FormInput {
269        FormInput::new(
270            pairs
271                .iter()
272                .map(|(k, v)| (k.to_string(), v.to_string()))
273                .collect::<HashMap<_, _>>(),
274        )
275    }
276
277    #[test]
278    fn required_field_returns_trimmed_value() {
279        let mut errors = FieldErrors::new();
280        let input = form(&[("title", "  Hello  ")]);
281
282        assert_eq!(TITLE.check_required(&input, &mut errors), Some("Hello"));
283        assert!(errors.is_empty());
284    }
285
286    #[test]
287    fn missing_required_field_records_a_message() {
288        let mut errors = FieldErrors::new();
289
290        assert_eq!(TITLE.check_required(&form(&[]), &mut errors), None);
291        assert_eq!(
292            errors.get("title").map(String::as_str),
293            Some("Title is required.")
294        );
295    }
296
297    const PRICE: Field = Field {
298        name: "price",
299        label: "Price",
300        kind: FieldKind::Decimal("any"),
301        required: true,
302    };
303
304    const LAUNCH: Field = Field {
305        name: "launch",
306        label: "Launch",
307        kind: FieldKind::DateTime,
308        required: true,
309    };
310
311    #[test]
312    fn a_decimal_accepts_whole_and_fractional_numbers() {
313        let mut errors = FieldErrors::new();
314
315        assert_eq!(PRICE.check_decimal::<f64>("9.5", &mut errors), Some(9.5));
316        assert_eq!(PRICE.check_decimal::<f64>("-3", &mut errors), Some(-3.0));
317        assert_eq!(PRICE.check_decimal::<f32>("0.25", &mut errors), Some(0.25));
318        assert!(errors.is_empty());
319    }
320
321    #[test]
322    fn a_decimal_refuses_text_and_values_that_are_not_finite() {
323        for text in ["abc", "9,5", "NaN", "inf", ""] {
324            let mut errors = FieldErrors::new();
325            assert_eq!(
326                PRICE.check_decimal::<f64>(text, &mut errors),
327                None,
328                "{text}"
329            );
330            assert_eq!(
331                errors.get("price").map(String::as_str),
332                Some("Price must be a number."),
333                "{text}"
334            );
335        }
336        let mut errors = FieldErrors::new();
337        assert_eq!(PRICE.check_decimal::<f32>("1e300", &mut errors), None);
338        assert!(errors.contains_key("price"));
339    }
340
341    #[test]
342    fn a_datetime_accepts_the_input_format_with_or_without_seconds() {
343        let mut errors = FieldErrors::new();
344        let expected = chrono::NaiveDate::from_ymd_opt(2026, 11, 10)
345            .unwrap()
346            .and_hms_opt(14, 30, 0)
347            .unwrap();
348
349        assert_eq!(
350            LAUNCH.check_datetime("2026-11-10T14:30", &mut errors),
351            Some(expected)
352        );
353        assert_eq!(
354            LAUNCH.check_datetime("2026-11-10 14:30:00", &mut errors),
355            Some(expected)
356        );
357        assert!(errors.is_empty());
358    }
359
360    #[test]
361    fn a_datetime_refuses_what_is_not_a_date_and_time() {
362        for text in ["soon", "2026-11-10", "2026-13-40T10:00", "10/11/2026 14:30"] {
363            let mut errors = FieldErrors::new();
364            assert_eq!(LAUNCH.check_datetime(text, &mut errors), None, "{text}");
365            assert_eq!(
366                errors.get("launch").map(String::as_str),
367                Some("Launch must be a date and time, as YYYY-MM-DD HH:MM."),
368                "{text}"
369            );
370        }
371    }
372
373    #[test]
374    fn a_choice_must_be_one_of_the_choices() {
375        let choices = [("draft", "Draft"), ("published", "Published")];
376        let mut errors = FieldErrors::new();
377
378        assert!(TITLE.check_choice("draft", &choices, &mut errors));
379        assert!(errors.is_empty());
380        assert!(!TITLE.check_choice("archived", &choices, &mut errors));
381        assert_eq!(
382            errors.get("title").map(String::as_str),
383            Some("Choose one of the options.")
384        );
385    }
386
387    #[test]
388    fn blank_required_field_is_missing() {
389        let mut errors = FieldErrors::new();
390
391        assert_eq!(
392            TITLE.check_required(&form(&[("title", "   ")]), &mut errors),
393            None
394        );
395        assert!(errors.contains_key("title"));
396    }
397}