diff.rs 48 KB

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