renderer.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. use super::cache::Segment;
  2. use crate::cache::StringCache;
  3. use dioxus_core::{prelude::*, AttributeValue, DynamicNode, RenderReturn};
  4. use std::collections::HashMap;
  5. use std::fmt::Write;
  6. use std::sync::Arc;
  7. /// A virtualdom renderer that caches the templates it has seen for faster rendering
  8. #[derive(Default)]
  9. pub struct Renderer {
  10. /// should we do our best to prettify the output?
  11. pub pretty: bool,
  12. /// Control if elements are written onto a new line
  13. pub newline: bool,
  14. /// Should we sanitize text nodes? (escape HTML)
  15. pub sanitize: bool,
  16. /// Choose to write ElementIDs into elements so the page can be re-hydrated later on
  17. pub pre_render: bool,
  18. // Currently not implemented
  19. // Don't proceed onto new components. Instead, put the name of the component.
  20. pub skip_components: bool,
  21. /// A cache of templates that have been rendered
  22. template_cache: HashMap<&'static str, Arc<StringCache>>,
  23. }
  24. impl Renderer {
  25. pub fn new() -> Self {
  26. Self::default()
  27. }
  28. pub fn render(&mut self, dom: &VirtualDom) -> String {
  29. let mut buf = String::new();
  30. self.render_to(&mut buf, dom).unwrap();
  31. buf
  32. }
  33. pub fn render_to(&mut self, buf: &mut impl Write, dom: &VirtualDom) -> std::fmt::Result {
  34. self.render_scope(buf, dom, ScopeId(0))
  35. }
  36. pub fn render_scope(
  37. &mut self,
  38. buf: &mut impl Write,
  39. dom: &VirtualDom,
  40. scope: ScopeId,
  41. ) -> std::fmt::Result {
  42. // We should never ever run into async or errored nodes in SSR
  43. // Error boundaries and suspense boundaries will convert these to sync
  44. if let RenderReturn::Ready(node) = dom.get_scope(scope).unwrap().root_node() {
  45. self.render_template(buf, dom, node)?
  46. };
  47. Ok(())
  48. }
  49. fn render_template(
  50. &mut self,
  51. buf: &mut impl Write,
  52. dom: &VirtualDom,
  53. template: &VNode,
  54. ) -> std::fmt::Result {
  55. let entry = self
  56. .template_cache
  57. .entry(template.template.get().name)
  58. .or_insert_with(|| Arc::new(StringCache::from_template(template).unwrap()))
  59. .clone();
  60. let mut inner_html = None;
  61. // We need to keep track of the dynamic styles so we can insert them into the right place
  62. let mut accumulated_dynamic_styles = Vec::new();
  63. for segment in entry.segments.iter() {
  64. match segment {
  65. Segment::Attr(idx) => {
  66. let attr = &template.dynamic_attrs[*idx];
  67. attr.attribute_type().try_for_each(|attr| {
  68. if attr.name == "dangerous_inner_html" {
  69. inner_html = Some(attr);
  70. } else if attr.namespace == Some("style") {
  71. accumulated_dynamic_styles.push(attr);
  72. } else {
  73. match attr.value {
  74. AttributeValue::Text(value) => {
  75. write!(buf, " {}=\"{}\"", attr.name, value)?
  76. }
  77. AttributeValue::Bool(value) => {
  78. write!(buf, " {}={}", attr.name, value)?
  79. }
  80. AttributeValue::Int(value) => {
  81. write!(buf, " {}={}", attr.name, value)?
  82. }
  83. AttributeValue::Float(value) => {
  84. write!(buf, " {}={}", attr.name, value)?
  85. }
  86. _ => {}
  87. };
  88. }
  89. Ok(())
  90. })?;
  91. }
  92. Segment::Node(idx) => match &template.dynamic_nodes[*idx] {
  93. DynamicNode::Component(node) => {
  94. if self.skip_components {
  95. write!(buf, "<{}><{}/>", node.name, node.name)?;
  96. } else {
  97. let id = node.mounted_scope().unwrap();
  98. let scope = dom.get_scope(id).unwrap();
  99. let node = scope.root_node();
  100. match node {
  101. RenderReturn::Ready(node) => {
  102. self.render_template(buf, dom, node)?
  103. }
  104. _ => todo!(
  105. "generally, scopes should be sync, only if being traversed"
  106. ),
  107. }
  108. }
  109. }
  110. DynamicNode::Text(text) => {
  111. // in SSR, we are concerned that we can't hunt down the right text node since they might get merged
  112. if self.pre_render {
  113. write!(buf, "<!--#-->")?;
  114. }
  115. write!(
  116. buf,
  117. "{}",
  118. askama_escape::escape(text.value, askama_escape::Html)
  119. )?;
  120. if self.pre_render {
  121. write!(buf, "<!--#-->")?;
  122. }
  123. }
  124. DynamicNode::Fragment(nodes) => {
  125. for child in *nodes {
  126. self.render_template(buf, dom, child)?;
  127. }
  128. }
  129. DynamicNode::Placeholder(_el) => {
  130. if self.pre_render {
  131. write!(buf, "<pre></pre>")?;
  132. }
  133. }
  134. },
  135. Segment::PreRendered(contents) => write!(buf, "{contents}")?,
  136. Segment::StyleMarker { inside_style_tag } => {
  137. if !accumulated_dynamic_styles.is_empty() {
  138. // if we are inside a style tag, we don't need to write the style attribute
  139. if !*inside_style_tag {
  140. write!(buf, " style=\"")?;
  141. }
  142. for attr in &accumulated_dynamic_styles {
  143. match attr.value {
  144. AttributeValue::Text(value) => {
  145. write!(buf, "{}:{};", attr.name, value)?
  146. }
  147. AttributeValue::Bool(value) => {
  148. write!(buf, "{}:{};", attr.name, value)?
  149. }
  150. AttributeValue::Float(f) => write!(buf, "{}:{};", attr.name, f)?,
  151. AttributeValue::Int(i) => write!(buf, "{}:{};", attr.name, i)?,
  152. _ => {}
  153. };
  154. }
  155. if !*inside_style_tag {
  156. write!(buf, "\"")?;
  157. }
  158. // clear the accumulated styles
  159. accumulated_dynamic_styles.clear();
  160. }
  161. }
  162. Segment::InnerHtmlMarker => {
  163. if let Some(inner_html) = inner_html.take() {
  164. let inner_html = &inner_html.value;
  165. match inner_html {
  166. AttributeValue::Text(value) => write!(buf, "{}", value)?,
  167. AttributeValue::Bool(value) => write!(buf, "{}", value)?,
  168. AttributeValue::Float(f) => write!(buf, "{}", f)?,
  169. AttributeValue::Int(i) => write!(buf, "{}", i)?,
  170. _ => {}
  171. }
  172. }
  173. }
  174. }
  175. }
  176. Ok(())
  177. }
  178. }
  179. #[test]
  180. fn to_string_works() {
  181. use dioxus::prelude::*;
  182. fn app(cx: Scope) -> Element {
  183. let dynamic = 123;
  184. let dyn2 = "</diiiiiiiiv>"; // this should be escaped
  185. render! {
  186. div { class: "asdasdasd", class: "asdasdasd", id: "id-{dynamic}",
  187. "Hello world 1 -->" "{dynamic}" "<-- Hello world 2"
  188. div { "nest 1" }
  189. div {}
  190. div { "nest 2" }
  191. "{dyn2}"
  192. (0..5).map(|i| rsx! { div { "finalize {i}" } })
  193. }
  194. }
  195. }
  196. let mut dom = VirtualDom::new(app);
  197. _ = dom.rebuild();
  198. let mut renderer = Renderer::new();
  199. let out = renderer.render(&dom);
  200. for item in renderer.template_cache.iter() {
  201. if item.1.segments.len() > 5 {
  202. assert_eq!(
  203. item.1.segments,
  204. vec![
  205. PreRendered("<div class=\"asdasdasd\" class=\"asdasdasd\"".into(),),
  206. Attr(0,),
  207. StyleMarker {
  208. inside_style_tag: false,
  209. },
  210. PreRendered(">".into()),
  211. InnerHtmlMarker,
  212. PreRendered("Hello world 1 --&gt;".into(),),
  213. Node(0,),
  214. PreRendered(
  215. "&lt;-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>".into(),
  216. ),
  217. Node(1,),
  218. Node(2,),
  219. PreRendered("</div>".into(),),
  220. ]
  221. );
  222. }
  223. }
  224. use Segment::*;
  225. assert_eq!(out, "<div class=\"asdasdasd\" class=\"asdasdasd\" id=\"id-123\">Hello world 1 --&gt;123&lt;-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>&lt;/diiiiiiiiv&gt;<div>finalize 0</div><div>finalize 1</div><div>finalize 2</div><div>finalize 3</div><div>finalize 4</div></div>");
  226. }