create.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. use crate::factory::RenderReturn;
  2. use crate::innerlude::{VComponent, VFragment, VText};
  3. use crate::mutations::Mutation;
  4. use crate::mutations::Mutation::*;
  5. use crate::nodes::VNode;
  6. use crate::nodes::{DynamicNode, TemplateNode};
  7. use crate::virtual_dom::VirtualDom;
  8. use crate::{AttributeValue, ScopeId, SuspenseContext, TemplateAttribute};
  9. impl<'b> VirtualDom {
  10. /// Create a new template [`VNode`] and write it to the [`Mutations`] buffer.
  11. ///
  12. /// This method pushes the ScopeID to the internal scopestack and returns the number of nodes created.
  13. pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize {
  14. self.scope_stack.push(scope);
  15. let out = self.create(template);
  16. self.scope_stack.pop();
  17. out
  18. }
  19. /// Create this template and write its mutations
  20. pub(crate) fn create(&mut self, template: &'b VNode<'b>) -> usize {
  21. // The best renderers will have templates prehydrated and registered
  22. // Just in case, let's create the template using instructions anyways
  23. if !self.templates.contains_key(&template.template.id) {
  24. self.register_template(template);
  25. }
  26. // Walk the roots, creating nodes and assigning IDs
  27. // todo: adjust dynamic nodes to be in the order of roots and then leaves (ie BFS)
  28. let mut dynamic_attrs = template.template.attr_paths.iter().enumerate().peekable();
  29. let mut dynamic_nodes = template.template.node_paths.iter().enumerate().peekable();
  30. let cur_scope = self.scope_stack.last().copied().unwrap();
  31. let mut on_stack = 0;
  32. for (root_idx, root) in template.template.roots.iter().enumerate() {
  33. // We might need to generate an ID for the root node
  34. on_stack += match root {
  35. TemplateNode::DynamicText(id) | TemplateNode::Dynamic(id) => {
  36. match &template.dynamic_nodes[*id] {
  37. // a dynamic text node doesn't replace a template node, instead we create it on the fly
  38. DynamicNode::Text(VText { id: slot, value }) => {
  39. let id = self.next_element(template, template.template.node_paths[*id]);
  40. slot.set(id);
  41. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  42. let unbounded_text = unsafe { std::mem::transmute(*value) };
  43. self.mutations.push(CreateTextNode {
  44. value: unbounded_text,
  45. id,
  46. });
  47. 1
  48. }
  49. DynamicNode::Fragment(VFragment::Empty(slot)) => {
  50. let id = self.next_element(template, template.template.node_paths[*id]);
  51. slot.set(id);
  52. self.mutations.push(CreatePlaceholder { id });
  53. 1
  54. }
  55. DynamicNode::Fragment(VFragment::NonEmpty(_))
  56. | 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. event_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(template, 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(
  206. &mut self,
  207. template: &'b VNode<'b>,
  208. node: &'b TemplateNode<'static>,
  209. ) {
  210. match *node {
  211. // Todo: create the children's template
  212. TemplateNode::Dynamic(_) => self
  213. .mutations
  214. .template_mutations
  215. .push(CreateStaticPlaceholder {}),
  216. TemplateNode::Text(value) => self
  217. .mutations
  218. .template_mutations
  219. .push(CreateStaticText { value }),
  220. TemplateNode::DynamicText { .. } => self
  221. .mutations
  222. .template_mutations
  223. .push(CreateTextPlaceholder),
  224. TemplateNode::Element {
  225. attrs,
  226. children,
  227. namespace,
  228. tag,
  229. ..
  230. } => {
  231. if let Some(namespace) = namespace {
  232. self.mutations
  233. .template_mutations
  234. .push(CreateElementNamespace {
  235. name: tag,
  236. namespace,
  237. });
  238. } else {
  239. self.mutations
  240. .template_mutations
  241. .push(CreateElement { name: tag });
  242. }
  243. self.mutations
  244. .template_mutations
  245. .extend(attrs.into_iter().filter_map(|attr| match attr {
  246. TemplateAttribute::Static {
  247. name,
  248. value,
  249. namespace,
  250. ..
  251. } => Some(SetStaticAttribute {
  252. name,
  253. value,
  254. ns: *namespace,
  255. }),
  256. _ => None,
  257. }));
  258. if children.is_empty() {
  259. return;
  260. }
  261. children
  262. .into_iter()
  263. .for_each(|child| self.create_static_node(template, child));
  264. self.mutations
  265. .template_mutations
  266. .push(AppendChildren { m: children.len() })
  267. }
  268. }
  269. }
  270. pub(crate) fn create_dynamic_node(
  271. &mut self,
  272. template: &'b VNode<'b>,
  273. node: &'b DynamicNode<'b>,
  274. idx: usize,
  275. ) -> usize {
  276. use DynamicNode::*;
  277. match node {
  278. Text(text) => self.create_dynamic_text(template, text, idx),
  279. Fragment(frag) => self.create_fragment(frag, template, idx),
  280. Component(component) => self.create_component_node(template, component, idx),
  281. }
  282. }
  283. fn create_dynamic_text(
  284. &mut self,
  285. template: &'b VNode<'b>,
  286. text: &'b VText<'b>,
  287. idx: usize,
  288. ) -> usize {
  289. // Allocate a dynamic element reference for this text node
  290. let new_id = self.next_element(template, template.template.node_paths[idx]);
  291. // Make sure the text node is assigned to the correct element
  292. text.id.set(new_id);
  293. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  294. let value = unsafe { std::mem::transmute(text.value) };
  295. // Add the mutation to the list
  296. self.mutations.push(HydrateText {
  297. id: new_id,
  298. path: &template.template.node_paths[idx][1..],
  299. value,
  300. });
  301. // Since we're hydrating an existing node, we don't create any new nodes
  302. 0
  303. }
  304. pub(crate) fn create_fragment(
  305. &mut self,
  306. frag: &'b VFragment<'b>,
  307. template: &'b VNode<'b>,
  308. idx: usize,
  309. ) -> usize {
  310. match frag {
  311. VFragment::NonEmpty(nodes) => {
  312. nodes.iter().fold(0, |acc, child| acc + self.create(child))
  313. }
  314. VFragment::Empty(slot) => {
  315. // Allocate a dynamic element reference for this text node
  316. let id = self.next_element(template, template.template.node_paths[idx]);
  317. // Make sure the text node is assigned to the correct element
  318. slot.set(id);
  319. // Assign the ID to the existing node in the template
  320. self.mutations.push(AssignId {
  321. path: &template.template.node_paths[idx][1..],
  322. id,
  323. });
  324. // Since the placeholder is already in the DOM, we don't create any new nodes
  325. 0
  326. }
  327. }
  328. }
  329. pub(super) fn create_component_node(
  330. &mut self,
  331. template: &'b VNode<'b>,
  332. component: &'b VComponent<'b>,
  333. idx: usize,
  334. ) -> usize {
  335. let props = component
  336. .props
  337. .replace(None)
  338. .expect("Props to always exist when a component is being created");
  339. let unbounded_props = unsafe { std::mem::transmute(props) };
  340. let scope = self.new_scope(unbounded_props).id;
  341. component.scope.set(Some(scope));
  342. let return_nodes = unsafe { self.run_scope(scope).extend_lifetime_ref() };
  343. use RenderReturn::*;
  344. match return_nodes {
  345. Sync(Ok(t)) => self.mount_component(scope, template, t, idx),
  346. Sync(Err(_e)) => todo!("Propogate error upwards"),
  347. Async(_) => self.mount_component_placeholder(template, idx, scope),
  348. }
  349. }
  350. fn mount_component(
  351. &mut self,
  352. scope: ScopeId,
  353. parent: &'b VNode<'b>,
  354. new: &'b VNode<'b>,
  355. idx: usize,
  356. ) -> usize {
  357. // Keep track of how many mutations are in the buffer in case we need to split them out if a suspense boundary
  358. // is encountered
  359. let mutations_to_this_point = self.mutations.len();
  360. // Create the component's root element
  361. let created = self.create_scope(scope, new);
  362. // If there are no suspense leaves below us, then just don't bother checking anything suspense related
  363. if self.collected_leaves.is_empty() {
  364. return created;
  365. }
  366. // If running the scope has collected some leaves and *this* component is a boundary, then handle the suspense
  367. let boundary = match self.scopes[scope.0].has_context::<SuspenseContext>() {
  368. Some(boundary) => boundary,
  369. _ => return created,
  370. };
  371. // Since this is a boundary, use its placeholder within the template as the placeholder for the suspense tree
  372. let new_id = self.next_element(new, parent.template.node_paths[idx]);
  373. // Now connect everything to the boundary
  374. self.scopes[scope.0].placeholder.set(Some(new_id));
  375. // This involves breaking off the mutations to this point, and then creating a new placeholder for the boundary
  376. // Note that we break off dynamic mutations only - since static mutations aren't rendered immediately
  377. let split_off = unsafe {
  378. std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
  379. self.mutations.split_off(mutations_to_this_point),
  380. )
  381. };
  382. boundary.mutations.borrow_mut().edits.extend(split_off);
  383. boundary.created_on_stack.set(created);
  384. boundary
  385. .waiting_on
  386. .borrow_mut()
  387. .extend(self.collected_leaves.drain(..));
  388. // Now assign the placeholder in the DOM
  389. self.mutations.push(AssignId {
  390. id: new_id,
  391. path: &parent.template.node_paths[idx][1..],
  392. });
  393. 0
  394. }
  395. /// Take the rendered nodes from a component and handle them if they were async
  396. ///
  397. /// IE simply assign an ID to the placeholder
  398. fn mount_component_placeholder(
  399. &mut self,
  400. template: &VNode,
  401. idx: usize,
  402. scope: ScopeId,
  403. ) -> usize {
  404. let new_id = self.next_element(template, template.template.node_paths[idx]);
  405. // Set the placeholder of the scope
  406. self.scopes[scope.0].placeholder.set(Some(new_id));
  407. println!(
  408. "assigning id {:?} to path {:?}, template: {:?}",
  409. new_id, &template.template.node_paths, template.template
  410. );
  411. // Since the placeholder is already in the DOM, we don't create any new nodes
  412. self.mutations.push(AssignId {
  413. id: new_id,
  414. path: &template.template.node_paths[idx][1..],
  415. });
  416. 0
  417. }
  418. }