create.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. use std::cell::Cell;
  2. use std::rc::Rc;
  3. use crate::innerlude::{VComponent, VText};
  4. use crate::mutations::Mutation;
  5. use crate::mutations::Mutation::*;
  6. use crate::nodes::VNode;
  7. use crate::nodes::{DynamicNode, TemplateNode};
  8. use crate::virtual_dom::VirtualDom;
  9. use crate::{AttributeValue, ElementId, RenderReturn, ScopeId, SuspenseContext};
  10. impl<'b> VirtualDom {
  11. /// Create a new template [`VNode`] and write it to the [`Mutations`] buffer.
  12. ///
  13. /// This method pushes the ScopeID to the internal scopestack and returns the number of nodes created.
  14. pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize {
  15. self.scope_stack.push(scope);
  16. let out = self.create(template);
  17. self.scope_stack.pop();
  18. out
  19. }
  20. /// Create this template and write its mutations
  21. pub(crate) fn create(&mut self, template: &'b VNode<'b>) -> usize {
  22. // The best renderers will have templates prehydrated and registered
  23. // Just in case, let's create the template using instructions anyways
  24. if !self.templates.contains_key(&template.template.name) {
  25. self.register_template(template);
  26. }
  27. // Walk the roots, creating nodes and assigning IDs
  28. // todo: adjust dynamic nodes to be in the order of roots and then leaves (ie BFS)
  29. let mut dynamic_attrs = template.template.attr_paths.iter().enumerate().peekable();
  30. let mut dynamic_nodes = template.template.node_paths.iter().enumerate().peekable();
  31. let cur_scope = self.scope_stack.last().copied().unwrap();
  32. let mut on_stack = 0;
  33. for (root_idx, root) in template.template.roots.iter().enumerate() {
  34. // We might need to generate an ID for the root node
  35. on_stack += match root {
  36. TemplateNode::DynamicText { id } | TemplateNode::Dynamic { id } => {
  37. match &template.dynamic_nodes[*id] {
  38. // a dynamic text node doesn't replace a template node, instead we create it on the fly
  39. DynamicNode::Text(VText { id: slot, value }) => {
  40. let id = self.next_element(template, template.template.node_paths[*id]);
  41. slot.set(id);
  42. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  43. let unbounded_text = unsafe { std::mem::transmute(*value) };
  44. self.mutations.push(CreateTextNode {
  45. value: unbounded_text,
  46. id,
  47. });
  48. 1
  49. }
  50. DynamicNode::Placeholder(slot) => {
  51. let id = self.next_element(template, template.template.node_paths[*id]);
  52. slot.set(id);
  53. self.mutations.push(CreatePlaceholder { id });
  54. 1
  55. }
  56. DynamicNode::Fragment(_) | DynamicNode::Component { .. } => {
  57. self.create_dynamic_node(template, &template.dynamic_nodes[*id], *id)
  58. }
  59. }
  60. }
  61. TemplateNode::Element { .. } | TemplateNode::Text { .. } => {
  62. let this_id = self.next_root(template, root_idx);
  63. template.root_ids[root_idx].set(this_id);
  64. self.mutations.push(LoadTemplate {
  65. name: template.template.name,
  66. index: root_idx,
  67. id: this_id,
  68. });
  69. // we're on top of a node that has a dynamic attribute for a descendant
  70. // Set that attribute now before the stack gets in a weird state
  71. while let Some((mut attr_id, path)) =
  72. dynamic_attrs.next_if(|(_, p)| p[0] == root_idx as u8)
  73. {
  74. // if attribute is on a root node, then we've already created the element
  75. // Else, it's deep in the template and we should create a new id for it
  76. let id = match path.len() {
  77. 1 => this_id,
  78. _ => {
  79. let id = self
  80. .next_element(template, template.template.attr_paths[attr_id]);
  81. self.mutations.push(Mutation::AssignId {
  82. path: &path[1..],
  83. id,
  84. });
  85. id
  86. }
  87. };
  88. loop {
  89. let attribute = template.dynamic_attrs.get(attr_id).unwrap();
  90. attribute.mounted_element.set(id);
  91. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  92. let unbounded_name = unsafe { std::mem::transmute(attribute.name) };
  93. match &attribute.value {
  94. AttributeValue::Text(value) => {
  95. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  96. let unbounded_value = unsafe { std::mem::transmute(*value) };
  97. self.mutations.push(SetAttribute {
  98. name: unbounded_name,
  99. value: unbounded_value,
  100. ns: attribute.namespace,
  101. id,
  102. })
  103. }
  104. AttributeValue::Bool(value) => {
  105. self.mutations.push(SetBoolAttribute {
  106. name: unbounded_name,
  107. value: *value,
  108. id,
  109. })
  110. }
  111. AttributeValue::Listener(_) => {
  112. self.mutations.push(NewEventListener {
  113. // all listeners start with "on"
  114. name: &unbounded_name[2..],
  115. scope: cur_scope,
  116. id,
  117. })
  118. }
  119. AttributeValue::Float(_) => todo!(),
  120. AttributeValue::Int(_) => todo!(),
  121. AttributeValue::Any(_) => todo!(),
  122. AttributeValue::None => todo!(),
  123. }
  124. // Only push the dynamic attributes forward if they match the current path (same element)
  125. match dynamic_attrs.next_if(|(_, p)| *p == path) {
  126. Some((next_attr_id, _)) => attr_id = next_attr_id,
  127. None => break,
  128. }
  129. }
  130. }
  131. // We're on top of a node that has a dynamic child for a descendant
  132. // Skip any node that's a root
  133. let mut start = None;
  134. let mut end = None;
  135. // Collect all the dynamic nodes below this root
  136. // We assign the start and end of the range of dynamic nodes since they area ordered in terms of tree path
  137. //
  138. // [0]
  139. // [1, 1] <---|
  140. // [1, 1, 1] <---| these are the range of dynamic nodes below root 1
  141. // [1, 1, 2] <---|
  142. // [2]
  143. //
  144. // We collect each range and then create them and replace the placeholder in the template
  145. while let Some((idx, p)) =
  146. dynamic_nodes.next_if(|(_, p)| p[0] == root_idx as u8)
  147. {
  148. if p.len() == 1 {
  149. continue;
  150. }
  151. if start.is_none() {
  152. start = Some(idx);
  153. }
  154. end = Some(idx);
  155. }
  156. //
  157. if let (Some(start), Some(end)) = (start, end) {
  158. for idx in start..=end {
  159. let node = &template.dynamic_nodes[idx];
  160. let m = self.create_dynamic_node(template, node, idx);
  161. if m > 0 {
  162. self.mutations.push(ReplacePlaceholder {
  163. m,
  164. path: &template.template.node_paths[idx][1..],
  165. });
  166. }
  167. }
  168. }
  169. // elements create only one node :-)
  170. 1
  171. }
  172. };
  173. }
  174. on_stack
  175. }
  176. /// Insert a new template into the VirtualDom's template registry
  177. fn register_template(&mut self, template: &'b VNode<'b>) {
  178. // First, make sure we mark the template as seen, regardless if we process it
  179. self.templates
  180. .insert(template.template.name, template.template);
  181. // If it's all dynamic nodes, then we don't need to register it
  182. // Quickly run through and see if it's all just dynamic nodes
  183. let dynamic_roots = template
  184. .template
  185. .roots
  186. .iter()
  187. .filter(|root| {
  188. matches!(
  189. root,
  190. TemplateNode::Dynamic { .. } | TemplateNode::DynamicText { .. }
  191. )
  192. })
  193. .count();
  194. if dynamic_roots == template.template.roots.len() {
  195. return;
  196. }
  197. self.mutations.templates.push(template.template);
  198. }
  199. pub(crate) fn create_dynamic_node(
  200. &mut self,
  201. template: &'b VNode<'b>,
  202. node: &'b DynamicNode<'b>,
  203. idx: usize,
  204. ) -> usize {
  205. use DynamicNode::*;
  206. match node {
  207. Text(text) => self.create_dynamic_text(template, text, idx),
  208. Fragment(frag) => self.create_fragment(frag),
  209. Placeholder(frag) => self.create_placeholder(frag, template, idx),
  210. Component(component) => self.create_component_node(template, component, idx),
  211. }
  212. }
  213. fn create_dynamic_text(
  214. &mut self,
  215. template: &'b VNode<'b>,
  216. text: &'b VText<'b>,
  217. idx: usize,
  218. ) -> usize {
  219. // Allocate a dynamic element reference for this text node
  220. let new_id = self.next_element(template, template.template.node_paths[idx]);
  221. // Make sure the text node is assigned to the correct element
  222. text.id.set(new_id);
  223. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  224. let value = unsafe { std::mem::transmute(text.value) };
  225. // Add the mutation to the list
  226. self.mutations.push(HydrateText {
  227. id: new_id,
  228. path: &template.template.node_paths[idx][1..],
  229. value,
  230. });
  231. // Since we're hydrating an existing node, we don't create any new nodes
  232. 0
  233. }
  234. pub(crate) fn create_placeholder(
  235. &mut self,
  236. slot: &Cell<ElementId>,
  237. template: &'b VNode<'b>,
  238. idx: usize,
  239. ) -> usize {
  240. // Allocate a dynamic element reference for this text node
  241. let id = self.next_element(template, template.template.node_paths[idx]);
  242. // Make sure the text node is assigned to the correct element
  243. slot.set(id);
  244. // Assign the ID to the existing node in the template
  245. self.mutations.push(AssignId {
  246. path: &template.template.node_paths[idx][1..],
  247. id,
  248. });
  249. // Since the placeholder is already in the DOM, we don't create any new nodes
  250. 0
  251. }
  252. pub(crate) fn create_fragment(&mut self, nodes: &'b [VNode<'b>]) -> usize {
  253. nodes.iter().fold(0, |acc, child| acc + self.create(child))
  254. }
  255. pub(super) fn create_component_node(
  256. &mut self,
  257. template: &'b VNode<'b>,
  258. component: &'b VComponent<'b>,
  259. idx: usize,
  260. ) -> usize {
  261. let props = component
  262. .props
  263. .replace(None)
  264. .expect("Props to always exist when a component is being created");
  265. let unbounded_props = unsafe { std::mem::transmute(props) };
  266. let scope = self.new_scope(unbounded_props).id;
  267. component.scope.set(Some(scope));
  268. let return_nodes = unsafe { self.run_scope(scope).extend_lifetime_ref() };
  269. use RenderReturn::*;
  270. match return_nodes {
  271. Sync(Ok(t)) => self.mount_component(scope, template, t, idx),
  272. Sync(Err(_e)) => todo!("Propogate error upwards"),
  273. Async(_) => self.mount_component_placeholder(template, idx, scope),
  274. }
  275. }
  276. fn mount_component(
  277. &mut self,
  278. scope: ScopeId,
  279. parent: &'b VNode<'b>,
  280. new: &'b VNode<'b>,
  281. idx: usize,
  282. ) -> usize {
  283. // Keep track of how many mutations are in the buffer in case we need to split them out if a suspense boundary
  284. // is encountered
  285. let mutations_to_this_point = self.mutations.edits.len();
  286. // Create the component's root element
  287. let created = self.create_scope(scope, new);
  288. // If there are no suspense leaves below us, then just don't bother checking anything suspense related
  289. if self.collected_leaves.is_empty() {
  290. return created;
  291. }
  292. // If running the scope has collected some leaves and *this* component is a boundary, then handle the suspense
  293. let boundary = match self.scopes[scope.0].has_context::<Rc<SuspenseContext>>() {
  294. Some(boundary) => boundary,
  295. _ => return created,
  296. };
  297. // Since this is a boundary, use its placeholder within the template as the placeholder for the suspense tree
  298. let new_id = self.next_element(new, parent.template.node_paths[idx]);
  299. // Now connect everything to the boundary
  300. self.scopes[scope.0].placeholder.set(Some(new_id));
  301. // This involves breaking off the mutations to this point, and then creating a new placeholder for the boundary
  302. // Note that we break off dynamic mutations only - since static mutations aren't rendered immediately
  303. let split_off = unsafe {
  304. std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
  305. self.mutations.edits.split_off(mutations_to_this_point),
  306. )
  307. };
  308. boundary.mutations.borrow_mut().edits.extend(split_off);
  309. boundary.created_on_stack.set(created);
  310. boundary
  311. .waiting_on
  312. .borrow_mut()
  313. .extend(self.collected_leaves.drain(..));
  314. // Now assign the placeholder in the DOM
  315. self.mutations.push(AssignId {
  316. id: new_id,
  317. path: &parent.template.node_paths[idx][1..],
  318. });
  319. 0
  320. }
  321. /// Take the rendered nodes from a component and handle them if they were async
  322. ///
  323. /// IE simply assign an ID to the placeholder
  324. fn mount_component_placeholder(
  325. &mut self,
  326. template: &VNode,
  327. idx: usize,
  328. scope: ScopeId,
  329. ) -> usize {
  330. let new_id = self.next_element(template, template.template.node_paths[idx]);
  331. // Set the placeholder of the scope
  332. self.scopes[scope.0].placeholder.set(Some(new_id));
  333. // Since the placeholder is already in the DOM, we don't create any new nodes
  334. self.mutations.push(AssignId {
  335. id: new_id,
  336. path: &template.template.node_paths[idx][1..],
  337. });
  338. 0
  339. }
  340. }