use crate::vdom::Node;
use std::fmt;
pub enum Leaf<MSG> {
Text(String),
SafeHtml(String),
Comment(String),
Fragment(Vec<Node<MSG>>),
DocType(String),
}
impl<MSG> Leaf<MSG> {
pub fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
pub fn is_safe_html(&self) -> bool {
matches!(self, Self::SafeHtml(_))
}
pub fn unwrap_text(&self) -> &str {
match self {
Self::Text(ref text) => text,
_ => panic!("node is not a text"),
}
}
pub fn unwrap_safe_html(&self) -> &str {
match self {
Self::SafeHtml(ref html) => html,
_ => panic!("node is not a text"),
}
}
}
impl<MSG> fmt::Debug for Leaf<MSG> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Text(v) => write!(f, "Text({v})"),
Self::SafeHtml(v) => write!(f, "SafeHtml({v})"),
Self::Comment(v) => write!(f, "Comment({v})"),
Self::Fragment(v) => {
write!(f, "Fragment:")?;
f.debug_list().entries(v).finish()
}
Self::DocType(v) => write!(f, "DocType({v})"),
}
}
}
impl<MSG> Clone for Leaf<MSG> {
fn clone(&self) -> Self {
match self {
Self::Text(v) => Self::Text(v.clone()),
Self::SafeHtml(v) => Self::SafeHtml(v.clone()),
Self::Comment(v) => Self::Comment(v.clone()),
Self::Fragment(v) => Self::Fragment(v.clone()),
Self::DocType(v) => Self::DocType(v.clone()),
}
}
}
impl<MSG> PartialEq for Leaf<MSG> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Text(v), Self::Text(o)) => v == o,
(Self::SafeHtml(v), Self::SafeHtml(o)) => v == o,
(Self::Comment(v), Self::Comment(o)) => v == o,
(Self::Fragment(v), Self::Fragment(o)) => v == o,
(Self::DocType(v), Self::DocType(o)) => v == o,
_ => false,
}
}
}
pub fn text<MSG>(s: impl ToString) -> Leaf<MSG> {
Leaf::Text(s.to_string())
}
pub fn safe_html<MSG>(s: impl ToString) -> Leaf<MSG> {
Leaf::SafeHtml(s.to_string())
}
pub fn comment<MSG>(s: impl ToString) -> Leaf<MSG> {
Leaf::Comment(s.to_string())
}
pub fn fragment<MSG>(nodes: impl IntoIterator<Item = Node<MSG>>) -> Leaf<MSG> {
Leaf::Fragment(nodes.into_iter().collect())
}
pub fn doctype<MSG>(s: impl ToString) -> Leaf<MSG> {
Leaf::DocType(s.to_string())
}