1
0

create.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. use crate::any_props::AnyProps;
  2. use crate::innerlude::{VComponent, VPlaceholder, 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, ElementId, RenderReturn, ScopeId, SuspenseContext};
  9. use std::cell::Cell;
  10. use std::iter::{Enumerate, Peekable};
  11. use std::rc::Rc;
  12. use std::slice;
  13. use TemplateNode::*;
  14. impl<'b> VirtualDom {
  15. /// Create a new template [`VNode`] and write it to the [`Mutations`] buffer.
  16. ///
  17. /// This method pushes the ScopeID to the internal scopestack and returns the number of nodes created.
  18. pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize {
  19. self.scope_stack.push(scope);
  20. let out = self.create(template);
  21. self.scope_stack.pop();
  22. out
  23. }
  24. /// Create this template and write its mutations
  25. pub(crate) fn create(&mut self, node: &'b VNode<'b>) -> usize {
  26. // The best renderers will have templates prehydrated and registered
  27. // Just in case, let's create the template using instructions anyways
  28. if !self.templates.contains_key(&node.template.name) {
  29. self.register_template(node);
  30. }
  31. // we know that this will generate at least one mutation per node
  32. self.mutations.edits.reserve(node.template.roots.len());
  33. // Walk the roots, creating nodes and assigning IDs
  34. // todo: adjust dynamic nodes to be in the order of roots and then leaves (ie BFS)
  35. let mut attrs = node.template.attr_paths.iter().enumerate().peekable();
  36. let mut nodes = node.template.node_paths.iter().enumerate().peekable();
  37. node.template
  38. .roots
  39. .iter()
  40. .enumerate()
  41. .map(|(idx, root)| match root {
  42. DynamicText { id } | Dynamic { id } => {
  43. nodes.next().unwrap();
  44. self.write_dynamic_root(node, *id)
  45. }
  46. Element { .. } => self.write_element_root(node, idx, &mut attrs, &mut nodes),
  47. Text { .. } => self.write_static_text_root(node, idx),
  48. })
  49. .sum()
  50. }
  51. fn write_static_text_root(&mut self, node: &VNode, idx: usize) -> usize {
  52. // Simply just load the template root, no modifications needed
  53. self.load_template_root(node, idx);
  54. // Text producs just one node on the stack
  55. 1
  56. }
  57. fn write_dynamic_root(&mut self, template: &'b VNode<'b>, idx: usize) -> usize {
  58. use DynamicNode::*;
  59. match &template.dynamic_nodes[idx] {
  60. node @ Fragment(_) => self.create_dynamic_node(template, node, idx),
  61. node @ Component { .. } => dbg!(self.create_dynamic_node(template, node, idx)),
  62. Placeholder(VPlaceholder { id }) => {
  63. let id = self.set_slot(template, id, idx);
  64. self.mutations.push(CreatePlaceholder { id });
  65. 1
  66. }
  67. Text(VText { id, value }) => {
  68. let id = self.set_slot(template, id, idx);
  69. self.create_static_text(value, id);
  70. 1
  71. }
  72. }
  73. }
  74. fn create_static_text(&mut self, value: &str, id: ElementId) {
  75. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  76. let unbounded_text: &str = unsafe { std::mem::transmute(value) };
  77. self.mutations.push(CreateTextNode {
  78. value: unbounded_text,
  79. id,
  80. });
  81. }
  82. /// We write all the descndent data for this element
  83. ///
  84. /// Elements can contain other nodes - and those nodes can be dynamic or static
  85. ///
  86. /// We want to make sure we write these nodes while on top of the root
  87. fn write_element_root(
  88. &mut self,
  89. template: &'b VNode<'b>,
  90. root_idx: usize,
  91. dynamic_attrs: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
  92. dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
  93. ) -> usize {
  94. // Load the template root and get the ID for the node on the stack
  95. let root_on_stack = self.load_template_root(template, root_idx);
  96. // Write all the attributes below this root
  97. self.write_attrs_on_root(dynamic_attrs, root_idx, root_on_stack, template);
  98. // Load in all of the placeholder or dynamic content under this root too
  99. self.load_placeholders(dynamic_nodes, root_idx, template);
  100. 1
  101. }
  102. /// Load all of the placeholder nodes for descendents of this root node
  103. ///
  104. /// ```rust, ignore
  105. /// rsx! {
  106. /// div {
  107. /// // This is a placeholder
  108. /// some_value,
  109. ///
  110. /// // Load this too
  111. /// "{some_text}"
  112. /// }
  113. /// }
  114. /// ```
  115. fn load_placeholders(
  116. &mut self,
  117. dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
  118. root_idx: usize,
  119. template: &'b VNode<'b>,
  120. ) {
  121. let (start, end) = match collect_dyn_node_range(dynamic_nodes, root_idx) {
  122. Some((a, b)) => (a, b),
  123. None => {
  124. println!("No dynamic nodes found for root {}", root_idx);
  125. return;
  126. }
  127. };
  128. for idx in (start..=end).rev() {
  129. let m = self.create_dynamic_node(template, &template.dynamic_nodes[idx], idx);
  130. if m > 0 {
  131. // The path is one shorter because the top node is the root
  132. let path = &template.template.node_paths[idx][1..];
  133. self.mutations.push(ReplacePlaceholder { m, path });
  134. }
  135. }
  136. }
  137. fn write_attrs_on_root(
  138. &mut self,
  139. attrs: &mut Peekable<Enumerate<slice::Iter<&'static [u8]>>>,
  140. root_idx: usize,
  141. root: ElementId,
  142. node: &VNode,
  143. ) {
  144. while let Some((mut attr_id, path)) = attrs.next_if(|(_, p)| p[0] == root_idx as u8) {
  145. let id = self.assign_static_node_as_dynamic(path, root, node, attr_id);
  146. loop {
  147. self.write_attribute(&node.dynamic_attrs[attr_id], id);
  148. // Only push the dynamic attributes forward if they match the current path (same element)
  149. match attrs.next_if(|(_, p)| *p == path) {
  150. Some((next_attr_id, _)) => attr_id = next_attr_id,
  151. None => break,
  152. }
  153. }
  154. }
  155. }
  156. fn write_attribute(&mut self, attribute: &crate::Attribute, id: ElementId) {
  157. // Make sure we set the attribute's associated id
  158. attribute.mounted_element.set(id);
  159. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  160. let unbounded_name: &str = unsafe { std::mem::transmute(attribute.name) };
  161. match &attribute.value {
  162. AttributeValue::Text(value) => {
  163. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  164. let unbounded_value: &str = unsafe { std::mem::transmute(*value) };
  165. self.mutations.push(SetAttribute {
  166. name: unbounded_name,
  167. value: unbounded_value,
  168. ns: attribute.namespace,
  169. id,
  170. })
  171. }
  172. AttributeValue::Bool(value) => self.mutations.push(SetBoolAttribute {
  173. name: unbounded_name,
  174. value: *value,
  175. id,
  176. }),
  177. AttributeValue::Listener(_) => {
  178. self.mutations.push(NewEventListener {
  179. // all listeners start with "on"
  180. name: &unbounded_name[2..],
  181. id,
  182. })
  183. }
  184. AttributeValue::Float(_) => todo!(),
  185. AttributeValue::Int(_) => todo!(),
  186. AttributeValue::Any(_) => todo!(),
  187. AttributeValue::None => todo!(),
  188. }
  189. }
  190. fn load_template_root(&mut self, template: &VNode, root_idx: usize) -> ElementId {
  191. // Get an ID for this root since it's a real root
  192. let this_id = self.next_root(template, root_idx);
  193. template.root_ids[root_idx].set(Some(this_id));
  194. self.mutations.push(LoadTemplate {
  195. name: template.template.name,
  196. index: root_idx,
  197. id: this_id,
  198. });
  199. this_id
  200. }
  201. /// We have some dynamic attributes attached to a some node
  202. ///
  203. /// That node needs to be loaded at runtime, so we need to give it an ID
  204. ///
  205. /// If the node in question is on the stack, we just return that ID
  206. ///
  207. /// If the node is not on the stack, we create a new ID for it and assign it
  208. fn assign_static_node_as_dynamic(
  209. &mut self,
  210. path: &'static [u8],
  211. this_id: ElementId,
  212. template: &VNode,
  213. attr_id: usize,
  214. ) -> ElementId {
  215. if path.len() == 1 {
  216. return this_id;
  217. }
  218. // if attribute is on a root node, then we've already created the element
  219. // Else, it's deep in the template and we should create a new id for it
  220. let id = self.next_element(template, template.template.attr_paths[attr_id]);
  221. self.mutations.push(Mutation::AssignId {
  222. path: &path[1..],
  223. id,
  224. });
  225. id
  226. }
  227. /// Insert a new template into the VirtualDom's template registry
  228. fn register_template(&mut self, template: &'b VNode<'b>) {
  229. // First, make sure we mark the template as seen, regardless if we process it
  230. self.templates
  231. .insert(template.template.name, template.template);
  232. // If it's all dynamic nodes, then we don't need to register it
  233. if !template.template.is_completely_dynamic() {
  234. self.mutations.templates.push(template.template);
  235. }
  236. }
  237. pub(crate) fn create_dynamic_node(
  238. &mut self,
  239. template: &'b VNode<'b>,
  240. node: &'b DynamicNode<'b>,
  241. idx: usize,
  242. ) -> usize {
  243. use DynamicNode::*;
  244. match node {
  245. Text(text) => self.create_dynamic_text(template, text, idx),
  246. Fragment(frag) => self.create_fragment(frag),
  247. Placeholder(frag) => self.create_placeholder(frag, template, idx),
  248. Component(component) => self.create_component_node(template, component, idx),
  249. }
  250. }
  251. fn create_dynamic_text(
  252. &mut self,
  253. template: &'b VNode<'b>,
  254. text: &'b VText<'b>,
  255. idx: usize,
  256. ) -> usize {
  257. // Allocate a dynamic element reference for this text node
  258. let new_id = self.next_element(template, template.template.node_paths[idx]);
  259. // Make sure the text node is assigned to the correct element
  260. text.id.set(Some(new_id));
  261. // Safety: we promise not to re-alias this text later on after committing it to the mutation
  262. let value = unsafe { std::mem::transmute(text.value) };
  263. // Add the mutation to the list
  264. self.mutations.push(HydrateText {
  265. id: new_id,
  266. path: &template.template.node_paths[idx][1..],
  267. value,
  268. });
  269. // Since we're hydrating an existing node, we don't create any new nodes
  270. 0
  271. }
  272. pub(crate) fn create_placeholder(
  273. &mut self,
  274. placeholder: &VPlaceholder,
  275. template: &'b VNode<'b>,
  276. idx: usize,
  277. ) -> usize {
  278. // Allocate a dynamic element reference for this text node
  279. let id = self.next_element(template, template.template.node_paths[idx]);
  280. // Make sure the text node is assigned to the correct element
  281. placeholder.id.set(Some(id));
  282. // Assign the ID to the existing node in the template
  283. self.mutations.push(AssignId {
  284. path: &template.template.node_paths[idx][1..],
  285. id,
  286. });
  287. // Since the placeholder is already in the DOM, we don't create any new nodes
  288. 0
  289. }
  290. pub(crate) fn create_fragment(&mut self, nodes: &'b [VNode<'b>]) -> usize {
  291. nodes.iter().map(|child| self.create(child)).sum()
  292. }
  293. pub(super) fn create_component_node(
  294. &mut self,
  295. template: &'b VNode<'b>,
  296. component: &'b VComponent<'b>,
  297. idx: usize,
  298. ) -> usize {
  299. let scope = match component.props.take() {
  300. Some(props) => {
  301. let unbounded_props: Box<dyn AnyProps> = unsafe { std::mem::transmute(props) };
  302. let scope = self.new_scope(unbounded_props, component.name);
  303. scope.id
  304. }
  305. // Component is coming back, it probably still exists, right?
  306. None => component.scope.get().unwrap(),
  307. };
  308. component.scope.set(Some(scope));
  309. let return_nodes = unsafe { self.run_scope(scope).extend_lifetime_ref() };
  310. use RenderReturn::*;
  311. match return_nodes {
  312. Sync(Ok(t)) => self.mount_component(scope, template, t, idx),
  313. Sync(Err(_e)) => todo!("Propogate error upwards"),
  314. Async(_) => self.mount_component_placeholder(template, idx, scope),
  315. }
  316. }
  317. fn mount_component(
  318. &mut self,
  319. scope: ScopeId,
  320. parent: &'b VNode<'b>,
  321. new: &'b VNode<'b>,
  322. idx: usize,
  323. ) -> usize {
  324. // Keep track of how many mutations are in the buffer in case we need to split them out if a suspense boundary
  325. // is encountered
  326. let mutations_to_this_point = self.mutations.edits.len();
  327. // Create the component's root element
  328. let created = self.create_scope(scope, new);
  329. // If there are no suspense leaves below us, then just don't bother checking anything suspense related
  330. if self.collected_leaves.is_empty() {
  331. return created;
  332. }
  333. // If running the scope has collected some leaves and *this* component is a boundary, then handle the suspense
  334. let boundary = match self.scopes[scope.0].has_context::<Rc<SuspenseContext>>() {
  335. Some(boundary) => boundary,
  336. _ => return created,
  337. };
  338. // Since this is a boundary, use its placeholder within the template as the placeholder for the suspense tree
  339. let new_id = self.next_element(new, parent.template.node_paths[idx]);
  340. // Now connect everything to the boundary
  341. self.scopes[scope.0].placeholder.set(Some(new_id));
  342. // This involves breaking off the mutations to this point, and then creating a new placeholder for the boundary
  343. // Note that we break off dynamic mutations only - since static mutations aren't rendered immediately
  344. let split_off = unsafe {
  345. std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
  346. self.mutations.edits.split_off(mutations_to_this_point),
  347. )
  348. };
  349. boundary.mutations.borrow_mut().edits.extend(split_off);
  350. boundary.created_on_stack.set(created);
  351. boundary
  352. .waiting_on
  353. .borrow_mut()
  354. .extend(self.collected_leaves.drain(..));
  355. // Now assign the placeholder in the DOM
  356. self.mutations.push(AssignId {
  357. id: new_id,
  358. path: &parent.template.node_paths[idx][1..],
  359. });
  360. 0
  361. }
  362. /// Take the rendered nodes from a component and handle them if they were async
  363. ///
  364. /// IE simply assign an ID to the placeholder
  365. fn mount_component_placeholder(
  366. &mut self,
  367. template: &VNode,
  368. idx: usize,
  369. scope: ScopeId,
  370. ) -> usize {
  371. let new_id = self.next_element(template, template.template.node_paths[idx]);
  372. // Set the placeholder of the scope
  373. self.scopes[scope.0].placeholder.set(Some(new_id));
  374. // Since the placeholder is already in the DOM, we don't create any new nodes
  375. self.mutations.push(AssignId {
  376. id: new_id,
  377. path: &template.template.node_paths[idx][1..],
  378. });
  379. 0
  380. }
  381. fn set_slot(
  382. &mut self,
  383. template: &'b VNode<'b>,
  384. slot: &'b Cell<Option<ElementId>>,
  385. id: usize,
  386. ) -> ElementId {
  387. let id = self.next_element(template, template.template.node_paths[id]);
  388. slot.set(Some(id));
  389. id
  390. }
  391. }
  392. fn collect_dyn_node_range(
  393. dynamic_nodes: &mut Peekable<Enumerate<slice::Iter<&[u8]>>>,
  394. root_idx: usize,
  395. ) -> Option<(usize, usize)> {
  396. let start = match dynamic_nodes.peek() {
  397. Some((idx, p)) if p[0] == root_idx as u8 => *idx,
  398. _ => return None,
  399. };
  400. let mut end = start;
  401. while let Some((idx, p)) = dynamic_nodes.next_if(|(_, p)| p[0] == root_idx as u8) {
  402. if p.len() == 1 {
  403. continue;
  404. }
  405. end = idx;
  406. }
  407. Some((start, end))
  408. }