blitz_dom/node/
attributes.rs

1use std::ops::{Deref, DerefMut};
2
3use markup5ever::QualName;
4
5/// A tag attribute, e.g. `class="test"` in `<div class="test" ...>`.
6#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
7pub struct Attribute {
8    /// The name of the attribute (e.g. the `class` in `<div class="test">`)
9    pub name: QualName,
10    /// The value of the attribute (e.g. the `"test"` in `<div class="test">`)
11    pub value: String,
12}
13
14#[derive(Clone, Debug)]
15pub struct Attributes {
16    inner: Vec<Attribute>,
17}
18
19impl Attributes {
20    pub fn new(inner: Vec<Attribute>) -> Self {
21        Self { inner }
22    }
23
24    pub fn set(&mut self, name: QualName, value: &str) {
25        let existing_attr = self.inner.iter_mut().find(|a| a.name == name);
26        if let Some(existing_attr) = existing_attr {
27            existing_attr.value.clear();
28            existing_attr.value.push_str(value);
29        } else {
30            self.push(Attribute {
31                name: name.clone(),
32                value: value.to_string(),
33            });
34        }
35    }
36
37    pub fn remove(&mut self, name: &QualName) -> Option<Attribute> {
38        let idx = self.inner.iter().position(|attr| attr.name == *name);
39        idx.map(|idx| self.inner.remove(idx))
40    }
41}
42
43impl Deref for Attributes {
44    type Target = Vec<Attribute>;
45    fn deref(&self) -> &Self::Target {
46        &self.inner
47    }
48}
49impl DerefMut for Attributes {
50    fn deref_mut(&mut self) -> &mut Self::Target {
51        &mut self.inner
52    }
53}