use crate::node::attribute::AttValue;
use crate::node::attribute::Callback;
use crate::node::Attribute;
use crate::node::Node;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Element<NS, TAG, ATT, VAL, EVENT, MSG> {
pub(crate) namespace: Option<NS>,
pub(crate) tag: TAG,
pub(crate) attrs: Vec<Attribute<NS, ATT, VAL, EVENT, MSG>>,
pub(crate) children: Vec<Node<NS, TAG, ATT, VAL, EVENT, MSG>>,
}
impl<NS, TAG, ATT, VAL, EVENT, MSG> Element<NS, TAG, ATT, VAL, EVENT, MSG> {
pub fn new(
namespace: Option<NS>,
tag: TAG,
attrs: Vec<Attribute<NS, ATT, VAL, EVENT, MSG>>,
children: Vec<Node<NS, TAG, ATT, VAL, EVENT, MSG>>,
) -> Self {
Element {
namespace,
tag,
attrs,
children,
}
}
pub fn add_attributes(&mut self, attrs: Vec<Attribute<NS, ATT, VAL, EVENT, MSG>>) {
self.attrs.extend(attrs)
}
pub fn add_children(&mut self, children: Vec<Node<NS, TAG, ATT, VAL, EVENT, MSG>>) {
self.children.extend(children);
}
pub fn get_children(&self) -> &[Node<NS, TAG, ATT, VAL, EVENT, MSG>] {
&self.children
}
pub fn children_mut(&mut self) -> &mut [Node<NS, TAG, ATT, VAL, EVENT, MSG>] {
&mut self.children
}
pub fn take_children(self) -> Vec<Node<NS, TAG, ATT, VAL, EVENT, MSG>> {
self.children
}
pub fn get_attributes(&self) -> &[Attribute<NS, ATT, VAL, EVENT, MSG>] {
&self.attrs
}
pub fn namespace(&self) -> Option<&NS> {
self.namespace.as_ref()
}
pub fn tag(&self) -> &TAG {
&self.tag
}
pub fn set_tag(&mut self, tag: TAG) {
self.tag = tag;
}
}
impl<NS, TAG, ATT, VAL, EVENT, MSG> Element<NS, TAG, ATT, VAL, EVENT, MSG>
where
ATT: PartialEq,
{
pub fn remove_attribute(&mut self, key: &ATT) {
self.attrs.retain(|att| att.name != *key)
}
pub fn set_attributes(&mut self, attrs: Vec<Attribute<NS, ATT, VAL, EVENT, MSG>>) {
attrs
.iter()
.for_each(|att| self.remove_attribute(&att.name));
self.add_attributes(attrs);
}
pub fn get_attribute_values(&self, key: &ATT) -> Vec<&AttValue<VAL, EVENT, MSG>> {
self.attrs
.iter()
.filter(|att| att.name == *key)
.map(|att| &att.value)
.collect()
}
fn get_attribute_names(&self) -> Vec<&ATT> {
let mut names: Vec<&ATT> = vec![];
for att in self.attrs.iter() {
if !names.contains(&&att.name) {
names.push(&att.name);
}
}
names
}
pub fn get_attribute_key_values(&self) -> Vec<(&ATT, Vec<&AttValue<VAL, EVENT, MSG>>)> {
let mut key_values = vec![];
let names = self.get_attribute_names();
for name in names {
key_values.push((name, self.get_attribute_values(name)));
}
key_values
}
}
impl<NS, TAG, ATT, VAL, EVENT, MSG> Element<NS, TAG, ATT, VAL, EVENT, MSG>
where
EVENT: 'static,
MSG: 'static,
{
pub fn map_callback<MSG2>(
self,
cb: Callback<MSG, MSG2>,
) -> Element<NS, TAG, ATT, VAL, EVENT, MSG2>
where
MSG2: 'static,
{
Element {
namespace: self.namespace,
tag: self.tag,
attrs: self
.attrs
.into_iter()
.map(|attr| attr.map_callback(cb.clone()))
.collect(),
children: self
.children
.into_iter()
.map(|child| child.map_callback(cb.clone()))
.collect(),
}
}
}