serenade_form/
collection.rs1use std::collections::{BTreeMap, HashMap};
4
5use crate::{FormError, escape_attr};
6
7pub const COLLECTION_PROTOTYPE_INDEX: &str = "__name__";
9
10#[must_use]
23pub fn collection_field_name(collection: &str, index: &str, field: &str) -> String {
24 format!("{collection}[{index}][{field}]")
25}
26
27#[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#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct CollectionPrototypeMeta {
39 pub name: String,
41 pub prototype_index: &'static str,
43}
44
45impl CollectionPrototypeMeta {
46 #[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 #[must_use]
57 pub fn field_name(&self, field: &str) -> String {
58 collection_prototype_field_name(&self.name, field)
59 }
60
61 #[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#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum NestedData {
75 Value(String),
77 Map(BTreeMap<String, Self>),
79}
80
81impl NestedData {
82 #[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 #[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
101pub 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#[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}