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
|
use std::collections::HashMap;
pub trait Component {
fn render(self: Box<Self>) -> Vec<RenderNode>;
}
pub enum RenderNode {
Component(Box<dyn Component>),
Element {
name: String,
attributes: HashMap<String, String>,
children: Vec<RenderNode>
},
TextNode {
content: String,
},
Portal,
Null,
}
impl RenderNode {
pub(crate) fn render_to_string(self) -> String {
match self {
RenderNode::Component(component) => {
let elements = component.render();
elements.into_iter()
.map(|child| child.render_to_string())
.collect::<Vec<_>>().join("")
},
RenderNode::Element { name, attributes, children } => {
let text_attributes = attributes.into_iter()
.map(|(key, value)| format!(" {key}=\"{value}\""))
.collect::<Vec<_>>().join("");
let rendered_children = children.into_iter()
.map(|child| child.render_to_string())
.collect::<Vec<_>>().join("");
format!("<{name}{text_attributes}>{rendered_children}</{name}>")
},
RenderNode::TextNode { content } => content,
RenderNode::Portal => todo!(),
RenderNode::Null => "".to_string(),
}
}
}
|