duid_core/core/html/attributes/
attribute.rs

1use std::fmt::Debug;
2use crate::core::html::attributes::AttributeValue;
3
4#[derive(Clone, Debug, PartialEq)]
5pub struct Attribute<MSG> {
6    pub namespace: Option<&'static str>,
7    pub name: &'static str,
8    pub value: Vec<AttributeValue<MSG>>,
9}
10
11impl<MSG> Attribute<MSG> {
12    pub fn new(namespace: Option<&'static str>, name: &'static str, value: AttributeValue<MSG>) -> Self {
13        Attribute {
14            namespace,
15            name,
16            value: vec![value]
17        }
18    }
19
20    pub fn with_multiple_values(
21        namespace: Option<&'static str>,
22        name: &'static str,
23        value: &[AttributeValue<MSG>],
24    ) -> Self {
25        Attribute {
26            name,
27            value: value.to_vec(),
28            namespace,
29        }
30    }
31
32    pub fn name(&self) -> &'static str {
33        &self.name
34    }
35
36    pub fn value(&self) -> &[AttributeValue<MSG>] {
37        &self.value
38    }
39
40    pub fn namespace(&self) -> Option<&'static str> {
41        self.namespace
42    }
43}
44
45
46#[inline]
47pub fn attr<MSG>(name: &'static str, value: AttributeValue<MSG>) -> Attribute<MSG>
48{
49    attr_ns(None, name, value)
50}
51
52
53#[inline]
54pub fn attr_ns<MSG>(
55    namespace: Option<&'static str>,
56    name: &'static str,
57    value: AttributeValue<MSG>,
58) -> Attribute<MSG>
59{
60    Attribute::new(namespace, name, value)
61}
62
63#[doc(hidden)]
64pub fn merge_attributes_of_same_name<MSG>(
65    attributes: &[&Attribute<MSG>],
66) -> Vec<Attribute<MSG>>
67{
68    let mut merged: Vec<Attribute<MSG>> = vec![];
69    for att in attributes {
70        if let Some(existing) =
71            merged.iter_mut().find(|m_att| m_att.name == att.name)
72        {
73            existing.value.extend(att.value.clone());
74        } else {
75            merged.push(Attribute {
76                namespace: None,
77                name: att.name.clone(),
78                value: att.value.clone(),
79            });
80        }
81    }
82    merged
83}
84
85#[doc(hidden)]
86pub fn group_attributes_per_name<MSG>(
87    attributes: &[Attribute<MSG>],
88) -> Vec<(&'static str, Vec<&Attribute<MSG>>)>
89{
90    let mut grouped: Vec<(&'static str, Vec<&Attribute<MSG>>)> = vec![];
91    for attr in attributes {
92        if let Some(existing) = grouped
93            .iter_mut()
94            .find(|(g_att, _)| *g_att == attr.name)
95            .map(|(_, attr)| attr)
96        {
97            existing.push(attr);
98        } else {
99            grouped.push((&attr.name, vec![attr]))
100        }
101    }
102    grouped
103}