diff.rs 49 KB

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