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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//! This contains a trait to be able to render
//! virtual dom into a writable buffer
//!
use crate::{html::attributes, Attribute, Element, Node};
use std::fmt;

/// render node, elements to a writable buffer
pub trait Render {
    // ISSUE: sublte difference in `render` and `render_to_string`:
    //  - flow content element such as span will treat the whitespace in between them as html text
    //  node
    //  Example:
    //  in `render`
    //  ```html
    //     <span>hello</span>
    //     <span> world</span>
    //  ```
    //     will displayed as "hello  world"
    //
    //  where us `render_to_string`
    //  ```html
    //  <span>hello</span><span> world</span>
    //  ```
    //  will result to a desirable output: "hello world"
    //
    /// render the node to a writable buffer
    fn render(&self, buffer: &mut dyn fmt::Write) -> fmt::Result {
        self.render_with_indent(buffer, 0, &mut Some(0), false)
    }

    /// no new_lines, no indents
    fn render_compressed(&self, buffer: &mut dyn fmt::Write) -> fmt::Result {
        self.render_with_indent(buffer, 0, &mut Some(0), true)
    }
    /// render instance to a writable buffer with indention
    /// node_idx is for debugging purposes
    fn render_with_indent(
        &self,
        buffer: &mut dyn fmt::Write,
        indent: usize,
        node_idx: &mut Option<usize>,
        compressed: bool,
    ) -> fmt::Result;

    /// render compressed html to string
    fn render_to_string(&self) -> String {
        let mut buffer = String::new();
        self.render_compressed(&mut buffer).expect("must render");
        buffer
    }
}

impl<MSG> Render for Node<MSG> {
    fn render_with_indent(
        &self,
        buffer: &mut dyn fmt::Write,
        indent: usize,
        node_idx: &mut Option<usize>,
        compressed: bool,
    ) -> fmt::Result {
        match self {
            Node::Element(element) => {
                element.render_with_indent(buffer, indent, node_idx, compressed)
            }
            Node::Text(text) => write!(buffer, "{}", text.text),
        }
    }
}

fn extract_inner_html<MSG>(merged_attributes: &[Attribute<MSG>]) -> String {
    merged_attributes
        .iter()
        .flat_map(|attr| {
            let (_callbacks, _plain_values, func_values) =
                attributes::partition_callbacks_from_plain_and_func_calls(
                    &attr,
                );

            if *attr.name() == "inner_html" {
                attributes::merge_plain_attributes_values(&func_values)
            } else {
                None
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

impl<MSG> Render for Element<MSG> {
    fn render_with_indent(
        &self,
        buffer: &mut dyn fmt::Write,
        indent: usize,
        node_idx: &mut Option<usize>,
        compressed: bool,
    ) -> fmt::Result {
        write!(buffer, "<{}", self.tag())?;

        let ref_attrs: Vec<&Attribute<MSG>> =
            self.get_attributes().iter().map(|att| att).collect();
        let merged_attributes: Vec<Attribute<MSG>> =
            mt_dom::merge_attributes_of_same_name(&ref_attrs);

        for attr in &merged_attributes {
            // dont render empty attribute
            // TODO: must check the attribute value for empty value
            if !attr.name().is_empty() {
                write!(buffer, " ")?;
                attr.render_with_indent(buffer, indent, node_idx, compressed)?;
            }
        }

        if self.self_closing {
            write!(buffer, "/>")?;
        } else {
            write!(buffer, ">")?;
        }

        let children = self.get_children();
        let first_child = children.get(0);
        let is_first_child_text_node =
            first_child.map(|node| node.is_text()).unwrap_or(false);

        let is_lone_child_text_node =
            children.len() == 1 && is_first_child_text_node;

        // do not indent if it is only text child node
        if is_lone_child_text_node {
            node_idx.as_mut().map(|idx| *idx += 1);
            first_child
                .unwrap()
                .render_with_indent(buffer, indent, node_idx, compressed)?;
        } else {
            // otherwise print all child nodes with each line and indented
            for child in self.get_children() {
                node_idx.as_mut().map(|idx| *idx += 1);
                if !compressed {
                    write!(buffer, "\n{}", "    ".repeat(indent + 1))?;
                }
                child.render_with_indent(
                    buffer,
                    indent + 1,
                    node_idx,
                    compressed,
                )?;
            }
        }

        // do not make a new line it if is only a text child node or it has no child nodes
        if !is_lone_child_text_node && !children.is_empty() {
            if !compressed {
                write!(buffer, "\n{}", "    ".repeat(indent))?;
            }
        }

        let inner_html = extract_inner_html(&merged_attributes);
        if !inner_html.is_empty() {
            write!(buffer, "{}", inner_html)?;
        }

        if !self.self_closing {
            write!(buffer, "</{}>", self.tag())?;
        }
        Ok(())
    }
}

impl<MSG> Render for Attribute<MSG> {
    fn render_with_indent(
        &self,
        buffer: &mut dyn fmt::Write,
        _indent: usize,
        _node_idx: &mut Option<usize>,
        _compressed: bool,
    ) -> fmt::Result {
        let (_callbacks, plain_values, _func_values) =
            attributes::partition_callbacks_from_plain_and_func_calls(&self);
        if let Some(merged_plain_values) =
            attributes::merge_plain_attributes_values(&plain_values)
        {
            write!(buffer, "{}=\"{}\"", self.name(), merged_plain_values)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::prelude::*;

    #[test]
    fn test_render_classes() {
        let view: Node<()> =
            div(vec![class("frame"), class("component")], vec![]);
        let expected = r#"<div class="frame component"></div>"#;
        let mut buffer = String::new();
        view.render(&mut buffer).expect("must render");
        assert_eq!(expected, buffer);
    }

    #[test]
    fn test_render_class_flag() {
        let view: Node<()> = div(
            vec![
                class("frame"),
                classes_flag([("component", true), ("layer", false)]),
            ],
            vec![],
        );
        let expected = r#"<div class="frame component"></div>"#;
        let mut buffer = String::new();
        view.render(&mut buffer).expect("must render");
        assert_eq!(expected, buffer);
    }
}