diff.rs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. //! This module contains the stateful DiffMachine and all methods to diff VNodes, their properties, and their children.
  2. //! The DiffMachine calculates the diffs between the old and new frames, updates the new nodes, and modifies the real dom.
  3. //!
  4. //! ## Notice:
  5. //! The inspiration and code for this module was originally taken from Dodrio (@fitzgen) and then modified to support
  6. //! Components, Fragments, Suspense, SubTree memoization, and additional batching operations.
  7. //!
  8. //! ## Implementation Details:
  9. //!
  10. //! ### IDs for elements
  11. //! --------------------
  12. //! All nodes are addressed by their IDs. The RealDom provides an imperative interface for making changes to these nodes.
  13. //! We don't necessarily require that DOM changes happen instnatly during the diffing process, so the implementor may choose
  14. //! to batch nodes if it is more performant for their application. The expectation is that renderers use a Slotmap for nodes
  15. //! whose keys can be converted to u64 on FFI boundaries.
  16. //!
  17. //! When new nodes are created through `render`, they won't know which real node they correspond to. During diffing, we
  18. //! always make sure to copy over the ID. If we don't do this properly, the ElementId will be populated incorrectly and
  19. //! brick the user's page.
  20. //!
  21. //! ### Fragment Support
  22. //!
  23. //! Fragments (nodes without a parent) are supported through a combination of "replace with" and anchor vnodes. Fragments
  24. //! can be particularly challenging when they are empty, so the placeholder node lets us "reserve" a spot for the empty
  25. //! fragment to be replaced with when it is no longer empty. This is guaranteed by logic in the NodeFactory - it is
  26. //! impossible to craft a fragment with 0 elements - they must always have at least a single placeholder element. This is
  27. //! slightly inefficient, but represents a such an uncommon use case that it is not worth optimizing.
  28. //!
  29. //! ## Subtree Memoization
  30. //! -----------------------
  31. //! We also employ "subtree memoization" which saves us from having to check trees which take no dynamic content. We can
  32. //! detect if a subtree is "static" by checking if its children are "static". Since we dive into the tree depth-first, the
  33. //! calls to "create" propogate this information upwards. Structures like the one below are entirely static:
  34. //! ```rust
  35. //! rsx!( div { class: "hello world", "this node is entirely static" } )
  36. //! ```
  37. //! Because the subtrees won't be diffed, their "real node" data will be stale (invalid), so its up to the reconciler to
  38. //! track nodes created in a scope and clean up all relevant data. Support for this is currently WIP
  39. //!
  40. //! ## Bloom Filter and Heuristics
  41. //! ------------------------------
  42. //! For all components, we employ some basic heuristics to speed up allocations and pre-size bump arenas. The heuristics are
  43. //! currently very rough, but will get better as time goes on. For FFI, we recommend using a bloom filter to cache strings.
  44. //!
  45. //!
  46. //! ## Garbage Collection
  47. //! ---------------------
  48. //! Dioxus uses a passive garbage collection system to clean up old nodes once the work has been completed. This garabge
  49. //! collection is done internally once the main diffing work is complete. After the "garbage" is collected, Dioxus will then
  50. //! start to re-use old keys for new nodes. This results in a passive memory management system that is very efficient.
  51. //!
  52. //! The IDs used by the key/map are just an index into a vec. This means that Dioxus will drive the key allocation strategy
  53. //! so the client only needs to maintain a simple list of nodes. By default, Dioxus will not manually clean up old nodes
  54. //! for the client. As new nodes are created, old nodes will be over-written.
  55. //!
  56. //! HEADS-UP:
  57. //! For now, deferred garabge collection is disabled. The code-paths are almost wired up, but it's quite complex to
  58. //! get working safely and efficiently. For now, garabge is collected immediately during diffing. This adds extra
  59. //! overhead, but is faster to implement in the short term.
  60. //!
  61. //! Further Reading and Thoughts
  62. //! ----------------------------
  63. //! There are more ways of increasing diff performance here that are currently not implemented.
  64. //! More info on how to improve this diffing algorithm:
  65. //! - https://hacks.mozilla.org/2019/03/fast-bump-allocated-virtual-doms-with-rust-and-wasm/
  66. use crate::{arena::SharedResources, innerlude::*};
  67. use futures_util::Future;
  68. use fxhash::{FxBuildHasher, FxHashMap, FxHashSet};
  69. use smallvec::{smallvec, SmallVec};
  70. use std::{any::Any, cell::Cell, cmp::Ordering, marker::PhantomData, pin::Pin};
  71. use DomEdit::*;
  72. pub struct DiffMachine<'r, 'bump> {
  73. pub vdom: &'bump SharedResources,
  74. pub mutations: Mutations<'bump>,
  75. pub scope_stack: SmallVec<[ScopeId; 5]>,
  76. pub diffed: FxHashSet<ScopeId>,
  77. // will be used later for garbage collection
  78. // we check every seen node and then schedule its eventual deletion
  79. pub seen_scopes: FxHashSet<ScopeId>,
  80. _r: PhantomData<&'r ()>,
  81. }
  82. impl<'r, 'bump> DiffMachine<'r, 'bump> {
  83. pub(crate) fn new(
  84. edits: Mutations<'bump>,
  85. cur_scope: ScopeId,
  86. shared: &'bump SharedResources,
  87. ) -> Self {
  88. Self {
  89. mutations: edits,
  90. scope_stack: smallvec![cur_scope],
  91. vdom: shared,
  92. diffed: FxHashSet::default(),
  93. seen_scopes: FxHashSet::default(),
  94. _r: PhantomData,
  95. }
  96. }
  97. /// Allows the creation of a diff machine without the concept of scopes or a virtualdom
  98. /// this is mostly useful for testing
  99. ///
  100. /// This will PANIC if any component elements are passed in.
  101. pub fn new_headless(shared: &'bump SharedResources) -> Self {
  102. Self {
  103. mutations: Mutations { edits: Vec::new() },
  104. scope_stack: smallvec![ScopeId(0)],
  105. vdom: shared,
  106. diffed: FxHashSet::default(),
  107. seen_scopes: FxHashSet::default(),
  108. _r: PhantomData,
  109. }
  110. }
  111. //
  112. pub fn diff_scope(&mut self, id: ScopeId) -> Result<()> {
  113. let component = self.get_scope_mut(&id).ok_or_else(|| Error::NotMounted)?;
  114. let (old, new) = (component.frames.wip_head(), component.frames.fin_head());
  115. self.diff_node(old, new);
  116. Ok(())
  117. }
  118. // Diff the `old` node with the `new` node. Emits instructions to modify a
  119. // physical DOM node that reflects `old` into something that reflects `new`.
  120. //
  121. // the real stack should be what it is coming in and out of this function (ideally empty)
  122. //
  123. // each function call assumes the stack is fresh (empty).
  124. pub fn diff_node(&mut self, old_node: &'bump VNode<'bump>, new_node: &'bump VNode<'bump>) {
  125. match (&old_node.kind, &new_node.kind) {
  126. // Handle the "sane" cases first.
  127. // The rsx and html macros strongly discourage dynamic lists not encapsulated by a "Fragment".
  128. // So the sane (and fast!) cases are where the virtual structure stays the same and is easily diffable.
  129. (VNodeKind::Text(old), VNodeKind::Text(new)) => {
  130. let root = old_node.direct_id();
  131. if old.text != new.text {
  132. self.edit_push_root(root);
  133. self.edit_set_text(new.text);
  134. self.edit_pop();
  135. }
  136. new.dom_id.set(Some(root));
  137. }
  138. (VNodeKind::Element(old), VNodeKind::Element(new)) => {
  139. let root = old_node.direct_id();
  140. // If the element type is completely different, the element needs to be re-rendered completely
  141. // This is an optimization React makes due to how users structure their code
  142. //
  143. // This case is rather rare (typically only in non-keyed lists)
  144. if new.tag_name != old.tag_name || new.namespace != old.namespace {
  145. self.replace_node_with_node(root, old_node, new_node);
  146. return;
  147. }
  148. new.dom_id.set(Some(root));
  149. // Don't push the root if we don't have to
  150. let mut has_comitted = false;
  151. let mut please_commit = |edits: &mut Vec<DomEdit>| {
  152. if !has_comitted {
  153. has_comitted = true;
  154. edits.push(PushRoot { id: root.as_u64() });
  155. }
  156. };
  157. // Diff Attributes
  158. //
  159. // It's extraordinarily rare to have the number/order of attributes change
  160. // In these cases, we just completely erase the old set and make a new set
  161. //
  162. // TODO: take a more efficient path than this
  163. if old.attributes.len() == new.attributes.len() {
  164. for (old_attr, new_attr) in old.attributes.iter().zip(new.attributes.iter()) {
  165. if old_attr.value != new_attr.value {
  166. please_commit(&mut self.mutations.edits);
  167. self.edit_set_attribute(new_attr);
  168. }
  169. }
  170. } else {
  171. // TODO: provide some sort of report on how "good" the diffing was
  172. please_commit(&mut self.mutations.edits);
  173. for attribute in old.attributes {
  174. self.edit_remove_attribute(attribute);
  175. }
  176. for attribute in new.attributes {
  177. self.edit_set_attribute(attribute)
  178. }
  179. }
  180. // Diff listeners
  181. //
  182. // It's extraordinarily rare to have the number/order of listeners change
  183. // In the cases where the listeners change, we completely wipe the data attributes and add new ones
  184. //
  185. // We also need to make sure that all listeners are properly attached to the parent scope (fix_listener)
  186. //
  187. // TODO: take a more efficient path than this
  188. let cur_scope: ScopeId = self.scope_stack.last().unwrap().clone();
  189. if old.listeners.len() == new.listeners.len() {
  190. for (old_l, new_l) in old.listeners.iter().zip(new.listeners.iter()) {
  191. if old_l.event != new_l.event {
  192. please_commit(&mut self.mutations.edits);
  193. self.edit_remove_event_listener(old_l.event);
  194. self.edit_new_event_listener(new_l, cur_scope);
  195. }
  196. new_l.mounted_node.set(old_l.mounted_node.get());
  197. self.fix_listener(new_l);
  198. }
  199. } else {
  200. please_commit(&mut self.mutations.edits);
  201. for listener in old.listeners {
  202. self.edit_remove_event_listener(listener.event);
  203. }
  204. for listener in new.listeners {
  205. listener.mounted_node.set(Some(root));
  206. self.edit_new_event_listener(listener, cur_scope);
  207. // Make sure the listener gets attached to the scope list
  208. self.fix_listener(listener);
  209. }
  210. }
  211. if has_comitted {
  212. self.edit_pop();
  213. }
  214. self.diff_children(old.children, new.children);
  215. }
  216. (VNodeKind::Component(old), VNodeKind::Component(new)) => {
  217. let scope_addr = old.ass_scope.get().unwrap();
  218. // Make sure we're dealing with the same component (by function pointer)
  219. if old.user_fc == new.user_fc {
  220. //
  221. self.scope_stack.push(scope_addr);
  222. // Make sure the new component vnode is referencing the right scope id
  223. new.ass_scope.set(Some(scope_addr));
  224. // make sure the component's caller function is up to date
  225. let scope = self.get_scope_mut(&scope_addr).unwrap();
  226. scope
  227. .update_scope_dependencies(new.caller.clone(), ScopeChildren(new.children));
  228. // React doesn't automatically memoize, but we do.
  229. let compare = old.comparator.unwrap();
  230. match compare(new) {
  231. true => {
  232. // the props are the same...
  233. }
  234. false => {
  235. // the props are different...
  236. scope.run_scope().unwrap();
  237. self.diff_node(scope.frames.wip_head(), scope.frames.fin_head());
  238. }
  239. }
  240. self.scope_stack.pop();
  241. self.seen_scopes.insert(scope_addr);
  242. } else {
  243. let mut old_iter = RealChildIterator::new(old_node, &self.vdom);
  244. let first = old_iter
  245. .next()
  246. .expect("Components should generate a placeholder root");
  247. // remove any leftovers
  248. for to_remove in old_iter {
  249. self.edit_push_root(to_remove.direct_id());
  250. self.edit_remove();
  251. }
  252. // seems like we could combine this into a single instruction....
  253. self.replace_node_with_node(first.direct_id(), old_node, new_node);
  254. // Wipe the old one and plant the new one
  255. let old_scope = old.ass_scope.get().unwrap();
  256. self.destroy_scopes(old_scope);
  257. }
  258. }
  259. (VNodeKind::Fragment(old), VNodeKind::Fragment(new)) => {
  260. // This is the case where options or direct vnodes might be used.
  261. // In this case, it's faster to just skip ahead to their diff
  262. if old.children.len() == 1 && new.children.len() == 1 {
  263. self.diff_node(&old.children[0], &new.children[0]);
  264. return;
  265. }
  266. self.diff_children(old.children, new.children);
  267. }
  268. (VNodeKind::Anchor(old), VNodeKind::Anchor(new)) => {
  269. new.dom_id.set(old.dom_id.get());
  270. }
  271. // The strategy here is to pick the first possible node from the previous set and use that as our replace with root
  272. //
  273. // We also walk the "real node" list to make sure all latent roots are claened up
  274. // This covers the case any time a fragment or component shows up with pretty much anything else
  275. //
  276. // This likely isn't the fastest way to go about replacing one node with a virtual node, but the "insane" cases
  277. // are pretty rare. IE replacing a list (component or fragment) with a single node.
  278. (
  279. VNodeKind::Component(_)
  280. | VNodeKind::Fragment(_)
  281. | VNodeKind::Text(_)
  282. | VNodeKind::Element(_)
  283. | VNodeKind::Anchor(_),
  284. VNodeKind::Component(_)
  285. | VNodeKind::Fragment(_)
  286. | VNodeKind::Text(_)
  287. | VNodeKind::Element(_)
  288. | VNodeKind::Anchor(_),
  289. ) => {
  290. self.replace_and_create_many_with_many([old_node], [new_node]);
  291. }
  292. // TODO
  293. (VNodeKind::Suspended(old), new) => {
  294. //
  295. self.replace_and_create_many_with_many([old_node], [new_node]);
  296. }
  297. // a node that was once real is now suspended
  298. (old, VNodeKind::Suspended(_)) => {
  299. //
  300. self.replace_and_create_many_with_many([old_node], [new_node]);
  301. }
  302. }
  303. }
  304. // Emit instructions to create the given virtual node.
  305. //
  306. // The change list stack may have any shape upon entering this function:
  307. //
  308. // [...]
  309. //
  310. // When this function returns, the new node is on top of the change list stack:
  311. //
  312. // [... node]
  313. pub fn create_vnode(&mut self, node: &'bump VNode<'bump>) -> CreateMeta {
  314. match &node.kind {
  315. VNodeKind::Text(text) => {
  316. let real_id = self.vdom.reserve_node();
  317. self.edit_create_text_node(text.text, real_id);
  318. text.dom_id.set(Some(real_id));
  319. CreateMeta::new(text.is_static, 1)
  320. }
  321. VNodeKind::Anchor(anchor) => {
  322. let real_id = self.vdom.reserve_node();
  323. self.edit_create_placeholder(real_id);
  324. anchor.dom_id.set(Some(real_id));
  325. CreateMeta::new(false, 1)
  326. }
  327. VNodeKind::Element(el) => {
  328. // we have the potential to completely eliminate working on this node in the future(!)
  329. //
  330. // This can only be done if all of the elements properties (attrs, children, listeners, etc) are static
  331. // While creating these things, keep track if we can memoize this element.
  332. // At the end, we'll set this flag on the element to skip it
  333. let mut is_static: bool = true;
  334. let VElement {
  335. tag_name,
  336. listeners,
  337. attributes,
  338. children,
  339. namespace,
  340. static_attrs: _,
  341. static_children: _,
  342. static_listeners: _,
  343. dom_id,
  344. } = el;
  345. let real_id = self.vdom.reserve_node();
  346. self.edit_create_element(tag_name, *namespace, real_id);
  347. dom_id.set(Some(real_id));
  348. let cur_scope = self.current_scope().unwrap();
  349. listeners.iter().for_each(|listener| {
  350. self.fix_listener(listener);
  351. listener.mounted_node.set(Some(real_id));
  352. self.edit_new_event_listener(listener, cur_scope.clone());
  353. // if the node has an event listener, then it must be visited ?
  354. is_static = false;
  355. });
  356. for attr in *attributes {
  357. is_static = is_static && attr.is_static;
  358. self.edit_set_attribute(attr);
  359. }
  360. // Fast path: if there is a single text child, it is faster to
  361. // create-and-append the text node all at once via setting the
  362. // parent's `textContent` in a single change list instruction than
  363. // to emit three instructions to (1) create a text node, (2) set its
  364. // text content, and finally (3) append the text node to this
  365. // parent.
  366. //
  367. // Notice: this is a web-specific optimization and may be changed in the future
  368. //
  369. // TODO move over
  370. // if children.len() == 1 {
  371. // if let VNodeKind::Text(text) = &children[0].kind {
  372. // self.set_text(text.text);
  373. // return CreateMeta::new(is_static, 1);
  374. // }
  375. // }
  376. for child in *children {
  377. let child_meta = self.create_vnode(child);
  378. is_static = is_static && child_meta.is_static;
  379. // append whatever children were generated by this call
  380. self.edit_append_children(child_meta.added_to_stack);
  381. }
  382. CreateMeta::new(is_static, 1)
  383. }
  384. VNodeKind::Component(vcomponent) => {
  385. let caller = vcomponent.caller.clone();
  386. let parent_idx = self.scope_stack.last().unwrap().clone();
  387. // Insert a new scope into our component list
  388. let new_idx = self.vdom.insert_scope_with_key(|new_idx| {
  389. let parent_scope = self.get_scope(&parent_idx).unwrap();
  390. let height = parent_scope.height + 1;
  391. Scope::new(
  392. caller,
  393. new_idx,
  394. Some(parent_idx),
  395. height,
  396. ScopeChildren(vcomponent.children),
  397. self.vdom.clone(),
  398. )
  399. });
  400. // Actually initialize the caller's slot with the right address
  401. vcomponent.ass_scope.set(Some(new_idx));
  402. if !vcomponent.can_memoize {
  403. let cur_scope = self.get_scope_mut(&parent_idx).unwrap();
  404. let extended = *vcomponent as *const VComponent;
  405. let extended: *const VComponent<'static> =
  406. unsafe { std::mem::transmute(extended) };
  407. cur_scope.borrowed_props.borrow_mut().push(extended);
  408. }
  409. // TODO:
  410. // add noderefs to current noderef list Noderefs
  411. // add effects to current effect list Effects
  412. let new_component = self.get_scope_mut(&new_idx).unwrap();
  413. // Run the scope for one iteration to initialize it
  414. match new_component.run_scope() {
  415. Ok(_) => {
  416. // all good, new nodes exist
  417. }
  418. Err(err) => {
  419. // failed to run. this is the first time the component ran, and it failed
  420. // we manually set its head node to an empty fragment
  421. panic!("failing components not yet implemented");
  422. }
  423. }
  424. // Take the node that was just generated from running the component
  425. let nextnode = new_component.frames.fin_head();
  426. // Push the new scope onto the stack
  427. self.scope_stack.push(new_idx);
  428. // Run the creation algorithm with this scope on the stack
  429. let meta = self.create_vnode(nextnode);
  430. // pop the scope off the stack
  431. self.scope_stack.pop();
  432. if meta.added_to_stack == 0 {
  433. panic!("Components should *always* generate nodes - even if they fail");
  434. }
  435. // Finally, insert this scope as a seen node.
  436. self.seen_scopes.insert(new_idx);
  437. CreateMeta::new(vcomponent.is_static, meta.added_to_stack)
  438. }
  439. // Fragments are the only nodes that can contain dynamic content (IE through curlies or iterators).
  440. // We can never ignore their contents, so the prescence of a fragment indicates that we need always diff them.
  441. // Fragments will just put all their nodes onto the stack after creation
  442. VNodeKind::Fragment(frag) => self.create_children(frag.children),
  443. VNodeKind::Suspended(VSuspended { node: real_node }) => {
  444. let id = self.vdom.reserve_node();
  445. self.edit_create_placeholder(id);
  446. real_node.set(Some(id));
  447. CreateMeta::new(false, 1)
  448. }
  449. }
  450. }
  451. fn create_children(&mut self, children: &'bump [VNode<'bump>]) -> CreateMeta {
  452. let mut is_static = true;
  453. let mut added_to_stack = 0;
  454. // add them backwards
  455. for child in children.iter().rev() {
  456. let child_meta = self.create_vnode(child);
  457. is_static = is_static && child_meta.is_static;
  458. added_to_stack += child_meta.added_to_stack;
  459. }
  460. CreateMeta {
  461. is_static,
  462. added_to_stack,
  463. }
  464. }
  465. /// Destroy a scope and all of its descendents.
  466. ///
  467. /// Calling this will run the destuctors on all hooks in the tree.
  468. /// It will also add the destroyed nodes to the `seen_nodes` cache to prevent them from being renderered.
  469. fn destroy_scopes(&mut self, old_scope: ScopeId) {
  470. let mut nodes_to_delete = vec![old_scope];
  471. let mut scopes_to_explore = vec![old_scope];
  472. // explore the scope tree breadth first
  473. while let Some(scope_id) = scopes_to_explore.pop() {
  474. // If we're planning on deleting this node, then we don't need to both rendering it
  475. self.seen_scopes.insert(scope_id);
  476. let scope = self.get_scope(&scope_id).unwrap();
  477. for child in scope.descendents.borrow().iter() {
  478. // Add this node to be explored
  479. scopes_to_explore.push(child.clone());
  480. // Also add it for deletion
  481. nodes_to_delete.push(child.clone());
  482. }
  483. }
  484. // Delete all scopes that we found as part of this subtree
  485. for node in nodes_to_delete {
  486. log::debug!("Removing scope {:#?}", node);
  487. let _scope = self.vdom.try_remove(node).unwrap();
  488. // do anything we need to do to delete the scope
  489. // I think we need to run the destructors on the hooks
  490. // TODO
  491. }
  492. }
  493. // Diff the given set of old and new children.
  494. //
  495. // The parent must be on top of the change list stack when this function is
  496. // entered:
  497. //
  498. // [... parent]
  499. //
  500. // the change list stack is in the same state when this function returns.
  501. //
  502. // If old no anchors are provided, then it's assumed that we can freely append to the parent.
  503. //
  504. // Remember, non-empty lists does not mean that there are real elements, just that there are virtual elements.
  505. fn diff_children(&mut self, old: &'bump [VNode<'bump>], new: &'bump [VNode<'bump>]) {
  506. const IS_EMPTY: bool = true;
  507. const IS_NOT_EMPTY: bool = false;
  508. match (old.is_empty(), new.is_empty()) {
  509. (IS_EMPTY, IS_EMPTY) => {}
  510. // Completely adding new nodes, removing any placeholder if it exists
  511. (IS_EMPTY, IS_NOT_EMPTY) => {
  512. let meta = self.create_children(new);
  513. self.edit_append_children(meta.added_to_stack);
  514. }
  515. // Completely removing old nodes and putting an anchor in its place
  516. // no anchor (old has nodes) and the new is empty
  517. // remove all the old nodes
  518. (IS_NOT_EMPTY, IS_EMPTY) => {
  519. for node in old {
  520. self.remove_vnode(node);
  521. }
  522. }
  523. (IS_NOT_EMPTY, IS_NOT_EMPTY) => {
  524. let first_old = &old[0];
  525. let first_new = &new[0];
  526. match (&first_old.kind, &first_new.kind) {
  527. // Anchors can only appear in empty fragments
  528. (VNodeKind::Anchor(old_anchor), VNodeKind::Anchor(new_anchor)) => {
  529. old_anchor.dom_id.set(new_anchor.dom_id.get());
  530. }
  531. // Replace the anchor with whatever new nodes are coming down the pipe
  532. (VNodeKind::Anchor(anchor), _) => {
  533. self.edit_push_root(anchor.dom_id.get().unwrap());
  534. let mut added = 0;
  535. for el in new {
  536. let meta = self.create_vnode(el);
  537. added += meta.added_to_stack;
  538. }
  539. self.edit_replace_with(1, added);
  540. }
  541. // Replace whatever nodes are sitting there with the anchor
  542. (_, VNodeKind::Anchor(anchor)) => {
  543. self.replace_and_create_many_with_many(old, [first_new]);
  544. }
  545. // Use the complex diff algorithm to diff the nodes
  546. _ => {
  547. let new_is_keyed = new[0].key.is_some();
  548. let old_is_keyed = old[0].key.is_some();
  549. debug_assert!(
  550. new.iter().all(|n| n.key.is_some() == new_is_keyed),
  551. "all siblings must be keyed or all siblings must be non-keyed"
  552. );
  553. debug_assert!(
  554. old.iter().all(|o| o.key.is_some() == old_is_keyed),
  555. "all siblings must be keyed or all siblings must be non-keyed"
  556. );
  557. if new_is_keyed && old_is_keyed {
  558. self.diff_keyed_children(old, new);
  559. } else {
  560. self.diff_non_keyed_children(old, new);
  561. }
  562. }
  563. }
  564. }
  565. }
  566. }
  567. // Diffing "keyed" children.
  568. //
  569. // With keyed children, we care about whether we delete, move, or create nodes
  570. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  571. // transition animation that makes the virtual DOM diffing algorithm
  572. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  573. // must reuse (or not reuse) the same physical DOM nodes.
  574. //
  575. // This is loosely based on Inferno's keyed patching implementation. However, we
  576. // have to modify the algorithm since we are compiling the diff down into change
  577. // list instructions that will be executed later, rather than applying the
  578. // changes to the DOM directly as we compare virtual DOMs.
  579. //
  580. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  581. //
  582. // The stack is empty upon entry.
  583. fn diff_keyed_children(&mut self, old: &'bump [VNode<'bump>], new: &'bump [VNode<'bump>]) {
  584. if cfg!(debug_assertions) {
  585. let mut keys = fxhash::FxHashSet::default();
  586. let mut assert_unique_keys = |children: &'bump [VNode<'bump>]| {
  587. keys.clear();
  588. for child in children {
  589. let key = child.key;
  590. debug_assert!(
  591. key.is_some(),
  592. "if any sibling is keyed, all siblings must be keyed"
  593. );
  594. keys.insert(key);
  595. }
  596. debug_assert_eq!(
  597. children.len(),
  598. keys.len(),
  599. "keyed siblings must each have a unique key"
  600. );
  601. };
  602. assert_unique_keys(old);
  603. assert_unique_keys(new);
  604. }
  605. // First up, we diff all the nodes with the same key at the beginning of the
  606. // children.
  607. //
  608. // `shared_prefix_count` is the count of how many nodes at the start of
  609. // `new` and `old` share the same keys.
  610. //
  611. // TODO: just inline this
  612. let shared_prefix_count = match self.diff_keyed_prefix(old, new) {
  613. KeyedPrefixResult::Finished => return,
  614. KeyedPrefixResult::MoreWorkToDo(count) => count,
  615. };
  616. // Next, we find out how many of the nodes at the end of the children have
  617. // the same key. We do _not_ diff them yet, since we want to emit the change
  618. // list instructions such that they can be applied in a single pass over the
  619. // DOM. Instead, we just save this information for later.
  620. //
  621. // `shared_suffix_count` is the count of how many nodes at the end of `new`
  622. // and `old` share the same keys.
  623. let shared_suffix_count = old[shared_prefix_count..]
  624. .iter()
  625. .rev()
  626. .zip(new[shared_prefix_count..].iter().rev())
  627. .take_while(|&(old, new)| old.key == new.key)
  628. .count();
  629. let old_shared_suffix_start = old.len() - shared_suffix_count;
  630. let new_shared_suffix_start = new.len() - shared_suffix_count;
  631. // Ok, we now hopefully have a smaller range of children in the middle
  632. // within which to re-order nodes with the same keys, remove old nodes with
  633. // now-unused keys, and create new nodes with fresh keys.
  634. self.diff_keyed_middle(
  635. &old[shared_prefix_count..old_shared_suffix_start],
  636. &new[shared_prefix_count..new_shared_suffix_start],
  637. shared_prefix_count,
  638. shared_suffix_count,
  639. old_shared_suffix_start,
  640. );
  641. // Finally, diff the nodes at the end of `old` and `new` that share keys.
  642. let old_suffix = &old[old_shared_suffix_start..];
  643. let new_suffix = &new[new_shared_suffix_start..];
  644. debug_assert_eq!(old_suffix.len(), new_suffix.len());
  645. if !old_suffix.is_empty() {
  646. self.diff_keyed_suffix(old_suffix, new_suffix, new_shared_suffix_start)
  647. }
  648. }
  649. // Diff the prefix of children in `new` and `old` that share the same keys in
  650. // the same order.
  651. //
  652. // The stack is empty upon entry.
  653. fn diff_keyed_prefix(
  654. &mut self,
  655. old: &'bump [VNode<'bump>],
  656. new: &'bump [VNode<'bump>],
  657. ) -> KeyedPrefixResult {
  658. let mut shared_prefix_count = 0;
  659. for (old, new) in old.iter().zip(new.iter()) {
  660. // abort early if we finally run into nodes with different keys
  661. if old.key() != new.key() {
  662. break;
  663. }
  664. self.diff_node(old, new);
  665. shared_prefix_count += 1;
  666. }
  667. // If that was all of the old children, then create and append the remaining
  668. // new children and we're finished.
  669. if shared_prefix_count == old.len() {
  670. // Load the last element
  671. let last_node = self.find_last_element(new.last().unwrap()).direct_id();
  672. self.edit_push_root(last_node);
  673. // Create the new children and insert them after
  674. let meta = self.create_children(&new[shared_prefix_count..]);
  675. self.edit_insert_after(meta.added_to_stack);
  676. return KeyedPrefixResult::Finished;
  677. }
  678. // And if that was all of the new children, then remove all of the remaining
  679. // old children and we're finished.
  680. if shared_prefix_count == new.len() {
  681. self.remove_children(&old[shared_prefix_count..]);
  682. return KeyedPrefixResult::Finished;
  683. }
  684. KeyedPrefixResult::MoreWorkToDo(shared_prefix_count)
  685. }
  686. // Create the given children and append them to the parent node.
  687. //
  688. // The parent node must currently be on top of the change list stack:
  689. //
  690. // [... parent]
  691. //
  692. // When this function returns, the change list stack is in the same state.
  693. pub fn create_and_append_children(&mut self, new: &'bump [VNode<'bump>]) {
  694. for child in new {
  695. let meta = self.create_vnode(child);
  696. self.edit_append_children(meta.added_to_stack);
  697. }
  698. }
  699. // The most-general, expensive code path for keyed children diffing.
  700. //
  701. // We find the longest subsequence within `old` of children that are relatively
  702. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  703. // of the old child's index within `new`). The children that are elements of
  704. // this subsequence will remain in place, minimizing the number of DOM moves we
  705. // will have to do.
  706. //
  707. // Upon entry to this function, the change list stack must be empty.
  708. //
  709. // This function will load the appropriate nodes onto the stack and do diffing in place.
  710. //
  711. // Upon exit from this function, it will be restored to that same state.
  712. fn diff_keyed_middle(
  713. &mut self,
  714. old: &'bump [VNode<'bump>],
  715. mut new: &'bump [VNode<'bump>],
  716. shared_prefix_count: usize,
  717. shared_suffix_count: usize,
  718. old_shared_suffix_start: usize,
  719. ) {
  720. // Should have already diffed the shared-key prefixes and suffixes.
  721. debug_assert_ne!(new.first().map(|n| n.key()), old.first().map(|o| o.key()));
  722. debug_assert_ne!(new.last().map(|n| n.key()), old.last().map(|o| o.key()));
  723. // // The algorithm below relies upon using `u32::MAX` as a sentinel
  724. // // value, so if we have that many new nodes, it won't work. This
  725. // // check is a bit academic (hence only enabled in debug), since
  726. // // wasm32 doesn't have enough address space to hold that many nodes
  727. // // in memory.
  728. // debug_assert!(new.len() < u32::MAX as usize);
  729. // Map from each `old` node's key to its index within `old`.
  730. // IE if the keys were A B C, then we would have (A, 1) (B, 2) (C, 3).
  731. let mut old_key_to_old_index = old
  732. .iter()
  733. .enumerate()
  734. .map(|(i, o)| (o.key().unwrap(), i))
  735. .collect::<FxHashMap<_, _>>();
  736. // The set of shared keys between `new` and `old`.
  737. let mut shared_keys = FxHashSet::default();
  738. // let mut to_remove = FxHashSet::default();
  739. let mut to_add = FxHashSet::default();
  740. // Map from each index in `new` to the index of the node in `old` that
  741. // has the same key.
  742. let mut new_index_to_old_index = new
  743. .iter()
  744. .map(|n| {
  745. let key = n.key().unwrap();
  746. match old_key_to_old_index.get(&key) {
  747. Some(&index) => {
  748. shared_keys.insert(key);
  749. index
  750. }
  751. None => {
  752. //
  753. to_add.insert(key);
  754. u32::MAX as usize
  755. }
  756. }
  757. })
  758. .collect::<Vec<_>>();
  759. dbg!(&shared_keys);
  760. dbg!(&to_add);
  761. // If none of the old keys are reused by the new children, then we
  762. // remove all the remaining old children and create the new children
  763. // afresh.
  764. if shared_suffix_count == 0 && shared_keys.is_empty() {
  765. self.replace_and_create_many_with_many(old, new);
  766. return;
  767. }
  768. // // Remove any old children whose keys were not reused in the new
  769. // // children. Remove from the end first so that we don't mess up indices.
  770. // for old_child in old.iter().rev() {
  771. // if !shared_keys.contains(&old_child.key()) {
  772. // self.remove_child(old_child);
  773. // }
  774. // }
  775. // let old_keyds = old.iter().map(|f| f.key()).collect::<Vec<_>>();
  776. // let new_keyds = new.iter().map(|f| f.key()).collect::<Vec<_>>();
  777. // dbg!(old_keyds);
  778. // dbg!(new_keyds);
  779. // // If there aren't any more new children, then we are done!
  780. // if new.is_empty() {
  781. // return;
  782. // }
  783. // The longest increasing subsequence within `new_index_to_old_index`. This
  784. // is the longest sequence on DOM nodes in `old` that are relatively ordered
  785. // correctly within `new`. We will leave these nodes in place in the DOM,
  786. // and only move nodes that are not part of the LIS. This results in the
  787. // maximum number of DOM nodes left in place, AKA the minimum number of DOM
  788. // nodes moved.
  789. let mut new_index_is_in_lis = FxHashSet::default();
  790. new_index_is_in_lis.reserve(new_index_to_old_index.len());
  791. let mut predecessors = vec![0; new_index_to_old_index.len()];
  792. let mut starts = vec![0; new_index_to_old_index.len()];
  793. longest_increasing_subsequence::lis_with(
  794. &new_index_to_old_index,
  795. &mut new_index_is_in_lis,
  796. |a, b| a < b,
  797. &mut predecessors,
  798. &mut starts,
  799. );
  800. dbg!(&new_index_is_in_lis);
  801. // use the old nodes to navigate the new nodes
  802. let mut lis_in_order = new_index_is_in_lis.into_iter().collect::<Vec<_>>();
  803. lis_in_order.sort_unstable();
  804. dbg!(&lis_in_order);
  805. // we walk front to back, creating the head node
  806. // diff the shared, in-place nodes first
  807. // this makes sure we can rely on their first/last nodes being correct later on
  808. for id in &lis_in_order {
  809. let new_node = &new[*id];
  810. let key = new_node.key().unwrap();
  811. let old_index = old_key_to_old_index.get(&key).unwrap();
  812. let old_node = &old[*old_index];
  813. self.diff_node(old_node, new_node);
  814. }
  815. // return the old node from the key
  816. let load_old_node_from_lsi = |key| -> &VNode {
  817. let old_index = old_key_to_old_index.get(key).unwrap();
  818. let old_node = &old[*old_index];
  819. old_node
  820. };
  821. let mut root = None;
  822. let mut new_iter = new.iter().enumerate();
  823. for lis_id in &lis_in_order {
  824. eprintln!("tracking {:?}", lis_id);
  825. // this is the next milestone node we are working up to
  826. let new_anchor = &new[*lis_id];
  827. root = Some(new_anchor);
  828. let anchor_el = self.find_first_element(new_anchor);
  829. self.edit_push_root(anchor_el.direct_id());
  830. // let mut pushed = false;
  831. 'inner: loop {
  832. let (next_id, next_new) = new_iter.next().unwrap();
  833. if next_id == *lis_id {
  834. // we've reached the milestone, break this loop so we can step to the next milestone
  835. // remember: we already diffed this node
  836. eprintln!("breaking {:?}", next_id);
  837. break 'inner;
  838. } else {
  839. let key = next_new.key().unwrap();
  840. eprintln!("found key {:?}", key);
  841. if shared_keys.contains(&key) {
  842. eprintln!("key is contained {:?}", key);
  843. shared_keys.remove(key);
  844. // diff the two nodes
  845. let old_node = load_old_node_from_lsi(key);
  846. self.diff_node(old_node, next_new);
  847. // now move all the nodes into the right spot
  848. for child in RealChildIterator::new(next_new, self.vdom) {
  849. let el = child.direct_id();
  850. self.edit_push_root(el);
  851. self.edit_insert_before(1);
  852. }
  853. } else {
  854. eprintln!("key is not contained {:?}", key);
  855. // new node needs to be created
  856. // insert it before the current milestone
  857. let meta = self.create_vnode(next_new);
  858. self.edit_insert_before(meta.added_to_stack);
  859. }
  860. }
  861. }
  862. self.edit_pop();
  863. }
  864. let final_lis_node = root.unwrap();
  865. let final_el_node = self.find_last_element(final_lis_node);
  866. let final_el = final_el_node.direct_id();
  867. self.edit_push_root(final_el);
  868. let mut last_iter = new.iter().rev().enumerate();
  869. let last_key = final_lis_node.key().unwrap();
  870. loop {
  871. let (last_id, last_node) = last_iter.next().unwrap();
  872. let key = last_node.key().unwrap();
  873. eprintln!("checking final nodes {:?}", key);
  874. if last_key == key {
  875. eprintln!("breaking final nodes");
  876. break;
  877. }
  878. if shared_keys.contains(&key) {
  879. eprintln!("key is contained {:?}", key);
  880. shared_keys.remove(key);
  881. // diff the two nodes
  882. let old_node = load_old_node_from_lsi(key);
  883. self.diff_node(old_node, last_node);
  884. // now move all the nodes into the right spot
  885. for child in RealChildIterator::new(last_node, self.vdom) {
  886. let el = child.direct_id();
  887. self.edit_push_root(el);
  888. self.edit_insert_after(1);
  889. }
  890. } else {
  891. eprintln!("key is not contained {:?}", key);
  892. // new node needs to be created
  893. // insert it before the current milestone
  894. let meta = self.create_vnode(last_node);
  895. self.edit_insert_after(meta.added_to_stack);
  896. }
  897. }
  898. self.edit_pop();
  899. }
  900. // Diff the suffix of keyed children that share the same keys in the same order.
  901. //
  902. // The parent must be on the change list stack when we enter this function:
  903. //
  904. // [... parent]
  905. //
  906. // When this function exits, the change list stack remains the same.
  907. fn diff_keyed_suffix(
  908. &mut self,
  909. old: &'bump [VNode<'bump>],
  910. new: &'bump [VNode<'bump>],
  911. new_shared_suffix_start: usize,
  912. ) {
  913. debug_assert_eq!(old.len(), new.len());
  914. debug_assert!(!old.is_empty());
  915. for (old_child, new_child) in old.iter().zip(new.iter()) {
  916. self.diff_node(old_child, new_child);
  917. }
  918. }
  919. // Diff children that are not keyed.
  920. //
  921. // The parent must be on the top of the change list stack when entering this
  922. // function:
  923. //
  924. // [... parent]
  925. //
  926. // the change list stack is in the same state when this function returns.
  927. fn diff_non_keyed_children(&mut self, old: &'bump [VNode<'bump>], new: &'bump [VNode<'bump>]) {
  928. // Handled these cases in `diff_children` before calling this function.
  929. //
  930. debug_assert!(!new.is_empty());
  931. debug_assert!(!old.is_empty());
  932. match old.len().cmp(&new.len()) {
  933. // old.len > new.len -> removing some nodes
  934. Ordering::Greater => {
  935. // diff them together
  936. for (new_child, old_child) in new.iter().zip(old.iter()) {
  937. self.diff_node(old_child, new_child);
  938. }
  939. // todo: we would emit fewer instructions if we just did a replace many
  940. // remove whatever is still dangling
  941. for item in &old[new.len()..] {
  942. for i in RealChildIterator::new(item, self.vdom) {
  943. self.edit_push_root(i.direct_id());
  944. self.edit_remove();
  945. }
  946. }
  947. }
  948. // old.len < new.len -> adding some nodes
  949. // this is wrong in the case where we're diffing fragments
  950. //
  951. // we need to save the last old element and then replace it with all the new ones
  952. Ordering::Less => {
  953. // Add the new elements to the last old element while it still exists
  954. let last = self.find_last_element(old.last().unwrap());
  955. self.edit_push_root(last.direct_id());
  956. // create the rest and insert them
  957. let meta = self.create_children(&new[old.len()..]);
  958. self.edit_insert_after(meta.added_to_stack);
  959. self.edit_pop();
  960. // diff the rest
  961. new.iter()
  962. .zip(old.iter())
  963. .for_each(|(new_child, old_child)| self.diff_node(old_child, new_child));
  964. }
  965. // old.len == new.len -> no nodes added/removed, but perhaps changed
  966. Ordering::Equal => {
  967. for (new_child, old_child) in new.iter().zip(old.iter()) {
  968. self.diff_node(old_child, new_child);
  969. }
  970. }
  971. }
  972. }
  973. // ======================
  974. // Support methods
  975. // ======================
  976. // Remove all of a node's children.
  977. //
  978. // The change list stack must have this shape upon entry to this function:
  979. //
  980. // [... parent]
  981. //
  982. // When this function returns, the change list stack is in the same state.
  983. fn remove_all_children(&mut self, old: &'bump [VNode<'bump>]) {
  984. // debug_assert!(self.traversal_is_committed());
  985. log::debug!("REMOVING CHILDREN");
  986. for _child in old {
  987. // registry.remove_subtree(child);
  988. }
  989. // Fast way to remove all children: set the node's textContent to an empty
  990. // string.
  991. todo!()
  992. // self.set_inner_text("");
  993. }
  994. // Remove the current child and all of its following siblings.
  995. //
  996. // The change list stack must have this shape upon entry to this function:
  997. //
  998. // [... parent child]
  999. //
  1000. // After the function returns, the child is no longer on the change list stack:
  1001. //
  1002. // [... parent]
  1003. fn remove_children(&mut self, old: &'bump [VNode<'bump>]) {
  1004. self.replace_and_create_many_with_many(old, None)
  1005. }
  1006. fn find_last_element(&mut self, vnode: &'bump VNode<'bump>) -> &'bump VNode<'bump> {
  1007. let mut search_node = Some(vnode);
  1008. loop {
  1009. let node = search_node.take().unwrap();
  1010. match &node.kind {
  1011. // the ones that have a direct id
  1012. VNodeKind::Text(_)
  1013. | VNodeKind::Element(_)
  1014. | VNodeKind::Anchor(_)
  1015. | VNodeKind::Suspended(_) => break node,
  1016. VNodeKind::Fragment(frag) => {
  1017. search_node = frag.children.last();
  1018. }
  1019. VNodeKind::Component(el) => {
  1020. let scope_id = el.ass_scope.get().unwrap();
  1021. let scope = self.get_scope(&scope_id).unwrap();
  1022. search_node = Some(scope.root());
  1023. }
  1024. }
  1025. }
  1026. }
  1027. fn find_first_element(&mut self, vnode: &'bump VNode<'bump>) -> &'bump VNode<'bump> {
  1028. let mut search_node = Some(vnode);
  1029. loop {
  1030. let node = search_node.take().unwrap();
  1031. match &node.kind {
  1032. // the ones that have a direct id
  1033. VNodeKind::Text(_)
  1034. | VNodeKind::Element(_)
  1035. | VNodeKind::Anchor(_)
  1036. | VNodeKind::Suspended(_) => break node,
  1037. VNodeKind::Fragment(frag) => {
  1038. search_node = Some(&frag.children[0]);
  1039. }
  1040. VNodeKind::Component(el) => {
  1041. let scope_id = el.ass_scope.get().unwrap();
  1042. let scope = self.get_scope(&scope_id).unwrap();
  1043. search_node = Some(scope.root());
  1044. }
  1045. }
  1046. }
  1047. }
  1048. fn remove_child(&mut self, node: &'bump VNode<'bump>) {
  1049. self.replace_and_create_many_with_many(Some(node), None);
  1050. }
  1051. /// Remove all the old nodes and replace them with newly created new nodes.
  1052. ///
  1053. /// The new nodes *will* be created - don't create them yourself!
  1054. fn replace_and_create_many_with_many(
  1055. &mut self,
  1056. old_nodes: impl IntoIterator<Item = &'bump VNode<'bump>>,
  1057. new_nodes: impl IntoIterator<Item = &'bump VNode<'bump>>,
  1058. ) {
  1059. let mut nodes_to_replace = Vec::new();
  1060. let mut nodes_to_search = old_nodes.into_iter().collect::<Vec<_>>();
  1061. let mut scopes_obliterated = Vec::new();
  1062. while let Some(node) = nodes_to_search.pop() {
  1063. match &node.kind {
  1064. // the ones that have a direct id return immediately
  1065. VNodeKind::Text(el) => nodes_to_replace.push(el.dom_id.get().unwrap()),
  1066. VNodeKind::Element(el) => nodes_to_replace.push(el.dom_id.get().unwrap()),
  1067. VNodeKind::Anchor(el) => nodes_to_replace.push(el.dom_id.get().unwrap()),
  1068. VNodeKind::Suspended(el) => nodes_to_replace.push(el.node.get().unwrap()),
  1069. // Fragments will either have a single anchor or a list of children
  1070. VNodeKind::Fragment(frag) => {
  1071. for child in frag.children {
  1072. nodes_to_search.push(child);
  1073. }
  1074. }
  1075. // Components can be any of the nodes above
  1076. // However, we do need to track which components need to be removed
  1077. VNodeKind::Component(el) => {
  1078. let scope_id = el.ass_scope.get().unwrap();
  1079. let scope = self.get_scope(&scope_id).unwrap();
  1080. let root = scope.root();
  1081. nodes_to_search.push(root);
  1082. scopes_obliterated.push(scope_id);
  1083. }
  1084. }
  1085. // TODO: enable internal garabge collection
  1086. // self.create_garbage(node);
  1087. }
  1088. let n = nodes_to_replace.len();
  1089. for node in nodes_to_replace {
  1090. self.edit_push_root(node);
  1091. }
  1092. let mut nodes_created = 0;
  1093. for node in new_nodes {
  1094. let meta = self.create_vnode(node);
  1095. nodes_created += meta.added_to_stack;
  1096. }
  1097. // if 0 nodes are created, then it gets interperted as a deletion
  1098. self.edit_replace_with(n as u32, nodes_created);
  1099. // obliterate!
  1100. for scope in scopes_obliterated {
  1101. self.destroy_scopes(scope);
  1102. }
  1103. }
  1104. fn create_garbage(&mut self, node: &'bump VNode<'bump>) {
  1105. match self.current_scope().and_then(|id| self.get_scope(&id)) {
  1106. Some(scope) => {
  1107. let garbage: &'bump VNode<'static> = unsafe { std::mem::transmute(node) };
  1108. scope.pending_garbage.borrow_mut().push(garbage);
  1109. }
  1110. None => {
  1111. log::info!("No scope to collect garbage into")
  1112. }
  1113. }
  1114. }
  1115. fn immediately_dispose_garabage(&mut self, node: ElementId) {
  1116. self.vdom.collect_garbage(node)
  1117. }
  1118. fn replace_node_with_node(
  1119. &mut self,
  1120. anchor: ElementId,
  1121. old_node: &'bump VNode<'bump>,
  1122. new_node: &'bump VNode<'bump>,
  1123. ) {
  1124. self.edit_push_root(anchor);
  1125. let meta = self.create_vnode(new_node);
  1126. self.edit_replace_with(1, meta.added_to_stack);
  1127. self.create_garbage(old_node);
  1128. self.edit_pop();
  1129. }
  1130. fn remove_vnode(&mut self, node: &'bump VNode<'bump>) {
  1131. match &node.kind {
  1132. VNodeKind::Text(el) => self.immediately_dispose_garabage(node.direct_id()),
  1133. VNodeKind::Element(el) => {
  1134. self.immediately_dispose_garabage(node.direct_id());
  1135. for child in el.children {
  1136. self.remove_vnode(&child);
  1137. }
  1138. }
  1139. VNodeKind::Anchor(a) => {
  1140. //
  1141. }
  1142. VNodeKind::Fragment(frag) => {
  1143. for child in frag.children {
  1144. self.remove_vnode(&child);
  1145. }
  1146. }
  1147. VNodeKind::Component(el) => {
  1148. //
  1149. // self.destroy_scopes(old_scope)
  1150. }
  1151. VNodeKind::Suspended(_) => todo!(),
  1152. }
  1153. }
  1154. fn current_scope(&self) -> Option<ScopeId> {
  1155. self.scope_stack.last().map(|f| f.clone())
  1156. }
  1157. fn fix_listener<'a>(&mut self, listener: &'a Listener<'a>) {
  1158. let scope_id = self.current_scope();
  1159. if let Some(scope_id) = scope_id {
  1160. let scope = self.get_scope(&scope_id).unwrap();
  1161. let mut queue = scope.listeners.borrow_mut();
  1162. let long_listener: &'a Listener<'static> = unsafe { std::mem::transmute(listener) };
  1163. queue.push(long_listener as *const _)
  1164. }
  1165. }
  1166. pub fn get_scope_mut(&mut self, id: &ScopeId) -> Option<&'bump mut Scope> {
  1167. // ensure we haven't seen this scope before
  1168. // if we have, then we're trying to alias it, which is not allowed
  1169. debug_assert!(!self.seen_scopes.contains(id));
  1170. unsafe { self.vdom.get_scope_mut(*id) }
  1171. }
  1172. pub fn get_scope(&mut self, id: &ScopeId) -> Option<&'bump Scope> {
  1173. // ensure we haven't seen this scope before
  1174. // if we have, then we're trying to alias it, which is not allowed
  1175. unsafe { self.vdom.get_scope(*id) }
  1176. }
  1177. // Navigation
  1178. pub(crate) fn edit_push_root(&mut self, root: ElementId) {
  1179. let id = root.as_u64();
  1180. self.mutations.edits.push(PushRoot { id });
  1181. }
  1182. pub(crate) fn edit_pop(&mut self) {
  1183. self.mutations.edits.push(PopRoot {});
  1184. }
  1185. // Add Nodes to the dom
  1186. // add m nodes from the stack
  1187. pub(crate) fn edit_append_children(&mut self, many: u32) {
  1188. self.mutations.edits.push(AppendChildren { many });
  1189. }
  1190. // replace the n-m node on the stack with the m nodes
  1191. // ends with the last element of the chain on the top of the stack
  1192. pub(crate) fn edit_replace_with(&mut self, n: u32, m: u32) {
  1193. self.mutations.edits.push(ReplaceWith { n, m });
  1194. }
  1195. pub(crate) fn edit_insert_after(&mut self, n: u32) {
  1196. self.mutations.edits.push(InsertAfter { n });
  1197. }
  1198. pub(crate) fn edit_insert_before(&mut self, n: u32) {
  1199. self.mutations.edits.push(InsertBefore { n });
  1200. }
  1201. // Remove Nodesfrom the dom
  1202. pub(crate) fn edit_remove(&mut self) {
  1203. self.mutations.edits.push(Remove);
  1204. }
  1205. // Create
  1206. pub(crate) fn edit_create_text_node(&mut self, text: &'bump str, id: ElementId) {
  1207. let id = id.as_u64();
  1208. self.mutations.edits.push(CreateTextNode { text, id });
  1209. }
  1210. pub(crate) fn edit_create_element(
  1211. &mut self,
  1212. tag: &'static str,
  1213. ns: Option<&'static str>,
  1214. id: ElementId,
  1215. ) {
  1216. let id = id.as_u64();
  1217. match ns {
  1218. Some(ns) => self.mutations.edits.push(CreateElementNs { id, ns, tag }),
  1219. None => self.mutations.edits.push(CreateElement { id, tag }),
  1220. }
  1221. }
  1222. // placeholders are nodes that don't get rendered but still exist as an "anchor" in the real dom
  1223. pub(crate) fn edit_create_placeholder(&mut self, id: ElementId) {
  1224. let id = id.as_u64();
  1225. self.mutations.edits.push(CreatePlaceholder { id });
  1226. }
  1227. // events
  1228. pub(crate) fn edit_new_event_listener(&mut self, listener: &Listener, scope: ScopeId) {
  1229. let Listener {
  1230. event,
  1231. mounted_node,
  1232. ..
  1233. } = listener;
  1234. let element_id = mounted_node.get().unwrap().as_u64();
  1235. self.mutations.edits.push(NewEventListener {
  1236. scope,
  1237. event_name: event,
  1238. mounted_node_id: element_id,
  1239. });
  1240. }
  1241. pub(crate) fn edit_remove_event_listener(&mut self, event: &'static str) {
  1242. self.mutations.edits.push(RemoveEventListener { event });
  1243. }
  1244. // modify
  1245. pub(crate) fn edit_set_text(&mut self, text: &'bump str) {
  1246. self.mutations.edits.push(SetText { text });
  1247. }
  1248. pub(crate) fn edit_set_attribute(&mut self, attribute: &'bump Attribute) {
  1249. let Attribute {
  1250. name,
  1251. value,
  1252. is_static,
  1253. is_volatile,
  1254. namespace,
  1255. } = attribute;
  1256. // field: &'static str,
  1257. // value: &'bump str,
  1258. // ns: Option<&'static str>,
  1259. self.mutations.edits.push(SetAttribute {
  1260. field: name,
  1261. value,
  1262. ns: *namespace,
  1263. });
  1264. }
  1265. pub(crate) fn edit_set_attribute_ns(
  1266. &mut self,
  1267. attribute: &'bump Attribute,
  1268. namespace: &'bump str,
  1269. ) {
  1270. let Attribute {
  1271. name,
  1272. value,
  1273. is_static,
  1274. is_volatile,
  1275. // namespace,
  1276. ..
  1277. } = attribute;
  1278. // field: &'static str,
  1279. // value: &'bump str,
  1280. // ns: Option<&'static str>,
  1281. self.mutations.edits.push(SetAttribute {
  1282. field: name,
  1283. value,
  1284. ns: Some(namespace),
  1285. });
  1286. }
  1287. pub(crate) fn edit_remove_attribute(&mut self, attribute: &Attribute) {
  1288. let name = attribute.name;
  1289. self.mutations.edits.push(RemoveAttribute { name });
  1290. }
  1291. }
  1292. // When we create new nodes, we need to propagate some information back up the call chain.
  1293. // This gives the caller some information on how to handle things like insertins, appending, and subtree discarding.
  1294. #[derive(Debug)]
  1295. pub struct CreateMeta {
  1296. pub is_static: bool,
  1297. pub added_to_stack: u32,
  1298. }
  1299. impl CreateMeta {
  1300. fn new(is_static: bool, added_to_tack: u32) -> Self {
  1301. Self {
  1302. is_static,
  1303. added_to_stack: added_to_tack,
  1304. }
  1305. }
  1306. }
  1307. enum KeyedPrefixResult {
  1308. // Fast path: we finished diffing all the children just by looking at the
  1309. // prefix of shared keys!
  1310. Finished,
  1311. // There is more diffing work to do. Here is a count of how many children at
  1312. // the beginning of `new` and `old` we already processed.
  1313. MoreWorkToDo(usize),
  1314. }
  1315. fn find_first_real_node<'a>(
  1316. nodes: impl IntoIterator<Item = &'a VNode<'a>>,
  1317. scopes: &'a SharedResources,
  1318. ) -> Option<&'a VNode<'a>> {
  1319. for node in nodes {
  1320. let mut iter = RealChildIterator::new(node, scopes);
  1321. if let Some(node) = iter.next() {
  1322. return Some(node);
  1323. }
  1324. }
  1325. None
  1326. }
  1327. /// This iterator iterates through a list of virtual children and only returns real children (Elements, Text, Anchors).
  1328. ///
  1329. /// This iterator is useful when it's important to load the next real root onto the top of the stack for operations like
  1330. /// "InsertBefore".
  1331. pub struct RealChildIterator<'a> {
  1332. scopes: &'a SharedResources,
  1333. // Heuristcally we should never bleed into 4 completely nested fragments/components
  1334. // Smallvec lets us stack allocate our little stack machine so the vast majority of cases are sane
  1335. // TODO: use const generics instead of the 4 estimation
  1336. stack: smallvec::SmallVec<[(u16, &'a VNode<'a>); 4]>,
  1337. }
  1338. impl<'a> RealChildIterator<'a> {
  1339. pub fn new(starter: &'a VNode<'a>, scopes: &'a SharedResources) -> Self {
  1340. Self {
  1341. scopes,
  1342. stack: smallvec::smallvec![(0, starter)],
  1343. }
  1344. }
  1345. // keep the memory around
  1346. pub fn reset_with(&mut self, node: &'a VNode<'a>) {
  1347. self.stack.clear();
  1348. self.stack.push((0, node));
  1349. }
  1350. }
  1351. impl<'a> Iterator for RealChildIterator<'a> {
  1352. type Item = &'a VNode<'a>;
  1353. fn next(&mut self) -> Option<&'a VNode<'a>> {
  1354. let mut should_pop = false;
  1355. let mut returned_node: Option<&'a VNode<'a>> = None;
  1356. let mut should_push = None;
  1357. while returned_node.is_none() {
  1358. if let Some((count, node)) = self.stack.last_mut() {
  1359. match &node.kind {
  1360. // We can only exit our looping when we get "real" nodes
  1361. // This includes fragments and components when they're empty (have a single root)
  1362. VNodeKind::Element(_) | VNodeKind::Text(_) => {
  1363. // We've recursed INTO an element/text
  1364. // We need to recurse *out* of it and move forward to the next
  1365. should_pop = true;
  1366. returned_node = Some(&*node);
  1367. }
  1368. // If we get a fragment we push the next child
  1369. VNodeKind::Fragment(frag) => {
  1370. let subcount = *count as usize;
  1371. if frag.children.len() == 0 {
  1372. should_pop = true;
  1373. returned_node = Some(&*node);
  1374. }
  1375. if subcount >= frag.children.len() {
  1376. should_pop = true;
  1377. } else {
  1378. should_push = Some(&frag.children[subcount]);
  1379. }
  1380. }
  1381. // // If we get a fragment we push the next child
  1382. // VNodeKind::Fragment(frag) => {
  1383. // let subcount = *count as usize;
  1384. // if frag.children.len() == 0 {
  1385. // should_pop = true;
  1386. // returned_node = Some(&*node);
  1387. // }
  1388. // if subcount >= frag.children.len() {
  1389. // should_pop = true;
  1390. // } else {
  1391. // should_push = Some(&frag.children[subcount]);
  1392. // }
  1393. // }
  1394. // Immediately abort suspended nodes - can't do anything with them yet
  1395. VNodeKind::Suspended(node) => {
  1396. // VNodeKind::Suspended => should_pop = true,
  1397. todo!()
  1398. }
  1399. VNodeKind::Anchor(a) => {
  1400. todo!()
  1401. }
  1402. // For components, we load their root and push them onto the stack
  1403. VNodeKind::Component(sc) => {
  1404. let scope =
  1405. unsafe { self.scopes.get_scope(sc.ass_scope.get().unwrap()) }.unwrap();
  1406. // let scope = self.scopes.get(sc.ass_scope.get().unwrap()).unwrap();
  1407. // Simply swap the current node on the stack with the root of the component
  1408. *node = scope.frames.fin_head();
  1409. }
  1410. }
  1411. } else {
  1412. // If there's no more items on the stack, we're done!
  1413. return None;
  1414. }
  1415. if should_pop {
  1416. self.stack.pop();
  1417. if let Some((id, _)) = self.stack.last_mut() {
  1418. *id += 1;
  1419. }
  1420. should_pop = false;
  1421. }
  1422. if let Some(push) = should_push {
  1423. self.stack.push((0, push));
  1424. should_push = None;
  1425. }
  1426. }
  1427. returned_node
  1428. }
  1429. }
  1430. fn compare_strs(a: &str, b: &str) -> bool {
  1431. // Check by pointer, optimizing for static strs
  1432. if !std::ptr::eq(a, b) {
  1433. // If the pointers are different then check by value
  1434. a == b
  1435. } else {
  1436. true
  1437. }
  1438. }