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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Rendering backend for Server Side Rendering, aka. SSR.

use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::rc::{Rc, Weak};

use ahash::AHashMap;
use once_cell::sync::Lazy;
use wasm_bindgen::prelude::*;

use crate::generic_node::{EventHandler, GenericNode};
use crate::reactive::create_root;
use crate::template::Template;

static VOID_ELEMENTS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
    vec![
        "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
        "source", "track", "wbr", "command", "keygen", "menuitem",
    ]
    .into_iter()
    .collect()
});

/// Inner representation for [`SsrNode`].
#[derive(Debug, Clone)]
enum SsrNodeType {
    Element(RefCell<Element>),
    Comment(RefCell<Comment>),
    Text(RefCell<Text>),
    RawText(RefCell<RawText>),
}

#[derive(Debug, Clone)]
struct SsrNodeInner {
    ty: Rc<SsrNodeType>,
    /// No parent if `Weak::upgrade` returns `None`.
    parent: RefCell<Weak<SsrNodeInner>>,
}

/// Rendering backend for Server Side Rendering, aka. SSR.
///
/// _This API requires the following crate features to be activated: `ssr`_
#[derive(Debug, Clone)]
pub struct SsrNode(Rc<SsrNodeInner>);

impl PartialEq for SsrNode {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0.ty, &other.0.ty)
    }
}

impl Eq for SsrNode {}

impl Hash for SsrNode {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Rc::as_ptr(&self.0).hash(state);
    }
}

impl SsrNode {
    fn new(ty: SsrNodeType) -> Self {
        Self(Rc::new(SsrNodeInner {
            ty: Rc::new(ty),
            parent: RefCell::new(Weak::new()), // no parent
        }))
    }

    fn set_parent(&self, parent: Weak<SsrNodeInner>) {
        if let Some(old_parent) = self.parent_node() {
            old_parent.try_remove_child(self);
        }

        *self.0.parent.borrow_mut() = parent;
    }

    #[track_caller]
    pub fn unwrap_element(&self) -> &RefCell<Element> {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(e) => e,
            _ => panic!("node is not an element"),
        }
    }

    #[track_caller]
    pub fn unwrap_text(&self) -> &RefCell<Text> {
        match &self.0.ty.as_ref() {
            SsrNodeType::Text(e) => e,
            _ => panic!("node is not a text node"),
        }
    }

    fn try_remove_child(&self, child: &Self) {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(e) => {
                let children = e
                    .borrow()
                    .children
                    .clone()
                    .into_iter()
                    .filter(|node| node != child)
                    .collect();
                e.borrow_mut().children = children;
            }
            _ => panic!("node type cannot have children"),
        }
    }

    /// Create a new raw text node.
    ///
    /// Do not pass unsanitized user input to this function. When the node is rendered, no escaping
    /// will be performed which might lead to a XSS (Cross Site Scripting) attack.
    pub fn raw_text_node(html: &str) -> Self {
        SsrNode::new(SsrNodeType::RawText(RefCell::new(RawText(
            html.to_string(),
        ))))
    }
}

impl GenericNode for SsrNode {
    fn element(tag: &str) -> Self {
        SsrNode::new(SsrNodeType::Element(RefCell::new(Element {
            name: tag.to_string(),
            attributes: AHashMap::new(),
            children: Default::default(),
        })))
    }

    fn text_node(text: &str) -> Self {
        SsrNode::new(SsrNodeType::Text(RefCell::new(Text(text.to_string()))))
    }

    fn marker() -> Self {
        SsrNode::new(SsrNodeType::Comment(Default::default()))
    }

    fn set_attribute(&self, name: &str, value: &str) {
        self.unwrap_element()
            .borrow_mut()
            .attributes
            .insert(name.to_string(), value.to_string());
    }

    fn remove_attribute(&self, name: &str) {
        self.unwrap_element().borrow_mut().attributes.remove(name);
    }

    fn set_class_name(&self, value: &str) {
        self.set_attribute("class", value);
    }

    fn set_property(&self, _name: &str, _value: &JsValue) {
        // Noop.
    }

    fn remove_property(&self, _name: &str) {
        // Noop.
    }

    fn append_child(&self, child: &Self) {
        child.set_parent(Rc::downgrade(&self.0));

        match self.0.ty.as_ref() {
            SsrNodeType::Element(element) => element.borrow_mut().children.push(child.clone()),
            _ => panic!("node type cannot have children"),
        }
    }

    fn first_child(&self) -> Option<Self> {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(element) => element.borrow_mut().children.first().cloned(),
            _ => panic!("node type cannot have children"),
        }
    }

    fn insert_child_before(&self, new_node: &Self, reference_node: Option<&Self>) {
        new_node.set_parent(Rc::downgrade(&self.0));

        match reference_node {
            None => self.append_child(new_node),
            Some(reference) => {
                match self.0.ty.as_ref() {
                    SsrNodeType::Element(e) => {
                        let children = &mut e.borrow_mut().children;
                        let index = children
                            .iter()
                            .enumerate()
                            .find_map(|(i, child)| (child == reference).then(|| i))
                            .expect("reference node is not a child of this node");
                        children.insert(index, new_node.clone());
                    }
                    _ => panic!("node type cannot have children"),
                };
            }
        }
    }

    fn remove_child(&self, child: &Self) {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(e) => {
                let initial_children_len = e.borrow().children.len();
                if child.parent_node().as_ref() != Some(self) {
                    panic!("the node to be removed is not a child of this node");
                }
                child.set_parent(Weak::new());
                debug_assert_eq!(e.borrow().children.len(), initial_children_len - 1);
            }
            _ => panic!("node type cannot have children"),
        }
    }

    fn replace_child(&self, old: &Self, new: &Self) {
        new.set_parent(Rc::downgrade(&self.0));

        let mut ele = self.unwrap_element().borrow_mut();
        let children = &mut ele.children;
        let index = children
            .iter()
            .enumerate()
            .find_map(|(i, c)| (c == old).then(|| i))
            .expect("the node to be replaced is not a child of this node");
        *children[index].0.parent.borrow_mut() = Weak::new();
        children[index] = new.clone();
    }

    fn insert_sibling_before(&self, child: &Self) {
        child.set_parent(Rc::downgrade(
            &self.parent_node().expect("no parent for this node").0,
        ));

        self.parent_node()
            .unwrap()
            .insert_child_before(child, Some(self));
    }

    fn parent_node(&self) -> Option<Self> {
        self.0.parent.borrow().upgrade().map(SsrNode)
    }

    fn next_sibling(&self) -> Option<Self> {
        let parent = self.parent_node().expect("node must have a parent");
        match parent.0.ty.as_ref() {
            SsrNodeType::Element(e) => {
                let children = &e.borrow().children;
                children
                    .iter()
                    .skip_while(|child| *child != self)
                    .skip(1)
                    .take(1)
                    .cloned()
                    .next()
            }
            _ => panic!("node type cannot have children"),
        }
    }

    fn remove_self(&self) {
        self.parent_node()
            .expect("node must have a parent")
            .remove_child(self);
    }

    fn event(&self, _name: &str, _handler: Box<EventHandler>) {
        // Noop. Events are attached on client side.
    }

    fn update_inner_text(&self, text: &str) {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(el) => el.borrow_mut().children = vec![SsrNode::text_node(text)],
            SsrNodeType::Comment(_c) => panic!("cannot update inner text on comment node"),
            SsrNodeType::Text(t) => t.borrow_mut().0 = text.to_string(),
            SsrNodeType::RawText(_t) => panic!("cannot update inner text on raw text node"),
        }
    }

    fn dangerously_set_inner_html(&self, html: &str) {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(el) => {
                el.borrow_mut().children = vec![SsrNode::raw_text_node(html)];
            }
            SsrNodeType::Comment(_c) => panic!("cannot update inner text on comment node"),
            SsrNodeType::Text(_t) => panic!("cannot update inner text on text node"),
            SsrNodeType::RawText(t) => t.borrow_mut().0 = html.to_string(),
        }
    }

    fn clone_node(&self) -> Self {
        let inner = SsrNodeInner {
            ty: Rc::new(self.0.ty.as_ref().clone()),
            parent: RefCell::new(Weak::new()),
        };
        Self(Rc::new(inner))
    }
}

trait WriteToString {
    fn write_to_string(&self, s: &mut String);
}

impl WriteToString for SsrNode {
    fn write_to_string(&self, s: &mut String) {
        match self.0.ty.as_ref() {
            SsrNodeType::Element(x) => x.borrow().write_to_string(s),
            SsrNodeType::Comment(x) => x.borrow().write_to_string(s),
            SsrNodeType::Text(x) => x.borrow().write_to_string(s),
            SsrNodeType::RawText(x) => x.borrow().write_to_string(s),
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Element {
    name: String,
    attributes: AHashMap<String, String>,
    children: Vec<SsrNode>,
}

impl WriteToString for Element {
    fn write_to_string(&self, s: &mut String) {
        s.reserve("<".len() + self.name.len());
        s.push('<');
        s.push_str(&self.name);
        for (name, value) in &self.attributes {
            let value_escaped = html_escape::encode_double_quoted_attribute(value);
            s.reserve(" ".len() + name.len() + "=\"".len() + value_escaped.len() + "\"".len());
            s.push(' ');
            s.push_str(name);
            s.push_str("=\"");
            s.push_str(&value_escaped);
            s.push('"');
        }

        // Check if self-closing tag (void-element).
        if self.children.is_empty() && VOID_ELEMENTS.contains(self.name.as_str()) {
            s.push_str("/>");
        } else {
            s.push('>');
            for child in &self.children {
                child.write_to_string(s);
            }
            s.reserve("</".len() + self.name.len() + ">".len());
            s.push_str("</");
            s.push_str(&self.name);
            s.push('>');
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct Comment(String);

impl WriteToString for Comment {
    fn write_to_string(&self, s: &mut String) {
        let escaped = self.0.replace("-->", "--&gt;");
        s.reserve("<!--".len() + escaped.len() + "-->".len());
        s.push_str("<!--");
        s.push_str(&escaped);
        s.push_str("-->");
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct Text(String);

impl WriteToString for Text {
    fn write_to_string(&self, s: &mut String) {
        s.push_str(&html_escape::encode_text_minimal(&self.0));
    }
}

/// Un-escaped text node.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct RawText(String);

impl WriteToString for RawText {
    fn write_to_string(&self, s: &mut String) {
        s.push_str(&self.0);
    }
}

/// Render a [`Template`] into a static [`String`]. Useful
/// for rendering to a string on the server side.
///
/// _This API requires the following crate features to be activated: `ssr`_
pub fn render_to_string(template: impl FnOnce() -> Template<SsrNode>) -> String {
    let mut ret = String::new();
    let _scope = create_root(|| {
        for node in template().flatten() {
            node.write_to_string(&mut ret);
        }
    });

    ret
}

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

    #[test]
    fn render_hello_world() {
        assert_eq!(
            render_to_string(|| template! {
                "Hello World!"
            }),
            "Hello World!"
        );
    }

    #[test]
    fn append_child() {
        let node = SsrNode::element("div");
        let p = SsrNode::element("p");
        let p2 = SsrNode::element("p");

        node.append_child(&p);
        node.append_child(&p2);

        // p and p2 parents should be updated
        assert_eq!(p.parent_node().as_ref(), Some(&node));
        assert_eq!(p2.parent_node().as_ref(), Some(&node));

        // node.first_child should be p
        assert_eq!(node.first_child().as_ref(), Some(&p));

        // p.next_sibling should be p2
        assert_eq!(p.next_sibling().as_ref(), Some(&p2));
    }

    #[test]
    fn remove_child() {
        let node = SsrNode::element("div");
        let p = SsrNode::element("p");

        node.append_child(&p);
        // p parent should be updated
        assert_eq!(p.parent_node().as_ref(), Some(&node));
        // node.first_child should be p
        assert_eq!(node.first_child().as_ref(), Some(&p));

        // remove p from node
        node.remove_child(&p);
        // p parent should be updated
        assert_eq!(p.parent_node().as_ref(), None);
        // node.first_child should be None
        assert_eq!(node.first_child().as_ref(), None);
    }

    #[test]
    fn remove_child_2() {
        let node = SsrNode::element("div");
        let p = SsrNode::element("p");
        let p2 = SsrNode::element("p");
        let p3 = SsrNode::element("p");

        node.append_child(&p);
        node.append_child(&p2);
        node.append_child(&p3);

        // node.first_child should be p
        assert_eq!(node.first_child().as_ref(), Some(&p));

        // remove p from node
        node.remove_child(&p);
        // p parent should be updated
        assert_eq!(p.parent_node().as_ref(), None);
        // node.first_child should be p2
        assert_eq!(node.first_child().as_ref(), Some(&p2));
    }
}