summary refs log tree commit diff
path: root/src/render.rs
blob: 94b193b3d7bfd66f88a41a09412ea42d77b8b386 (plain)
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
use std::pin::Pin;
use std::collections::HashMap;
use std::future::Future;
use futures::future::join_all;

pub trait Component {
    fn render(self: Box<Self>) -> Vec<RenderNode>;
}

pub enum RenderNode {
    Suspense {
        fallback: Box<RenderNode>,
        children: Pin<Box<dyn Future<Output = Vec<RenderNode>>>>
    },
    Component(Box<dyn Component>),
    Element {
        name: String,
        attributes: HashMap<String, String>,
        children: Vec<RenderNode>
    },
    Fragment {
        children: Vec<RenderNode>
    },
    TextNode {
        content: String,
    },
    Null,
}

impl RenderNode {
    pub(crate) fn render_to_string(self) -> Pin<Box<dyn Future<Output = String>>> {
        match self {
            RenderNode::Component(component) => {
                let elements = component.render();
                Box::pin((async move || {
                    join_all(elements.into_iter()
                        .map(|child| child.render_to_string())
                        .collect::<Vec<_>>()).await.join("")
                })())
            },

            RenderNode::Suspense {fallback: _, children} => {
                Box::pin((async move || {
                    join_all(children.await.into_iter()
                        .map(|child| child.render_to_string())).await
                        .join("")
                })())
            },

            RenderNode::Element { name, attributes, children } => {
                let text_attributes = attributes.into_iter()
                    .map(|(key, value)| format!(" {key}=\"{value}\""))
                    .collect::<Vec<_>>().join("");

                Box::pin((async move || {
                    let rendered_children = join_all(children.into_iter()
                        .map(|child| child.render_to_string())
                        .collect::<Vec<_>>()).await.join("");

                    format!("<{name}{text_attributes}>{rendered_children}</{name}>")

                })())
            },
            RenderNode::Fragment { children } => {
                Box::pin((async move || {
                    join_all(children.into_iter()
                        .map(|child| child.render_to_string())).await
                        .join("")
                })())
            }

            RenderNode::TextNode { content } => Box::pin((async move || content)()),
            RenderNode::Null => Box::pin((async move || "".to_string())()),
        }
    }
}