diff.rs 48 KB

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