diff.rs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. //! This module contains the stateful DiffMachine and all methods to diff VNodes, their properties, and their children.
  2. //!
  3. //! Notice:
  4. //! ------
  5. //!
  6. //! The inspiration and code for this module was originally taken from Dodrio (@fitzgen) and modified to support Components,
  7. //! Fragments, Suspense, and additional batching operations.
  8. //!
  9. //! Implementation Details:
  10. //! -----------------------
  11. //!
  12. //! All nodes are addressed by their IDs. The RealDom provides an imperative interface for making changes to these nodes.
  13. //! We don't necessarily intend for changes to happen exactly during the diffing process, so the implementor may choose
  14. //! to batch nodes if it is more performant for their application. The u32 should be a no-op to hash,
  15. //!
  16. //!
  17. //! Further Reading and Thoughts
  18. //! ----------------------------
  19. //!
  20. //! There are more ways of increasing diff performance here that are currently not implemented.
  21. //! More info on how to improve this diffing algorithm:
  22. //! - https://hacks.mozilla.org/2019/03/fast-bump-allocated-virtual-doms-with-rust-and-wasm/
  23. use crate::{arena::ScopeArena, innerlude::*};
  24. use fxhash::{FxHashMap, FxHashSet};
  25. use std::{
  26. any::Any,
  27. cell::Cell,
  28. cmp::Ordering,
  29. rc::{Rc, Weak},
  30. };
  31. /// The accompanying "real dom" exposes an imperative API for controlling the UI layout
  32. ///
  33. /// Instead of having handles directly over nodes, Dioxus uses simple u32s as node IDs.
  34. /// This allows layouts with up to 4,294,967,295 nodes. If we use nohasher, then retrieving is very fast.
  35. pub trait RealDom {
  36. fn delete_root(&self, root: RealDomNode);
  37. // ===========
  38. // Create
  39. // ===========
  40. /// Create a new text node and push it on to the top of the stack
  41. fn create_text_node(&self, text: &str) -> RealDomNode;
  42. /// Create a new text node and push it on to the top of the stack
  43. fn create_element(&self, tag: &str) -> RealDomNode;
  44. /// Create a new namespaced element and push it on to the top of the stack
  45. fn create_element_ns(&self, tag: &str, namespace: &str) -> RealDomNode;
  46. fn append_node(&self, child: RealDomNode, parent: RealDomNode);
  47. // ===========
  48. // Remove
  49. // ===========
  50. fn remove_node(&self, node: RealDomNode);
  51. fn remove_all_children(&self, node: RealDomNode);
  52. // ===========
  53. // Replace
  54. // ===========
  55. fn replace_node_with(&self, old: RealDomNode, new: RealDomNode);
  56. fn new_event_listener(&self, node: RealDomNode, event: &str);
  57. fn set_inner_text(&self, node: RealDomNode, text: &str);
  58. fn set_class(&self, node: RealDomNode);
  59. fn set_attr(&self, node: RealDomNode, name: &str, value: &str);
  60. fn remove_attr(&self, node: RealDomNode);
  61. fn raw_node_as_any_mut(&self) -> &mut dyn Any;
  62. }
  63. /// The DiffState is a cursor internal to the VirtualDOM's diffing algorithm that allows persistence of state while
  64. /// diffing trees of components. This means we can "re-enter" a subtree of a component by queuing a "NeedToDiff" event.
  65. ///
  66. /// By re-entering via NodeDiff, we can connect disparate edits together into a single EditList. This batching of edits
  67. /// leads to very fast re-renders (all done in a single animation frame).
  68. ///
  69. /// It also means diffing two trees is only ever complex as diffing a single smaller tree, and then re-entering at a
  70. /// different cursor position.
  71. ///
  72. /// The order of these re-entrances is stored in the DiffState itself. The DiffState comes pre-loaded with a set of components
  73. /// that were modified by the eventtrigger. This prevents doubly evaluating components if they were both updated via
  74. /// subscriptions and props changes.
  75. pub struct DiffMachine<'a, Dom: RealDom> {
  76. pub dom: &'a mut Dom,
  77. pub cur_idx: ScopeIdx,
  78. pub diffed: FxHashSet<ScopeIdx>,
  79. pub components: ScopeArena,
  80. pub event_queue: EventQueue,
  81. pub seen_nodes: FxHashSet<ScopeIdx>,
  82. }
  83. // todo: see if unsafe works better
  84. static COUNTER: Cell<u32> = Cell::new(1);
  85. fn next_id() -> u32 {
  86. let out = COUNTER.get();
  87. COUNTER.set(out + 1);
  88. out
  89. }
  90. impl<'a, Dom: RealDom> DiffMachine<'a, Dom> {
  91. pub fn new(
  92. dom: &'a mut Dom,
  93. components: ScopeArena,
  94. cur_idx: ScopeIdx,
  95. event_queue: EventQueue,
  96. ) -> Self {
  97. Self {
  98. components,
  99. dom,
  100. cur_idx,
  101. event_queue,
  102. diffed: FxHashSet::default(),
  103. seen_nodes: FxHashSet::default(),
  104. }
  105. }
  106. pub fn diff_node(&self, old_node: &mut VNode<'a>, new_node: &mut VNode<'a>) {
  107. // pub fn diff_node(&self, old: &VNode<'a>, new: &VNode<'a>) {
  108. /*
  109. For each valid case, we "commit traversal", meaning we save this current position in the tree.
  110. Then, we diff and queue an edit event (via chagelist). s single trees - when components show up, we save that traversal and then re-enter later.
  111. When re-entering, we reuse the EditList in DiffState
  112. */
  113. match (old_node, new_node) {
  114. (VNode::Text(old), VNode::Text(new)) => {
  115. new.dom_id = old.dom_id;
  116. if old.text != new.text {
  117. self.dom.set_inner_text(new.dom_id.get(), new.text);
  118. }
  119. }
  120. (VNode::Text(old), VNode::Element(new)) => {
  121. // // self.dom.commit_traversal();
  122. self.create_and_repalce(new_node, old.dom_id.get())
  123. // self.create(new_node);
  124. // self.dom.replace_node_with(old.dom_id, old.dom_id);
  125. // self.dom.replace_with();
  126. }
  127. (VNode::Element(old), VNode::Text(new)) => {
  128. // // self.dom.commit_traversal();
  129. self.create_and_repalce(new_node, old.dom_id.get())
  130. // self.create(new_node);
  131. // self.dom.replace_node_with(old.dom_id, new.dom_id);
  132. // self.dom.replace_with();
  133. }
  134. (VNode::Element(old), VNode::Element(new)) => {
  135. // If the element type is completely different, the element needs to be re-rendered completely
  136. if new.tag_name != old.tag_name || new.namespace != old.namespace {
  137. // // self.dom.commit_traversal();
  138. // self.dom.replace_with();
  139. self.dom
  140. .replace_node_with(old.dom_id.get(), new.dom_id.get());
  141. return;
  142. }
  143. self.diff_listeners(old.listeners, new.listeners);
  144. self.diff_attr(old.attributes, new.attributes, new.namespace.is_some());
  145. self.diff_children(old.children, new.children);
  146. }
  147. (VNode::Component(old), VNode::Component(new)) => {
  148. // Make sure we're dealing with the same component (by function pointer)
  149. if old.user_fc == new.user_fc {
  150. // Make sure the new component vnode is referencing the right scope id
  151. let scope_id = old.ass_scope.borrow().clone();
  152. *new.ass_scope.borrow_mut() = scope_id;
  153. // make sure the component's caller function is up to date
  154. self.components
  155. .with_scope(scope_id.unwrap(), |scope| {
  156. scope.caller = Rc::downgrade(&new.caller)
  157. })
  158. .unwrap();
  159. // React doesn't automatically memoize, but we do.
  160. // The cost is low enough to make it worth checking
  161. let should_render = match old.comparator {
  162. Some(comparator) => comparator(new),
  163. None => true,
  164. };
  165. if should_render {
  166. // // self.dom.commit_traversal();
  167. self.components
  168. .with_scope(scope_id.unwrap(), |f| {
  169. f.run_scope().unwrap();
  170. })
  171. .unwrap();
  172. // diff_machine.change_list.load_known_root(root_id);
  173. // run the scope
  174. //
  175. } else {
  176. // Component has memoized itself and doesn't need to be re-rendered.
  177. // We still need to make sure the child's props are up-to-date.
  178. // Don't commit traversal
  179. }
  180. } else {
  181. // A new component has shown up! We need to destroy the old node
  182. // Wipe the old one and plant the new one
  183. // self.dom.commit_traversal();
  184. // self.dom.replace_node_with(old.dom_id, new.dom_id);
  185. // self.create(new_node);
  186. // self.dom.replace_with();
  187. self.create_and_repalce(new_node, old.mounted_root.get());
  188. // Now we need to remove the old scope and all of its descendents
  189. let old_scope = old.ass_scope.borrow().as_ref().unwrap().clone();
  190. self.destroy_scopes(old_scope);
  191. }
  192. }
  193. // todo: knock out any listeners
  194. (old, VNode::Component(_)) => {
  195. // self.dom.commit_traversal();
  196. // self.create(new_node);
  197. // self.dom.replace_with();
  198. self.create_and_repalce(new_node, old.dom_id.get())
  199. }
  200. // A component is being torn down in favor of a non-component node
  201. (VNode::Component(_old), _) => {
  202. // self.dom.commit_traversal();
  203. // self.create(new_node);
  204. // self.dom.replace_with();
  205. self.create_and_repalce(new_node, old.dom_id.get())
  206. // Destroy the original scope and any of its children
  207. self.destroy_scopes(_old.ass_scope.borrow().unwrap());
  208. }
  209. // Anything suspended is not enabled ATM
  210. (VNode::Suspended, _) | (_, VNode::Suspended) => {
  211. todo!("Suspended components not currently available")
  212. }
  213. // Fragments are special
  214. // we actually have to remove a bunch of nodes
  215. (VNode::Fragment(_), _) => {
  216. todo!("Fragments not currently supported in diffing")
  217. }
  218. (VNode::Fragment(_), VNode::Fragment(_)) => {
  219. todo!("Fragments not currently supported in diffing")
  220. }
  221. (old_n, VNode::Fragment(_)) => {
  222. match old_n {
  223. VNode::Element(_) => todo!(),
  224. VNode::Text(_) => todo!(),
  225. VNode::Fragment(_) => todo!(),
  226. VNode::Suspended => todo!(),
  227. VNode::Component(_) => todo!(),
  228. }
  229. todo!("Fragments not currently supported in diffing")
  230. }
  231. }
  232. }
  233. // create a node and replace another node
  234. // this method doesn't work with
  235. fn create_and_repalce(&self, node: &mut VNode<'a>, parent: RealDomNode) {}
  236. // create and append creates the series of elements and immediately appends them to whatever parent is provided
  237. // this way we can handle a series of children
  238. fn create_and_append(&self, node: &mut VNode<'a>, parent: RealDomNode) {
  239. // debug_assert!(self.dom.traversal_is_committed());
  240. match node {
  241. VNode::Text(text) => {
  242. let real_id = self.dom.create_text_node(text.text);
  243. text.dom_id.set(real_id);
  244. }
  245. VNode::Element(&el) => {
  246. let VElement {
  247. key,
  248. tag_name,
  249. listeners,
  250. attributes,
  251. children,
  252. namespace,
  253. dom_id,
  254. } = el;
  255. // log::info!("Creating {:#?}", node);
  256. let real_id = if let Some(namespace) = namespace {
  257. self.dom.create_element_ns(tag_name, namespace)
  258. } else {
  259. self.dom.create_element(tag_name)
  260. };
  261. el.dom_id = real_id;
  262. listeners.iter().enumerate().for_each(|(_id, listener)| {
  263. todo!()
  264. // dom
  265. // .new_event_listener(listener.event, listener.scope, listener.id)
  266. });
  267. for attr in attributes {
  268. todo!()
  269. // dom
  270. // .set_attribute(&attr.name, &attr.value, namespace.is_some());
  271. }
  272. // Fast path: if there is a single text child, it is faster to
  273. // create-and-append the text node all at once via setting the
  274. // parent's `textContent` in a single change list instruction than
  275. // to emit three instructions to (1) create a text node, (2) set its
  276. // text content, and finally (3) append the text node to this
  277. // parent.
  278. if children.len() == 1 {
  279. if let VNode::Text(text) = children[0] {
  280. self.dom.set_inner_text(real_id, text.text);
  281. return;
  282. }
  283. }
  284. for child in children {
  285. self.create(child, real_id);
  286. if let VNode::Fragment(_) = child {
  287. // do nothing
  288. // fragments append themselves
  289. } else {
  290. self.dom.append_child();
  291. }
  292. }
  293. }
  294. VNode::Component(component) => {
  295. self.dom.create_text_node("placeholder for vcomponent");
  296. // let root_id = next_id();
  297. // self.dom.save_known_root(root_id);
  298. log::debug!("Mounting a new component");
  299. let caller: Weak<OpaqueComponent> = Rc::downgrade(&component.caller);
  300. // We're modifying the component arena while holding onto references into the assoiated bump arenas of its children
  301. // those references are stable, even if the component arena moves around in memory, thanks to the bump arenas.
  302. // However, there is no way to convey this to rust, so we need to use unsafe to pierce through the lifetime.
  303. let parent_idx = self.cur_idx;
  304. // Insert a new scope into our component list
  305. let idx = self
  306. .components
  307. .with(|components| {
  308. components.insert_with(|new_idx| {
  309. let parent_scope = self.components.try_get(parent_idx).unwrap();
  310. let height = parent_scope.height + 1;
  311. Scope::new(
  312. caller,
  313. new_idx,
  314. Some(parent_idx),
  315. height,
  316. self.event_queue.new_channel(height, new_idx),
  317. self.components.clone(),
  318. component.children,
  319. )
  320. })
  321. })
  322. .unwrap();
  323. {
  324. let cur_component = self.components.try_get_mut(idx).unwrap();
  325. let mut ch = cur_component.descendents.borrow_mut();
  326. ch.insert(idx);
  327. std::mem::drop(ch);
  328. }
  329. // yaaaaay lifetimes out of thin air
  330. // really tho, we're merging the frame lifetimes together
  331. let inner: &'a mut _ = unsafe { &mut *self.components.0.borrow().arena.get() };
  332. let new_component = inner.get_mut(idx).unwrap();
  333. // Actually initialize the caller's slot with the right address
  334. *component.ass_scope.borrow_mut() = Some(idx);
  335. // Run the scope for one iteration to initialize it
  336. new_component.run_scope().unwrap();
  337. // And then run the diff algorithm
  338. todo!();
  339. // self.diff_node(new_component.old_frame(), new_component.next_frame());
  340. // Finally, insert this node as a seen node.
  341. self.seen_nodes.insert(idx);
  342. }
  343. // we go the the "known root" but only operate on a sibling basis
  344. VNode::Fragment(frag) => {
  345. // create the children directly in the space
  346. for child in frag.children {
  347. todo!()
  348. // self.create(child);
  349. // self.dom.append_child();
  350. }
  351. }
  352. VNode::Suspended => {
  353. todo!("Creation of VNode::Suspended not yet supported")
  354. }
  355. }
  356. }
  357. /// Destroy a scope and all of its descendents.
  358. ///
  359. /// Calling this will run the destuctors on all hooks in the tree.
  360. /// It will also add the destroyed nodes to the `seen_nodes` cache to prevent them from being renderered.
  361. fn destroy_scopes(&self, old_scope: ScopeIdx) {
  362. let mut nodes_to_delete = vec![old_scope];
  363. let mut scopes_to_explore = vec![old_scope];
  364. // explore the scope tree breadth first
  365. while let Some(scope_id) = scopes_to_explore.pop() {
  366. // If we're planning on deleting this node, then we don't need to both rendering it
  367. self.seen_nodes.insert(scope_id);
  368. let scope = self.components.try_get(scope_id).unwrap();
  369. for child in scope.descendents.borrow().iter() {
  370. // Add this node to be explored
  371. scopes_to_explore.push(child.clone());
  372. // Also add it for deletion
  373. nodes_to_delete.push(child.clone());
  374. }
  375. }
  376. // Delete all scopes that we found as part of this subtree
  377. for node in nodes_to_delete {
  378. log::debug!("Removing scope {:#?}", node);
  379. let _scope = self.components.try_remove(node).unwrap();
  380. // do anything we need to do to delete the scope
  381. // I think we need to run the destructors on the hooks
  382. // TODO
  383. }
  384. }
  385. // Diff event listeners between `old` and `new`.
  386. //
  387. // The listeners' node must be on top of the change list stack:
  388. //
  389. // [... node]
  390. //
  391. // The change list stack is left unchanged.
  392. fn diff_listeners(&self, old: &[Listener<'_>], new: &[Listener<'_>]) {
  393. if !old.is_empty() || !new.is_empty() {
  394. // self.dom.commit_traversal();
  395. }
  396. 'outer1: for (_l_idx, new_l) in new.iter().enumerate() {
  397. // go through each new listener
  398. // find its corresponding partner in the old list
  399. // if any characteristics changed, remove and then re-add
  400. // if nothing changed, then just move on
  401. let event_type = new_l.event;
  402. for old_l in old {
  403. if new_l.event == old_l.event {
  404. if new_l.id != old_l.id {
  405. self.dom.remove_event_listener(event_type);
  406. self.dom
  407. .update_event_listener(event_type, new_l.scope, new_l.id)
  408. }
  409. continue 'outer1;
  410. }
  411. }
  412. self.dom
  413. .new_event_listener(event_type, new_l.scope, new_l.id);
  414. }
  415. 'outer2: for old_l in old {
  416. for new_l in new {
  417. if new_l.event == old_l.event {
  418. continue 'outer2;
  419. }
  420. }
  421. self.dom.remove_event_listener(old_l.event);
  422. }
  423. }
  424. // Diff a node's attributes.
  425. //
  426. // The attributes' node must be on top of the change list stack:
  427. //
  428. // [... node]
  429. //
  430. // The change list stack is left unchanged.
  431. fn diff_attr(&self, old: &'a [Attribute<'a>], new: &'a [Attribute<'a>], is_namespaced: bool) {
  432. // Do O(n^2) passes to add/update and remove attributes, since
  433. // there are almost always very few attributes.
  434. //
  435. // The "fast" path is when the list of attributes name is identical and in the same order
  436. // With the Rsx and Html macros, this will almost always be the case
  437. 'outer: for new_attr in new {
  438. if new_attr.is_volatile() {
  439. // self.dom.commit_traversal();
  440. self.dom
  441. .set_attribute(new_attr.name, new_attr.value, is_namespaced);
  442. } else {
  443. for old_attr in old {
  444. if old_attr.name == new_attr.name {
  445. if old_attr.value != new_attr.value {
  446. // self.dom.commit_traversal();
  447. self.dom
  448. .set_attribute(new_attr.name, new_attr.value, is_namespaced);
  449. }
  450. continue 'outer;
  451. } else {
  452. // names are different, a varying order of attributes has arrived
  453. }
  454. }
  455. // self.dom.commit_traversal();
  456. self.dom
  457. .set_attribute(new_attr.name, new_attr.value, is_namespaced);
  458. }
  459. }
  460. 'outer2: for old_attr in old {
  461. for new_attr in new {
  462. if old_attr.name == new_attr.name {
  463. continue 'outer2;
  464. }
  465. }
  466. // self.dom.commit_traversal();
  467. self.dom.remove_attribute(old_attr.name);
  468. }
  469. }
  470. // Diff the given set of old and new children.
  471. //
  472. // The parent must be on top of the change list stack when this function is
  473. // entered:
  474. //
  475. // [... parent]
  476. //
  477. // the change list stack is in the same state when this function returns.
  478. fn diff_children(&self, old: &'a [VNode<'a>], new: &'a [VNode<'a>]) {
  479. if new.is_empty() {
  480. if !old.is_empty() {
  481. // self.dom.commit_traversal();
  482. self.remove_all_children(old);
  483. }
  484. return;
  485. }
  486. if new.len() == 1 {
  487. match (old.first(), &new[0]) {
  488. (Some(&VNode::Text(old_text)), &VNode::Text(new_text)) if old_text == new_text => {
  489. // Don't take this fast path...
  490. }
  491. (_, &VNode::Text(text)) => {
  492. // self.dom.commit_traversal();
  493. self.dom.set_text(text);
  494. return;
  495. }
  496. // todo: any more optimizations
  497. (_, _) => {}
  498. }
  499. }
  500. if old.is_empty() {
  501. if !new.is_empty() {
  502. // self.dom.commit_traversal();
  503. self.create_and_append_children(new);
  504. }
  505. return;
  506. }
  507. let new_is_keyed = new[0].key().is_some();
  508. let old_is_keyed = old[0].key().is_some();
  509. debug_assert!(
  510. new.iter().all(|n| n.key().is_some() == new_is_keyed),
  511. "all siblings must be keyed or all siblings must be non-keyed"
  512. );
  513. debug_assert!(
  514. old.iter().all(|o| o.key().is_some() == old_is_keyed),
  515. "all siblings must be keyed or all siblings must be non-keyed"
  516. );
  517. if new_is_keyed && old_is_keyed {
  518. let t = self.dom.next_temporary();
  519. self.diff_keyed_children(old, new);
  520. self.dom.set_next_temporary(t);
  521. } else {
  522. self.diff_non_keyed_children(old, new);
  523. }
  524. }
  525. // Diffing "keyed" children.
  526. //
  527. // With keyed children, we care about whether we delete, move, or create nodes
  528. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  529. // transition animation that makes the virtual DOM diffing algorithm
  530. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  531. // must reuse (or not reuse) the same physical DOM nodes.
  532. //
  533. // This is loosely based on Inferno's keyed patching implementation. However, we
  534. // have to modify the algorithm since we are compiling the diff down into change
  535. // list instructions that will be executed later, rather than applying the
  536. // changes to the DOM directly as we compare virtual DOMs.
  537. //
  538. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  539. //
  540. // When entering this function, the parent must be on top of the change list
  541. // stack:
  542. //
  543. // [... parent]
  544. //
  545. // Upon exiting, the change list stack is in the same state.
  546. fn diff_keyed_children(&self, old: &[VNode<'a>], new: &[VNode<'a>]) {
  547. // if cfg!(debug_assertions) {
  548. // let mut keys = fxhash::FxHashSet::default();
  549. // let mut assert_unique_keys = |children: &[VNode]| {
  550. // keys.clear();
  551. // for child in children {
  552. // let key = child.key();
  553. // debug_assert!(
  554. // key.is_some(),
  555. // "if any sibling is keyed, all siblings must be keyed"
  556. // );
  557. // keys.insert(key);
  558. // }
  559. // debug_assert_eq!(
  560. // children.len(),
  561. // keys.len(),
  562. // "keyed siblings must each have a unique key"
  563. // );
  564. // };
  565. // assert_unique_keys(old);
  566. // assert_unique_keys(new);
  567. // }
  568. // First up, we diff all the nodes with the same key at the beginning of the
  569. // children.
  570. //
  571. // `shared_prefix_count` is the count of how many nodes at the start of
  572. // `new` and `old` share the same keys.
  573. let shared_prefix_count = match self.diff_keyed_prefix(old, new) {
  574. KeyedPrefixResult::Finished => return,
  575. KeyedPrefixResult::MoreWorkToDo(count) => count,
  576. };
  577. match self.diff_keyed_prefix(old, new) {
  578. KeyedPrefixResult::Finished => return,
  579. KeyedPrefixResult::MoreWorkToDo(count) => count,
  580. };
  581. // Next, we find out how many of the nodes at the end of the children have
  582. // the same key. We do _not_ diff them yet, since we want to emit the change
  583. // list instructions such that they can be applied in a single pass over the
  584. // DOM. Instead, we just save this information for later.
  585. //
  586. // `shared_suffix_count` is the count of how many nodes at the end of `new`
  587. // and `old` share the same keys.
  588. let shared_suffix_count = old[shared_prefix_count..]
  589. .iter()
  590. .rev()
  591. .zip(new[shared_prefix_count..].iter().rev())
  592. .take_while(|&(old, new)| old.key() == new.key())
  593. .count();
  594. let old_shared_suffix_start = old.len() - shared_suffix_count;
  595. let new_shared_suffix_start = new.len() - shared_suffix_count;
  596. // Ok, we now hopefully have a smaller range of children in the middle
  597. // within which to re-order nodes with the same keys, remove old nodes with
  598. // now-unused keys, and create new nodes with fresh keys.
  599. self.diff_keyed_middle(
  600. &old[shared_prefix_count..old_shared_suffix_start],
  601. &new[shared_prefix_count..new_shared_suffix_start],
  602. shared_prefix_count,
  603. shared_suffix_count,
  604. old_shared_suffix_start,
  605. );
  606. // Finally, diff the nodes at the end of `old` and `new` that share keys.
  607. let old_suffix = &old[old_shared_suffix_start..];
  608. let new_suffix = &new[new_shared_suffix_start..];
  609. debug_assert_eq!(old_suffix.len(), new_suffix.len());
  610. if !old_suffix.is_empty() {
  611. self.diff_keyed_suffix(old_suffix, new_suffix, new_shared_suffix_start)
  612. }
  613. }
  614. // Diff the prefix of children in `new` and `old` that share the same keys in
  615. // the same order.
  616. //
  617. // Upon entry of this function, the change list stack must be:
  618. //
  619. // [... parent]
  620. //
  621. // Upon exit, the change list stack is the same.
  622. fn diff_keyed_prefix(&self, old: &[VNode<'a>], new: &[VNode<'a>]) -> KeyedPrefixResult {
  623. // self.dom.go_down();
  624. let mut shared_prefix_count = 0;
  625. for (i, (old, new)) in old.iter().zip(new.iter()).enumerate() {
  626. if old.key() != new.key() {
  627. break;
  628. }
  629. self.dom.go_to_sibling(i);
  630. self.diff_node(old, new);
  631. shared_prefix_count += 1;
  632. }
  633. // If that was all of the old children, then create and append the remaining
  634. // new children and we're finished.
  635. if shared_prefix_count == old.len() {
  636. self.dom.go_up();
  637. // self.dom.commit_traversal();
  638. self.create_and_append_children(&new[shared_prefix_count..]);
  639. return KeyedPrefixResult::Finished;
  640. }
  641. // And if that was all of the new children, then remove all of the remaining
  642. // old children and we're finished.
  643. if shared_prefix_count == new.len() {
  644. self.dom.go_to_sibling(shared_prefix_count);
  645. // self.dom.commit_traversal();
  646. self.remove_self_and_next_siblings(&old[shared_prefix_count..]);
  647. return KeyedPrefixResult::Finished;
  648. }
  649. self.dom.go_up();
  650. KeyedPrefixResult::MoreWorkToDo(shared_prefix_count)
  651. }
  652. // The most-general, expensive code path for keyed children diffing.
  653. //
  654. // We find the longest subsequence within `old` of children that are relatively
  655. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  656. // of the old child's index within `new`). The children that are elements of
  657. // this subsequence will remain in place, minimizing the number of DOM moves we
  658. // will have to do.
  659. //
  660. // Upon entry to this function, the change list stack must be:
  661. //
  662. // [... parent]
  663. //
  664. // Upon exit from this function, it will be restored to that same state.
  665. fn diff_keyed_middle(
  666. &self,
  667. old: &[VNode<'a>],
  668. mut new: &[VNode<'a>],
  669. shared_prefix_count: usize,
  670. shared_suffix_count: usize,
  671. old_shared_suffix_start: usize,
  672. ) {
  673. // Should have already diffed the shared-key prefixes and suffixes.
  674. debug_assert_ne!(new.first().map(|n| n.key()), old.first().map(|o| o.key()));
  675. debug_assert_ne!(new.last().map(|n| n.key()), old.last().map(|o| o.key()));
  676. // The algorithm below relies upon using `u32::MAX` as a sentinel
  677. // value, so if we have that many new nodes, it won't work. This
  678. // check is a bit academic (hence only enabled in debug), since
  679. // wasm32 doesn't have enough address space to hold that many nodes
  680. // in memory.
  681. debug_assert!(new.len() < u32::MAX as usize);
  682. // Map from each `old` node's key to its index within `old`.
  683. let mut old_key_to_old_index = FxHashMap::default();
  684. old_key_to_old_index.reserve(old.len());
  685. old_key_to_old_index.extend(old.iter().enumerate().map(|(i, o)| (o.key(), i)));
  686. // The set of shared keys between `new` and `old`.
  687. let mut shared_keys = FxHashSet::default();
  688. // Map from each index in `new` to the index of the node in `old` that
  689. // has the same key.
  690. let mut new_index_to_old_index = Vec::with_capacity(new.len());
  691. new_index_to_old_index.extend(new.iter().map(|n| {
  692. let key = n.key();
  693. if let Some(&i) = old_key_to_old_index.get(&key) {
  694. shared_keys.insert(key);
  695. i
  696. } else {
  697. u32::MAX as usize
  698. }
  699. }));
  700. // If none of the old keys are reused by the new children, then we
  701. // remove all the remaining old children and create the new children
  702. // afresh.
  703. if shared_suffix_count == 0 && shared_keys.is_empty() {
  704. if shared_prefix_count == 0 {
  705. // self.dom.commit_traversal();
  706. self.remove_all_children(old);
  707. } else {
  708. self.dom.go_down_to_child(shared_prefix_count);
  709. // self.dom.commit_traversal();
  710. self.remove_self_and_next_siblings(&old[shared_prefix_count..]);
  711. }
  712. self.create_and_append_children(new);
  713. return;
  714. }
  715. // Save each of the old children whose keys are reused in the new
  716. // children.
  717. let mut old_index_to_temp = vec![u32::MAX; old.len()];
  718. let mut start = 0;
  719. loop {
  720. let end = (start..old.len())
  721. .find(|&i| {
  722. let key = old[i].key();
  723. !shared_keys.contains(&key)
  724. })
  725. .unwrap_or(old.len());
  726. if end - start > 0 {
  727. // self.dom.commit_traversal();
  728. let mut t = self.dom.save_children_to_temporaries(
  729. shared_prefix_count + start,
  730. shared_prefix_count + end,
  731. );
  732. for i in start..end {
  733. old_index_to_temp[i] = t;
  734. t += 1;
  735. }
  736. }
  737. debug_assert!(end <= old.len());
  738. if end == old.len() {
  739. break;
  740. } else {
  741. start = end + 1;
  742. }
  743. }
  744. // Remove any old children whose keys were not reused in the new
  745. // children. Remove from the end first so that we don't mess up indices.
  746. let mut removed_count = 0;
  747. for (i, old_child) in old.iter().enumerate().rev() {
  748. if !shared_keys.contains(&old_child.key()) {
  749. // registry.remove_subtree(old_child);
  750. // todo
  751. // self.dom.commit_traversal();
  752. self.dom.remove_child(i + shared_prefix_count);
  753. removed_count += 1;
  754. }
  755. }
  756. // If there aren't any more new children, then we are done!
  757. if new.is_empty() {
  758. return;
  759. }
  760. // The longest increasing subsequence within `new_index_to_old_index`. This
  761. // is the longest sequence on DOM nodes in `old` that are relatively ordered
  762. // correctly within `new`. We will leave these nodes in place in the DOM,
  763. // and only move nodes that are not part of the LIS. This results in the
  764. // maximum number of DOM nodes left in place, AKA the minimum number of DOM
  765. // nodes moved.
  766. let mut new_index_is_in_lis = FxHashSet::default();
  767. new_index_is_in_lis.reserve(new_index_to_old_index.len());
  768. let mut predecessors = vec![0; new_index_to_old_index.len()];
  769. let mut starts = vec![0; new_index_to_old_index.len()];
  770. longest_increasing_subsequence::lis_with(
  771. &new_index_to_old_index,
  772. &mut new_index_is_in_lis,
  773. |a, b| a < b,
  774. &mut predecessors,
  775. &mut starts,
  776. );
  777. // Now we will iterate from the end of the new children back to the
  778. // beginning, diffing old children we are reusing and if they aren't in the
  779. // LIS moving them to their new destination, or creating new children. Note
  780. // that iterating in reverse order lets us use `Node.prototype.insertBefore`
  781. // to move/insert children.
  782. //
  783. // But first, we ensure that we have a child on the change list stack that
  784. // we can `insertBefore`. We handle this once before looping over `new`
  785. // children, so that we don't have to keep checking on every loop iteration.
  786. if shared_suffix_count > 0 {
  787. // There is a shared suffix after these middle children. We will be
  788. // inserting before that shared suffix, so add the first child of that
  789. // shared suffix to the change list stack.
  790. //
  791. // [... parent]
  792. self.dom
  793. .go_down_to_child(old_shared_suffix_start - removed_count);
  794. // [... parent first_child_of_shared_suffix]
  795. } else {
  796. // There is no shared suffix coming after these middle children.
  797. // Therefore we have to process the last child in `new` and move it to
  798. // the end of the parent's children if it isn't already there.
  799. let last_index = new.len() - 1;
  800. // uhhhh why an unwrap?
  801. let last = new.last().unwrap();
  802. // let last = new.last().unwrap_throw();
  803. new = &new[..new.len() - 1];
  804. if shared_keys.contains(&last.key()) {
  805. let old_index = new_index_to_old_index[last_index];
  806. let temp = old_index_to_temp[old_index];
  807. // [... parent]
  808. self.dom.go_down_to_temp_child(temp);
  809. // [... parent last]
  810. self.diff_node(&old[old_index], last);
  811. if new_index_is_in_lis.contains(&last_index) {
  812. // Don't move it, since it is already where it needs to be.
  813. } else {
  814. // self.dom.commit_traversal();
  815. // [... parent last]
  816. self.dom.append_child();
  817. // [... parent]
  818. self.dom.go_down_to_temp_child(temp);
  819. // [... parent last]
  820. }
  821. } else {
  822. // self.dom.commit_traversal();
  823. // [... parent]
  824. self.create(last);
  825. // [... parent last]
  826. self.dom.append_child();
  827. // [... parent]
  828. self.dom.go_down_to_reverse_child(0);
  829. // [... parent last]
  830. }
  831. }
  832. for (new_index, new_child) in new.iter().enumerate().rev() {
  833. let old_index = new_index_to_old_index[new_index];
  834. if old_index == u32::MAX as usize {
  835. debug_assert!(!shared_keys.contains(&new_child.key()));
  836. // self.dom.commit_traversal();
  837. // [... parent successor]
  838. self.create(new_child);
  839. // [... parent successor new_child]
  840. self.dom.insert_before();
  841. // [... parent new_child]
  842. } else {
  843. debug_assert!(shared_keys.contains(&new_child.key()));
  844. let temp = old_index_to_temp[old_index];
  845. debug_assert_ne!(temp, u32::MAX);
  846. if new_index_is_in_lis.contains(&new_index) {
  847. // [... parent successor]
  848. self.dom.go_to_temp_sibling(temp);
  849. // [... parent new_child]
  850. } else {
  851. // self.dom.commit_traversal();
  852. // [... parent successor]
  853. self.dom.push_temporary(temp);
  854. // [... parent successor new_child]
  855. self.dom.insert_before();
  856. // [... parent new_child]
  857. }
  858. self.diff_node(&old[old_index], new_child);
  859. }
  860. }
  861. // [... parent child]
  862. self.dom.go_up();
  863. // [... parent]
  864. }
  865. // Diff the suffix of keyed children that share the same keys in the same order.
  866. //
  867. // The parent must be on the change list stack when we enter this function:
  868. //
  869. // [... parent]
  870. //
  871. // When this function exits, the change list stack remains the same.
  872. fn diff_keyed_suffix(
  873. &self,
  874. old: &[VNode<'a>],
  875. new: &[VNode<'a>],
  876. new_shared_suffix_start: usize,
  877. ) {
  878. debug_assert_eq!(old.len(), new.len());
  879. debug_assert!(!old.is_empty());
  880. // [... parent]
  881. self.dom.go_down();
  882. // [... parent new_child]
  883. for (i, (old_child, new_child)) in old.iter().zip(new.iter()).enumerate() {
  884. self.dom.go_to_sibling(new_shared_suffix_start + i);
  885. self.diff_node(old_child, new_child);
  886. }
  887. // [... parent]
  888. self.dom.go_up();
  889. }
  890. // Diff children that are not keyed.
  891. //
  892. // The parent must be on the top of the change list stack when entering this
  893. // function:
  894. //
  895. // [... parent]
  896. //
  897. // the change list stack is in the same state when this function returns.
  898. fn diff_non_keyed_children(&self, old: &'a [VNode<'a>], new: &'a [VNode<'a>]) {
  899. // Handled these cases in `diff_children` before calling this function.
  900. debug_assert!(!new.is_empty());
  901. debug_assert!(!old.is_empty());
  902. // [... parent]
  903. self.dom.go_down();
  904. // [... parent child]
  905. for (i, (new_child, old_child)) in new.iter().zip(old.iter()).enumerate() {
  906. // [... parent prev_child]
  907. self.dom.go_to_sibling(i);
  908. // [... parent this_child]
  909. self.diff_node(old_child, new_child);
  910. }
  911. match old.len().cmp(&new.len()) {
  912. // old.len > new.len -> removing some nodes
  913. Ordering::Greater => {
  914. // [... parent prev_child]
  915. self.dom.go_to_sibling(new.len());
  916. // [... parent first_child_to_remove]
  917. // self.dom.commit_traversal();
  918. // support::remove_self_and_next_siblings(state, &old[new.len()..]);
  919. self.remove_self_and_next_siblings(&old[new.len()..]);
  920. // [... parent]
  921. }
  922. // old.len < new.len -> adding some nodes
  923. Ordering::Less => {
  924. // [... parent last_child]
  925. self.dom.go_up();
  926. // [... parent]
  927. // self.dom.commit_traversal();
  928. self.create_and_append_children(&new[old.len()..]);
  929. }
  930. // old.len == new.len -> no nodes added/removed, but πerhaps changed
  931. Ordering::Equal => {
  932. // [... parent child]
  933. self.dom.go_up();
  934. // [... parent]
  935. }
  936. }
  937. }
  938. // ======================
  939. // Support methods
  940. // ======================
  941. // Remove all of a node's children.
  942. //
  943. // The change list stack must have this shape upon entry to this function:
  944. //
  945. // [... parent]
  946. //
  947. // When this function returns, the change list stack is in the same state.
  948. pub fn remove_all_children(&self, old: &[VNode<'a>]) {
  949. // debug_assert!(self.dom.traversal_is_committed());
  950. log::debug!("REMOVING CHILDREN");
  951. for _child in old {
  952. // registry.remove_subtree(child);
  953. }
  954. // Fast way to remove all children: set the node's textContent to an empty
  955. // string.
  956. todo!()
  957. // self.dom.set_inner_text("");
  958. }
  959. // Create the given children and append them to the parent node.
  960. //
  961. // The parent node must currently be on top of the change list stack:
  962. //
  963. // [... parent]
  964. //
  965. // When this function returns, the change list stack is in the same state.
  966. pub fn create_and_append_children(&self, new: &[VNode<'a>]) {
  967. // debug_assert!(self.dom.traversal_is_committed());
  968. for child in new {
  969. self.create_and_append(node, parent)
  970. // self.create(child);
  971. // self.dom.append_child();
  972. }
  973. }
  974. // Remove the current child and all of its following siblings.
  975. //
  976. // The change list stack must have this shape upon entry to this function:
  977. //
  978. // [... parent child]
  979. //
  980. // After the function returns, the child is no longer on the change list stack:
  981. //
  982. // [... parent]
  983. pub fn remove_self_and_next_siblings(&self, old: &[VNode<'a>]) {
  984. // debug_assert!(self.dom.traversal_is_committed());
  985. for child in old {
  986. if let VNode::Component(vcomp) = child {
  987. // dom
  988. // .create_text_node("placeholder for vcomponent");
  989. todo!()
  990. // let root_id = vcomp.stable_addr.as_ref().borrow().unwrap();
  991. // self.lifecycle_events.push_back(LifeCycleEvent::Remove {
  992. // root_id,
  993. // stable_scope_addr: Rc::downgrade(&vcomp.ass_scope),
  994. // })
  995. // let id = get_id();
  996. // *component.stable_addr.as_ref().borrow_mut() = Some(id);
  997. // self.dom.save_known_root(id);
  998. // let scope = Rc::downgrade(&component.ass_scope);
  999. // self.lifecycle_events.push_back(LifeCycleEvent::Mount {
  1000. // caller: Rc::downgrade(&component.caller),
  1001. // root_id: id,
  1002. // stable_scope_addr: scope,
  1003. // });
  1004. }
  1005. // registry.remove_subtree(child);
  1006. }
  1007. self.dom.remove_self_and_next_siblings();
  1008. }
  1009. }
  1010. enum KeyedPrefixResult {
  1011. // Fast path: we finished diffing all the children just by looking at the
  1012. // prefix of shared keys!
  1013. Finished,
  1014. // There is more diffing work to do. Here is a count of how many children at
  1015. // the beginning of `new` and `old` we already processed.
  1016. MoreWorkToDo(usize),
  1017. }