diff.rs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. use crate::{
  2. any_props::AnyProps,
  3. arena::ElementId,
  4. innerlude::{BorrowedAttributeValue, DirtyScope, VComponent, VPlaceholder, VText},
  5. mutations::Mutation,
  6. nodes::RenderReturn,
  7. nodes::{DynamicNode, VNode},
  8. scopes::ScopeId,
  9. virtual_dom::VirtualDom,
  10. Attribute, TemplateNode,
  11. };
  12. use rustc_hash::{FxHashMap, FxHashSet};
  13. use DynamicNode::*;
  14. impl<'b> VirtualDom {
  15. pub(super) fn diff_scope(&mut self, scope: ScopeId) {
  16. self.runtime.scope_stack.borrow_mut().push(scope);
  17. let scope_state = &mut self.get_scope(scope).unwrap();
  18. unsafe {
  19. // Load the old and new bump arenas
  20. let old = scope_state
  21. .previous_frame()
  22. .try_load_node()
  23. .expect("Call rebuild before diffing");
  24. let new = scope_state
  25. .current_frame()
  26. .try_load_node()
  27. .expect("Call rebuild before diffing");
  28. use RenderReturn::{Aborted, Ready};
  29. match (old, new) {
  30. // Normal pathway
  31. (Ready(l), Ready(r)) => self.diff_node(l, r),
  32. // Unwind the mutations if need be
  33. (Ready(l), Aborted(p)) => self.diff_ok_to_err(l, p),
  34. // Just move over the placeholder
  35. (Aborted(l), Aborted(r)) => r.id.set(l.id.get()),
  36. // Placeholder becomes something
  37. // We should also clear the error now
  38. (Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
  39. };
  40. }
  41. self.runtime.scope_stack.borrow_mut().pop();
  42. }
  43. fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
  44. let id = self.next_null();
  45. p.id.set(Some(id));
  46. self.mutations.push(Mutation::CreatePlaceholder { id });
  47. let pre_edits = self.mutations.edits.len();
  48. self.remove_node(l, true);
  49. // We should always have a remove mutation
  50. // Eventually we don't want to generate placeholders, so this might not be true. But it's true today
  51. assert!(self.mutations.edits.len() > pre_edits);
  52. // We want to optimize the replace case to use one less mutation if possible
  53. // Since mutations are done in reverse, the last node removed will be the first in the stack
  54. // Instead of *just* removing it, we can use the replace mutation
  55. match self.mutations.edits.pop().unwrap() {
  56. Mutation::Remove { id } => self.mutations.push(Mutation::ReplaceWith { id, m: 1 }),
  57. _ => panic!("Expected remove mutation from remove_node"),
  58. };
  59. }
  60. fn diff_node(&mut self, left_template: &'b VNode<'b>, right_template: &'b VNode<'b>) {
  61. // If hot reloading is enabled, we need to make sure we're using the latest template
  62. #[cfg(debug_assertions)]
  63. {
  64. let (path, byte_index) = right_template.template.get().name.rsplit_once(':').unwrap();
  65. if let Some(map) = self.templates.get(path) {
  66. let byte_index = byte_index.parse::<usize>().unwrap();
  67. if let Some(&template) = map.get(&byte_index) {
  68. right_template.template.set(template);
  69. if template != left_template.template.get() {
  70. return self.replace(left_template, [right_template]);
  71. }
  72. }
  73. }
  74. }
  75. // If the templates are the same, we don't need to do anything, nor do we want to
  76. if templates_are_the_same(left_template, right_template) {
  77. return;
  78. }
  79. // If the templates are different by name, we need to replace the entire template
  80. if templates_are_different(left_template, right_template) {
  81. return self.light_diff_templates(left_template, right_template);
  82. }
  83. // If the templates are the same, we can diff the attributes and children
  84. // Start with the attributes
  85. left_template
  86. .dynamic_attrs
  87. .iter()
  88. .zip(right_template.dynamic_attrs.iter())
  89. .for_each(|(left_attr, right_attr)| {
  90. // Move over the ID from the old to the new
  91. right_attr
  92. .mounted_element
  93. .set(left_attr.mounted_element.get());
  94. // We want to make sure anything that gets pulled is valid
  95. self.update_template(left_attr.mounted_element.get(), right_template);
  96. // If the attributes are different (or volatile), we need to update them
  97. if left_attr.value != right_attr.value || left_attr.volatile {
  98. self.update_attribute(right_attr, left_attr);
  99. }
  100. });
  101. // Now diff the dynamic nodes
  102. left_template
  103. .dynamic_nodes
  104. .iter()
  105. .zip(right_template.dynamic_nodes.iter())
  106. .for_each(|(left_node, right_node)| {
  107. self.diff_dynamic_node(left_node, right_node, right_template);
  108. });
  109. // Make sure the roots get transferred over while we're here
  110. {
  111. let mut right = right_template.root_ids.borrow_mut();
  112. right.clear();
  113. for &element in left_template.root_ids.borrow().iter() {
  114. right.push(element);
  115. }
  116. }
  117. let root_ids = right_template.root_ids.borrow();
  118. // Update the node refs
  119. for i in 0..root_ids.len() {
  120. if let Some(root_id) = root_ids.get(i) {
  121. self.update_template(*root_id, right_template);
  122. }
  123. }
  124. }
  125. fn diff_dynamic_node(
  126. &mut self,
  127. left_node: &'b DynamicNode<'b>,
  128. right_node: &'b DynamicNode<'b>,
  129. node: &'b VNode<'b>,
  130. ) {
  131. match (left_node, right_node) {
  132. (Text(left), Text(right)) => self.diff_vtext(left, right, node),
  133. (Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
  134. (Placeholder(left), Placeholder(right)) => right.id.set(left.id.get()),
  135. (Component(left), Component(right)) => self.diff_vcomponent(left, right, node),
  136. (Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right),
  137. (Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right),
  138. _ => todo!("This is an usual custom case for dynamic nodes. We don't know how to handle it yet."),
  139. };
  140. }
  141. fn update_attribute(&mut self, right_attr: &'b Attribute<'b>, left_attr: &'b Attribute) {
  142. let name = unsafe { std::mem::transmute(left_attr.name) };
  143. let value: BorrowedAttributeValue<'b> = (&right_attr.value).into();
  144. let value = unsafe { std::mem::transmute(value) };
  145. self.mutations.push(Mutation::SetAttribute {
  146. id: left_attr.mounted_element.get(),
  147. ns: right_attr.namespace,
  148. name,
  149. value,
  150. });
  151. }
  152. fn diff_vcomponent(
  153. &mut self,
  154. left: &'b VComponent<'b>,
  155. right: &'b VComponent<'b>,
  156. right_template: &'b VNode<'b>,
  157. ) {
  158. if std::ptr::eq(left, right) {
  159. return;
  160. }
  161. // Replace components that have different render fns
  162. if left.render_fn != right.render_fn {
  163. return self.replace_vcomponent(right_template, right, left);
  164. }
  165. // Make sure the new vcomponent has the right scopeid associated to it
  166. let scope_id = left.scope.get().unwrap();
  167. right.scope.set(Some(scope_id));
  168. // copy out the box for both
  169. let old_scope = &self.scopes[scope_id.0];
  170. let old = old_scope.props.as_ref();
  171. let new: Box<dyn AnyProps> = right.props.take().unwrap();
  172. let new: Box<dyn AnyProps> = unsafe { std::mem::transmute(new) };
  173. // If the props are static, then we try to memoize by setting the new with the old
  174. // The target scopestate still has the reference to the old props, so there's no need to update anything
  175. // This also implicitly drops the new props since they're not used
  176. if left.static_props && unsafe { old.as_ref().unwrap().memoize(new.as_ref()) } {
  177. tracing::trace!(
  178. "Memoized props for component {:#?} ({})",
  179. scope_id,
  180. old_scope.context().name
  181. );
  182. return;
  183. }
  184. // First, move over the props from the old to the new, dropping old props in the process
  185. self.scopes[scope_id.0].props = Some(new);
  186. // Now run the component and diff it
  187. self.run_scope(scope_id);
  188. self.diff_scope(scope_id);
  189. self.dirty_scopes.remove(&DirtyScope {
  190. height: self.runtime.get_context(scope_id).unwrap().height,
  191. id: scope_id,
  192. });
  193. }
  194. fn replace_vcomponent(
  195. &mut self,
  196. right_template: &'b VNode<'b>,
  197. right: &'b VComponent<'b>,
  198. left: &'b VComponent<'b>,
  199. ) {
  200. let m = self.create_component_node(right_template, right);
  201. let pre_edits = self.mutations.edits.len();
  202. self.remove_component_node(left, true);
  203. assert!(self.mutations.edits.len() > pre_edits);
  204. // We want to optimize the replace case to use one less mutation if possible
  205. // Since mutations are done in reverse, the last node removed will be the first in the stack
  206. // Instead of *just* removing it, we can use the replace mutation
  207. match self.mutations.edits.pop().unwrap() {
  208. Mutation::Remove { id } => self.mutations.push(Mutation::ReplaceWith { id, m }),
  209. at => panic!("Expected remove mutation from remove_node {:#?}", at),
  210. };
  211. }
  212. /// Lightly diff the two templates, checking only their roots.
  213. ///
  214. /// The goal here is to preserve any existing component state that might exist. This is to preserve some React-like
  215. /// behavior where the component state is preserved when the component is re-rendered.
  216. ///
  217. /// This is implemented by iterating each root, checking if the component is the same, if it is, then diff it.
  218. ///
  219. /// We then pass the new template through "create" which should be smart enough to skip roots.
  220. ///
  221. /// Currently, we only handle the case where the roots are the same component list. If there's any sort of deviation,
  222. /// IE more nodes, less nodes, different nodes, or expressions, then we just replace the whole thing.
  223. ///
  224. /// This is mostly implemented to help solve the issue where the same component is rendered under two different
  225. /// conditions:
  226. ///
  227. /// ```rust, ignore
  228. /// if enabled {
  229. /// rsx!{ Component { enabled_sign: "abc" } }
  230. /// } else {
  231. /// rsx!{ Component { enabled_sign: "xyz" } }
  232. /// }
  233. /// ```
  234. ///
  235. /// However, we should not that it's explicit in the docs that this is not a guarantee. If you need to preserve state,
  236. /// then you should be passing in separate props instead.
  237. ///
  238. /// ```rust, ignore
  239. /// let props = if enabled {
  240. /// ComponentProps { enabled_sign: "abc" }
  241. /// } else {
  242. /// ComponentProps { enabled_sign: "xyz" }
  243. /// };
  244. ///
  245. /// rsx! {
  246. /// Component { ..props }
  247. /// }
  248. /// ```
  249. fn light_diff_templates(&mut self, left: &'b VNode<'b>, right: &'b VNode<'b>) {
  250. match matching_components(left, right) {
  251. None => self.replace(left, [right]),
  252. Some(components) => components
  253. .into_iter()
  254. .for_each(|(l, r)| self.diff_vcomponent(l, r, right)),
  255. }
  256. }
  257. /// Diff the two text nodes
  258. ///
  259. /// This just moves the ID of the old node over to the new node, and then sets the text of the new node if it's
  260. /// different.
  261. fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>, node: &'b VNode<'b>) {
  262. let id = left
  263. .id
  264. .get()
  265. .unwrap_or_else(|| self.next_element(node, &[0]));
  266. right.id.set(Some(id));
  267. if left.value != right.value {
  268. let value = unsafe { std::mem::transmute(right.value) };
  269. self.mutations.push(Mutation::SetText { id, value });
  270. }
  271. }
  272. fn diff_non_empty_fragment(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  273. let new_is_keyed = new[0].key.is_some();
  274. let old_is_keyed = old[0].key.is_some();
  275. debug_assert!(
  276. new.iter().all(|n| n.key.is_some() == new_is_keyed),
  277. "all siblings must be keyed or all siblings must be non-keyed"
  278. );
  279. debug_assert!(
  280. old.iter().all(|o| o.key.is_some() == old_is_keyed),
  281. "all siblings must be keyed or all siblings must be non-keyed"
  282. );
  283. if new_is_keyed && old_is_keyed {
  284. self.diff_keyed_children(old, new);
  285. } else {
  286. self.diff_non_keyed_children(old, new);
  287. }
  288. }
  289. // Diff children that are not keyed.
  290. //
  291. // The parent must be on the top of the change list stack when entering this
  292. // function:
  293. //
  294. // [... parent]
  295. //
  296. // the change list stack is in the same state when this function returns.
  297. fn diff_non_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  298. use std::cmp::Ordering;
  299. // Handled these cases in `diff_children` before calling this function.
  300. debug_assert!(!new.is_empty());
  301. debug_assert!(!old.is_empty());
  302. match old.len().cmp(&new.len()) {
  303. Ordering::Greater => self.remove_nodes(&old[new.len()..]),
  304. Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
  305. Ordering::Equal => {}
  306. }
  307. for (new, old) in new.iter().zip(old.iter()) {
  308. self.diff_node(old, new);
  309. }
  310. }
  311. // Diffing "keyed" children.
  312. //
  313. // With keyed children, we care about whether we delete, move, or create nodes
  314. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  315. // transition animation that makes the virtual DOM diffing algorithm
  316. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  317. // must reuse (or not reuse) the same physical DOM nodes.
  318. //
  319. // This is loosely based on Inferno's keyed patching implementation. However, we
  320. // have to modify the algorithm since we are compiling the diff down into change
  321. // list instructions that will be executed later, rather than applying the
  322. // changes to the DOM directly as we compare virtual DOMs.
  323. //
  324. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  325. //
  326. // The stack is empty upon entry.
  327. fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  328. if cfg!(debug_assertions) {
  329. let mut keys = rustc_hash::FxHashSet::default();
  330. let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
  331. keys.clear();
  332. for child in children {
  333. let key = child.key;
  334. debug_assert!(
  335. key.is_some(),
  336. "if any sibling is keyed, all siblings must be keyed"
  337. );
  338. keys.insert(key);
  339. }
  340. debug_assert_eq!(
  341. children.len(),
  342. keys.len(),
  343. "keyed siblings must each have a unique key"
  344. );
  345. };
  346. assert_unique_keys(old);
  347. assert_unique_keys(new);
  348. }
  349. // First up, we diff all the nodes with the same key at the beginning of the
  350. // children.
  351. //
  352. // `shared_prefix_count` is the count of how many nodes at the start of
  353. // `new` and `old` share the same keys.
  354. let (left_offset, right_offset) = match self.diff_keyed_ends(old, new) {
  355. Some(count) => count,
  356. None => return,
  357. };
  358. // Ok, we now hopefully have a smaller range of children in the middle
  359. // within which to re-order nodes with the same keys, remove old nodes with
  360. // now-unused keys, and create new nodes with fresh keys.
  361. let old_middle = &old[left_offset..(old.len() - right_offset)];
  362. let new_middle = &new[left_offset..(new.len() - right_offset)];
  363. debug_assert!(
  364. !((old_middle.len() == new_middle.len()) && old_middle.is_empty()),
  365. "keyed children must have the same number of children"
  366. );
  367. if new_middle.is_empty() {
  368. // remove the old elements
  369. self.remove_nodes(old_middle);
  370. } else if old_middle.is_empty() {
  371. // there were no old elements, so just create the new elements
  372. // we need to find the right "foothold" though - we shouldn't use the "append" at all
  373. if left_offset == 0 {
  374. // insert at the beginning of the old list
  375. let foothold = &old[old.len() - right_offset];
  376. self.create_and_insert_before(new_middle, foothold);
  377. } else if right_offset == 0 {
  378. // insert at the end the old list
  379. let foothold = old.last().unwrap();
  380. self.create_and_insert_after(new_middle, foothold);
  381. } else {
  382. // inserting in the middle
  383. let foothold = &old[left_offset - 1];
  384. self.create_and_insert_after(new_middle, foothold);
  385. }
  386. } else {
  387. self.diff_keyed_middle(old_middle, new_middle);
  388. }
  389. }
  390. /// Diff both ends of the children that share keys.
  391. ///
  392. /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing.
  393. ///
  394. /// If there is no offset, then this function returns None and the diffing is complete.
  395. fn diff_keyed_ends(
  396. &mut self,
  397. old: &'b [VNode<'b>],
  398. new: &'b [VNode<'b>],
  399. ) -> Option<(usize, usize)> {
  400. let mut left_offset = 0;
  401. for (old, new) in old.iter().zip(new.iter()) {
  402. // abort early if we finally run into nodes with different keys
  403. if old.key != new.key {
  404. break;
  405. }
  406. self.diff_node(old, new);
  407. left_offset += 1;
  408. }
  409. // If that was all of the old children, then create and append the remaining
  410. // new children and we're finished.
  411. if left_offset == old.len() {
  412. self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
  413. return None;
  414. }
  415. // And if that was all of the new children, then remove all of the remaining
  416. // old children and we're finished.
  417. if left_offset == new.len() {
  418. self.remove_nodes(&old[left_offset..]);
  419. return None;
  420. }
  421. // if the shared prefix is less than either length, then we need to walk backwards
  422. let mut right_offset = 0;
  423. for (old, new) in old.iter().rev().zip(new.iter().rev()) {
  424. // abort early if we finally run into nodes with different keys
  425. if old.key != new.key {
  426. break;
  427. }
  428. self.diff_node(old, new);
  429. right_offset += 1;
  430. }
  431. Some((left_offset, right_offset))
  432. }
  433. // The most-general, expensive code path for keyed children diffing.
  434. //
  435. // We find the longest subsequence within `old` of children that are relatively
  436. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  437. // of the old child's index within `new`). The children that are elements of
  438. // this subsequence will remain in place, minimizing the number of DOM moves we
  439. // will have to do.
  440. //
  441. // Upon entry to this function, the change list stack must be empty.
  442. //
  443. // This function will load the appropriate nodes onto the stack and do diffing in place.
  444. //
  445. // Upon exit from this function, it will be restored to that same self.
  446. #[allow(clippy::too_many_lines)]
  447. fn diff_keyed_middle(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  448. /*
  449. 1. Map the old keys into a numerical ordering based on indices.
  450. 2. Create a map of old key to its index
  451. 3. Map each new key to the old key, carrying over the old index.
  452. - IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3
  453. - if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist
  454. now, we should have a list of integers that indicates where in the old list the new items map to.
  455. 4. Compute the LIS of this list
  456. - this indicates the longest list of new children that won't need to be moved.
  457. 5. Identify which nodes need to be removed
  458. 6. Identify which nodes will need to be diffed
  459. 7. Going along each item in the new list, create it and insert it before the next closest item in the LIS.
  460. - if the item already existed, just move it to the right place.
  461. 8. Finally, generate instructions to remove any old children.
  462. 9. Generate instructions to finally diff children that are the same between both
  463. */
  464. // 0. Debug sanity checks
  465. // Should have already diffed the shared-key prefixes and suffixes.
  466. debug_assert_ne!(new.first().map(|i| i.key), old.first().map(|i| i.key));
  467. debug_assert_ne!(new.last().map(|i| i.key), old.last().map(|i| i.key));
  468. // 1. Map the old keys into a numerical ordering based on indices.
  469. // 2. Create a map of old key to its index
  470. // IE if the keys were A B C, then we would have (A, 1) (B, 2) (C, 3).
  471. let old_key_to_old_index = old
  472. .iter()
  473. .enumerate()
  474. .map(|(i, o)| (o.key.unwrap(), i))
  475. .collect::<FxHashMap<_, _>>();
  476. let mut shared_keys = FxHashSet::default();
  477. // 3. Map each new key to the old key, carrying over the old index.
  478. let new_index_to_old_index = new
  479. .iter()
  480. .map(|node| {
  481. let key = node.key.unwrap();
  482. if let Some(&index) = old_key_to_old_index.get(&key) {
  483. shared_keys.insert(key);
  484. index
  485. } else {
  486. u32::MAX as usize
  487. }
  488. })
  489. .collect::<Vec<_>>();
  490. // If none of the old keys are reused by the new children, then we remove all the remaining old children and
  491. // create the new children afresh.
  492. if shared_keys.is_empty() {
  493. if old.first().is_some() {
  494. self.remove_nodes(&old[1..]);
  495. self.replace(&old[0], new);
  496. } else {
  497. // I think this is wrong - why are we appending?
  498. // only valid of the if there are no trailing elements
  499. // self.create_and_append_children(new);
  500. todo!("we should never be appending - just creating N");
  501. }
  502. return;
  503. }
  504. // remove any old children that are not shared
  505. // todo: make this an iterator
  506. for child in old {
  507. let key = child.key.unwrap();
  508. if !shared_keys.contains(&key) {
  509. self.remove_node(child, true);
  510. }
  511. }
  512. // 4. Compute the LIS of this list
  513. let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
  514. let mut predecessors = vec![0; new_index_to_old_index.len()];
  515. let mut starts = vec![0; new_index_to_old_index.len()];
  516. longest_increasing_subsequence::lis_with(
  517. &new_index_to_old_index,
  518. &mut lis_sequence,
  519. |a, b| a < b,
  520. &mut predecessors,
  521. &mut starts,
  522. );
  523. // the lis comes out backwards, I think. can't quite tell.
  524. lis_sequence.sort_unstable();
  525. // if a new node gets u32 max and is at the end, then it might be part of our LIS (because u32 max is a valid LIS)
  526. if lis_sequence.last().map(|f| new_index_to_old_index[*f]) == Some(u32::MAX as usize) {
  527. lis_sequence.pop();
  528. }
  529. for idx in &lis_sequence {
  530. self.diff_node(&old[new_index_to_old_index[*idx]], &new[*idx]);
  531. }
  532. let mut nodes_created = 0;
  533. // add mount instruction for the first items not covered by the lis
  534. let last = *lis_sequence.last().unwrap();
  535. if last < (new.len() - 1) {
  536. for (idx, new_node) in new[(last + 1)..].iter().enumerate() {
  537. let new_idx = idx + last + 1;
  538. let old_index = new_index_to_old_index[new_idx];
  539. if old_index == u32::MAX as usize {
  540. nodes_created += self.create(new_node);
  541. } else {
  542. self.diff_node(&old[old_index], new_node);
  543. nodes_created += self.push_all_real_nodes(new_node);
  544. }
  545. }
  546. let id = self.find_last_element(&new[last]);
  547. if nodes_created > 0 {
  548. self.mutations.push(Mutation::InsertAfter {
  549. id,
  550. m: nodes_created,
  551. })
  552. }
  553. nodes_created = 0;
  554. }
  555. // for each spacing, generate a mount instruction
  556. let mut lis_iter = lis_sequence.iter().rev();
  557. let mut last = *lis_iter.next().unwrap();
  558. for next in lis_iter {
  559. if last - next > 1 {
  560. for (idx, new_node) in new[(next + 1)..last].iter().enumerate() {
  561. let new_idx = idx + next + 1;
  562. let old_index = new_index_to_old_index[new_idx];
  563. if old_index == u32::MAX as usize {
  564. nodes_created += self.create(new_node);
  565. } else {
  566. self.diff_node(&old[old_index], new_node);
  567. nodes_created += self.push_all_real_nodes(new_node);
  568. }
  569. }
  570. let id = self.find_first_element(&new[last]);
  571. if nodes_created > 0 {
  572. self.mutations.push(Mutation::InsertBefore {
  573. id,
  574. m: nodes_created,
  575. });
  576. }
  577. nodes_created = 0;
  578. }
  579. last = *next;
  580. }
  581. // add mount instruction for the last items not covered by the lis
  582. let first_lis = *lis_sequence.first().unwrap();
  583. if first_lis > 0 {
  584. for (idx, new_node) in new[..first_lis].iter().enumerate() {
  585. let old_index = new_index_to_old_index[idx];
  586. if old_index == u32::MAX as usize {
  587. nodes_created += self.create(new_node);
  588. } else {
  589. self.diff_node(&old[old_index], new_node);
  590. nodes_created += self.push_all_real_nodes(new_node);
  591. }
  592. }
  593. let id = self.find_first_element(&new[first_lis]);
  594. if nodes_created > 0 {
  595. self.mutations.push(Mutation::InsertBefore {
  596. id,
  597. m: nodes_created,
  598. });
  599. }
  600. }
  601. }
  602. /// Push all the real nodes on the stack
  603. fn push_all_real_nodes(&mut self, node: &'b VNode<'b>) -> usize {
  604. node.template
  605. .get()
  606. .roots
  607. .iter()
  608. .enumerate()
  609. .map(|(idx, _)| {
  610. let node = match node.dynamic_root(idx) {
  611. Some(node) => node,
  612. None => {
  613. self.mutations.push(Mutation::PushRoot {
  614. id: node.root_ids.borrow()[idx],
  615. });
  616. return 1;
  617. }
  618. };
  619. match node {
  620. Text(t) => {
  621. self.mutations.push(Mutation::PushRoot {
  622. id: t.id.get().unwrap(),
  623. });
  624. 1
  625. }
  626. Placeholder(t) => {
  627. self.mutations.push(Mutation::PushRoot {
  628. id: t.id.get().unwrap(),
  629. });
  630. 1
  631. }
  632. Fragment(nodes) => nodes
  633. .iter()
  634. .map(|node| self.push_all_real_nodes(node))
  635. .sum(),
  636. Component(comp) => {
  637. let scope = comp.scope.get().unwrap();
  638. match unsafe {
  639. self.get_scope(scope)
  640. .unwrap()
  641. .root_node()
  642. .extend_lifetime_ref()
  643. } {
  644. RenderReturn::Ready(node) => self.push_all_real_nodes(node),
  645. RenderReturn::Aborted(_node) => todo!(),
  646. }
  647. }
  648. }
  649. })
  650. .sum()
  651. }
  652. fn create_children(&mut self, nodes: impl IntoIterator<Item = &'b VNode<'b>>) -> usize {
  653. nodes
  654. .into_iter()
  655. .fold(0, |acc, child| acc + self.create(child))
  656. }
  657. fn create_and_insert_before(&mut self, new: &'b [VNode<'b>], before: &'b VNode<'b>) {
  658. let m = self.create_children(new);
  659. let id = self.find_first_element(before);
  660. self.mutations.push(Mutation::InsertBefore { id, m })
  661. }
  662. fn create_and_insert_after(&mut self, new: &'b [VNode<'b>], after: &'b VNode<'b>) {
  663. let m = self.create_children(new);
  664. let id = self.find_last_element(after);
  665. self.mutations.push(Mutation::InsertAfter { id, m })
  666. }
  667. /// Simply replace a placeholder with a list of nodes
  668. fn replace_placeholder(
  669. &mut self,
  670. l: &'b VPlaceholder,
  671. r: impl IntoIterator<Item = &'b VNode<'b>>,
  672. ) {
  673. let m = self.create_children(r);
  674. let id = l.id.get().unwrap();
  675. self.mutations.push(Mutation::ReplaceWith { id, m });
  676. self.reclaim(id);
  677. }
  678. fn replace(&mut self, left: &'b VNode<'b>, right: impl IntoIterator<Item = &'b VNode<'b>>) {
  679. let m = self.create_children(right);
  680. let pre_edits = self.mutations.edits.len();
  681. self.remove_node(left, true);
  682. // We should always have a remove mutation
  683. // Eventually we don't want to generate placeholders, so this might not be true. But it's true today
  684. assert!(self.mutations.edits.len() > pre_edits);
  685. // We want to optimize the replace case to use one less mutation if possible
  686. // Since mutations are done in reverse, the last node removed will be the first in the stack
  687. // Instead of *just* removing it, we can use the replace mutation
  688. match self.mutations.edits.pop().unwrap() {
  689. Mutation::Remove { id } => self.mutations.push(Mutation::ReplaceWith { id, m }),
  690. _ => panic!("Expected remove mutation from remove_node"),
  691. };
  692. }
  693. fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder) {
  694. // Create the placeholder first, ensuring we get a dedicated ID for the placeholder
  695. let placeholder = self.next_element(&l[0], &[]);
  696. r.id.set(Some(placeholder));
  697. self.mutations
  698. .push(Mutation::CreatePlaceholder { id: placeholder });
  699. self.remove_nodes(l);
  700. // We want to optimize the replace case to use one less mutation if possible
  701. // Since mutations are done in reverse, the last node removed will be the first in the stack
  702. // Instead of *just* removing it, we can use the replace mutation
  703. match self.mutations.edits.pop().unwrap() {
  704. Mutation::Remove { id } => self.mutations.push(Mutation::ReplaceWith { id, m: 1 }),
  705. _ => panic!("Expected remove mutation from remove_node"),
  706. };
  707. }
  708. /// Remove these nodes from the dom
  709. /// Wont generate mutations for the inner nodes
  710. fn remove_nodes(&mut self, nodes: &'b [VNode<'b>]) {
  711. nodes
  712. .iter()
  713. .rev()
  714. .for_each(|node| self.remove_node(node, true));
  715. }
  716. fn remove_node(&mut self, node: &'b VNode<'b>, gen_muts: bool) {
  717. // Clean up any attributes that have claimed a static node as dynamic for mount/unmounta
  718. // Will not generate mutations!
  719. self.reclaim_attributes(node);
  720. // Remove the nested dynamic nodes
  721. // We don't generate mutations for these, as they will be removed by the parent (in the next line)
  722. // But we still need to make sure to reclaim them from the arena and drop their hooks, etc
  723. self.remove_nested_dyn_nodes(node);
  724. // Clean up the roots, assuming we need to generate mutations for these
  725. // This is done last in order to preserve Node ID reclaim order (reclaim in reverse order of claim)
  726. self.reclaim_roots(node, gen_muts);
  727. }
  728. fn reclaim_roots(&mut self, node: &VNode, gen_muts: bool) {
  729. for (idx, _) in node.template.get().roots.iter().enumerate() {
  730. if let Some(dy) = node.dynamic_root(idx) {
  731. self.remove_dynamic_node(dy, gen_muts);
  732. } else {
  733. let id = node.root_ids.borrow()[idx];
  734. if gen_muts {
  735. self.mutations.push(Mutation::Remove { id });
  736. }
  737. self.reclaim(id);
  738. }
  739. }
  740. }
  741. fn reclaim_attributes(&mut self, node: &VNode) {
  742. let mut id = None;
  743. for (idx, attr) in node.dynamic_attrs.iter().enumerate() {
  744. // We'll clean up the root nodes either way, so don't worry
  745. let path_len = node
  746. .template
  747. .get()
  748. .attr_paths
  749. .get(idx)
  750. .map(|path| path.len());
  751. // if the path is 1 the attribute is in the root, so we don't need to clean it up
  752. // if the path is 0, the attribute is a not attached at all, so we don't need to clean it up
  753. if let Some(len) = path_len {
  754. if (..=1).contains(&len) {
  755. continue;
  756. }
  757. }
  758. let next_id = attr.mounted_element.get();
  759. if id == Some(next_id) {
  760. continue;
  761. }
  762. id = Some(next_id);
  763. self.reclaim(next_id);
  764. }
  765. }
  766. fn remove_nested_dyn_nodes(&mut self, node: &VNode) {
  767. for (idx, dyn_node) in node.dynamic_nodes.iter().enumerate() {
  768. let path_len = node
  769. .template
  770. .get()
  771. .node_paths
  772. .get(idx)
  773. .map(|path| path.len());
  774. // Roots are cleaned up automatically above and nodes with a empty path are placeholders
  775. if let Some(2..) = path_len {
  776. self.remove_dynamic_node(dyn_node, false)
  777. }
  778. }
  779. }
  780. fn remove_dynamic_node(&mut self, node: &DynamicNode, gen_muts: bool) {
  781. match node {
  782. Component(comp) => self.remove_component_node(comp, gen_muts),
  783. Text(t) => self.remove_text_node(t, gen_muts),
  784. Placeholder(t) => self.remove_placeholder(t, gen_muts),
  785. Fragment(nodes) => nodes
  786. .iter()
  787. .for_each(|node| self.remove_node(node, gen_muts)),
  788. };
  789. }
  790. fn remove_placeholder(&mut self, t: &VPlaceholder, gen_muts: bool) {
  791. if let Some(id) = t.id.take() {
  792. if gen_muts {
  793. self.mutations.push(Mutation::Remove { id });
  794. }
  795. self.reclaim(id)
  796. }
  797. }
  798. fn remove_text_node(&mut self, t: &VText, gen_muts: bool) {
  799. if let Some(id) = t.id.take() {
  800. if gen_muts {
  801. self.mutations.push(Mutation::Remove { id });
  802. }
  803. self.reclaim(id)
  804. }
  805. }
  806. fn remove_component_node(&mut self, comp: &VComponent, gen_muts: bool) {
  807. // Remove the component reference from the vcomponent so they're not tied together
  808. let scope = comp
  809. .scope
  810. .take()
  811. .expect("VComponents to always have a scope");
  812. // Remove the component from the dom
  813. match unsafe {
  814. self.get_scope(scope)
  815. .unwrap()
  816. .root_node()
  817. .extend_lifetime_ref()
  818. } {
  819. RenderReturn::Ready(t) => self.remove_node(t, gen_muts),
  820. RenderReturn::Aborted(placeholder) => self.remove_placeholder(placeholder, gen_muts),
  821. };
  822. // Restore the props back to the vcomponent in case it gets rendered again
  823. let props = self.scopes[scope.0].props.take();
  824. *comp.props.borrow_mut() = unsafe { std::mem::transmute(props) };
  825. // Now drop all the resouces
  826. self.drop_scope(scope, false);
  827. }
  828. fn find_first_element(&self, node: &'b VNode<'b>) -> ElementId {
  829. match node.dynamic_root(0) {
  830. None => node.root_ids.borrow()[0],
  831. Some(Text(t)) => t.id.get().unwrap(),
  832. Some(Fragment(t)) => self.find_first_element(&t[0]),
  833. Some(Placeholder(t)) => t.id.get().unwrap(),
  834. Some(Component(comp)) => {
  835. let scope = comp.scope.get().unwrap();
  836. match unsafe {
  837. self.get_scope(scope)
  838. .unwrap()
  839. .root_node()
  840. .extend_lifetime_ref()
  841. } {
  842. RenderReturn::Ready(t) => self.find_first_element(t),
  843. _ => todo!("cannot handle nonstandard nodes"),
  844. }
  845. }
  846. }
  847. }
  848. fn find_last_element(&self, node: &'b VNode<'b>) -> ElementId {
  849. match node.dynamic_root(node.template.get().roots.len() - 1) {
  850. None => *node.root_ids.borrow().last().unwrap(),
  851. Some(Text(t)) => t.id.get().unwrap(),
  852. Some(Fragment(t)) => self.find_last_element(t.last().unwrap()),
  853. Some(Placeholder(t)) => t.id.get().unwrap(),
  854. Some(Component(comp)) => {
  855. let scope = comp.scope.get().unwrap();
  856. match unsafe {
  857. self.get_scope(scope)
  858. .unwrap()
  859. .root_node()
  860. .extend_lifetime_ref()
  861. } {
  862. RenderReturn::Ready(t) => self.find_last_element(t),
  863. _ => todo!("cannot handle nonstandard nodes"),
  864. }
  865. }
  866. }
  867. }
  868. }
  869. /// Are the templates the same?
  870. ///
  871. /// We need to check for the obvious case, and the non-obvious case where the template as cloned
  872. ///
  873. /// We use the pointer of the dynamic_node list in this case
  874. fn templates_are_the_same<'b>(left_template: &'b VNode<'b>, right_template: &'b VNode<'b>) -> bool {
  875. std::ptr::eq(left_template, right_template)
  876. }
  877. fn templates_are_different(left_template: &VNode, right_template: &VNode) -> bool {
  878. let left_template_name = left_template.template.get().name;
  879. let right_template_name = right_template.template.get().name;
  880. // we want to re-create the node if the template name is different by pointer even if the value is the same so that we can detect when hot reloading changes the template
  881. !std::ptr::eq(left_template_name, right_template_name)
  882. }
  883. fn matching_components<'a>(
  884. left: &'a VNode<'a>,
  885. right: &'a VNode<'a>,
  886. ) -> Option<Vec<(&'a VComponent<'a>, &'a VComponent<'a>)>> {
  887. let left_template = left.template.get();
  888. let right_template = right.template.get();
  889. if left_template.roots.len() != right_template.roots.len() {
  890. return None;
  891. }
  892. // run through the components, ensuring they're the same
  893. left_template
  894. .roots
  895. .iter()
  896. .zip(right_template.roots.iter())
  897. .map(|(l, r)| {
  898. let (l, r) = match (l, r) {
  899. (TemplateNode::Dynamic { id: l }, TemplateNode::Dynamic { id: r }) => (l, r),
  900. _ => return None,
  901. };
  902. let (l, r) = match (&left.dynamic_nodes[*l], &right.dynamic_nodes[*r]) {
  903. (Component(l), Component(r)) => (l, r),
  904. _ => return None,
  905. };
  906. Some((l, r))
  907. })
  908. .collect()
  909. }
  910. /// We can apply various optimizations to dynamic nodes that are the single child of their parent.
  911. ///
  912. /// IE
  913. /// - for text - we can use SetTextContent
  914. /// - for clearning children we can use RemoveChildren
  915. /// - for appending children we can use AppendChildren
  916. #[allow(dead_code)]
  917. fn is_dyn_node_only_child(node: &VNode, idx: usize) -> bool {
  918. let template = node.template.get();
  919. let path = template.node_paths[idx];
  920. // use a loop to index every static node's children until the path has run out
  921. // only break if the last path index is a dynamic node
  922. let mut static_node = &template.roots[path[0] as usize];
  923. for i in 1..path.len() - 1 {
  924. match static_node {
  925. TemplateNode::Element { children, .. } => static_node = &children[path[i] as usize],
  926. _ => return false,
  927. }
  928. }
  929. match static_node {
  930. TemplateNode::Element { children, .. } => children.len() == 1,
  931. _ => false,
  932. }
  933. }