diff.rs 55 KB

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