Skip to main content

forms/
choice.rs

1//! `choice` fields: option keys are exact, an empty value takes the default.
2
3use crate::descriptor::{Field, Kind};
4use crate::values::{FormValues, Row};
5
6pub(crate) fn unknown_key(options: &[(&str, &str)], value: &str) -> Option<String> {
7    if options.iter().any(|(key, _)| *key == value) {
8        return None;
9    }
10    let keys: Vec<&str> = options.iter().map(|(key, _)| *key).collect();
11    Some(format!("must be one of: {}", keys.join(", ")))
12}
13
14/// The value a handler sees: trimmed, with a present empty value replaced by
15/// the default when there is one.
16fn normal<'a>(field: &Field, value: &'a str) -> &'a str {
17    let value = value.trim();
18    match field.kind {
19        Kind::Choice {
20            default: Some(default),
21            ..
22        } if value.is_empty() => default,
23        _ => value,
24    }
25}
26
27fn is_choice(field: &Field) -> bool {
28    matches!(field.kind, Kind::Choice { .. })
29}
30
31impl FormValues {
32    /// A copy with every present `choice` value normalised; absent values stay
33    /// absent.
34    #[must_use]
35    pub fn normalized(&self, form: &crate::Form) -> Self {
36        let mut values = self.clone();
37        for field in form.fields {
38            match field.kind {
39                Kind::Rows { fields, .. } => values.normalize_rows(field.key, fields),
40                _ if is_choice(field) => values.normalize_text(field),
41                _ => {}
42            }
43        }
44        values
45    }
46
47    fn normalize_text(&mut self, field: &Field) {
48        if let Some(text) = self
49            .text(field.key)
50            .map(|text| normal(field, text).to_string())
51        {
52            self.set(field.key, &text);
53        }
54    }
55
56    fn normalize_rows(&mut self, key: &str, fields: &[Field]) {
57        let Some(rows) = self.rows(key) else {
58            return;
59        };
60        let rows: Vec<Row> = rows.iter().map(|row| normal_row(fields, row)).collect();
61        self.replace_rows(key, rows);
62    }
63}
64
65fn normal_row(fields: &[Field], row: &Row) -> Row {
66    let mut row = row.clone();
67    for field in fields.iter().filter(|field| is_choice(field)) {
68        if let Some(text) = row.get_mut(field.key) {
69            *text = normal(field, text).to_string();
70        }
71    }
72    row
73}