renderer.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. 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 if BOOL_ATTRS.contains(&attr.name) {
  72. if truthy(&attr.value) {
  73. write!(buf, " {}=", attr.name)?;
  74. write_value(buf, &attr.value)?;
  75. }
  76. } else {
  77. write!(buf, " {}=", attr.name)?;
  78. write_value(buf, &attr.value)?;
  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.mounted_scope().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. write!(buf, "{}:", attr.name)?;
  133. write_value_unquoted(buf, &attr.value)?;
  134. write!(buf, ";")?;
  135. }
  136. if !*inside_style_tag {
  137. write!(buf, "\"")?;
  138. }
  139. // clear the accumulated styles
  140. accumulated_dynamic_styles.clear();
  141. }
  142. }
  143. Segment::InnerHtmlMarker => {
  144. if let Some(inner_html) = inner_html.take() {
  145. let inner_html = &inner_html.value;
  146. match inner_html {
  147. AttributeValue::Text(value) => write!(buf, "{}", value)?,
  148. AttributeValue::Bool(value) => write!(buf, "{}", value)?,
  149. AttributeValue::Float(f) => write!(buf, "{}", f)?,
  150. AttributeValue::Int(i) => write!(buf, "{}", i)?,
  151. _ => {}
  152. }
  153. }
  154. }
  155. }
  156. }
  157. Ok(())
  158. }
  159. }
  160. #[test]
  161. fn to_string_works() {
  162. use dioxus::prelude::*;
  163. fn app(cx: Scope) -> Element {
  164. let dynamic = 123;
  165. let dyn2 = "</diiiiiiiiv>"; // this should be escaped
  166. render! {
  167. div { class: "asdasdasd", class: "asdasdasd", id: "id-{dynamic}",
  168. "Hello world 1 -->" "{dynamic}" "<-- Hello world 2"
  169. div { "nest 1" }
  170. div {}
  171. div { "nest 2" }
  172. "{dyn2}"
  173. (0..5).map(|i| rsx! { div { "finalize {i}" } })
  174. }
  175. }
  176. }
  177. let mut dom = VirtualDom::new(app);
  178. _ = dom.rebuild();
  179. let mut renderer = Renderer::new();
  180. let out = renderer.render(&dom);
  181. for item in renderer.template_cache.iter() {
  182. if item.1.segments.len() > 5 {
  183. assert_eq!(
  184. item.1.segments,
  185. vec![
  186. PreRendered("<div class=\"asdasdasd\" class=\"asdasdasd\"".into(),),
  187. Attr(0,),
  188. StyleMarker {
  189. inside_style_tag: false,
  190. },
  191. PreRendered(">".into()),
  192. InnerHtmlMarker,
  193. PreRendered("Hello world 1 --&gt;".into(),),
  194. Node(0,),
  195. PreRendered(
  196. "&lt;-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>".into(),
  197. ),
  198. Node(1,),
  199. Node(2,),
  200. PreRendered("</div>".into(),),
  201. ]
  202. );
  203. }
  204. }
  205. use Segment::*;
  206. 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>");
  207. }
  208. pub(crate) const BOOL_ATTRS: &[&str] = &[
  209. "allowfullscreen",
  210. "allowpaymentrequest",
  211. "async",
  212. "autofocus",
  213. "autoplay",
  214. "checked",
  215. "controls",
  216. "default",
  217. "defer",
  218. "disabled",
  219. "formnovalidate",
  220. "hidden",
  221. "ismap",
  222. "itemscope",
  223. "loop",
  224. "multiple",
  225. "muted",
  226. "nomodule",
  227. "novalidate",
  228. "open",
  229. "playsinline",
  230. "readonly",
  231. "required",
  232. "reversed",
  233. "selected",
  234. "truespeed",
  235. "webkitdirectory",
  236. ];
  237. pub(crate) fn str_truthy(value: &str) -> bool {
  238. !value.is_empty() && value != "0" && value.to_lowercase() != "false"
  239. }
  240. pub(crate) fn truthy(value: &AttributeValue) -> bool {
  241. match value {
  242. AttributeValue::Text(value) => str_truthy(value),
  243. AttributeValue::Bool(value) => *value,
  244. AttributeValue::Int(value) => *value != 0,
  245. AttributeValue::Float(value) => *value != 0.0,
  246. _ => false,
  247. }
  248. }
  249. pub(crate) fn write_value(buf: &mut impl Write, value: &AttributeValue) -> std::fmt::Result {
  250. match value {
  251. AttributeValue::Text(value) => write!(buf, "\"{}\"", value),
  252. AttributeValue::Bool(value) => write!(buf, "{}", value),
  253. AttributeValue::Int(value) => write!(buf, "{}", value),
  254. AttributeValue::Float(value) => write!(buf, "{}", value),
  255. _ => Ok(()),
  256. }
  257. }
  258. pub(crate) fn write_value_unquoted(
  259. buf: &mut impl Write,
  260. value: &AttributeValue,
  261. ) -> std::fmt::Result {
  262. match value {
  263. AttributeValue::Text(value) => write!(buf, "{}", value),
  264. AttributeValue::Bool(value) => write!(buf, "{}", value),
  265. AttributeValue::Int(value) => write!(buf, "{}", value),
  266. AttributeValue::Float(value) => write!(buf, "{}", value),
  267. _ => Ok(()),
  268. }
  269. }