use std::fmt::{self, Display, Formatter};
use super::write_children;
use crate::Node;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Element {
pub name: String,
pub attributes: Vec<(String, Option<String>)>,
pub children: Option<Vec<Node>>,
}
impl Display for Element {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "<{}", self.name)?;
for (key, value) in &self.attributes {
write!(f, " {key}")?;
if let Some(value) = value {
let encoded_value = html_escape::encode_double_quoted_attribute(value);
write!(f, r#"="{encoded_value}""#)?;
}
}
write!(f, ">")?;
if let Some(children) = &self.children {
write_children(f, children, false)?;
write!(f, "</{}>", self.name)?;
};
Ok(())
}
}
impl<N> From<N> for Element
where
N: Into<String>,
{
fn from(name: N) -> Self {
Self {
name: name.into(),
attributes: Vec::new(),
children: None,
}
}
}