renderer.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. use super::cache::Segment;
  2. use crate::cache::StringCache;
  3. use dioxus_core::Attribute;
  4. use dioxus_core::{prelude::*, AttributeValue, DynamicNode, RenderReturn};
  5. use std::collections::HashMap;
  6. use std::fmt::Write;
  7. use std::sync::Arc;
  8. /// A virtualdom renderer that caches the templates it has seen for faster rendering
  9. #[derive(Default)]
  10. pub struct Renderer {
  11. /// should we do our best to prettify the output?
  12. pub pretty: bool,
  13. /// Control if elements are written onto a new line
  14. pub newline: bool,
  15. /// Should we sanitize text nodes? (escape HTML)
  16. pub sanitize: bool,
  17. /// Choose to write ElementIDs into elements so the page can be re-hydrated later on
  18. pub pre_render: bool,
  19. // Currently not implemented
  20. // Don't proceed onto new components. Instead, put the name of the component.
  21. pub skip_components: bool,
  22. /// A cache of templates that have been rendered
  23. template_cache: HashMap<&'static str, Arc<StringCache>>,
  24. /// The current dynamic node id for hydration
  25. dynamic_node_id: usize,
  26. }
  27. impl Renderer {
  28. pub fn new() -> Self {
  29. Self::default()
  30. }
  31. pub fn render(&mut self, dom: &VirtualDom) -> String {
  32. let mut buf = String::new();
  33. self.render_to(&mut buf, dom).unwrap();
  34. buf
  35. }
  36. pub fn render_to(&mut self, buf: &mut impl Write, dom: &VirtualDom) -> std::fmt::Result {
  37. self.render_scope(buf, dom, ScopeId::ROOT)
  38. }
  39. pub fn render_scope(
  40. &mut self,
  41. buf: &mut impl Write,
  42. dom: &VirtualDom,
  43. scope: ScopeId,
  44. ) -> std::fmt::Result {
  45. // We should never ever run into async or errored nodes in SSR
  46. // Error boundaries and suspense boundaries will convert these to sync
  47. if let RenderReturn::Ready(node) = dom.get_scope(scope).unwrap().root_node() {
  48. self.dynamic_node_id = 0;
  49. self.render_template(buf, dom, node)?
  50. };
  51. Ok(())
  52. }
  53. fn render_template(
  54. &mut self,
  55. buf: &mut impl Write,
  56. dom: &VirtualDom,
  57. template: &VNode,
  58. ) -> std::fmt::Result {
  59. let entry = self
  60. .template_cache
  61. .entry(template.template.get().name)
  62. .or_insert_with({
  63. let prerender = self.pre_render;
  64. move || Arc::new(StringCache::from_template(template, prerender).unwrap())
  65. })
  66. .clone();
  67. let mut inner_html = None;
  68. // We need to keep track of the dynamic styles so we can insert them into the right place
  69. let mut accumulated_dynamic_styles = Vec::new();
  70. // We need to keep track of the listeners so we can insert them into the right place
  71. let mut accumulated_listeners = Vec::new();
  72. for segment in entry.segments.iter() {
  73. match segment {
  74. Segment::Attr(idx) => {
  75. let attr = &template.dynamic_attrs[*idx];
  76. if attr.name == "dangerous_inner_html" {
  77. inner_html = Some(attr);
  78. } else if attr.namespace == Some("style") {
  79. accumulated_dynamic_styles.push(attr);
  80. } else if BOOL_ATTRS.contains(&attr.name) {
  81. if truthy(&attr.value) {
  82. write!(buf, " {}=", attr.name)?;
  83. write_value(buf, &attr.value)?;
  84. }
  85. } else {
  86. write_attribute(buf, attr)?;
  87. }
  88. if self.pre_render {
  89. if let AttributeValue::Listener(_) = &attr.value {
  90. // The onmounted event doesn't need a DOM listener
  91. if attr.name != "onmounted" {
  92. accumulated_listeners.push(attr.name);
  93. }
  94. }
  95. }
  96. }
  97. Segment::Node(idx) => match &template.dynamic_nodes[*idx] {
  98. DynamicNode::Component(node) => {
  99. if self.skip_components {
  100. write!(buf, "<{}><{}/>", node.name, node.name)?;
  101. } else {
  102. let id = node.mounted_scope().unwrap();
  103. let scope = dom.get_scope(id).unwrap();
  104. let node = scope.root_node();
  105. match node {
  106. RenderReturn::Ready(node) => {
  107. self.render_template(buf, dom, node)?
  108. }
  109. _ => todo!(
  110. "generally, scopes should be sync, only if being traversed"
  111. ),
  112. }
  113. }
  114. }
  115. DynamicNode::Text(text) => {
  116. // in SSR, we are concerned that we can't hunt down the right text node since they might get merged
  117. if self.pre_render {
  118. write!(buf, "<!--node-id{}-->", self.dynamic_node_id)?;
  119. self.dynamic_node_id += 1;
  120. }
  121. write!(
  122. buf,
  123. "{}",
  124. askama_escape::escape(text.value, askama_escape::Html)
  125. )?;
  126. if self.pre_render {
  127. write!(buf, "<!--#-->")?;
  128. }
  129. }
  130. DynamicNode::Fragment(nodes) => {
  131. for child in *nodes {
  132. self.render_template(buf, dom, child)?;
  133. }
  134. }
  135. DynamicNode::Placeholder(_) => {
  136. if self.pre_render {
  137. write!(
  138. buf,
  139. "<pre data-node-hydration={}></pre>",
  140. self.dynamic_node_id
  141. )?;
  142. self.dynamic_node_id += 1;
  143. }
  144. }
  145. },
  146. Segment::PreRendered(contents) => write!(buf, "{contents}")?,
  147. Segment::StyleMarker { inside_style_tag } => {
  148. if !accumulated_dynamic_styles.is_empty() {
  149. // if we are inside a style tag, we don't need to write the style attribute
  150. if !*inside_style_tag {
  151. write!(buf, " style=\"")?;
  152. }
  153. for attr in &accumulated_dynamic_styles {
  154. write!(buf, "{}:", attr.name)?;
  155. write_value_unquoted(buf, &attr.value)?;
  156. write!(buf, ";")?;
  157. }
  158. if !*inside_style_tag {
  159. write!(buf, "\"")?;
  160. }
  161. // clear the accumulated styles
  162. accumulated_dynamic_styles.clear();
  163. }
  164. }
  165. Segment::InnerHtmlMarker => {
  166. if let Some(inner_html) = inner_html.take() {
  167. let inner_html = &inner_html.value;
  168. match inner_html {
  169. AttributeValue::Text(value) => write!(buf, "{}", value)?,
  170. AttributeValue::Bool(value) => write!(buf, "{}", value)?,
  171. AttributeValue::Float(f) => write!(buf, "{}", f)?,
  172. AttributeValue::Int(i) => write!(buf, "{}", i)?,
  173. _ => {}
  174. }
  175. }
  176. }
  177. Segment::AttributeNodeMarker => {
  178. // first write the id
  179. write!(buf, "{}", self.dynamic_node_id)?;
  180. self.dynamic_node_id += 1;
  181. // then write any listeners
  182. for name in accumulated_listeners.drain(..) {
  183. write!(buf, ",{}:", &name[2..])?;
  184. write!(buf, "{}", dioxus_html::event_bubbles(name) as u8)?;
  185. }
  186. }
  187. Segment::RootNodeMarker => {
  188. write!(buf, "{}", self.dynamic_node_id)?;
  189. self.dynamic_node_id += 1
  190. }
  191. }
  192. }
  193. Ok(())
  194. }
  195. }
  196. #[test]
  197. fn to_string_works() {
  198. use dioxus::prelude::*;
  199. fn app(cx: Scope) -> Element {
  200. let dynamic = 123;
  201. let dyn2 = "</diiiiiiiiv>"; // this should be escaped
  202. render! {
  203. div { class: "asdasdasd", class: "asdasdasd", id: "id-{dynamic}",
  204. "Hello world 1 -->"
  205. "{dynamic}"
  206. "<-- Hello world 2"
  207. div { "nest 1" }
  208. div {}
  209. div { "nest 2" }
  210. "{dyn2}"
  211. (0..5).map(|i| rsx! { div { "finalize {i}" } })
  212. }
  213. }
  214. }
  215. let mut dom = VirtualDom::new(app);
  216. _ = dom.rebuild();
  217. let mut renderer = Renderer::new();
  218. let out = renderer.render(&dom);
  219. for item in renderer.template_cache.iter() {
  220. if item.1.segments.len() > 5 {
  221. assert_eq!(
  222. item.1.segments,
  223. vec![
  224. PreRendered("<div class=\"asdasdasd\" class=\"asdasdasd\"".into(),),
  225. Attr(0,),
  226. StyleMarker {
  227. inside_style_tag: false,
  228. },
  229. PreRendered(">".into()),
  230. InnerHtmlMarker,
  231. PreRendered("Hello world 1 --&gt;".into(),),
  232. Node(0,),
  233. PreRendered(
  234. "&lt;-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>".into(),
  235. ),
  236. Node(1,),
  237. Node(2,),
  238. PreRendered("</div>".into(),),
  239. ]
  240. );
  241. }
  242. }
  243. use Segment::*;
  244. 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>");
  245. }
  246. pub(crate) const BOOL_ATTRS: &[&str] = &[
  247. "allowfullscreen",
  248. "allowpaymentrequest",
  249. "async",
  250. "autofocus",
  251. "autoplay",
  252. "checked",
  253. "controls",
  254. "default",
  255. "defer",
  256. "disabled",
  257. "formnovalidate",
  258. "hidden",
  259. "ismap",
  260. "itemscope",
  261. "loop",
  262. "multiple",
  263. "muted",
  264. "nomodule",
  265. "novalidate",
  266. "open",
  267. "playsinline",
  268. "readonly",
  269. "required",
  270. "reversed",
  271. "selected",
  272. "truespeed",
  273. "webkitdirectory",
  274. ];
  275. pub(crate) fn str_truthy(value: &str) -> bool {
  276. !value.is_empty() && value != "0" && value.to_lowercase() != "false"
  277. }
  278. pub(crate) fn truthy(value: &AttributeValue) -> bool {
  279. match value {
  280. AttributeValue::Text(value) => str_truthy(value),
  281. AttributeValue::Bool(value) => *value,
  282. AttributeValue::Int(value) => *value != 0,
  283. AttributeValue::Float(value) => *value != 0.0,
  284. _ => false,
  285. }
  286. }
  287. pub(crate) fn write_attribute(buf: &mut impl Write, attr: &Attribute) -> std::fmt::Result {
  288. let name = &attr.name;
  289. match attr.value {
  290. AttributeValue::Text(value) => write!(buf, " {name}=\"{value}\""),
  291. AttributeValue::Bool(value) => write!(buf, " {name}={value}"),
  292. AttributeValue::Int(value) => write!(buf, " {name}={value}"),
  293. AttributeValue::Float(value) => write!(buf, " {name}={value}"),
  294. _ => Ok(()),
  295. }
  296. }
  297. pub(crate) fn write_value(buf: &mut impl Write, value: &AttributeValue) -> std::fmt::Result {
  298. match value {
  299. AttributeValue::Text(value) => write!(buf, "\"{}\"", value),
  300. AttributeValue::Bool(value) => write!(buf, "{}", value),
  301. AttributeValue::Int(value) => write!(buf, "{}", value),
  302. AttributeValue::Float(value) => write!(buf, "{}", value),
  303. _ => Ok(()),
  304. }
  305. }
  306. pub(crate) fn write_value_unquoted(
  307. buf: &mut impl Write,
  308. value: &AttributeValue,
  309. ) -> std::fmt::Result {
  310. match value {
  311. AttributeValue::Text(value) => write!(buf, "{}", value),
  312. AttributeValue::Bool(value) => write!(buf, "{}", value),
  313. AttributeValue::Int(value) => write!(buf, "{}", value),
  314. AttributeValue::Float(value) => write!(buf, "{}", value),
  315. _ => Ok(()),
  316. }
  317. }