From f79215b5ee45d62276fd6bf062aae542b28c36cd Mon Sep 17 00:00:00 2001 From: sepiropht Date: Thu, 6 Jun 2019 08:21:01 +0200 Subject: [PATCH] whtml_stringify (wip) --- src/node.rs | 31 ++++++++++++++++++++++++++++++- src/render_context.rs | 15 +++++++++------ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/node.rs b/src/node.rs index 1e86b73..e51becb 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,10 +1,11 @@ +use crate::Render; +use crate::RenderContext; use crate::{cached_set::CacheId, RootRender, VdomWeak}; use bumpalo::Bump; use std::fmt; use std::iter; use std::mem; use std::u32; - /// A virtual DOM node. #[derive(Debug, Clone)] pub struct Node<'a> { @@ -269,3 +270,31 @@ impl Listener<'_> { } } } + +pub fn html_string(component: &R) -> String +where + R: Render, +{ + fn html_string_recursive(cx: &mut RenderContext, s: &mut String, node: &Node) { + match node.kind { + NodeKind::Text(ref t) => s.push_str(t.text), + NodeKind::Element(ref e) => { + s.push_str(e.tag_name); + for c in e.children { + html_string_recursive(cx, s, c); + } + s.push_str(&format!("", e.tag_name)); + } + NodeKind::Cached(ref c) => { + html_string_recursive(cx, s, cx.cached_set.borrow().get(c.id).0); + } + } + } + + RenderContext::empty(|cx| { + let node = component.render(cx); + let mut s = String::new(); + html_string_recursive(cx, &mut s, &node); + s + }) +} diff --git a/src/render_context.rs b/src/render_context.rs index 98ae4a3..57c87b4 100644 --- a/src/render_context.rs +++ b/src/render_context.rs @@ -61,16 +61,19 @@ impl<'a> RenderContext<'a> { } /// return an empty rendering context pub_unstable_internal! { - pub(crate) fn empty() -> Self { - let cached_set = &RefCell::new(CachedSet::default()); - let bump = &Bump::new(); - let templates = &mut FxHashMap::default(); - RenderContext { + pub(crate) fn empty(f: F) -> T + where F: FnOnce(&mut RenderContext) -> T, + { + let cached_set = &RefCell::new(CachedSet::default()); + let bump = &Bump::new(); + let templates = &mut FxHashMap::default(); + + f(&mut RenderContext { bump, cached_set, templates, _non_exhaustive: (), - } + }) } }