1
//! `choice` fields: option keys are exact, an empty value takes the default.
2

            
3
use crate::descriptor::{Field, Kind};
4
use crate::values::{FormValues, Row};
5

            
6
37248
pub(crate) fn unknown_key(options: &[(&str, &str)], value: &str) -> Option<String> {
7
87360
    if options.iter().any(|(key, _)| *key == value) {
8
34752
        return None;
9
2496
    }
10
7872
    let keys: Vec<&str> = options.iter().map(|(key, _)| *key).collect();
11
2496
    Some(format!("must be one of: {}", keys.join(", ")))
12
37248
}
13

            
14
/// The value a handler sees: trimmed, with a present empty value replaced by
15
/// the default when there is one.
16
41280
fn normal<'a>(field: &Field, value: &'a str) -> &'a str {
17
41280
    let value = value.trim();
18
41280
    match field.kind {
19
        Kind::Choice {
20
            default: Some(default),
21
            ..
22
40128
        } if value.is_empty() => default,
23
37248
        _ => value,
24
    }
25
41280
}
26

            
27
2110464
fn is_choice(field: &Field) -> bool {
28
2110464
    matches!(field.kind, Kind::Choice { .. })
29
2110464
}
30

            
31
impl FormValues {
32
    /// A copy with every present `choice` value normalised; absent values stay
33
    /// absent.
34
    #[must_use]
35
228672
    pub fn normalized(&self, form: &crate::Form) -> Self {
36
228672
        let mut values = self.clone();
37
228672
        for field in form.fields {
38
1146048
            match field.kind {
39
306432
                Kind::Rows { fields, .. } => values.normalize_rows(field.key, fields),
40
839616
                _ if is_choice(field) => values.normalize_text(field),
41
751872
                _ => {}
42
            }
43
        }
44
228672
        values
45
228672
    }
46

            
47
87744
    fn normalize_text(&mut self, field: &Field) {
48
87744
        if let Some(text) = self
49
87744
            .text(field.key)
50
19392
            .map(|text| normal(field, text).to_string())
51
        {
52
19392
            self.set(field.key, &text);
53
68352
        }
54
87744
    }
55

            
56
306432
    fn normalize_rows(&mut self, key: &str, fields: &[Field]) {
57
306432
        let Some(rows) = self.rows(key) else {
58
85632
            return;
59
        };
60
220800
        let rows: Vec<Row> = rows.iter().map(|row| normal_row(fields, row)).collect();
61
220800
        self.replace_rows(key, rows);
62
306432
    }
63
}
64

            
65
212736
fn normal_row(fields: &[Field], row: &Row) -> Row {
66
212736
    let mut row = row.clone();
67
1270848
    for field in fields.iter().filter(|field| is_choice(field)) {
68
49152
        if let Some(text) = row.get_mut(field.key) {
69
21888
            *text = normal(field, text).to_string();
70
27264
        }
71
    }
72
212736
    row
73
212736
}