diff.rs 52 KB

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