diff.rs 51 KB

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