feat: support cached ssr
This commit is contained in:
1 parent
4a31b29703
commit
b6c0bce89c
11 files changed
+433
-178
No files matched your search
+86
-88
@@ -1,9 +1,10 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
|
||||
use std::fmt::{Display, Formatter, Write};
|
||||
mod template;
|
||||
|
||||
use dioxus_core::exports::bumpalo;
|
||||
use dioxus_core::IntoVNode;
|
||||
|
||||
use dioxus_core::*;
|
||||
|
||||
fn app(_cx: Scope) -> Element {
|
||||
@@ -25,9 +26,7 @@ impl SsrRenderer {
|
||||
|
||||
pub fn render_lazy<'a>(&'a mut self, f: LazyNodes<'a, '_>) -> String {
|
||||
let scope = self.vdom.base_scope();
|
||||
let factory = NodeFactory::new(scope);
|
||||
|
||||
let root = f.into_vnode(factory);
|
||||
let root = f.call(scope);
|
||||
format!(
|
||||
"{:}",
|
||||
TextRenderer {
|
||||
@@ -55,8 +54,7 @@ pub fn render_lazy<'a>(f: LazyNodes<'a, '_>) -> String {
|
||||
// Therefore, we cast our local bump allocator to the right lifetime. This is okay because our usage of the bump
|
||||
// arena is *definitely* shorter than the <'a> lifetime, and we return *owned* data - not borrowed data.
|
||||
let scope = unsafe { &*scope };
|
||||
|
||||
let root = f.into_vnode(NodeFactory::new(scope));
|
||||
let root = f.call(scope);
|
||||
|
||||
let vdom = Some(&vdom);
|
||||
|
||||
@@ -148,99 +146,99 @@ impl<'a: 'c, 'c> TextRenderer<'a, '_, 'c> {
|
||||
il: u16,
|
||||
last_node_was_text: &mut bool,
|
||||
) -> std::fmt::Result {
|
||||
match &node {
|
||||
VNode::Text(text) => {
|
||||
if *last_node_was_text {
|
||||
write!(f, "<!--spacer-->")?;
|
||||
}
|
||||
// match &node {
|
||||
// VNode::Text(text) => {
|
||||
// if *last_node_was_text {
|
||||
// write!(f, "<!--spacer-->")?;
|
||||
// }
|
||||
|
||||
if self.cfg.indent {
|
||||
for _ in 0..il {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
}
|
||||
// if self.cfg.indent {
|
||||
// for _ in 0..il {
|
||||
// write!(f, " ")?;
|
||||
// }
|
||||
// }
|
||||
|
||||
*last_node_was_text = true;
|
||||
// *last_node_was_text = true;
|
||||
|
||||
write!(f, "{}", text.text)?
|
||||
}
|
||||
VNode::Element(el) => {
|
||||
*last_node_was_text = false;
|
||||
// write!(f, "{}", text.text)?
|
||||
// }
|
||||
// VNode::Element(el) => {
|
||||
// *last_node_was_text = false;
|
||||
|
||||
if self.cfg.indent {
|
||||
for _ in 0..il {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
}
|
||||
// if self.cfg.indent {
|
||||
// for _ in 0..il {
|
||||
// write!(f, " ")?;
|
||||
// }
|
||||
// }
|
||||
|
||||
write!(f, "<{}", el.tag)?;
|
||||
// write!(f, "<{}", el.tag)?;
|
||||
|
||||
let inner_html = render_attributes(el.attributes.iter(), f)?;
|
||||
// let inner_html = render_attributes(el.attributes.iter(), f)?;
|
||||
|
||||
match self.cfg.newline {
|
||||
true => writeln!(f, ">")?,
|
||||
false => write!(f, ">")?,
|
||||
}
|
||||
// match self.cfg.newline {
|
||||
// true => writeln!(f, ">")?,
|
||||
// false => write!(f, ">")?,
|
||||
// }
|
||||
|
||||
if let Some(inner_html) = inner_html {
|
||||
write!(f, "{}", inner_html)?;
|
||||
} else {
|
||||
let mut last_node_was_text = false;
|
||||
for child in el.children {
|
||||
self.html_render(child, f, il + 1, &mut last_node_was_text)?;
|
||||
}
|
||||
}
|
||||
// if let Some(inner_html) = inner_html {
|
||||
// write!(f, "{}", inner_html)?;
|
||||
// } else {
|
||||
// let mut last_node_was_text = false;
|
||||
// for child in el.children {
|
||||
// self.html_render(child, f, il + 1, &mut last_node_was_text)?;
|
||||
// }
|
||||
// }
|
||||
|
||||
if self.cfg.newline {
|
||||
writeln!(f)?;
|
||||
}
|
||||
if self.cfg.indent {
|
||||
for _ in 0..il {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
}
|
||||
// if self.cfg.newline {
|
||||
// writeln!(f)?;
|
||||
// }
|
||||
// if self.cfg.indent {
|
||||
// for _ in 0..il {
|
||||
// write!(f, " ")?;
|
||||
// }
|
||||
// }
|
||||
|
||||
write!(f, "</{}>", el.tag)?;
|
||||
if self.cfg.newline {
|
||||
writeln!(f)?;
|
||||
}
|
||||
}
|
||||
VNode::Fragment(frag) => match frag.children.len() {
|
||||
0 => {
|
||||
*last_node_was_text = false;
|
||||
if self.cfg.indent {
|
||||
for _ in 0..il {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
}
|
||||
write!(f, "<!--placeholder-->")?;
|
||||
}
|
||||
_ => {
|
||||
for child in frag.children {
|
||||
self.html_render(child, f, il + 1, last_node_was_text)?;
|
||||
}
|
||||
}
|
||||
},
|
||||
VNode::Component(vcomp) => {
|
||||
let idx = vcomp.scope.get().unwrap();
|
||||
// write!(f, "</{}>", el.tag)?;
|
||||
// if self.cfg.newline {
|
||||
// writeln!(f)?;
|
||||
// }
|
||||
// }
|
||||
// VNode::Fragment(frag) => match frag.children.len() {
|
||||
// 0 => {
|
||||
// *last_node_was_text = false;
|
||||
// if self.cfg.indent {
|
||||
// for _ in 0..il {
|
||||
// write!(f, " ")?;
|
||||
// }
|
||||
// }
|
||||
// write!(f, "<!--placeholder-->")?;
|
||||
// }
|
||||
// _ => {
|
||||
// for child in frag.children {
|
||||
// self.html_render(child, f, il + 1, last_node_was_text)?;
|
||||
// }
|
||||
// }
|
||||
// },
|
||||
// VNode::Component(vcomp) => {
|
||||
// let idx = vcomp.scope.get().unwrap();
|
||||
|
||||
if let (Some(vdom), false) = (self.vdom, self.cfg.skip_components) {
|
||||
let new_node = vdom.get_scope(idx).unwrap().root_node();
|
||||
self.html_render(new_node, f, il + 1, last_node_was_text)?;
|
||||
} else {
|
||||
}
|
||||
}
|
||||
VNode::Template(t) => {
|
||||
if let Some(vdom) = self.vdom {
|
||||
todo!()
|
||||
} else {
|
||||
panic!("Cannot render template without vdom");
|
||||
}
|
||||
}
|
||||
VNode::Placeholder(_) => {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
// if let (Some(vdom), false) = (self.vdom, self.cfg.skip_components) {
|
||||
// let new_node = vdom.get_scope(idx).unwrap().root_node();
|
||||
// self.html_render(new_node, f, il + 1, last_node_was_text)?;
|
||||
// } else {
|
||||
// }
|
||||
// }
|
||||
// VNode::Template(t) => {
|
||||
// if let Some(vdom) = self.vdom {
|
||||
// todo!()
|
||||
// } else {
|
||||
// panic!("Cannot render template without vdom");
|
||||
// }
|
||||
// }
|
||||
// VNode::Placeholder(_) => {
|
||||
// todo!()
|
||||
// }
|
||||
// }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
use dioxus_core::prelude::*;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// A virtualdom renderer that caches the templates it has seen for faster rendering
|
||||
#[derive(Default)]
|
||||
pub struct SsrRender {
|
||||
template_cache: RefCell<HashMap<Template<'static>, Rc<StringCache>>>,
|
||||
}
|
||||
|
||||
struct StringCache {
|
||||
segments: Vec<Segment>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct StringChain {
|
||||
segments: Vec<Segment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Segment {
|
||||
Attr(usize),
|
||||
Dyn(usize),
|
||||
PreRendered(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Write for StringChain {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
match self.segments.last_mut() {
|
||||
Some(Segment::PreRendered(s2)) => s2.push_str(s),
|
||||
_ => self.segments.push(Segment::PreRendered(s.to_string())),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl StringCache {
|
||||
fn from_template(template: &VNode) -> Result<Self, std::fmt::Error> {
|
||||
let mut chain = StringChain::default();
|
||||
|
||||
let mut cur_path = vec![];
|
||||
|
||||
for (root_idx, root) in template.template.roots.iter().enumerate() {
|
||||
Self::recurse(root, &mut cur_path, root_idx, &mut chain)?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
segments: chain.segments,
|
||||
})
|
||||
}
|
||||
|
||||
fn recurse(
|
||||
root: &TemplateNode,
|
||||
cur_path: &mut Vec<usize>,
|
||||
root_idx: usize,
|
||||
chain: &mut StringChain,
|
||||
) -> Result<(), std::fmt::Error> {
|
||||
match root {
|
||||
TemplateNode::Element {
|
||||
tag,
|
||||
attrs,
|
||||
children,
|
||||
..
|
||||
} => {
|
||||
cur_path.push(root_idx);
|
||||
write!(chain, "<{}", tag)?;
|
||||
for attr in *attrs {
|
||||
match attr {
|
||||
TemplateAttribute::Static { name, value, .. } => {
|
||||
write!(chain, " {}=\"{}\"", name, value)?;
|
||||
}
|
||||
TemplateAttribute::Dynamic { index, .. } => {
|
||||
chain.segments.push(Segment::Attr(*index))
|
||||
}
|
||||
}
|
||||
}
|
||||
if children.len() == 0 {
|
||||
write!(chain, "/>")?;
|
||||
} else {
|
||||
write!(chain, ">")?;
|
||||
for child in *children {
|
||||
Self::recurse(child, cur_path, root_idx, chain)?;
|
||||
}
|
||||
write!(chain, "</{}>", tag)?;
|
||||
}
|
||||
cur_path.pop();
|
||||
}
|
||||
TemplateNode::Text(text) => write!(chain, "{}", text)?,
|
||||
TemplateNode::Dynamic(idx) => chain.segments.push(Segment::Dyn(*idx)),
|
||||
TemplateNode::DynamicText(idx) => chain.segments.push(Segment::Dyn(*idx)),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SsrRender {
|
||||
fn render_vdom(&mut self, dom: &VirtualDom) -> String {
|
||||
let scope = dom.base_scope();
|
||||
let root = scope.root_node();
|
||||
|
||||
let mut out = String::new();
|
||||
self.render_template(&mut out, root).unwrap();
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn render_template(&self, buf: &mut String, template: &VNode) -> std::fmt::Result {
|
||||
let entry = self
|
||||
.template_cache
|
||||
.borrow_mut()
|
||||
.entry(template.template)
|
||||
.or_insert_with(|| Rc::new(StringCache::from_template(template).unwrap()))
|
||||
.clone();
|
||||
|
||||
for segment in entry.segments.iter() {
|
||||
match segment {
|
||||
Segment::Attr(idx) => {
|
||||
todo!("properly implement attrs in the macro");
|
||||
// let loc = &template.dynamic_attrs[*idx];
|
||||
// for attr in loc.attrs.iter() {
|
||||
// write!(buf, " {}=\"{}\"", attr.name, attr.value)?;
|
||||
// }
|
||||
}
|
||||
Segment::Dyn(idx) => match &template.dynamic_nodes[*idx].kind {
|
||||
DynamicNodeKind::Text { value, .. } => write!(buf, "{}", value)?,
|
||||
DynamicNodeKind::Fragment { children } => {
|
||||
for child in *children {
|
||||
self.render_template(buf, child)?;
|
||||
}
|
||||
//
|
||||
}
|
||||
DynamicNodeKind::Component { .. } => {
|
||||
//
|
||||
}
|
||||
},
|
||||
|
||||
Segment::PreRendered(text) => buf.push_str(&text),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_string_works() {
|
||||
use dioxus::prelude::*;
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
let dynamic = 123;
|
||||
|
||||
cx.render(rsx! {
|
||||
div { class: "asdasdasd", class: "asdasdasd",
|
||||
"Hello world 1 -->"
|
||||
"{dynamic}"
|
||||
"<-- Hello world 2"
|
||||
div { "nest 1" }
|
||||
div {}
|
||||
div { "nest 2" }
|
||||
(0..5).map(|i| rsx! {
|
||||
div { "finalize {i}" }
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
let mut dom = VirtualDom::new(app);
|
||||
|
||||
let mut mutations = Vec::new();
|
||||
dom.rebuild(&mut mutations);
|
||||
|
||||
let cache = StringCache::from_template(&dom.base_scope().root_node()).unwrap();
|
||||
|
||||
dbg!(cache.segments);
|
||||
|
||||
let mut renderer = SsrRender::default();
|
||||
|
||||
dbg!(renderer.render_vdom(&dom));
|
||||
}
|
||||
Reference in new issue
Block a user