diff.rs 44 KB

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