diff.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. use std::any::Any;
  2. use crate::factory::RenderReturn;
  3. use crate::innerlude::{Mutations, VComponent, VFragment, VText};
  4. use crate::virtual_dom::VirtualDom;
  5. use crate::{Attribute, AttributeValue, TemplateNode};
  6. use crate::any_props::VProps;
  7. use DynamicNode::*;
  8. use crate::mutations::Mutation;
  9. use crate::nodes::{DynamicNode, Template, TemplateId};
  10. use crate::scopes::Scope;
  11. use crate::{
  12. any_props::AnyProps,
  13. arena::ElementId,
  14. bump_frame::BumpFrame,
  15. nodes::VNode,
  16. scopes::{ScopeId, ScopeState},
  17. };
  18. use fxhash::{FxHashMap, FxHashSet};
  19. use slab::Slab;
  20. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  21. pub struct DirtyScope {
  22. pub height: u32,
  23. pub id: ScopeId,
  24. }
  25. impl PartialOrd for DirtyScope {
  26. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  27. Some(self.height.cmp(&other.height))
  28. }
  29. }
  30. impl Ord for DirtyScope {
  31. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  32. self.height.cmp(&other.height)
  33. }
  34. }
  35. impl<'b> VirtualDom {
  36. pub fn diff_scope(&mut self, mutations: &mut Mutations<'b>, scope: ScopeId) {
  37. let scope_state = &mut self.scopes[scope.0];
  38. // Load the old and new bump arenas
  39. let cur_arena = scope_state.current_frame();
  40. let prev_arena = scope_state.previous_frame();
  41. // Make sure the nodes arent null (they've been set properly)
  42. // This is a rough check to make sure we're not entering any UB
  43. assert_ne!(
  44. cur_arena.node.get(),
  45. std::ptr::null_mut(),
  46. "Call rebuild before diffing"
  47. );
  48. assert_ne!(
  49. prev_arena.node.get(),
  50. std::ptr::null_mut(),
  51. "Call rebuild before diffing"
  52. );
  53. self.scope_stack.push(scope);
  54. unsafe {
  55. let cur_arena = cur_arena.load_node();
  56. let prev_arena = prev_arena.load_node();
  57. self.diff_maybe_node(mutations, prev_arena, cur_arena);
  58. }
  59. self.scope_stack.pop();
  60. }
  61. fn diff_maybe_node(
  62. &mut self,
  63. m: &mut Mutations<'b>,
  64. left: &'b RenderReturn<'b>,
  65. right: &'b RenderReturn<'b>,
  66. ) {
  67. use RenderReturn::{Async, Sync};
  68. match (left, right) {
  69. // diff
  70. (Sync(Some(l)), Sync(Some(r))) => self.diff_vnode(m, l, r),
  71. // remove old with placeholder
  72. (Sync(Some(l)), Sync(None)) | (Sync(Some(l)), Async(_)) => {
  73. //
  74. let id = self.next_element(l, &[]); // todo!
  75. m.push(Mutation::CreatePlaceholder { id });
  76. self.drop_template(m, l, true);
  77. }
  78. // remove placeholder with nodes
  79. (Sync(None), Sync(Some(_))) => {}
  80. (Async(_), Sync(Some(v))) => {}
  81. // nothing... just transfer the placeholders over
  82. (Async(_), Async(_))
  83. | (Sync(None), Sync(None))
  84. | (Sync(None), Async(_))
  85. | (Async(_), Sync(None)) => {}
  86. }
  87. }
  88. pub fn diff_vnode(
  89. &mut self,
  90. muts: &mut Mutations<'b>,
  91. left_template: &'b VNode<'b>,
  92. right_template: &'b VNode<'b>,
  93. ) {
  94. if left_template.template.id != right_template.template.id {
  95. return self.light_diff_templates(muts, left_template, right_template);
  96. }
  97. for (left_attr, right_attr) in left_template
  98. .dynamic_attrs
  99. .iter()
  100. .zip(right_template.dynamic_attrs.iter())
  101. {
  102. // Move over the ID from the old to the new
  103. right_attr
  104. .mounted_element
  105. .set(left_attr.mounted_element.get());
  106. if left_attr.value != right_attr.value {
  107. // todo: add more types of attribute values
  108. if let AttributeValue::Text(text) = right_attr.value {
  109. muts.push(Mutation::SetAttribute {
  110. id: left_attr.mounted_element.get(),
  111. name: left_attr.name,
  112. value: text,
  113. ns: right_attr.namespace,
  114. });
  115. }
  116. }
  117. }
  118. for (left_node, right_node) in left_template
  119. .dynamic_nodes
  120. .iter()
  121. .zip(right_template.dynamic_nodes.iter())
  122. {
  123. match (left_node, right_node) {
  124. (Component(left), Component(right)) => self.diff_vcomponent(muts, left, right),
  125. (Text(left), Text(right)) => self.diff_vtext(muts, left, right),
  126. (Fragment(left), Fragment(right)) => self.diff_vfragment(muts, left, right),
  127. (Placeholder(left), Placeholder(right)) => right.set(left.get()),
  128. _ => self.replace(muts, left_template, right_template, left_node, right_node),
  129. };
  130. }
  131. }
  132. fn replace(
  133. &mut self,
  134. muts: &mut Mutations<'b>,
  135. left_template: &'b VNode<'b>,
  136. right_template: &'b VNode<'b>,
  137. left: &'b DynamicNode<'b>,
  138. right: &'b DynamicNode<'b>,
  139. ) {
  140. }
  141. fn diff_vcomponent(
  142. &mut self,
  143. muts: &mut Mutations<'b>,
  144. left: &'b VComponent<'b>,
  145. right: &'b VComponent<'b>,
  146. ) {
  147. // Due to how templates work, we should never get two different components. The only way we could enter
  148. // this codepath is through "light_diff", but we check there that the pointers are the same
  149. assert_eq!(left.render_fn, right.render_fn);
  150. /*
  151. let left = rsx!{ Component {} }
  152. let right = rsx!{ Component {} }
  153. */
  154. // Make sure the new vcomponent has the right scopeid associated to it
  155. let scope_id = left.scope.get().unwrap();
  156. right.scope.set(Some(scope_id));
  157. // copy out the box for both
  158. let old = left.props.replace(None).unwrap();
  159. let new = right.props.replace(None).unwrap();
  160. // If the props are static, then we try to memoize by setting the new with the old
  161. // The target scopestate still has the reference to the old props, so there's no need to update anything
  162. // This also implicitly drops the new props since they're not used
  163. if left.static_props && unsafe { old.memoize(new.as_ref()) } {
  164. return right.props.set(Some(old));
  165. }
  166. // If the props are dynamic *or* the memoization failed, then we need to diff the props
  167. // First, move over the props from the old to the new, dropping old props in the process
  168. self.scopes[scope_id.0].props = unsafe { std::mem::transmute(new.as_ref()) };
  169. right.props.set(Some(new));
  170. // Now run the component and diff it
  171. self.run_scope(scope_id);
  172. self.diff_scope(muts, scope_id);
  173. }
  174. /// Lightly diff the two templates, checking only their roots.
  175. ///
  176. /// The goal here is to preserve any existing component state that might exist. This is to preserve some React-like
  177. /// behavior where the component state is preserved when the component is re-rendered.
  178. ///
  179. /// This is implemented by iterating each root, checking if the component is the same, if it is, then diff it.
  180. ///
  181. /// We then pass the new template through "create" which should be smart enough to skip roots.
  182. ///
  183. /// Currently, we only handle the case where the roots are the same component list. If there's any sort of deviation,
  184. /// IE more nodes, less nodes, different nodes, or expressions, then we just replace the whole thing.
  185. ///
  186. /// This is mostly implemented to help solve the issue where the same component is rendered under two different
  187. /// conditions:
  188. ///
  189. /// ```rust
  190. /// if enabled {
  191. /// rsx!{ Component { enabled_sign: "abc" } }
  192. /// } else {
  193. /// rsx!{ Component { enabled_sign: "xyz" } }
  194. /// }
  195. /// ```
  196. ///
  197. /// However, we should not that it's explicit in the docs that this is not a guarantee. If you need to preserve state,
  198. /// then you should be passing in separate props instead.
  199. ///
  200. /// ```
  201. ///
  202. /// let props = if enabled {
  203. /// ComponentProps { enabled_sign: "abc" }
  204. /// } else {
  205. /// ComponentProps { enabled_sign: "xyz" }
  206. /// };
  207. ///
  208. /// rsx! {
  209. /// Component { ..props }
  210. /// }
  211. /// ```
  212. fn light_diff_templates(
  213. &mut self,
  214. muts: &mut Mutations<'b>,
  215. left: &'b VNode<'b>,
  216. right: &'b VNode<'b>,
  217. ) {
  218. if let Some(components) = matching_components(left, right) {
  219. components
  220. .into_iter()
  221. .for_each(|(l, r)| self.diff_vcomponent(muts, l, r))
  222. }
  223. }
  224. /// Diff the two text nodes
  225. ///
  226. /// 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
  227. /// different.
  228. fn diff_vtext(&mut self, muts: &mut Mutations<'b>, left: &'b VText<'b>, right: &'b VText<'b>) {
  229. right.id.set(left.id.get());
  230. if left.value != right.value {
  231. muts.push(Mutation::SetText {
  232. id: left.id.get(),
  233. value: right.value,
  234. });
  235. }
  236. }
  237. fn diff_vfragment(
  238. &mut self,
  239. muts: &mut Mutations<'b>,
  240. left: &'b VFragment<'b>,
  241. right: &'b VFragment<'b>,
  242. ) {
  243. // match (left.nodes, right.nodes) {
  244. // ([], []) => rp.set(lp.get()),
  245. // ([], _) => {
  246. // //
  247. // todo!()
  248. // }
  249. // (_, []) => {
  250. // // if this fragment is the only child of its parent, then we can use the "RemoveAllChildren" mutation
  251. // todo!()
  252. // }
  253. // _ => {
  254. // let new_is_keyed = new[0].key.is_some();
  255. // let old_is_keyed = old[0].key.is_some();
  256. // debug_assert!(
  257. // new.iter().all(|n| n.key.is_some() == new_is_keyed),
  258. // "all siblings must be keyed or all siblings must be non-keyed"
  259. // );
  260. // debug_assert!(
  261. // old.iter().all(|o| o.key.is_some() == old_is_keyed),
  262. // "all siblings must be keyed or all siblings must be non-keyed"
  263. // );
  264. // if new_is_keyed && old_is_keyed {
  265. // self.diff_keyed_children(muts, old, new);
  266. // } else {
  267. // self.diff_non_keyed_children(muts, old, new);
  268. // }
  269. // }
  270. // }
  271. }
  272. // Diff children that are not keyed.
  273. //
  274. // The parent must be on the top of the change list stack when entering this
  275. // function:
  276. //
  277. // [... parent]
  278. //
  279. // the change list stack is in the same state when this function returns.
  280. fn diff_non_keyed_children(
  281. &mut self,
  282. muts: &mut Mutations<'b>,
  283. old: &'b [VNode<'b>],
  284. new: &'b [VNode<'b>],
  285. ) {
  286. use std::cmp::Ordering;
  287. // Handled these cases in `diff_children` before calling this function.
  288. debug_assert!(!new.is_empty());
  289. debug_assert!(!old.is_empty());
  290. match old.len().cmp(&new.len()) {
  291. Ordering::Greater => self.remove_nodes(muts, &old[new.len()..]),
  292. Ordering::Less => todo!(),
  293. // Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
  294. Ordering::Equal => {}
  295. }
  296. for (new, old) in new.iter().zip(old.iter()) {
  297. self.diff_vnode(muts, old, new);
  298. }
  299. }
  300. // Diffing "keyed" children.
  301. //
  302. // With keyed children, we care about whether we delete, move, or create nodes
  303. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  304. // transition animation that makes the virtual DOM diffing algorithm
  305. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  306. // must reuse (or not reuse) the same physical DOM nodes.
  307. //
  308. // This is loosely based on Inferno's keyed patching implementation. However, we
  309. // have to modify the algorithm since we are compiling the diff down into change
  310. // list instructions that will be executed later, rather than applying the
  311. // changes to the DOM directly as we compare virtual DOMs.
  312. //
  313. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  314. //
  315. // The stack is empty upon entry.
  316. fn diff_keyed_children(
  317. &mut self,
  318. muts: &mut Mutations<'b>,
  319. old: &'b [VNode<'b>],
  320. new: &'b [VNode<'b>],
  321. ) {
  322. // if cfg!(debug_assertions) {
  323. // let mut keys = fxhash::FxHashSet::default();
  324. // let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
  325. // keys.clear();
  326. // for child in children {
  327. // let key = child.key;
  328. // debug_assert!(
  329. // key.is_some(),
  330. // "if any sibling is keyed, all siblings must be keyed"
  331. // );
  332. // keys.insert(key);
  333. // }
  334. // debug_assert_eq!(
  335. // children.len(),
  336. // keys.len(),
  337. // "keyed siblings must each have a unique key"
  338. // );
  339. // };
  340. // assert_unique_keys(old);
  341. // assert_unique_keys(new);
  342. // }
  343. // // First up, we diff all the nodes with the same key at the beginning of the
  344. // // children.
  345. // //
  346. // // `shared_prefix_count` is the count of how many nodes at the start of
  347. // // `new` and `old` share the same keys.
  348. // let (left_offset, right_offset) = match self.diff_keyed_ends(muts, old, new) {
  349. // Some(count) => count,
  350. // None => return,
  351. // };
  352. // // Ok, we now hopefully have a smaller range of children in the middle
  353. // // within which to re-order nodes with the same keys, remove old nodes with
  354. // // now-unused keys, and create new nodes with fresh keys.
  355. // let old_middle = &old[left_offset..(old.len() - right_offset)];
  356. // let new_middle = &new[left_offset..(new.len() - right_offset)];
  357. // debug_assert!(
  358. // !((old_middle.len() == new_middle.len()) && old_middle.is_empty()),
  359. // "keyed children must have the same number of children"
  360. // );
  361. // if new_middle.is_empty() {
  362. // // remove the old elements
  363. // self.remove_nodes(muts, old_middle);
  364. // } else if old_middle.is_empty() {
  365. // // there were no old elements, so just create the new elements
  366. // // we need to find the right "foothold" though - we shouldn't use the "append" at all
  367. // if left_offset == 0 {
  368. // // insert at the beginning of the old list
  369. // let foothold = &old[old.len() - right_offset];
  370. // self.create_and_insert_before(new_middle, foothold);
  371. // } else if right_offset == 0 {
  372. // // insert at the end the old list
  373. // let foothold = old.last().unwrap();
  374. // self.create_and_insert_after(new_middle, foothold);
  375. // } else {
  376. // // inserting in the middle
  377. // let foothold = &old[left_offset - 1];
  378. // self.create_and_insert_after(new_middle, foothold);
  379. // }
  380. // } else {
  381. // self.diff_keyed_middle(muts, old_middle, new_middle);
  382. // }
  383. }
  384. // /// Diff both ends of the children that share keys.
  385. // ///
  386. // /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing.
  387. // ///
  388. // /// If there is no offset, then this function returns None and the diffing is complete.
  389. // fn diff_keyed_ends(
  390. // &mut self,
  391. // muts: &mut Renderer<'b>,
  392. // old: &'b [VNode<'b>],
  393. // new: &'b [VNode<'b>],
  394. // ) -> Option<(usize, usize)> {
  395. // let mut left_offset = 0;
  396. // for (old, new) in old.iter().zip(new.iter()) {
  397. // // abort early if we finally run into nodes with different keys
  398. // if old.key != new.key {
  399. // break;
  400. // }
  401. // self.diff_node(muts, old, new);
  402. // left_offset += 1;
  403. // }
  404. // // If that was all of the old children, then create and append the remaining
  405. // // new children and we're finished.
  406. // if left_offset == old.len() {
  407. // self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
  408. // return None;
  409. // }
  410. // // And if that was all of the new children, then remove all of the remaining
  411. // // old children and we're finished.
  412. // if left_offset == new.len() {
  413. // self.remove_nodes(muts, &old[left_offset..]);
  414. // return None;
  415. // }
  416. // // if the shared prefix is less than either length, then we need to walk backwards
  417. // let mut right_offset = 0;
  418. // for (old, new) in old.iter().rev().zip(new.iter().rev()) {
  419. // // abort early if we finally run into nodes with different keys
  420. // if old.key != new.key {
  421. // break;
  422. // }
  423. // self.diff_node(muts, old, new);
  424. // right_offset += 1;
  425. // }
  426. // Some((left_offset, right_offset))
  427. // }
  428. // // The most-general, expensive code path for keyed children diffing.
  429. // //
  430. // // We find the longest subsequence within `old` of children that are relatively
  431. // // ordered the same way in `new` (via finding a longest-increasing-subsequence
  432. // // of the old child's index within `new`). The children that are elements of
  433. // // this subsequence will remain in place, minimizing the number of DOM moves we
  434. // // will have to do.
  435. // //
  436. // // Upon entry to this function, the change list stack must be empty.
  437. // //
  438. // // This function will load the appropriate nodes onto the stack and do diffing in place.
  439. // //
  440. // // Upon exit from this function, it will be restored to that same self.
  441. // #[allow(clippy::too_many_lines)]
  442. // fn diff_keyed_middle(
  443. // &mut self,
  444. // muts: &mut Renderer<'b>,
  445. // old: &'b [VNode<'b>],
  446. // new: &'b [VNode<'b>],
  447. // ) {
  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 let Some(first_old) = old.get(0) {
  494. // self.remove_nodes(muts, &old[1..]);
  495. // let nodes_created = self.create_children(new);
  496. // self.replace_inner(first_old, nodes_created);
  497. // } else {
  498. // // I think this is wrong - why are we appending?
  499. // // only valid of the if there are no trailing elements
  500. // self.create_and_append_children(new);
  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. // todo!("remove node");
  510. // // self.remove_nodes(muts, [child]);
  511. // }
  512. // }
  513. // // 4. Compute the LIS of this list
  514. // let mut lis_sequence = Vec::default();
  515. // lis_sequence.reserve(new_index_to_old_index.len());
  516. // let mut predecessors = vec![0; new_index_to_old_index.len()];
  517. // let mut starts = vec![0; new_index_to_old_index.len()];
  518. // longest_increasing_subsequence::lis_with(
  519. // &new_index_to_old_index,
  520. // &mut lis_sequence,
  521. // |a, b| a < b,
  522. // &mut predecessors,
  523. // &mut starts,
  524. // );
  525. // // the lis comes out backwards, I think. can't quite tell.
  526. // lis_sequence.sort_unstable();
  527. // // 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)
  528. // if lis_sequence.last().map(|f| new_index_to_old_index[*f]) == Some(u32::MAX as usize) {
  529. // lis_sequence.pop();
  530. // }
  531. // for idx in &lis_sequence {
  532. // self.diff_node(muts, &old[new_index_to_old_index[*idx]], &new[*idx]);
  533. // }
  534. // let mut nodes_created = 0;
  535. // // add mount instruction for the first items not covered by the lis
  536. // let last = *lis_sequence.last().unwrap();
  537. // if last < (new.len() - 1) {
  538. // for (idx, new_node) in new[(last + 1)..].iter().enumerate() {
  539. // let new_idx = idx + last + 1;
  540. // let old_index = new_index_to_old_index[new_idx];
  541. // if old_index == u32::MAX as usize {
  542. // nodes_created += self.create(muts, new_node);
  543. // } else {
  544. // self.diff_node(muts, &old[old_index], new_node);
  545. // nodes_created += self.push_all_real_nodes(new_node);
  546. // }
  547. // }
  548. // self.mutations.insert_after(
  549. // self.find_last_element(&new[last]).unwrap(),
  550. // nodes_created as u32,
  551. // );
  552. // nodes_created = 0;
  553. // }
  554. // // for each spacing, generate a mount instruction
  555. // let mut lis_iter = lis_sequence.iter().rev();
  556. // let mut last = *lis_iter.next().unwrap();
  557. // for next in lis_iter {
  558. // if last - next > 1 {
  559. // for (idx, new_node) in new[(next + 1)..last].iter().enumerate() {
  560. // let new_idx = idx + next + 1;
  561. // let old_index = new_index_to_old_index[new_idx];
  562. // if old_index == u32::MAX as usize {
  563. // nodes_created += self.create(muts, new_node);
  564. // } else {
  565. // self.diff_node(muts, &old[old_index], new_node);
  566. // nodes_created += self.push_all_real_nodes(new_node);
  567. // }
  568. // }
  569. // self.mutations.insert_before(
  570. // self.find_first_element(&new[last]).unwrap(),
  571. // nodes_created as u32,
  572. // );
  573. // nodes_created = 0;
  574. // }
  575. // last = *next;
  576. // }
  577. // // add mount instruction for the last items not covered by the lis
  578. // let first_lis = *lis_sequence.first().unwrap();
  579. // if first_lis > 0 {
  580. // for (idx, new_node) in new[..first_lis].iter().enumerate() {
  581. // let old_index = new_index_to_old_index[idx];
  582. // if old_index == u32::MAX as usize {
  583. // nodes_created += self.create_node(new_node);
  584. // } else {
  585. // self.diff_node(muts, &old[old_index], new_node);
  586. // nodes_created += self.push_all_real_nodes(new_node);
  587. // }
  588. // }
  589. // self.mutations.insert_before(
  590. // self.find_first_element(&new[first_lis]).unwrap(),
  591. // nodes_created as u32,
  592. // );
  593. // }
  594. // }
  595. /// Remove these nodes from the dom
  596. /// Wont generate mutations for the inner nodes
  597. fn remove_nodes(&mut self, muts: &mut Mutations<'b>, nodes: &'b [VNode<'b>]) {
  598. //
  599. }
  600. }
  601. fn matching_components<'a>(
  602. left: &'a VNode<'a>,
  603. right: &'a VNode<'a>,
  604. ) -> Option<Vec<(&'a VComponent<'a>, &'a VComponent<'a>)>> {
  605. if left.template.roots.len() != right.template.roots.len() {
  606. return None;
  607. }
  608. // run through the components, ensuring they're the same
  609. left.template
  610. .roots
  611. .iter()
  612. .zip(right.template.roots.iter())
  613. .map(|(l, r)| {
  614. let (l, r) = match (l, r) {
  615. (TemplateNode::Dynamic(l), TemplateNode::Dynamic(r)) => (l, r),
  616. _ => return None,
  617. };
  618. let (l, r) = match (&left.dynamic_nodes[*l], &right.dynamic_nodes[*r]) {
  619. (Component(l), Component(r)) => (l, r),
  620. _ => return None,
  621. };
  622. (l.render_fn == r.render_fn).then(|| (l, r))
  623. })
  624. .collect()
  625. }
  626. /// We can apply various optimizations to dynamic nodes that are the single child of their parent.
  627. ///
  628. /// IE
  629. /// - for text - we can use SetTextContent
  630. /// - for clearning children we can use RemoveChildren
  631. /// - for appending children we can use AppendChildren
  632. fn is_dyn_node_only_child(node: &VNode, idx: usize) -> bool {
  633. let path = node.template.node_paths[idx];
  634. // use a loop to index every static node's children until the path has run out
  635. // only break if the last path index is a dynamic node
  636. let mut static_node = &node.template.roots[path[0] as usize];
  637. for i in 1..path.len() - 1 {
  638. match static_node {
  639. TemplateNode::Element { children, .. } => static_node = &children[path[i] as usize],
  640. _ => return false,
  641. }
  642. }
  643. match static_node {
  644. TemplateNode::Element { children, .. } => children.len() == 1,
  645. _ => false,
  646. }
  647. }