renderer.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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::rc::Rc;
  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, Rc<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(|| Rc::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. if attr.name == "dangerous_inner_html" {
  68. inner_html = Some(attr);
  69. } else if attr.namespace == Some("style") {
  70. accumulated_dynamic_styles.push(attr);
  71. } else {
  72. match attr.value {
  73. AttributeValue::Text(value) => {
  74. write!(buf, " {}=\"{}\"", attr.name, value)?
  75. }
  76. AttributeValue::Bool(value) => write!(buf, " {}={}", attr.name, value)?,
  77. _ => {}
  78. };
  79. }
  80. }
  81. Segment::Node(idx) => match &template.dynamic_nodes[*idx] {
  82. DynamicNode::Component(node) => {
  83. if self.skip_components {
  84. write!(buf, "<{}><{}/>", node.name, node.name)?;
  85. } else {
  86. let id = node.scope.get().unwrap();
  87. let scope = dom.get_scope(id).unwrap();
  88. let node = scope.root_node();
  89. match node {
  90. RenderReturn::Ready(node) => {
  91. self.render_template(buf, dom, node)?
  92. }
  93. _ => todo!(
  94. "generally, scopes should be sync, only if being traversed"
  95. ),
  96. }
  97. }
  98. }
  99. DynamicNode::Text(text) => {
  100. // in SSR, we are concerned that we can't hunt down the right text node since they might get merged
  101. if self.pre_render {
  102. write!(buf, "<!--#-->")?;
  103. }
  104. write!(
  105. buf,
  106. "{}",
  107. askama_escape::escape(text.value, askama_escape::Html)
  108. )?;
  109. if self.pre_render {
  110. write!(buf, "<!--#-->")?;
  111. }
  112. }
  113. DynamicNode::Fragment(nodes) => {
  114. for child in *nodes {
  115. self.render_template(buf, dom, child)?;
  116. }
  117. }
  118. DynamicNode::Placeholder(_el) => {
  119. if self.pre_render {
  120. write!(buf, "<pre></pre>")?;
  121. }
  122. }
  123. },
  124. Segment::PreRendered(contents) => write!(buf, "{contents}")?,
  125. Segment::StyleMarker { inside_style_tag } => {
  126. if !accumulated_dynamic_styles.is_empty() {
  127. // if we are inside a style tag, we don't need to write the style attribute
  128. if !*inside_style_tag {
  129. write!(buf, " style=\"")?;
  130. }
  131. for attr in &accumulated_dynamic_styles {
  132. match attr.value {
  133. AttributeValue::Text(value) => {
  134. write!(buf, "{}:{};", attr.name, value)?
  135. }
  136. AttributeValue::Bool(value) => {
  137. write!(buf, "{}:{};", attr.name, value)?
  138. }
  139. AttributeValue::Float(f) => write!(buf, "{}:{};", attr.name, f)?,
  140. AttributeValue::Int(i) => write!(buf, "{}:{};", attr.name, i)?,
  141. _ => {}
  142. };
  143. }
  144. if !*inside_style_tag {
  145. write!(buf, "\"")?;
  146. }
  147. // clear the accumulated styles
  148. accumulated_dynamic_styles.clear();
  149. }
  150. }
  151. Segment::InnerHtmlMarker => {
  152. if let Some(inner_html) = inner_html.take() {
  153. let inner_html = &inner_html.value;
  154. match inner_html {
  155. AttributeValue::Text(value) => write!(buf, "{}", value)?,
  156. AttributeValue::Bool(value) => write!(buf, "{}", value)?,
  157. AttributeValue::Float(f) => write!(buf, "{}", f)?,
  158. AttributeValue::Int(i) => write!(buf, "{}", i)?,
  159. _ => {}
  160. }
  161. }
  162. }
  163. }
  164. }
  165. Ok(())
  166. }
  167. }
  168. #[test]
  169. fn to_string_works() {
  170. use dioxus::prelude::*;
  171. fn app(cx: Scope) -> Element {
  172. let dynamic = 123;
  173. let dyn2 = "</diiiiiiiiv>"; // this should be escaped
  174. render! {
  175. div { class: "asdasdasd", class: "asdasdasd", id: "id-{dynamic}",
  176. "Hello world 1 -->" "{dynamic}" "<-- Hello world 2"
  177. div { "nest 1" }
  178. div {}
  179. div { "nest 2" }
  180. "{dyn2}"
  181. (0..5).map(|i| rsx! { div { "finalize {i}" } })
  182. }
  183. }
  184. }
  185. let mut dom = VirtualDom::new(app);
  186. _ = dom.rebuild();
  187. let mut renderer = Renderer::new();
  188. let out = renderer.render(&dom);
  189. for item in renderer.template_cache.iter() {
  190. if item.1.segments.len() > 5 {
  191. assert_eq!(
  192. item.1.segments,
  193. vec![
  194. PreRendered("<div class=\"asdasdasd\" class=\"asdasdasd\"".into(),),
  195. Attr(0,),
  196. StyleMarker {
  197. inside_style_tag: false,
  198. },
  199. PreRendered(">".into()),
  200. InnerHtmlMarker,
  201. PreRendered("Hello world 1 --&gt;".into(),),
  202. Node(0,),
  203. PreRendered(
  204. "&lt;-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>".into(),
  205. ),
  206. Node(1,),
  207. Node(2,),
  208. PreRendered("</div>".into(),),
  209. ]
  210. );
  211. }
  212. }
  213. use Segment::*;
  214. 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>");
  215. }