create.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. use std::cell::Cell;
  2. use crate::factory::RenderReturn;
  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, ScopeId, SuspenseContext, TemplateAttribute};
  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.id) {
  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.id,
  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.id, 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. for node in template.template.roots {
  198. self.create_static_node(node);
  199. }
  200. self.mutations.template_mutations.push(SaveTemplate {
  201. name: template.template.id,
  202. m: template.template.roots.len(),
  203. });
  204. }
  205. pub(crate) fn create_static_node(&mut self, node: &'b TemplateNode<'static>) {
  206. match *node {
  207. // Todo: create the children's template
  208. TemplateNode::Dynamic(_) => self
  209. .mutations
  210. .template_mutations
  211. .push(CreateStaticPlaceholder {}),
  212. TemplateNode::Text(value) => self
  213. .mutations
  214. .template_mutations
  215. .push(CreateStaticText { value }),
  216. TemplateNode::DynamicText { .. } => self
  217. .mutations
  218. .template_mutations
  219. .push(CreateTextPlaceholder),
  220. TemplateNode::Element {
  221. attrs,
  222. children,
  223. namespace,
  224. tag,
  225. ..
  226. } => {
  227. if let Some(namespace) = namespace {
  228. self.mutations
  229. .template_mutations
  230. .push(CreateElementNamespace {
  231. name: tag,
  232. namespace,
  233. });
  234. } else {
  235. self.mutations
  236. .template_mutations
  237. .push(CreateElement { name: tag });
  238. }
  239. self.mutations
  240. .template_mutations
  241. .extend(attrs.iter().filter_map(|attr| match attr {
  242. TemplateAttribute::Static {
  243. name,
  244. value,
  245. namespace,
  246. ..
  247. } => Some(SetStaticAttribute {
  248. name,
  249. value,
  250. ns: *namespace,
  251. }),
  252. _ => None,
  253. }));
  254. if children.is_empty() {
  255. return;
  256. }
  257. children
  258. .iter()
  259. .for_each(|child| self.create_static_node(child));
  260. self.mutations
  261. .template_mutations
  262. .push(AppendChildren { m: children.len() })
  263. }
  264. }
  265. }
  266. pub(crate) fn create_dynamic_node(
  267. &mut self,
  268. template: &'b VNode<'b>,
  269. node: &'b DynamicNode<'b>,
  270. idx: usize,
  271. ) -> usize {
  272. use DynamicNode::*;
  273. match node {
  274. Text(text) => self.create_dynamic_text(template, text, idx),
  275. Fragment(frag) => self.create_fragment(frag),
  276. Placeholder(frag) => self.create_placeholder(frag, template, idx),
  277. Component(component) => self.create_component_node(template, component, idx),
  278. }
  279. }
  280. fn create_dynamic_text(
  281. &mut self,
  282. template: &'b VNode<'b>,
  283. text: &'b VText<'b>,
  284. idx: usize,
  285. ) -> usize {
  286. // Allocate a dynamic element reference for this text node
  287. let new_id = self.next_element(template, template.template.node_paths[idx]);
  288. // Make sure the text node is assigned to the correct element
  289. text.id.set(new_id);
  290. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  291. let value = unsafe { std::mem::transmute(text.value) };
  292. // Add the mutation to the list
  293. self.mutations.push(HydrateText {
  294. id: new_id,
  295. path: &template.template.node_paths[idx][1..],
  296. value,
  297. });
  298. // Since we're hydrating an existing node, we don't create any new nodes
  299. 0
  300. }
  301. pub(crate) fn create_placeholder(
  302. &mut self,
  303. slot: &Cell<ElementId>,
  304. template: &'b VNode<'b>,
  305. idx: usize,
  306. ) -> usize {
  307. // Allocate a dynamic element reference for this text node
  308. let id = self.next_element(template, template.template.node_paths[idx]);
  309. // Make sure the text node is assigned to the correct element
  310. slot.set(id);
  311. // Assign the ID to the existing node in the template
  312. self.mutations.push(AssignId {
  313. path: &template.template.node_paths[idx][1..],
  314. id,
  315. });
  316. // Since the placeholder is already in the DOM, we don't create any new nodes
  317. 0
  318. }
  319. pub(crate) fn create_fragment(&mut self, nodes: &'b [VNode<'b>]) -> usize {
  320. nodes.iter().fold(0, |acc, child| acc + self.create(child))
  321. }
  322. pub(super) fn create_component_node(
  323. &mut self,
  324. template: &'b VNode<'b>,
  325. component: &'b VComponent<'b>,
  326. idx: usize,
  327. ) -> usize {
  328. let props = component
  329. .props
  330. .replace(None)
  331. .expect("Props to always exist when a component is being created");
  332. let unbounded_props = unsafe { std::mem::transmute(props) };
  333. let scope = self.new_scope(unbounded_props).id;
  334. component.scope.set(Some(scope));
  335. let return_nodes = unsafe { self.run_scope(scope).extend_lifetime_ref() };
  336. use RenderReturn::*;
  337. match return_nodes {
  338. Sync(Ok(t)) => self.mount_component(scope, template, t, idx),
  339. Sync(Err(_e)) => todo!("Propogate error upwards"),
  340. Async(_) => self.mount_component_placeholder(template, idx, scope),
  341. }
  342. }
  343. fn mount_component(
  344. &mut self,
  345. scope: ScopeId,
  346. parent: &'b VNode<'b>,
  347. new: &'b VNode<'b>,
  348. idx: usize,
  349. ) -> usize {
  350. // Keep track of how many mutations are in the buffer in case we need to split them out if a suspense boundary
  351. // is encountered
  352. let mutations_to_this_point = self.mutations.len();
  353. // Create the component's root element
  354. let created = self.create_scope(scope, new);
  355. // If there are no suspense leaves below us, then just don't bother checking anything suspense related
  356. if self.collected_leaves.is_empty() {
  357. return created;
  358. }
  359. // If running the scope has collected some leaves and *this* component is a boundary, then handle the suspense
  360. let boundary = match self.scopes[scope.0].has_context::<SuspenseContext>() {
  361. Some(boundary) => boundary,
  362. _ => return created,
  363. };
  364. // Since this is a boundary, use its placeholder within the template as the placeholder for the suspense tree
  365. let new_id = self.next_element(new, parent.template.node_paths[idx]);
  366. // Now connect everything to the boundary
  367. self.scopes[scope.0].placeholder.set(Some(new_id));
  368. // This involves breaking off the mutations to this point, and then creating a new placeholder for the boundary
  369. // Note that we break off dynamic mutations only - since static mutations aren't rendered immediately
  370. let split_off = unsafe {
  371. std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
  372. self.mutations.split_off(mutations_to_this_point),
  373. )
  374. };
  375. boundary.mutations.borrow_mut().edits.extend(split_off);
  376. boundary.created_on_stack.set(created);
  377. boundary
  378. .waiting_on
  379. .borrow_mut()
  380. .extend(self.collected_leaves.drain(..));
  381. // Now assign the placeholder in the DOM
  382. self.mutations.push(AssignId {
  383. id: new_id,
  384. path: &parent.template.node_paths[idx][1..],
  385. });
  386. 0
  387. }
  388. /// Take the rendered nodes from a component and handle them if they were async
  389. ///
  390. /// IE simply assign an ID to the placeholder
  391. fn mount_component_placeholder(
  392. &mut self,
  393. template: &VNode,
  394. idx: usize,
  395. scope: ScopeId,
  396. ) -> usize {
  397. let new_id = self.next_element(template, template.template.node_paths[idx]);
  398. // Set the placeholder of the scope
  399. self.scopes[scope.0].placeholder.set(Some(new_id));
  400. println!(
  401. "assigning id {:?} to path {:?}, template: {:?}",
  402. new_id, &template.template.node_paths, template.template
  403. );
  404. // Since the placeholder is already in the DOM, we don't create any new nodes
  405. self.mutations.push(AssignId {
  406. id: new_id,
  407. path: &template.template.node_paths[idx][1..],
  408. });
  409. 0
  410. }
  411. }