diff.rs 36 KB

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