1
//! Submit payload writer: `FormValues` to plist text, all values strings.
2

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

            
7
/// Write the payload in descriptor order. Absent values are omitted; a present
8
/// empty value is written, so an edit can clear the note.
9
#[must_use]
10
219648
pub fn write_payload(form: &Form, values: &FormValues) -> String {
11
219648
    let mut items = Vec::new();
12
219648
    for field in form.fields {
13
1064448
        push_field(field, values, &mut items);
14
    }
15
219648
    format!("({})", items.join(" "))
16
219648
}
17

            
18
1064448
fn push_field(field: &Field, values: &FormValues, items: &mut Vec<String>) {
19
1064448
    let key = field.key;
20
1064448
    match field.kind {
21
        Kind::Rows { fields, .. } => {
22
177600
            if let Some(rows) = values.rows(key) {
23
141120
                items.push(format!(":{key} {}", rows_text(fields, rows)));
24
36480
            }
25
        }
26
        _ => {
27
886848
            if let Some(text) = values.text(key) {
28
547392
                items.push(format!(":{key} {}", escape_str(text)));
29
339456
            }
30
        }
31
    }
32
1064448
}
33

            
34
141120
fn rows_text(fields: &[Field], rows: &[Row]) -> String {
35
161088
    let items: Vec<String> = rows.iter().map(|row| row_text(fields, row)).collect();
36
141120
    format!("({})", items.join(" "))
37
141120
}
38

            
39
161088
fn row_text(fields: &[Field], row: &Row) -> String {
40
161088
    let items: Vec<String> = fields
41
161088
        .iter()
42
919872
        .filter_map(|field| {
43
919872
            let text = row.get(field.key)?;
44
708288
            Some(format!(":{} {}", field.key, escape_str(text)))
45
919872
        })
46
        .collect();
47
161088
    format!("({})", items.join(" "))
48
161088
}