use std::fmt;
pub mod builder;
pub mod event;
mod value;
use crate::Callback;
pub use event::Event;
pub use value::Value;
pub use attribute::{
AttribValue,
Attribute,
};
pub use element::Element;
mod attribute;
mod element;
#[derive(Debug, Clone, PartialEq)]
pub enum Node<T, ATT, EVENT, MSG>
where
MSG: 'static,
EVENT: 'static,
ATT: Clone,
{
Element(Element<T, ATT, EVENT, MSG>),
Text(Text),
}
impl<T, ATT, EVENT, MSG> Node<T, ATT, EVENT, MSG>
where
EVENT: 'static,
MSG: 'static,
ATT: PartialEq + Ord + ToString + Clone,
{
pub fn map_msg<F, MSG2>(self, func: F) -> Node<T, ATT, EVENT, MSG2>
where
F: Fn(MSG) -> MSG2 + 'static,
MSG2: 'static,
{
let cb = Callback::from(func);
self.map_callback(cb)
}
fn map_callback<MSG2>(
self,
cb: Callback<MSG, MSG2>,
) -> Node<T, ATT, EVENT, MSG2>
where
MSG2: 'static,
{
match self {
Node::Element(element) => Node::Element(element.map_callback(cb)),
Node::Text(text) => Node::Text(Text::new(text.text)),
}
}
fn to_pretty_string(&self, indent: usize) -> String
where
T: ToString,
{
match self {
Node::Element(element) => element.to_pretty_string(indent),
Node::Text(text) => format!("{}", text),
}
}
fn is_text_node(&self) -> bool {
match self {
Node::Element(_) => false,
Node::Text(_) => true,
}
}
pub fn take_element(self) -> Option<Element<T, ATT, EVENT, MSG>> {
match self {
Node::Element(element) => Some(element),
Node::Text(_) => None,
}
}
pub fn as_element_mut(
&mut self,
) -> Option<&mut Element<T, ATT, EVENT, MSG>> {
match *self {
Node::Element(ref mut element) => Some(element),
Node::Text(_) => None,
}
}
pub fn as_element_ref(&self) -> Option<&Element<T, ATT, EVENT, MSG>> {
match *self {
Node::Element(ref element) => Some(element),
Node::Text(_) => None,
}
}
pub fn add_children(
mut self,
children: Vec<Node<T, ATT, EVENT, MSG>>,
) -> Self {
if let Some(element) = self.as_element_mut() {
element.add_children(children);
}
self
}
pub fn add_attributes(
mut self,
attributes: Vec<Attribute<ATT, EVENT, MSG>>,
) -> Self {
if let Some(elm) = self.as_element_mut() {
elm.add_attributes(attributes);
}
self
}
pub fn get_attributes(&self) -> Vec<Attribute<ATT, EVENT, MSG>> {
match *self {
Node::Element(ref element) => element.attributes(),
Node::Text(_) => vec![],
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Text {
pub text: String,
}
impl Text {
pub fn new<S: Into<String>>(s: S) -> Self {
Text { text: s.into() }
}
}
impl fmt::Display for Text {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.text)
}
}
impl<T, ATT, EVENT, MSG> fmt::Display for Node<T, ATT, EVENT, MSG>
where
T: ToString,
EVENT: 'static,
MSG: 'static,
ATT: PartialEq + Ord + ToString + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_pretty_string(0))
}
}