use std::collections::{BTreeMap, HashMap};
use crate::{FormError, escape_attr};
pub const COLLECTION_PROTOTYPE_INDEX: &str = "__name__";
#[must_use]
pub fn collection_field_name(collection: &str, index: &str, field: &str) -> String {
format!("{collection}[{index}][{field}]")
}
#[must_use]
pub fn collection_prototype_field_name(collection: &str, field: &str) -> String {
collection_field_name(collection, COLLECTION_PROTOTYPE_INDEX, field)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionPrototypeMeta {
pub name: String,
pub prototype_index: &'static str,
}
impl CollectionPrototypeMeta {
#[must_use]
pub fn new(collection: impl Into<String>) -> Self {
Self {
name: collection.into(),
prototype_index: COLLECTION_PROTOTYPE_INDEX,
}
}
#[must_use]
pub fn field_name(&self, field: &str) -> String {
collection_prototype_field_name(&self.name, field)
}
#[must_use]
pub fn data_attributes_html(&self) -> String {
format!(
r#"data-collection="{}" data-prototype-index="{}""#,
escape_attr(&self.name),
escape_attr(self.prototype_index),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NestedData {
Value(String),
Map(BTreeMap<String, Self>),
}
impl NestedData {
#[must_use]
pub const fn as_str(&self) -> Option<&str> {
match self {
Self::Value(v) => Some(v.as_str()),
Self::Map(_) => None,
}
}
#[must_use]
pub const fn as_map(&self) -> Option<&BTreeMap<String, Self>> {
match self {
Self::Map(map) => Some(map),
Self::Value(_) => None,
}
}
}
pub fn unflatten_form_data<S: ::std::hash::BuildHasher>(
flat: &HashMap<String, String, S>,
) -> Result<BTreeMap<String, NestedData>, FormError> {
let mut root = BTreeMap::new();
for (key, value) in flat {
let segments = key_segments(key);
if segments.is_empty() {
continue;
}
insert_path(&mut root, &segments, value.clone())?;
}
Ok(root)
}
#[must_use]
pub fn collection_indices<S: ::std::hash::BuildHasher>(
flat: &HashMap<String, String, S>,
collection: &str,
) -> Vec<usize> {
let prefix = format!("{collection}[");
let mut indices = Vec::new();
for key in flat.keys() {
if let Some(rest) = key.strip_prefix(&prefix)
&& let Some((index_str, _)) = rest.split_once(']')
&& let Ok(index) = index_str.parse::<usize>()
&& !indices.contains(&index)
{
indices.push(index);
}
}
indices.sort_unstable();
indices
}
fn key_segments(key: &str) -> Vec<String> {
let normalized = key.replace("][", ".").replace('[', ".").replace(']', "");
normalized
.split('.')
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect()
}
fn insert_path(
map: &mut BTreeMap<String, NestedData>,
segments: &[String],
value: String,
) -> Result<(), FormError> {
let Some((first, rest)) = segments.split_first() else {
return Ok(());
};
if rest.is_empty() {
match map.get(first) {
Some(NestedData::Map(_)) => {
return Err(FormError::NestedConflict(first.clone()));
}
Some(NestedData::Value(_)) | None => {
map.insert(first.clone(), NestedData::Value(value));
}
}
return Ok(());
}
let entry = map
.entry(first.clone())
.or_insert_with(|| NestedData::Map(BTreeMap::new()));
match entry {
NestedData::Map(child) => insert_path(child, rest, value),
NestedData::Value(_) => Err(FormError::NestedConflict(first.clone())),
}
}
#[cfg(test)]
mod insert_path_tests {
use super::*;
#[test]
fn empty_segments_are_noop() {
let mut map = BTreeMap::new();
insert_path(&mut map, &[], String::from("x")).expect("empty");
assert!(map.is_empty());
}
#[test]
fn leaf_then_child_conflicts() {
let mut map = BTreeMap::new();
insert_path(&mut map, &[String::from("geo")], String::from("leaf")).expect("leaf");
let err = insert_path(
&mut map,
&[String::from("geo"), String::from("lat")],
String::from("1"),
)
.expect_err("conflict");
assert!(matches!(err, FormError::NestedConflict(path) if path == "geo"));
}
#[test]
fn child_then_leaf_conflicts() {
let mut map = BTreeMap::new();
insert_path(
&mut map,
&[String::from("geo"), String::from("lat")],
String::from("1"),
)
.expect("child");
let err = insert_path(&mut map, &[String::from("geo")], String::from("leaf"))
.expect_err("conflict");
assert!(matches!(err, FormError::NestedConflict(path) if path == "geo"));
}
}