Skip to main content

serenade_form/
collection.rs

1//! Collection field names, prototypes, and nested data helpers.
2
3use std::collections::{BTreeMap, HashMap};
4
5use crate::{FormError, escape_attr};
6
7/// Placeholder index token used in HTML collection prototypes.
8pub const COLLECTION_PROTOTYPE_INDEX: &str = "__name__";
9
10/// Builds an indexed collection field name: `items[0][name]`.
11///
12/// # Examples
13///
14/// ```
15/// use serenade_form::collection_field_name;
16///
17/// assert_eq!(
18///     collection_field_name("items", "0", "name"),
19///     "items[0][name]"
20/// );
21/// ```
22#[must_use]
23pub fn collection_field_name(collection: &str, index: &str, field: &str) -> String {
24    format!("{collection}[{index}][{field}]")
25}
26
27/// Builds a prototype field name using [`COLLECTION_PROTOTYPE_INDEX`].
28#[must_use]
29pub fn collection_prototype_field_name(collection: &str, field: &str) -> String {
30    collection_field_name(collection, COLLECTION_PROTOTYPE_INDEX, field)
31}
32
33/// Metadata for progressive-enhancement HTML (no JS framework in core).
34///
35/// Apps can emit these as `data-*` attributes and replace `__name__` in a
36/// prototype row when adding entries client-side.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct CollectionPrototypeMeta {
39    /// Collection base name (for example `items`).
40    pub name: String,
41    /// Index placeholder (`__name__`).
42    pub prototype_index: &'static str,
43}
44
45impl CollectionPrototypeMeta {
46    /// Creates prototype metadata for `collection`.
47    #[must_use]
48    pub fn new(collection: impl Into<String>) -> Self {
49        Self {
50            name: collection.into(),
51            prototype_index: COLLECTION_PROTOTYPE_INDEX,
52        }
53    }
54
55    /// Prototype field name for a child field under this collection.
56    #[must_use]
57    pub fn field_name(&self, field: &str) -> String {
58        collection_prototype_field_name(&self.name, field)
59    }
60
61    /// Escaped `data-collection` and `data-prototype-index` attribute snippet.
62    #[must_use]
63    pub fn data_attributes_html(&self) -> String {
64        format!(
65            r#"data-collection="{}" data-prototype-index="{}""#,
66            escape_attr(&self.name),
67            escape_attr(self.prototype_index),
68        )
69    }
70}
71
72/// Nested tree node produced by [`unflatten_form_data`].
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum NestedData {
75    /// Leaf string value.
76    Value(String),
77    /// Nested map (compound or collection index).
78    Map(BTreeMap<String, Self>),
79}
80
81impl NestedData {
82    /// Returns the leaf string when this node is a value.
83    #[must_use]
84    pub const fn as_str(&self) -> Option<&str> {
85        match self {
86            Self::Value(v) => Some(v.as_str()),
87            Self::Map(_) => None,
88        }
89    }
90
91    /// Returns the nested map when this node is a map.
92    #[must_use]
93    pub const fn as_map(&self) -> Option<&BTreeMap<String, Self>> {
94        match self {
95            Self::Map(map) => Some(map),
96            Self::Value(_) => None,
97        }
98    }
99}
100
101/// Builds a nested map from flat urlencoded keys (`address.street`, `items[0][name]`).
102///
103/// # Errors
104///
105/// Returns [`FormError::NestedConflict`] when the same path is both a leaf and a map.
106///
107/// # Examples
108///
109/// ```
110/// use std::collections::HashMap;
111/// use serenade_form::{unflatten_form_data, NestedData};
112///
113/// let mut flat = HashMap::new();
114/// flat.insert("address.street".into(), "Main".into());
115/// let nested = unflatten_form_data(&flat).unwrap();
116/// assert_eq!(
117///     nested["address"].as_map().unwrap()["street"].as_str(),
118///     Some("Main")
119/// );
120/// ```
121pub fn unflatten_form_data<S: ::std::hash::BuildHasher>(
122    flat: &HashMap<String, String, S>,
123) -> Result<BTreeMap<String, NestedData>, FormError> {
124    let mut root = BTreeMap::new();
125    for (key, value) in flat {
126        let segments = key_segments(key);
127        if segments.is_empty() {
128            continue;
129        }
130        insert_path(&mut root, &segments, value.clone())?;
131    }
132    Ok(root)
133}
134
135/// Lists numeric indices present for `collection` in a flat map (`items[0][…]`).
136#[must_use]
137pub fn collection_indices<S: ::std::hash::BuildHasher>(
138    flat: &HashMap<String, String, S>,
139    collection: &str,
140) -> Vec<usize> {
141    let prefix = format!("{collection}[");
142    let mut indices = Vec::new();
143    for key in flat.keys() {
144        if let Some(rest) = key.strip_prefix(&prefix)
145            && let Some((index_str, _)) = rest.split_once(']')
146            && let Ok(index) = index_str.parse::<usize>()
147            && !indices.contains(&index)
148        {
149            indices.push(index);
150        }
151    }
152    indices.sort_unstable();
153    indices
154}
155
156fn key_segments(key: &str) -> Vec<String> {
157    let normalized = key.replace("][", ".").replace('[', ".").replace(']', "");
158    normalized
159        .split('.')
160        .filter(|s| !s.is_empty())
161        .map(str::to_owned)
162        .collect()
163}
164
165fn insert_path(
166    map: &mut BTreeMap<String, NestedData>,
167    segments: &[String],
168    value: String,
169) -> Result<(), FormError> {
170    let Some((first, rest)) = segments.split_first() else {
171        return Ok(());
172    };
173    if rest.is_empty() {
174        match map.get(first) {
175            Some(NestedData::Map(_)) => {
176                return Err(FormError::NestedConflict(first.clone()));
177            }
178            Some(NestedData::Value(_)) | None => {
179                map.insert(first.clone(), NestedData::Value(value));
180            }
181        }
182        return Ok(());
183    }
184    let entry = map
185        .entry(first.clone())
186        .or_insert_with(|| NestedData::Map(BTreeMap::new()));
187    match entry {
188        NestedData::Map(child) => insert_path(child, rest, value),
189        NestedData::Value(_) => Err(FormError::NestedConflict(first.clone())),
190    }
191}
192
193#[cfg(test)]
194mod insert_path_tests {
195    use super::*;
196
197    #[test]
198    fn empty_segments_are_noop() {
199        let mut map = BTreeMap::new();
200        insert_path(&mut map, &[], String::from("x")).expect("empty");
201        assert!(map.is_empty());
202    }
203
204    #[test]
205    fn leaf_then_child_conflicts() {
206        let mut map = BTreeMap::new();
207        insert_path(&mut map, &[String::from("geo")], String::from("leaf")).expect("leaf");
208        let err = insert_path(
209            &mut map,
210            &[String::from("geo"), String::from("lat")],
211            String::from("1"),
212        )
213        .expect_err("conflict");
214        assert!(matches!(err, FormError::NestedConflict(path) if path == "geo"));
215    }
216
217    #[test]
218    fn child_then_leaf_conflicts() {
219        let mut map = BTreeMap::new();
220        insert_path(
221            &mut map,
222            &[String::from("geo"), String::from("lat")],
223            String::from("1"),
224        )
225        .expect("child");
226        let err = insert_path(&mut map, &[String::from("geo")], String::from("leaf"))
227            .expect_err("conflict");
228        assert!(matches!(err, FormError::NestedConflict(path) if path == "geo"));
229    }
230}