Skip to main content

forms/
payload.rs

1//! Submit payload writer: `FormValues` to plist text, all values strings.
2
3use crate::descriptor::{Field, Form, Kind};
4use crate::sexpr::escape_str;
5use 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]
10pub fn write_payload(form: &Form, values: &FormValues) -> String {
11    let mut items = Vec::new();
12    for field in form.fields {
13        push_field(field, values, &mut items);
14    }
15    format!("({})", items.join(" "))
16}
17
18fn push_field(field: &Field, values: &FormValues, items: &mut Vec<String>) {
19    let key = field.key;
20    match field.kind {
21        Kind::Rows { fields, .. } => {
22            if let Some(rows) = values.rows(key) {
23                items.push(format!(":{key} {}", rows_text(fields, rows)));
24            }
25        }
26        _ => {
27            if let Some(text) = values.text(key) {
28                items.push(format!(":{key} {}", escape_str(text)));
29            }
30        }
31    }
32}
33
34fn rows_text(fields: &[Field], rows: &[Row]) -> String {
35    let items: Vec<String> = rows.iter().map(|row| row_text(fields, row)).collect();
36    format!("({})", items.join(" "))
37}
38
39fn row_text(fields: &[Field], row: &Row) -> String {
40    let items: Vec<String> = fields
41        .iter()
42        .filter_map(|field| {
43            let text = row.get(field.key)?;
44            Some(format!(":{} {}", field.key, escape_str(text)))
45        })
46        .collect();
47    format!("({})", items.join(" "))
48}