1
0

diff.rs 40 KB

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