diff.rs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. #![warn(clippy::pedantic)]
  2. #![allow(clippy::cast_possible_truncation)]
  3. //! This module contains the stateful [`DiffState`] and all methods to diff [`VNodes`], their properties, and their children.
  4. //!
  5. //! The [`DiffState`] calculates the diffs between the old and new frames, updates the new nodes, and generates a set
  6. //! of mutations for the [`RealDom`] to apply.
  7. //!
  8. //! ## Notice:
  9. //!
  10. //! The inspiration and code for this module was originally taken from Dodrio (@fitzgen) and then modified to support
  11. //! Components, Fragments, Suspense, [`SubTree`] memoization, incremental diffing, cancellation, [`NodeRefs`], pausing, priority
  12. //! scheduling, and additional batching operations.
  13. //!
  14. //! ## Implementation Details:
  15. //!
  16. //! ### IDs for elements
  17. //! --------------------
  18. //! All nodes are addressed by their IDs. The [`RealDom`] provides an imperative interface for making changes to these nodes.
  19. //! We don't necessarily require that DOM changes happen instantly during the diffing process, so the implementor may choose
  20. //! to batch nodes if it is more performant for their application. The element IDs are indices into the internal element
  21. //! array. The expectation is that implementors will use the ID as an index into a Vec of real nodes, allowing for passive
  22. //! garbage collection as the [`VirtualDOM`] replaces old nodes.
  23. //!
  24. //! When new vnodes are created through `cx.render`, they won't know which real node they correspond to. During diffing,
  25. //! we always make sure to copy over the ID. If we don't do this properly, the [`ElementId`] will be populated incorrectly
  26. //! and brick the user's page.
  27. //!
  28. //! ### Fragment Support
  29. //! --------------------
  30. //! Fragments (nodes without a parent) are supported through a combination of "replace with" and anchor vnodes. Fragments
  31. //! can be particularly challenging when they are empty, so the anchor node lets us "reserve" a spot for the empty
  32. //! fragment to be replaced with when it is no longer empty. This is guaranteed by logic in the [`NodeFactory`] - it is
  33. //! impossible to craft a fragment with 0 elements - they must always have at least a single placeholder element. Adding
  34. //! "dummy" nodes _is_ inefficient, but it makes our diffing algorithm faster and the implementation is completely up to
  35. //! the platform.
  36. //!
  37. //! Other implementations either don't support fragments or use a "child + sibling" pattern to represent them. Our code is
  38. //! vastly simpler and more performant when we can just create a placeholder element while the fragment has no children.
  39. //!
  40. //! ### Suspense
  41. //! ------------
  42. //! Dioxus implements Suspense slightly differently than React. In React, each fiber is manually progressed until it runs
  43. //! into a promise-like value. React will then work on the next "ready" fiber, checking back on the previous fiber once
  44. //! it has finished its new work. In Dioxus, we use a similar approach, but try to completely render the tree before
  45. //! switching sub-fibers. Instead, each future is submitted into a futures-queue and the node is manually loaded later on.
  46. //! Due to the frequent calls to [`yield_now`] we can get the pure "fetch-as-you-render" behavior of React Fiber.
  47. //!
  48. //! We're able to use this approach because we use placeholder nodes - futures that aren't ready still get submitted to
  49. //! DOM, but as a placeholder.
  50. //!
  51. //! Right now, the "suspense" queue is intertwined with hooks. In the future, we should allow any future to drive attributes
  52. //! and contents, without the need for the [`use_suspense`] hook. In the interim, this is the quickest way to get Suspense working.
  53. //!
  54. //! ## Subtree Memoization
  55. //! -----------------------
  56. //! We also employ "subtree memoization" which saves us from having to check trees which hold no dynamic content. We can
  57. //! detect if a subtree is "static" by checking if its children are "static". Since we dive into the tree depth-first, the
  58. //! calls to "create" propagate this information upwards. Structures like the one below are entirely static:
  59. //! ```rust, ignore
  60. //! rsx!( div { class: "hello world", "this node is entirely static" } )
  61. //! ```
  62. //! Because the subtrees won't be diffed, their "real node" data will be stale (invalid), so it's up to the reconciler to
  63. //! track nodes created in a scope and clean up all relevant data. Support for this is currently WIP and depends on comp-time
  64. //! hashing of the subtree from the rsx! macro. We do a very limited form of static analysis via static string pointers as
  65. //! a way of short-circuiting the most expensive checks.
  66. //!
  67. //! ## Bloom Filter and Heuristics
  68. //! ------------------------------
  69. //! For all components, we employ some basic heuristics to speed up allocations and pre-size bump arenas. The heuristics are
  70. //! currently very rough, but will get better as time goes on. The information currently tracked includes the size of a
  71. //! bump arena after first render, the number of hooks, and the number of nodes in the tree.
  72. //!
  73. //! ## Garbage Collection
  74. //! ---------------------
  75. //! Dioxus uses a passive garbage collection system to clean up old nodes once the work has been completed. This garbage
  76. //! collection is done internally once the main diffing work is complete. After the "garbage" is collected, Dioxus will then
  77. //! start to re-use old keys for new nodes. This results in a passive memory management system that is very efficient.
  78. //!
  79. //! The IDs used by the key/map are just an index into a Vec. This means that Dioxus will drive the key allocation strategy
  80. //! so the client only needs to maintain a simple list of nodes. By default, Dioxus will not manually clean up old nodes
  81. //! for the client. As new nodes are created, old nodes will be over-written.
  82. //!
  83. //! ## Further Reading and Thoughts
  84. //! ----------------------------
  85. //! There are more ways of increasing diff performance here that are currently not implemented.
  86. //! - Strong memoization of subtrees.
  87. //! - Guided diffing.
  88. //! - Certain web-dom-specific optimizations.
  89. //!
  90. //! More info on how to improve this diffing algorithm:
  91. //! - <https://hacks.mozilla.org/2019/03/fast-bump-allocated-virtual-doms-with-rust-and-wasm/>
  92. use crate::innerlude::{
  93. AnyProps, ElementId, Mutations, ScopeArena, ScopeId, VComponent, VElement, VFragment, VNode,
  94. VPlaceholder, VText,
  95. };
  96. use fxhash::{FxHashMap, FxHashSet};
  97. use smallvec::{smallvec, SmallVec};
  98. pub(crate) struct DiffState<'bump> {
  99. pub(crate) scopes: &'bump ScopeArena,
  100. pub(crate) mutations: Mutations<'bump>,
  101. pub(crate) force_diff: bool,
  102. pub(crate) element_stack: SmallVec<[ElementId; 10]>,
  103. pub(crate) scope_stack: SmallVec<[ScopeId; 5]>,
  104. }
  105. impl<'b> DiffState<'b> {
  106. pub fn new(scopes: &'b ScopeArena) -> Self {
  107. Self {
  108. scopes,
  109. mutations: Mutations::new(),
  110. force_diff: false,
  111. element_stack: smallvec![],
  112. scope_stack: smallvec![],
  113. }
  114. }
  115. pub fn diff_scope(&mut self, scopeid: ScopeId) {
  116. let (old, new) = (self.scopes.wip_head(scopeid), self.scopes.fin_head(scopeid));
  117. self.scope_stack.push(scopeid);
  118. let scope = self.scopes.get_scope(scopeid).unwrap();
  119. self.element_stack.push(scope.container);
  120. self.diff_node(old, new);
  121. self.mutations.mark_dirty_scope(scopeid);
  122. }
  123. pub fn diff_node(&mut self, old_node: &'b VNode<'b>, new_node: &'b VNode<'b>) {
  124. use VNode::{Component, Element, Fragment, Placeholder, Text};
  125. match (old_node, new_node) {
  126. // Check the most common cases first
  127. // these are *actual* elements, not wrappers around lists
  128. (Text(old), Text(new)) => {
  129. if std::ptr::eq(old, new) {
  130. return;
  131. }
  132. let root = old
  133. .id
  134. .get()
  135. .expect("existing text nodes should have an ElementId");
  136. if old.text != new.text {
  137. self.mutations.set_text(new.text, root.as_u64());
  138. }
  139. self.scopes.update_node(new_node, root);
  140. new.id.set(Some(root));
  141. }
  142. (Placeholder(old), Placeholder(new)) => {
  143. if std::ptr::eq(old, new) {
  144. return;
  145. }
  146. let root = old
  147. .id
  148. .get()
  149. .expect("existing placeholder nodes should have an ElementId");
  150. self.scopes.update_node(new_node, root);
  151. new.id.set(Some(root));
  152. }
  153. (Element(old), Element(new)) => {
  154. if std::ptr::eq(old, new) {
  155. return;
  156. }
  157. self.diff_element_nodes(old, new, old_node, new_node);
  158. }
  159. // These two sets are pointers to nodes but are not actually nodes themselves
  160. (Component(old), Component(new)) => {
  161. if std::ptr::eq(old, new) {
  162. return;
  163. }
  164. self.diff_component_nodes(old_node, new_node, *old, *new);
  165. }
  166. (Fragment(old), Fragment(new)) => {
  167. if std::ptr::eq(old, new) {
  168. return;
  169. }
  170. self.diff_fragment_nodes(old, new);
  171. }
  172. // Anything else is just a basic replace and create
  173. (
  174. Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
  175. Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
  176. ) => self.replace_node(old_node, new_node),
  177. }
  178. }
  179. pub fn create_node(&mut self, node: &'b VNode<'b>) -> usize {
  180. match node {
  181. VNode::Text(vtext) => self.create_text_node(vtext, node),
  182. VNode::Placeholder(anchor) => self.create_anchor_node(anchor, node),
  183. VNode::Element(element) => self.create_element_node(element, node),
  184. VNode::Fragment(frag) => self.create_fragment_node(frag),
  185. VNode::Component(component) => self.create_component_node(*component),
  186. }
  187. }
  188. fn create_text_node(&mut self, text: &'b VText<'b>, node: &'b VNode<'b>) -> usize {
  189. let real_id = self.scopes.reserve_node(node);
  190. text.id.set(Some(real_id));
  191. self.mutations.create_text_node(text.text, real_id);
  192. 1
  193. }
  194. fn create_anchor_node(&mut self, anchor: &'b VPlaceholder, node: &'b VNode<'b>) -> usize {
  195. let real_id = self.scopes.reserve_node(node);
  196. anchor.id.set(Some(real_id));
  197. self.mutations.create_placeholder(real_id);
  198. 1
  199. }
  200. fn create_element_node(&mut self, element: &'b VElement<'b>, node: &'b VNode<'b>) -> usize {
  201. let VElement {
  202. tag: tag_name,
  203. listeners,
  204. attributes,
  205. children,
  206. namespace,
  207. id: dom_id,
  208. parent: parent_id,
  209. ..
  210. } = &element;
  211. parent_id.set(self.element_stack.last().copied());
  212. let real_id = self.scopes.reserve_node(node);
  213. dom_id.set(Some(real_id));
  214. self.element_stack.push(real_id);
  215. {
  216. self.mutations.create_element(tag_name, *namespace, real_id);
  217. let cur_scope_id = self
  218. .current_scope()
  219. .expect("diffing should always have a scope");
  220. for listener in listeners.iter() {
  221. listener.mounted_node.set(Some(real_id));
  222. self.mutations.new_event_listener(listener, cur_scope_id);
  223. }
  224. for attr in attributes.iter() {
  225. self.mutations.set_attribute(attr, real_id.as_u64());
  226. }
  227. if !children.is_empty() {
  228. self.create_and_append_children(children);
  229. }
  230. }
  231. self.element_stack.pop();
  232. 1
  233. }
  234. fn create_fragment_node(&mut self, frag: &'b VFragment<'b>) -> usize {
  235. self.create_children(frag.children)
  236. }
  237. fn create_component_node(&mut self, vcomponent: &'b VComponent<'b>) -> usize {
  238. let parent_idx = self.current_scope().unwrap();
  239. // the component might already exist - if it does, we need to reuse it
  240. // this makes figure out when to drop the component more complicated
  241. let new_idx = if let Some(idx) = vcomponent.scope.get() {
  242. assert!(self.scopes.get_scope(idx).is_some());
  243. idx
  244. } else {
  245. // Insert a new scope into our component list
  246. let props: Box<dyn AnyProps + 'b> = vcomponent.props.borrow_mut().take().unwrap();
  247. let props: Box<dyn AnyProps + 'static> = unsafe { std::mem::transmute(props) };
  248. self.scopes.new_with_key(
  249. vcomponent.user_fc,
  250. props,
  251. Some(parent_idx),
  252. self.element_stack.last().copied().unwrap(),
  253. 0,
  254. )
  255. };
  256. // Actually initialize the caller's slot with the right address
  257. vcomponent.scope.set(Some(new_idx));
  258. log::trace!(
  259. "created component \"{}\", id: {:?} parent {:?} orig: {:?}",
  260. vcomponent.fn_name,
  261. new_idx,
  262. parent_idx,
  263. vcomponent.originator
  264. );
  265. // if vcomponent.can_memoize {
  266. // // todo: implement promotion logic. save us from boxing props that we don't need
  267. // } else {
  268. // // track this component internally so we know the right drop order
  269. // }
  270. self.enter_scope(new_idx);
  271. let created = {
  272. // Run the scope for one iteration to initialize it
  273. self.scopes.run_scope(new_idx);
  274. self.mutations.mark_dirty_scope(new_idx);
  275. // Take the node that was just generated from running the component
  276. let nextnode = self.scopes.fin_head(new_idx);
  277. self.create_node(nextnode)
  278. };
  279. self.leave_scope();
  280. created
  281. }
  282. fn diff_element_nodes(
  283. &mut self,
  284. old: &'b VElement<'b>,
  285. new: &'b VElement<'b>,
  286. old_node: &'b VNode<'b>,
  287. new_node: &'b VNode<'b>,
  288. ) {
  289. let root = old
  290. .id
  291. .get()
  292. .expect("existing element nodes should have an ElementId");
  293. // If the element type is completely different, the element needs to be re-rendered completely
  294. // This is an optimization React makes due to how users structure their code
  295. //
  296. // This case is rather rare (typically only in non-keyed lists)
  297. if new.tag != old.tag || new.namespace != old.namespace {
  298. self.replace_node(old_node, new_node);
  299. return;
  300. }
  301. self.scopes.update_node(new_node, root);
  302. new.id.set(Some(root));
  303. new.parent.set(old.parent.get());
  304. // todo: attributes currently rely on the element on top of the stack, but in theory, we only need the id of the
  305. // element to modify its attributes.
  306. // it would result in fewer instructions if we just set the id directly.
  307. // it would also clean up this code some, but that's not very important anyways
  308. // Diff Attributes
  309. //
  310. // It's extraordinarily rare to have the number/order of attributes change
  311. // In these cases, we just completely erase the old set and make a new set
  312. //
  313. // TODO: take a more efficient path than this
  314. if old.attributes.len() == new.attributes.len() {
  315. for (old_attr, new_attr) in old.attributes.iter().zip(new.attributes.iter()) {
  316. if old_attr.value != new_attr.value || new_attr.is_volatile {
  317. self.mutations.set_attribute(new_attr, root.as_u64());
  318. }
  319. }
  320. } else {
  321. for attribute in old.attributes {
  322. self.mutations.remove_attribute(attribute, root.as_u64());
  323. }
  324. for attribute in new.attributes {
  325. self.mutations.set_attribute(attribute, root.as_u64());
  326. }
  327. }
  328. // Diff listeners
  329. //
  330. // It's extraordinarily rare to have the number/order of listeners change
  331. // In the cases where the listeners change, we completely wipe the data attributes and add new ones
  332. //
  333. // We also need to make sure that all listeners are properly attached to the parent scope (fix_listener)
  334. //
  335. // TODO: take a more efficient path than this
  336. if let Some(cur_scope_id) = self.current_scope() {
  337. if old.listeners.len() == new.listeners.len() {
  338. for (old_l, new_l) in old.listeners.iter().zip(new.listeners.iter()) {
  339. if old_l.event != new_l.event {
  340. self.mutations
  341. .remove_event_listener(old_l.event, root.as_u64());
  342. self.mutations.new_event_listener(new_l, cur_scope_id);
  343. }
  344. new_l.mounted_node.set(old_l.mounted_node.get());
  345. }
  346. } else {
  347. for listener in old.listeners {
  348. self.mutations
  349. .remove_event_listener(listener.event, root.as_u64());
  350. }
  351. for listener in new.listeners {
  352. listener.mounted_node.set(Some(root));
  353. self.mutations.new_event_listener(listener, cur_scope_id);
  354. }
  355. }
  356. }
  357. match (old.children.len(), new.children.len()) {
  358. (0, 0) => {}
  359. (0, _) => {
  360. let created = self.create_children(new.children);
  361. self.mutations.append_children(created as u32);
  362. }
  363. (_, _) => self.diff_children(old.children, new.children),
  364. };
  365. }
  366. fn diff_component_nodes(
  367. &mut self,
  368. old_node: &'b VNode<'b>,
  369. new_node: &'b VNode<'b>,
  370. old: &'b VComponent<'b>,
  371. new: &'b VComponent<'b>,
  372. ) {
  373. let scope_addr = old
  374. .scope
  375. .get()
  376. .expect("existing component nodes should have a scope");
  377. if std::ptr::eq(old, new) {
  378. return;
  379. }
  380. // Make sure we're dealing with the same component (by function pointer)
  381. if old.user_fc == new.user_fc {
  382. self.enter_scope(scope_addr);
  383. {
  384. // Make sure the new component vnode is referencing the right scope id
  385. new.scope.set(Some(scope_addr));
  386. // make sure the component's caller function is up to date
  387. let scope = self
  388. .scopes
  389. .get_scope(scope_addr)
  390. .unwrap_or_else(|| panic!("could not find {:?}", scope_addr));
  391. // take the new props out regardless
  392. // when memoizing, push to the existing scope if memoization happens
  393. let new_props = new
  394. .props
  395. .borrow_mut()
  396. .take()
  397. .expect("new component props should exist");
  398. let should_diff = {
  399. if old.can_memoize {
  400. // safety: we trust the implementation of "memoize"
  401. let props_are_the_same = unsafe {
  402. let new_ref = new_props.as_ref();
  403. scope.props.borrow().as_ref().unwrap().memoize(new_ref)
  404. };
  405. !props_are_the_same || self.force_diff
  406. } else {
  407. true
  408. }
  409. };
  410. if should_diff {
  411. let _old_props = scope
  412. .props
  413. .replace(unsafe { std::mem::transmute(Some(new_props)) });
  414. // this should auto drop the previous props
  415. self.scopes.run_scope(scope_addr);
  416. self.mutations.mark_dirty_scope(scope_addr);
  417. self.diff_node(
  418. self.scopes.wip_head(scope_addr),
  419. self.scopes.fin_head(scope_addr),
  420. );
  421. } else {
  422. // memoization has taken place
  423. drop(new_props);
  424. };
  425. }
  426. self.leave_scope();
  427. } else {
  428. self.replace_node(old_node, new_node);
  429. }
  430. }
  431. fn diff_fragment_nodes(&mut self, old: &'b VFragment<'b>, new: &'b VFragment<'b>) {
  432. // This is the case where options or direct vnodes might be used.
  433. // In this case, it's faster to just skip ahead to their diff
  434. if old.children.len() == 1 && new.children.len() == 1 {
  435. if !std::ptr::eq(old, new) {
  436. self.diff_node(&old.children[0], &new.children[0]);
  437. }
  438. return;
  439. }
  440. debug_assert!(!old.children.is_empty());
  441. debug_assert!(!new.children.is_empty());
  442. self.diff_children(old.children, new.children);
  443. }
  444. // Diff the given set of old and new children.
  445. //
  446. // The parent must be on top of the change list stack when this function is
  447. // entered:
  448. //
  449. // [... parent]
  450. //
  451. // the change list stack is in the same state when this function returns.
  452. //
  453. // If old no anchors are provided, then it's assumed that we can freely append to the parent.
  454. //
  455. // Remember, non-empty lists does not mean that there are real elements, just that there are virtual elements.
  456. //
  457. // Fragment nodes cannot generate empty children lists, so we can assume that when a list is empty, it belongs only
  458. // to an element, and appending makes sense.
  459. fn diff_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  460. if std::ptr::eq(old, new) {
  461. return;
  462. }
  463. // Remember, fragments can never be empty (they always have a single child)
  464. match (old, new) {
  465. ([], []) => {}
  466. ([], _) => self.create_and_append_children(new),
  467. (_, []) => self.remove_nodes(old, true),
  468. _ => {
  469. let new_is_keyed = new[0].key().is_some();
  470. let old_is_keyed = old[0].key().is_some();
  471. debug_assert!(
  472. new.iter().all(|n| n.key().is_some() == new_is_keyed),
  473. "all siblings must be keyed or all siblings must be non-keyed"
  474. );
  475. debug_assert!(
  476. old.iter().all(|o| o.key().is_some() == old_is_keyed),
  477. "all siblings must be keyed or all siblings must be non-keyed"
  478. );
  479. if new_is_keyed && old_is_keyed {
  480. self.diff_keyed_children(old, new);
  481. } else {
  482. self.diff_non_keyed_children(old, new);
  483. }
  484. }
  485. }
  486. }
  487. // Diff children that are not keyed.
  488. //
  489. // The parent must be on the top of the change list stack when entering this
  490. // function:
  491. //
  492. // [... parent]
  493. //
  494. // the change list stack is in the same state when this function returns.
  495. fn diff_non_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  496. use std::cmp::Ordering;
  497. // Handled these cases in `diff_children` before calling this function.
  498. debug_assert!(!new.is_empty());
  499. debug_assert!(!old.is_empty());
  500. match old.len().cmp(&new.len()) {
  501. Ordering::Greater => self.remove_nodes(&old[new.len()..], true),
  502. Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
  503. Ordering::Equal => {}
  504. }
  505. for (new, old) in new.iter().zip(old.iter()) {
  506. self.diff_node(old, new);
  507. }
  508. }
  509. // Diffing "keyed" children.
  510. //
  511. // With keyed children, we care about whether we delete, move, or create nodes
  512. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  513. // transition animation that makes the virtual DOM diffing algorithm
  514. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  515. // must reuse (or not reuse) the same physical DOM nodes.
  516. //
  517. // This is loosely based on Inferno's keyed patching implementation. However, we
  518. // have to modify the algorithm since we are compiling the diff down into change
  519. // list instructions that will be executed later, rather than applying the
  520. // changes to the DOM directly as we compare virtual DOMs.
  521. //
  522. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  523. //
  524. // The stack is empty upon entry.
  525. fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  526. if cfg!(debug_assertions) {
  527. let mut keys = fxhash::FxHashSet::default();
  528. let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
  529. keys.clear();
  530. for child in children {
  531. let key = child.key();
  532. debug_assert!(
  533. key.is_some(),
  534. "if any sibling is keyed, all siblings must be keyed"
  535. );
  536. keys.insert(key);
  537. }
  538. debug_assert_eq!(
  539. children.len(),
  540. keys.len(),
  541. "keyed siblings must each have a unique key"
  542. );
  543. };
  544. assert_unique_keys(old);
  545. assert_unique_keys(new);
  546. }
  547. // First up, we diff all the nodes with the same key at the beginning of the
  548. // children.
  549. //
  550. // `shared_prefix_count` is the count of how many nodes at the start of
  551. // `new` and `old` share the same keys.
  552. let (left_offset, right_offset) = match self.diff_keyed_ends(old, new) {
  553. Some(count) => count,
  554. None => return,
  555. };
  556. // Ok, we now hopefully have a smaller range of children in the middle
  557. // within which to re-order nodes with the same keys, remove old nodes with
  558. // now-unused keys, and create new nodes with fresh keys.
  559. let old_middle = &old[left_offset..(old.len() - right_offset)];
  560. let new_middle = &new[left_offset..(new.len() - right_offset)];
  561. debug_assert!(
  562. !((old_middle.len() == new_middle.len()) && old_middle.is_empty()),
  563. "keyed children must have the same number of children"
  564. );
  565. if new_middle.is_empty() {
  566. // remove the old elements
  567. self.remove_nodes(old_middle, true);
  568. } else if old_middle.is_empty() {
  569. // there were no old elements, so just create the new elements
  570. // we need to find the right "foothold" though - we shouldn't use the "append" at all
  571. if left_offset == 0 {
  572. // insert at the beginning of the old list
  573. let foothold = &old[old.len() - right_offset];
  574. self.create_and_insert_before(new_middle, foothold);
  575. } else if right_offset == 0 {
  576. // insert at the end the old list
  577. let foothold = old.last().unwrap();
  578. self.create_and_insert_after(new_middle, foothold);
  579. } else {
  580. // inserting in the middle
  581. let foothold = &old[left_offset - 1];
  582. self.create_and_insert_after(new_middle, foothold);
  583. }
  584. } else {
  585. self.diff_keyed_middle(old_middle, new_middle);
  586. }
  587. }
  588. /// Diff both ends of the children that share keys.
  589. ///
  590. /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing.
  591. ///
  592. /// If there is no offset, then this function returns None and the diffing is complete.
  593. fn diff_keyed_ends(
  594. &mut self,
  595. old: &'b [VNode<'b>],
  596. new: &'b [VNode<'b>],
  597. ) -> Option<(usize, usize)> {
  598. let mut left_offset = 0;
  599. for (old, new) in old.iter().zip(new.iter()) {
  600. // abort early if we finally run into nodes with different keys
  601. if old.key() != new.key() {
  602. break;
  603. }
  604. self.diff_node(old, new);
  605. left_offset += 1;
  606. }
  607. // If that was all of the old children, then create and append the remaining
  608. // new children and we're finished.
  609. if left_offset == old.len() {
  610. self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
  611. return None;
  612. }
  613. // And if that was all of the new children, then remove all of the remaining
  614. // old children and we're finished.
  615. if left_offset == new.len() {
  616. self.remove_nodes(&old[left_offset..], true);
  617. return None;
  618. }
  619. // if the shared prefix is less than either length, then we need to walk backwards
  620. let mut right_offset = 0;
  621. for (old, new) in old.iter().rev().zip(new.iter().rev()) {
  622. // abort early if we finally run into nodes with different keys
  623. if old.key() != new.key() {
  624. break;
  625. }
  626. self.diff_node(old, new);
  627. right_offset += 1;
  628. }
  629. Some((left_offset, right_offset))
  630. }
  631. // The most-general, expensive code path for keyed children diffing.
  632. //
  633. // We find the longest subsequence within `old` of children that are relatively
  634. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  635. // of the old child's index within `new`). The children that are elements of
  636. // this subsequence will remain in place, minimizing the number of DOM moves we
  637. // will have to do.
  638. //
  639. // Upon entry to this function, the change list stack must be empty.
  640. //
  641. // This function will load the appropriate nodes onto the stack and do diffing in place.
  642. //
  643. // Upon exit from this function, it will be restored to that same self.
  644. #[allow(clippy::too_many_lines)]
  645. fn diff_keyed_middle(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  646. /*
  647. 1. Map the old keys into a numerical ordering based on indices.
  648. 2. Create a map of old key to its index
  649. 3. Map each new key to the old key, carrying over the old index.
  650. - IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3
  651. - if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist
  652. now, we should have a list of integers that indicates where in the old list the new items map to.
  653. 4. Compute the LIS of this list
  654. - this indicates the longest list of new children that won't need to be moved.
  655. 5. Identify which nodes need to be removed
  656. 6. Identify which nodes will need to be diffed
  657. 7. Going along each item in the new list, create it and insert it before the next closest item in the LIS.
  658. - if the item already existed, just move it to the right place.
  659. 8. Finally, generate instructions to remove any old children.
  660. 9. Generate instructions to finally diff children that are the same between both
  661. */
  662. // 0. Debug sanity checks
  663. // Should have already diffed the shared-key prefixes and suffixes.
  664. debug_assert_ne!(new.first().map(VNode::key), old.first().map(VNode::key));
  665. debug_assert_ne!(new.last().map(VNode::key), old.last().map(VNode::key));
  666. // 1. Map the old keys into a numerical ordering based on indices.
  667. // 2. Create a map of old key to its index
  668. // IE if the keys were A B C, then we would have (A, 1) (B, 2) (C, 3).
  669. let old_key_to_old_index = old
  670. .iter()
  671. .enumerate()
  672. .map(|(i, o)| (o.key().unwrap(), i))
  673. .collect::<FxHashMap<_, _>>();
  674. let mut shared_keys = FxHashSet::default();
  675. // 3. Map each new key to the old key, carrying over the old index.
  676. let new_index_to_old_index = new
  677. .iter()
  678. .map(|node| {
  679. let key = node.key().unwrap();
  680. if let Some(&index) = old_key_to_old_index.get(&key) {
  681. shared_keys.insert(key);
  682. index
  683. } else {
  684. u32::MAX as usize
  685. }
  686. })
  687. .collect::<Vec<_>>();
  688. // If none of the old keys are reused by the new children, then we remove all the remaining old children and
  689. // create the new children afresh.
  690. if shared_keys.is_empty() {
  691. if let Some(first_old) = old.get(0) {
  692. self.remove_nodes(&old[1..], true);
  693. let nodes_created = self.create_children(new);
  694. self.replace_inner(first_old, nodes_created);
  695. } else {
  696. // I think this is wrong - why are we appending?
  697. // only valid of the if there are no trailing elements
  698. self.create_and_append_children(new);
  699. }
  700. return;
  701. }
  702. // 4. Compute the LIS of this list
  703. let mut lis_sequence = Vec::default();
  704. lis_sequence.reserve(new_index_to_old_index.len());
  705. let mut predecessors = vec![0; new_index_to_old_index.len()];
  706. let mut starts = vec![0; new_index_to_old_index.len()];
  707. longest_increasing_subsequence::lis_with(
  708. &new_index_to_old_index,
  709. &mut lis_sequence,
  710. |a, b| a < b,
  711. &mut predecessors,
  712. &mut starts,
  713. );
  714. // the lis comes out backwards, I think. can't quite tell.
  715. lis_sequence.sort_unstable();
  716. // 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)
  717. if lis_sequence.last().map(|f| new_index_to_old_index[*f]) == Some(u32::MAX as usize) {
  718. lis_sequence.pop();
  719. }
  720. for idx in &lis_sequence {
  721. self.diff_node(&old[new_index_to_old_index[*idx]], &new[*idx]);
  722. }
  723. let mut nodes_created = 0;
  724. // add mount instruction for the first items not covered by the lis
  725. let last = *lis_sequence.last().unwrap();
  726. if last < (new.len() - 1) {
  727. for (idx, new_node) in new[(last + 1)..].iter().enumerate() {
  728. let new_idx = idx + last + 1;
  729. let old_index = new_index_to_old_index[new_idx];
  730. if old_index == u32::MAX as usize {
  731. nodes_created += self.create_node(new_node);
  732. } else {
  733. self.diff_node(&old[old_index], new_node);
  734. nodes_created += self.push_all_nodes(new_node);
  735. }
  736. }
  737. self.mutations.insert_after(
  738. self.find_last_element(&new[last]).unwrap(),
  739. nodes_created as u32,
  740. );
  741. nodes_created = 0;
  742. }
  743. // for each spacing, generate a mount instruction
  744. let mut lis_iter = lis_sequence.iter().rev();
  745. let mut last = *lis_iter.next().unwrap();
  746. for next in lis_iter {
  747. if last - next > 1 {
  748. for (idx, new_node) in new[(next + 1)..last].iter().enumerate() {
  749. let new_idx = idx + next + 1;
  750. let old_index = new_index_to_old_index[new_idx];
  751. if old_index == u32::MAX as usize {
  752. nodes_created += self.create_node(new_node);
  753. } else {
  754. self.diff_node(&old[old_index], new_node);
  755. nodes_created += self.push_all_nodes(new_node);
  756. }
  757. }
  758. self.mutations.insert_before(
  759. self.find_first_element(&new[last]).unwrap(),
  760. nodes_created as u32,
  761. );
  762. nodes_created = 0;
  763. }
  764. last = *next;
  765. }
  766. // add mount instruction for the last items not covered by the lis
  767. let first_lis = *lis_sequence.first().unwrap();
  768. if first_lis > 0 {
  769. for (idx, new_node) in new[..first_lis].iter().enumerate() {
  770. let old_index = new_index_to_old_index[idx];
  771. if old_index == u32::MAX as usize {
  772. nodes_created += self.create_node(new_node);
  773. } else {
  774. self.diff_node(&old[old_index], new_node);
  775. nodes_created += self.push_all_nodes(new_node);
  776. }
  777. }
  778. self.mutations.insert_before(
  779. self.find_first_element(&new[first_lis]).unwrap(),
  780. nodes_created as u32,
  781. );
  782. }
  783. }
  784. fn replace_node(&mut self, old: &'b VNode<'b>, new: &'b VNode<'b>) {
  785. let nodes_created = self.create_node(new);
  786. self.replace_inner(old, nodes_created);
  787. }
  788. fn replace_inner(&mut self, old: &'b VNode<'b>, nodes_created: usize) {
  789. match old {
  790. VNode::Element(el) => {
  791. let id = old
  792. .try_mounted_id()
  793. .unwrap_or_else(|| panic!("broke on {:?}", old));
  794. self.mutations.replace_with(id, nodes_created as u32);
  795. self.remove_nodes(el.children, false);
  796. self.scopes.collect_garbage(id);
  797. }
  798. VNode::Text(_) | VNode::Placeholder(_) => {
  799. let id = old
  800. .try_mounted_id()
  801. .unwrap_or_else(|| panic!("broke on {:?}", old));
  802. self.mutations.replace_with(id, nodes_created as u32);
  803. self.scopes.collect_garbage(id);
  804. }
  805. VNode::Fragment(f) => {
  806. self.replace_inner(&f.children[0], nodes_created);
  807. self.remove_nodes(f.children.iter().skip(1), true);
  808. }
  809. VNode::Component(c) => {
  810. log::trace!("Replacing component {:?}", old);
  811. let scope_id = c.scope.get().unwrap();
  812. let node = self.scopes.fin_head(scope_id);
  813. self.enter_scope(scope_id);
  814. {
  815. self.replace_inner(node, nodes_created);
  816. log::trace!("Replacing component x2 {:?}", old);
  817. // we can only remove components if they are actively being diffed
  818. if self.scope_stack.contains(&c.originator) {
  819. log::trace!("Removing component {:?}", old);
  820. self.scopes.try_remove(scope_id).unwrap();
  821. }
  822. }
  823. self.leave_scope();
  824. }
  825. }
  826. }
  827. pub fn remove_nodes(&mut self, nodes: impl IntoIterator<Item = &'b VNode<'b>>, gen_muts: bool) {
  828. for node in nodes {
  829. match node {
  830. VNode::Text(t) => {
  831. // this check exists because our null node will be removed but does not have an ID
  832. if let Some(id) = t.id.get() {
  833. self.scopes.collect_garbage(id);
  834. if gen_muts {
  835. self.mutations.remove(id.as_u64());
  836. }
  837. }
  838. }
  839. VNode::Placeholder(a) => {
  840. let id = a.id.get().unwrap();
  841. self.scopes.collect_garbage(id);
  842. if gen_muts {
  843. self.mutations.remove(id.as_u64());
  844. }
  845. }
  846. VNode::Element(e) => {
  847. let id = e.id.get().unwrap();
  848. if gen_muts {
  849. self.mutations.remove(id.as_u64());
  850. }
  851. self.scopes.collect_garbage(id);
  852. self.remove_nodes(e.children, false);
  853. }
  854. VNode::Fragment(f) => {
  855. self.remove_nodes(f.children, gen_muts);
  856. }
  857. VNode::Component(c) => {
  858. self.enter_scope(c.scope.get().unwrap());
  859. {
  860. let scope_id = c.scope.get().unwrap();
  861. let root = self.scopes.root_node(scope_id);
  862. self.remove_nodes([root], gen_muts);
  863. // we can only remove this node if the originator is actively in our stackß
  864. if self.scope_stack.contains(&c.originator) {
  865. self.scopes.try_remove(scope_id).unwrap();
  866. }
  867. }
  868. self.leave_scope();
  869. }
  870. }
  871. }
  872. }
  873. fn create_children(&mut self, nodes: &'b [VNode<'b>]) -> usize {
  874. let mut created = 0;
  875. for node in nodes {
  876. created += self.create_node(node);
  877. }
  878. created
  879. }
  880. fn create_and_append_children(&mut self, nodes: &'b [VNode<'b>]) {
  881. let created = self.create_children(nodes);
  882. self.mutations.append_children(created as u32);
  883. }
  884. fn create_and_insert_after(&mut self, nodes: &'b [VNode<'b>], after: &'b VNode<'b>) {
  885. let created = self.create_children(nodes);
  886. let last = self.find_last_element(after).unwrap();
  887. self.mutations.insert_after(last, created as u32);
  888. }
  889. fn create_and_insert_before(&mut self, nodes: &'b [VNode<'b>], before: &'b VNode<'b>) {
  890. let created = self.create_children(nodes);
  891. let first = self.find_first_element(before).unwrap();
  892. self.mutations.insert_before(first, created as u32);
  893. }
  894. fn current_scope(&self) -> Option<ScopeId> {
  895. self.scope_stack.last().copied()
  896. }
  897. fn enter_scope(&mut self, scope: ScopeId) {
  898. self.scope_stack.push(scope);
  899. }
  900. fn leave_scope(&mut self) {
  901. self.scope_stack.pop();
  902. }
  903. fn find_last_element(&self, vnode: &'b VNode<'b>) -> Option<ElementId> {
  904. let mut search_node = Some(vnode);
  905. loop {
  906. match &search_node.take().unwrap() {
  907. VNode::Text(t) => break t.id.get(),
  908. VNode::Element(t) => break t.id.get(),
  909. VNode::Placeholder(t) => break t.id.get(),
  910. VNode::Fragment(frag) => search_node = frag.children.last(),
  911. VNode::Component(el) => {
  912. let scope_id = el.scope.get().unwrap();
  913. search_node = Some(self.scopes.root_node(scope_id));
  914. }
  915. }
  916. }
  917. }
  918. fn find_first_element(&self, vnode: &'b VNode<'b>) -> Option<ElementId> {
  919. let mut search_node = Some(vnode);
  920. loop {
  921. match &search_node.take().expect("search node to have an ID") {
  922. VNode::Text(t) => break t.id.get(),
  923. VNode::Element(t) => break t.id.get(),
  924. VNode::Placeholder(t) => break t.id.get(),
  925. VNode::Fragment(frag) => search_node = Some(&frag.children[0]),
  926. VNode::Component(el) => {
  927. let scope = el.scope.get().expect("element to have a scope assigned");
  928. search_node = Some(self.scopes.root_node(scope));
  929. }
  930. }
  931. }
  932. }
  933. // recursively push all the nodes of a tree onto the stack and return how many are there
  934. fn push_all_nodes(&mut self, node: &'b VNode<'b>) -> usize {
  935. match node {
  936. VNode::Text(_) | VNode::Placeholder(_) => {
  937. self.mutations.push_root(node.mounted_id());
  938. 1
  939. }
  940. VNode::Fragment(frag) => {
  941. let mut added = 0;
  942. for child in frag.children {
  943. added += self.push_all_nodes(child);
  944. }
  945. added
  946. }
  947. VNode::Component(c) => {
  948. let scope_id = c.scope.get().unwrap();
  949. let root = self.scopes.root_node(scope_id);
  950. self.push_all_nodes(root)
  951. }
  952. VNode::Element(el) => {
  953. let mut num_on_stack = 0;
  954. for child in el.children.iter() {
  955. num_on_stack += self.push_all_nodes(child);
  956. }
  957. self.mutations.push_root(el.id.get().unwrap());
  958. num_on_stack + 1
  959. }
  960. }
  961. }
  962. }