diff.rs 35 KB

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