1use std::collections::HashMap;
2use web_sys::{window, Element};
3
4pub struct Component {
5 name: String,
6 attributes: HashMap<String, String>,
7 children: Vec<Box<Renderable>>,
8}
9
10impl Component {
11 pub fn new(
12 name: &str,
13 attributes: HashMap<String, String>,
14 children: Vec<Box<Renderable>>,
15 ) -> Component {
16 Component {
17 name: name.into(),
18 attributes,
19 children,
20 }
21 }
22}
23
24fn attr_to_string(key: &str, value: &str) -> String {
25 format!(" {}='{}'", key, value)
26}
27
28pub trait Renderable {
29 #[cfg(target_arch = "wasm32")]
30 fn render(&self) -> Element;
31
32 #[cfg(not(target_arch = "wasm32"))]
33 fn render(&self) -> String;
34}
35
36impl Renderable for Component {
37 fn render(&self) -> String {
38 let attributes = self
39 .attributes
40 .iter()
41 .map(|(key, value)| attr_to_string(&key, &value))
42 .collect::<Vec<String>>()
43 .join("");
44
45 let children = self
46 .children
47 .iter()
48 .map(|child| child.render())
49 .collect::<Vec<String>>()
50 .join("");
51
52 if children.len() > 0 {
53 format!("<{}{}>{}<{}>", &self.name, attributes, children, &self.name)
54 } else {
55 format!("<{}{} />", &self.name, attributes)
56 }
57 }
58}