1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
use std::collections::BTreeMap;
use std::fmt;
use crate::Callback;
pub mod builder;
mod event;
mod value;
pub use event::{Event, InputEvent, KeyEvent, MouseButton, MouseEvent};
pub use value::Value;
#[derive(Debug, PartialEq, Clone)]
pub enum Node<T> {
Element(Element<T>),
Text(Text),
}
#[derive(Debug, PartialEq, Clone, Default)]
pub struct Element<T> {
pub tag: T,
pub attrs: BTreeMap<String, Value>,
pub events: BTreeMap<String, Callback<Event>>,
pub children: Vec<Node<T>>,
pub namespace: Option<String>,
}
#[derive(Debug, PartialEq, Clone, Default)]
pub struct Text {
pub text: String,
}
impl<T> Element<T> {
pub fn new(tag: T) -> Self {
Element {
tag,
attrs: BTreeMap::new(),
events: BTreeMap::new(),
children: vec![],
namespace: None,
}
}
pub fn namespace(mut self, namespace: &str) -> Self {
self.namespace = Some(namespace.to_string());
self
}
}
impl<T> fmt::Display for Element<T>
where
T: ToString,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}", self.tag.to_string()).unwrap();
for (attr, value) in self.attrs.iter() {
write!(f, r#" {}="{}""#, attr, value)?;
}
write!(f, ">")?;
for child in self.children.iter() {
write!(f, "{}", child.to_string())?;
}
write!(f, "</{}>", self.tag.to_string())?;
Ok(())
}
}
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> fmt::Display for Node<T>
where
T: ToString,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Node::Element(element) => write!(f, "{}", element),
Node::Text(text) => write!(f, "{}", text),
}
}
}
impl<T> From<Element<T>> for Node<T> {
fn from(v: Element<T>) -> Self {
Node::Element(v)
}
}