diff_async.rs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. use crate::innerlude::*;
  2. use fxhash::{FxHashMap, FxHashSet};
  3. use smallvec::{smallvec, SmallVec};
  4. pub(crate) struct AsyncDiffState<'bump> {
  5. pub(crate) scopes: &'bump ScopeArena,
  6. pub(crate) mutations: Mutations<'bump>,
  7. pub(crate) force_diff: bool,
  8. pub(crate) element_stack: SmallVec<[ElementId; 10]>,
  9. pub(crate) scope_stack: SmallVec<[ScopeId; 5]>,
  10. }
  11. impl<'b> AsyncDiffState<'b> {
  12. pub fn new(scopes: &'b ScopeArena) -> Self {
  13. Self {
  14. scopes,
  15. mutations: Mutations::new(),
  16. force_diff: false,
  17. element_stack: smallvec![],
  18. scope_stack: smallvec![],
  19. }
  20. }
  21. pub fn diff_scope(&mut self, scopeid: ScopeId) {
  22. let (old, new) = (self.scopes.wip_head(scopeid), self.scopes.fin_head(scopeid));
  23. self.scope_stack.push(scopeid);
  24. let scope = self.scopes.get_scope(scopeid).unwrap();
  25. self.element_stack.push(scope.container);
  26. self.diff_node(old, new);
  27. }
  28. pub fn diff_node(&mut self, old_node: &'b VNode<'b>, new_node: &'b VNode<'b>) {
  29. use VNode::*;
  30. match (old_node, new_node) {
  31. // Check the most common cases first
  32. // these are *actual* elements, not wrappers around lists
  33. (Text(old), Text(new)) => {
  34. if std::ptr::eq(old, new) {
  35. log::trace!("skipping node diff - text are the sames");
  36. return;
  37. }
  38. if let Some(root) = old.id.get() {
  39. if old.text != new.text {
  40. self.mutations.set_text(new.text, root.as_u64());
  41. }
  42. self.scopes.update_node(new_node, root);
  43. new.id.set(Some(root));
  44. }
  45. }
  46. (Placeholder(old), Placeholder(new)) => {
  47. if std::ptr::eq(old, new) {
  48. log::trace!("skipping node diff - placeholder are the sames");
  49. return;
  50. }
  51. if let Some(root) = old.id.get() {
  52. self.scopes.update_node(new_node, root);
  53. new.id.set(Some(root))
  54. }
  55. }
  56. (Element(old), Element(new)) => {
  57. if std::ptr::eq(old, new) {
  58. log::trace!("skipping node diff - element are the sames");
  59. return;
  60. }
  61. self.diff_element_nodes(old, new, old_node, new_node)
  62. }
  63. // These two sets are pointers to nodes but are not actually nodes themselves
  64. (Component(old), Component(new)) => {
  65. if std::ptr::eq(old, new) {
  66. log::trace!("skipping node diff - placeholder are the sames");
  67. return;
  68. }
  69. self.diff_component_nodes(old_node, new_node, *old, *new)
  70. }
  71. (Fragment(old), Fragment(new)) => {
  72. if std::ptr::eq(old, new) {
  73. log::trace!("skipping node diff - fragment are the sames");
  74. return;
  75. }
  76. self.diff_fragment_nodes(old, new)
  77. }
  78. // The normal pathway still works, but generates slightly weird instructions
  79. // This pathway ensures uses the ReplaceAll, not the InsertAfter and remove
  80. (Placeholder(_), Fragment(_)) => {
  81. log::debug!("replacing placeholder with fragment {:?}", new_node);
  82. self.replace_node(old_node, new_node);
  83. }
  84. // Anything else is just a basic replace and create
  85. (
  86. Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
  87. Component(_) | Fragment(_) | Text(_) | Element(_) | Placeholder(_),
  88. ) => self.replace_node(old_node, new_node),
  89. }
  90. }
  91. pub fn create_node(&mut self, node: &'b VNode<'b>) -> usize {
  92. match node {
  93. VNode::Text(vtext) => self.create_text_node(vtext, node),
  94. VNode::Placeholder(anchor) => self.create_anchor_node(anchor, node),
  95. VNode::Element(element) => self.create_element_node(element, node),
  96. VNode::Fragment(frag) => self.create_fragment_node(frag),
  97. VNode::Component(component) => self.create_component_node(*component),
  98. }
  99. }
  100. fn create_text_node(&mut self, vtext: &'b VText<'b>, node: &'b VNode<'b>) -> usize {
  101. let real_id = self.scopes.reserve_node(node);
  102. self.mutations.create_text_node(vtext.text, real_id);
  103. vtext.id.set(Some(real_id));
  104. 1
  105. }
  106. fn create_anchor_node(&mut self, anchor: &'b VPlaceholder, node: &'b VNode<'b>) -> usize {
  107. let real_id = self.scopes.reserve_node(node);
  108. self.mutations.create_placeholder(real_id);
  109. anchor.id.set(Some(real_id));
  110. 1
  111. }
  112. fn create_element_node(&mut self, element: &'b VElement<'b>, node: &'b VNode<'b>) -> usize {
  113. let VElement {
  114. tag: tag_name,
  115. listeners,
  116. attributes,
  117. children,
  118. namespace,
  119. id: dom_id,
  120. parent: parent_id,
  121. ..
  122. } = element;
  123. // set the parent ID for event bubbling
  124. // self.stack.instructions.push(DiffInstruction::PopElement);
  125. let parent = self.element_stack.last().unwrap();
  126. parent_id.set(Some(*parent));
  127. // set the id of the element
  128. let real_id = self.scopes.reserve_node(node);
  129. self.element_stack.push(real_id);
  130. dom_id.set(Some(real_id));
  131. self.mutations.create_element(tag_name, *namespace, real_id);
  132. if let Some(cur_scope_id) = self.current_scope() {
  133. for listener in *listeners {
  134. listener.mounted_node.set(Some(real_id));
  135. self.mutations.new_event_listener(listener, cur_scope_id);
  136. }
  137. } else {
  138. log::warn!("create element called with no scope on the stack - this is an error for a live dom");
  139. }
  140. for attr in *attributes {
  141. self.mutations.set_attribute(attr, real_id.as_u64());
  142. }
  143. if !children.is_empty() {
  144. self.create_and_append_children(children);
  145. }
  146. 1
  147. }
  148. fn create_fragment_node(&mut self, frag: &'b VFragment<'b>) -> usize {
  149. self.create_children(frag.children)
  150. }
  151. fn create_component_node(&mut self, vcomponent: &'b VComponent<'b>) -> usize {
  152. let parent_idx = self.current_scope().unwrap();
  153. // the component might already exist - if it does, we need to reuse it
  154. // this makes figure out when to drop the component more complicated
  155. let new_idx = if let Some(idx) = vcomponent.scope.get() {
  156. assert!(self.scopes.get_scope(idx).is_some());
  157. idx
  158. } else {
  159. // Insert a new scope into our component list
  160. let props: Box<dyn AnyProps + 'b> = vcomponent.props.borrow_mut().take().unwrap();
  161. let props: Box<dyn AnyProps + 'static> = unsafe { std::mem::transmute(props) };
  162. let new_idx = self.scopes.new_with_key(
  163. vcomponent.user_fc,
  164. props,
  165. Some(parent_idx),
  166. self.element_stack.last().copied().unwrap(),
  167. 0,
  168. );
  169. new_idx
  170. };
  171. log::info!(
  172. "created component {:?} with parent {:?} and originator {:?}",
  173. new_idx,
  174. parent_idx,
  175. vcomponent.originator
  176. );
  177. // Actually initialize the caller's slot with the right address
  178. vcomponent.scope.set(Some(new_idx));
  179. match vcomponent.can_memoize {
  180. true => {
  181. // todo: implement promotion logic. save us from boxing props that we don't need
  182. }
  183. false => {
  184. // track this component internally so we know the right drop order
  185. }
  186. }
  187. // Run the scope for one iteration to initialize it
  188. self.scopes.run_scope(new_idx);
  189. self.mutations.mark_dirty_scope(new_idx);
  190. // self.stack.create_component(new_idx, nextnode);
  191. // Finally, insert this scope as a seen node.
  192. // Take the node that was just generated from running the component
  193. let nextnode = self.scopes.fin_head(new_idx);
  194. self.create_node(nextnode)
  195. }
  196. fn diff_element_nodes(
  197. &mut self,
  198. old: &'b VElement<'b>,
  199. new: &'b VElement<'b>,
  200. old_node: &'b VNode<'b>,
  201. new_node: &'b VNode<'b>,
  202. ) {
  203. let root = old.id.get().unwrap();
  204. // If the element type is completely different, the element needs to be re-rendered completely
  205. // This is an optimization React makes due to how users structure their code
  206. //
  207. // This case is rather rare (typically only in non-keyed lists)
  208. if new.tag != old.tag || new.namespace != old.namespace {
  209. self.replace_node(old_node, new_node);
  210. return;
  211. }
  212. self.scopes.update_node(new_node, root);
  213. new.id.set(Some(root));
  214. new.parent.set(old.parent.get());
  215. // todo: attributes currently rely on the element on top of the stack, but in theory, we only need the id of the
  216. // element to modify its attributes.
  217. // it would result in fewer instructions if we just set the id directly.
  218. // it would also clean up this code some, but that's not very important anyways
  219. // Diff Attributes
  220. //
  221. // It's extraordinarily rare to have the number/order of attributes change
  222. // In these cases, we just completely erase the old set and make a new set
  223. //
  224. // TODO: take a more efficient path than this
  225. if old.attributes.len() == new.attributes.len() {
  226. for (old_attr, new_attr) in old.attributes.iter().zip(new.attributes.iter()) {
  227. if old_attr.value != new_attr.value || new_attr.is_volatile {
  228. self.mutations.set_attribute(new_attr, root.as_u64());
  229. }
  230. }
  231. } else {
  232. for attribute in old.attributes {
  233. self.mutations.remove_attribute(attribute, root.as_u64());
  234. }
  235. for attribute in new.attributes {
  236. self.mutations.set_attribute(attribute, root.as_u64())
  237. }
  238. }
  239. // Diff listeners
  240. //
  241. // It's extraordinarily rare to have the number/order of listeners change
  242. // In the cases where the listeners change, we completely wipe the data attributes and add new ones
  243. //
  244. // We also need to make sure that all listeners are properly attached to the parent scope (fix_listener)
  245. //
  246. // TODO: take a more efficient path than this
  247. if let Some(cur_scope_id) = self.current_scope() {
  248. if old.listeners.len() == new.listeners.len() {
  249. for (old_l, new_l) in old.listeners.iter().zip(new.listeners.iter()) {
  250. if old_l.event != new_l.event {
  251. self.mutations
  252. .remove_event_listener(old_l.event, root.as_u64());
  253. self.mutations.new_event_listener(new_l, cur_scope_id);
  254. }
  255. new_l.mounted_node.set(old_l.mounted_node.get());
  256. }
  257. } else {
  258. for listener in old.listeners {
  259. self.mutations
  260. .remove_event_listener(listener.event, root.as_u64());
  261. }
  262. for listener in new.listeners {
  263. listener.mounted_node.set(Some(root));
  264. self.mutations.new_event_listener(listener, cur_scope_id);
  265. }
  266. }
  267. }
  268. match (old.children.len(), new.children.len()) {
  269. (0, 0) => {}
  270. (0, _) => {
  271. let created = self.create_children(new.children);
  272. self.mutations.append_children(created as u32);
  273. }
  274. (_, _) => {
  275. self.diff_children(old.children, new.children);
  276. }
  277. };
  278. }
  279. fn diff_component_nodes(
  280. &mut self,
  281. old_node: &'b VNode<'b>,
  282. new_node: &'b VNode<'b>,
  283. old: &'b VComponent<'b>,
  284. new: &'b VComponent<'b>,
  285. ) {
  286. let scope_addr = old.scope.get().unwrap();
  287. log::trace!(
  288. "diff_component_nodes. old: {:#?} new: {:#?}",
  289. old_node,
  290. new_node
  291. );
  292. if std::ptr::eq(old, new) {
  293. log::trace!("skipping component diff - component is the sames");
  294. return;
  295. }
  296. // Make sure we're dealing with the same component (by function pointer)
  297. if old.user_fc == new.user_fc {
  298. self.enter_scope(scope_addr);
  299. // Make sure the new component vnode is referencing the right scope id
  300. new.scope.set(Some(scope_addr));
  301. // make sure the component's caller function is up to date
  302. let scope = self
  303. .scopes
  304. .get_scope(scope_addr)
  305. .unwrap_or_else(|| panic!("could not find {:?}", scope_addr));
  306. // take the new props out regardless
  307. // when memoizing, push to the existing scope if memoization happens
  308. let new_props = new.props.borrow_mut().take().unwrap();
  309. let should_run = {
  310. if old.can_memoize {
  311. let props_are_the_same = unsafe {
  312. scope
  313. .props
  314. .borrow()
  315. .as_ref()
  316. .unwrap()
  317. .memoize(new_props.as_ref())
  318. };
  319. !props_are_the_same || self.force_diff
  320. } else {
  321. true
  322. }
  323. };
  324. if should_run {
  325. let _old_props = scope
  326. .props
  327. .replace(unsafe { std::mem::transmute(Some(new_props)) });
  328. // this should auto drop the previous props
  329. self.scopes.run_scope(scope_addr);
  330. self.mutations.mark_dirty_scope(scope_addr);
  331. self.diff_node(
  332. self.scopes.wip_head(scope_addr),
  333. self.scopes.fin_head(scope_addr),
  334. );
  335. } else {
  336. log::trace!("memoized");
  337. // memoization has taken place
  338. drop(new_props);
  339. };
  340. self.leave_scope();
  341. } else {
  342. log::debug!("scope stack is {:#?}", self.scope_stack);
  343. self.replace_node(old_node, new_node);
  344. }
  345. }
  346. fn diff_fragment_nodes(&mut self, old: &'b VFragment<'b>, new: &'b VFragment<'b>) {
  347. // This is the case where options or direct vnodes might be used.
  348. // In this case, it's faster to just skip ahead to their diff
  349. if old.children.len() == 1 && new.children.len() == 1 {
  350. self.diff_node(&old.children[0], &new.children[0]);
  351. return;
  352. }
  353. debug_assert!(!old.children.is_empty());
  354. debug_assert!(!new.children.is_empty());
  355. self.diff_children(old.children, new.children);
  356. }
  357. // =============================================
  358. // Utilities for creating new diff instructions
  359. // =============================================
  360. // Diff the given set of old and new children.
  361. //
  362. // The parent must be on top of the change list stack when this function is
  363. // entered:
  364. //
  365. // [... parent]
  366. //
  367. // the change list stack is in the same state when this function returns.
  368. //
  369. // If old no anchors are provided, then it's assumed that we can freely append to the parent.
  370. //
  371. // Remember, non-empty lists does not mean that there are real elements, just that there are virtual elements.
  372. //
  373. // Fragment nodes cannot generate empty children lists, so we can assume that when a list is empty, it belongs only
  374. // to an element, and appending makes sense.
  375. fn diff_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  376. // Remember, fragments can never be empty (they always have a single child)
  377. match (old, new) {
  378. ([], []) => {}
  379. ([], _) => self.create_and_append_children(new),
  380. (_, []) => self.remove_nodes(old, true),
  381. _ => {
  382. let new_is_keyed = new[0].key().is_some();
  383. let old_is_keyed = old[0].key().is_some();
  384. debug_assert!(
  385. new.iter().all(|n| n.key().is_some() == new_is_keyed),
  386. "all siblings must be keyed or all siblings must be non-keyed"
  387. );
  388. debug_assert!(
  389. old.iter().all(|o| o.key().is_some() == old_is_keyed),
  390. "all siblings must be keyed or all siblings must be non-keyed"
  391. );
  392. if new_is_keyed && old_is_keyed {
  393. self.diff_keyed_children(old, new);
  394. } else {
  395. self.diff_non_keyed_children(old, new);
  396. }
  397. }
  398. }
  399. }
  400. // Diff children that are not keyed.
  401. //
  402. // The parent must be on the top of the change list stack when entering this
  403. // function:
  404. //
  405. // [... parent]
  406. //
  407. // the change list stack is in the same state when this function returns.
  408. fn diff_non_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  409. // Handled these cases in `diff_children` before calling this function.
  410. debug_assert!(!new.is_empty());
  411. debug_assert!(!old.is_empty());
  412. use std::cmp::Ordering;
  413. match old.len().cmp(&new.len()) {
  414. Ordering::Greater => self.remove_nodes(&old[new.len()..], true),
  415. Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
  416. Ordering::Equal => {}
  417. }
  418. for (new, old) in new.iter().zip(old.iter()) {
  419. self.diff_node(old, new);
  420. }
  421. }
  422. // Diffing "keyed" children.
  423. //
  424. // With keyed children, we care about whether we delete, move, or create nodes
  425. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  426. // transition animation that makes the virtual DOM diffing algorithm
  427. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  428. // must reuse (or not reuse) the same physical DOM nodes.
  429. //
  430. // This is loosely based on Inferno's keyed patching implementation. However, we
  431. // have to modify the algorithm since we are compiling the diff down into change
  432. // list instructions that will be executed later, rather than applying the
  433. // changes to the DOM directly as we compare virtual DOMs.
  434. //
  435. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  436. //
  437. // The stack is empty upon entry.
  438. fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  439. if cfg!(debug_assertions) {
  440. let mut keys = fxhash::FxHashSet::default();
  441. let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
  442. keys.clear();
  443. for child in children {
  444. let key = child.key();
  445. debug_assert!(
  446. key.is_some(),
  447. "if any sibling is keyed, all siblings must be keyed"
  448. );
  449. keys.insert(key);
  450. }
  451. debug_assert_eq!(
  452. children.len(),
  453. keys.len(),
  454. "keyed siblings must each have a unique key"
  455. );
  456. };
  457. assert_unique_keys(old);
  458. assert_unique_keys(new);
  459. }
  460. // First up, we diff all the nodes with the same key at the beginning of the
  461. // children.
  462. //
  463. // `shared_prefix_count` is the count of how many nodes at the start of
  464. // `new` and `old` share the same keys.
  465. let (left_offset, right_offset) = match self.diff_keyed_ends(old, new) {
  466. Some(count) => count,
  467. None => return,
  468. };
  469. // Ok, we now hopefully have a smaller range of children in the middle
  470. // within which to re-order nodes with the same keys, remove old nodes with
  471. // now-unused keys, and create new nodes with fresh keys.
  472. let old_middle = &old[left_offset..(old.len() - right_offset)];
  473. let new_middle = &new[left_offset..(new.len() - right_offset)];
  474. debug_assert!(
  475. !((old_middle.len() == new_middle.len()) && old_middle.is_empty()),
  476. "keyed children must have the same number of children"
  477. );
  478. if new_middle.is_empty() {
  479. // remove the old elements
  480. self.remove_nodes(old_middle, true);
  481. } else if old_middle.is_empty() {
  482. // there were no old elements, so just create the new elements
  483. // we need to find the right "foothold" though - we shouldn't use the "append" at all
  484. if left_offset == 0 {
  485. // insert at the beginning of the old list
  486. let foothold = &old[old.len() - right_offset];
  487. self.create_and_insert_before(new_middle, foothold);
  488. } else if right_offset == 0 {
  489. // insert at the end the old list
  490. let foothold = old.last().unwrap();
  491. self.create_and_insert_after(new_middle, foothold);
  492. } else {
  493. // inserting in the middle
  494. let foothold = &old[left_offset - 1];
  495. self.create_and_insert_after(new_middle, foothold);
  496. }
  497. } else {
  498. self.diff_keyed_middle(old_middle, new_middle);
  499. }
  500. }
  501. /// Diff both ends of the children that share keys.
  502. ///
  503. /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing.
  504. ///
  505. /// If there is no offset, then this function returns None and the diffing is complete.
  506. fn diff_keyed_ends(
  507. &mut self,
  508. old: &'b [VNode<'b>],
  509. new: &'b [VNode<'b>],
  510. ) -> Option<(usize, usize)> {
  511. let mut left_offset = 0;
  512. for (old, new) in old.iter().zip(new.iter()) {
  513. // abort early if we finally run into nodes with different keys
  514. if old.key() != new.key() {
  515. break;
  516. }
  517. self.diff_node(old, new);
  518. left_offset += 1;
  519. }
  520. // If that was all of the old children, then create and append the remaining
  521. // new children and we're finished.
  522. if left_offset == old.len() {
  523. self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
  524. return None;
  525. }
  526. // And if that was all of the new children, then remove all of the remaining
  527. // old children and we're finished.
  528. if left_offset == new.len() {
  529. self.remove_nodes(&old[left_offset..], true);
  530. return None;
  531. }
  532. // if the shared prefix is less than either length, then we need to walk backwards
  533. let mut right_offset = 0;
  534. for (old, new) in old.iter().rev().zip(new.iter().rev()) {
  535. // abort early if we finally run into nodes with different keys
  536. if old.key() != new.key() {
  537. break;
  538. }
  539. self.diff_node(old, new);
  540. right_offset += 1;
  541. }
  542. Some((left_offset, right_offset))
  543. }
  544. // The most-general, expensive code path for keyed children diffing.
  545. //
  546. // We find the longest subsequence within `old` of children that are relatively
  547. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  548. // of the old child's index within `new`). The children that are elements of
  549. // this subsequence will remain in place, minimizing the number of DOM moves we
  550. // will have to do.
  551. //
  552. // Upon entry to this function, the change list stack must be empty.
  553. //
  554. // This function will load the appropriate nodes onto the stack and do diffing in place.
  555. //
  556. // Upon exit from this function, it will be restored to that same self.
  557. fn diff_keyed_middle(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
  558. /*
  559. 1. Map the old keys into a numerical ordering based on indices.
  560. 2. Create a map of old key to its index
  561. 3. Map each new key to the old key, carrying over the old index.
  562. - IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3
  563. - if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist
  564. now, we should have a list of integers that indicates where in the old list the new items map to.
  565. 4. Compute the LIS of this list
  566. - this indicates the longest list of new children that won't need to be moved.
  567. 5. Identify which nodes need to be removed
  568. 6. Identify which nodes will need to be diffed
  569. 7. Going along each item in the new list, create it and insert it before the next closest item in the LIS.
  570. - if the item already existed, just move it to the right place.
  571. 8. Finally, generate instructions to remove any old children.
  572. 9. Generate instructions to finally diff children that are the same between both
  573. */
  574. // 0. Debug sanity checks
  575. // Should have already diffed the shared-key prefixes and suffixes.
  576. debug_assert_ne!(new.first().map(|n| n.key()), old.first().map(|o| o.key()));
  577. debug_assert_ne!(new.last().map(|n| n.key()), old.last().map(|o| o.key()));
  578. // 1. Map the old keys into a numerical ordering based on indices.
  579. // 2. Create a map of old key to its index
  580. // IE if the keys were A B C, then we would have (A, 1) (B, 2) (C, 3).
  581. let old_key_to_old_index = old
  582. .iter()
  583. .enumerate()
  584. .map(|(i, o)| (o.key().unwrap(), i))
  585. .collect::<FxHashMap<_, _>>();
  586. let mut shared_keys = FxHashSet::default();
  587. // 3. Map each new key to the old key, carrying over the old index.
  588. let new_index_to_old_index = new
  589. .iter()
  590. .map(|node| {
  591. let key = node.key().unwrap();
  592. if let Some(&index) = old_key_to_old_index.get(&key) {
  593. shared_keys.insert(key);
  594. index
  595. } else {
  596. u32::MAX as usize
  597. }
  598. })
  599. .collect::<Vec<_>>();
  600. // If none of the old keys are reused by the new children, then we remove all the remaining old children and
  601. // create the new children afresh.
  602. if shared_keys.is_empty() {
  603. if let Some(first_old) = old.get(0) {
  604. self.remove_nodes(&old[1..], true);
  605. let nodes_created = self.create_children(new);
  606. self.replace_inner(first_old, nodes_created);
  607. } else {
  608. // I think this is wrong - why are we appending?
  609. // only valid of the if there are no trailing elements
  610. self.create_and_append_children(new);
  611. }
  612. return;
  613. }
  614. // 4. Compute the LIS of this list
  615. let mut lis_sequence = Vec::default();
  616. lis_sequence.reserve(new_index_to_old_index.len());
  617. let mut predecessors = vec![0; new_index_to_old_index.len()];
  618. let mut starts = vec![0; new_index_to_old_index.len()];
  619. longest_increasing_subsequence::lis_with(
  620. &new_index_to_old_index,
  621. &mut lis_sequence,
  622. |a, b| a < b,
  623. &mut predecessors,
  624. &mut starts,
  625. );
  626. // the lis comes out backwards, I think. can't quite tell.
  627. lis_sequence.sort_unstable();
  628. // 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)
  629. if lis_sequence.last().map(|f| new_index_to_old_index[*f]) == Some(u32::MAX as usize) {
  630. lis_sequence.pop();
  631. }
  632. for idx in lis_sequence.iter() {
  633. self.diff_node(&old[new_index_to_old_index[*idx]], &new[*idx]);
  634. }
  635. let mut nodes_created = 0;
  636. // add mount instruction for the first items not covered by the lis
  637. let last = *lis_sequence.last().unwrap();
  638. if last < (new.len() - 1) {
  639. for (idx, new_node) in new[(last + 1)..].iter().enumerate() {
  640. let new_idx = idx + last + 1;
  641. let old_index = new_index_to_old_index[new_idx];
  642. if old_index == u32::MAX as usize {
  643. nodes_created += self.create_node(new_node);
  644. } else {
  645. self.diff_node(&old[old_index], new_node);
  646. nodes_created += self.push_all_nodes(new_node);
  647. }
  648. }
  649. self.mutations.insert_after(
  650. self.find_last_element(&new[last]).unwrap(),
  651. nodes_created as u32,
  652. );
  653. nodes_created = 0;
  654. }
  655. // for each spacing, generate a mount instruction
  656. let mut lis_iter = lis_sequence.iter().rev();
  657. let mut last = *lis_iter.next().unwrap();
  658. for next in lis_iter {
  659. if last - next > 1 {
  660. for (idx, new_node) in new[(next + 1)..last].iter().enumerate() {
  661. let new_idx = idx + next + 1;
  662. let old_index = new_index_to_old_index[new_idx];
  663. if old_index == u32::MAX as usize {
  664. nodes_created += self.create_node(new_node);
  665. } else {
  666. self.diff_node(&old[old_index], new_node);
  667. nodes_created += self.push_all_nodes(new_node);
  668. }
  669. }
  670. self.mutations.insert_before(
  671. self.find_first_element(&new[last]).unwrap(),
  672. nodes_created as u32,
  673. );
  674. nodes_created = 0;
  675. }
  676. last = *next;
  677. }
  678. // add mount instruction for the last items not covered by the lis
  679. let first_lis = *lis_sequence.first().unwrap();
  680. if first_lis > 0 {
  681. for (idx, new_node) in new[..first_lis].iter().enumerate() {
  682. let old_index = new_index_to_old_index[idx];
  683. if old_index == u32::MAX as usize {
  684. nodes_created += self.create_node(new_node);
  685. } else {
  686. self.diff_node(&old[old_index], new_node);
  687. nodes_created += self.push_all_nodes(new_node);
  688. }
  689. }
  690. self.mutations.insert_before(
  691. self.find_first_element(&new[first_lis]).unwrap(),
  692. nodes_created as u32,
  693. );
  694. }
  695. }
  696. fn replace_node(&mut self, old: &'b VNode<'b>, new: &'b VNode<'b>) {
  697. // fn replace_node(&mut self, old: &'b VNode<'b>, new: &'b VNode<'b>) {
  698. log::debug!("Replacing node {:?}", old);
  699. let nodes_created = self.create_node(new);
  700. self.replace_inner(old, nodes_created);
  701. }
  702. fn replace_inner(&mut self, old: &'b VNode<'b>, nodes_created: usize) {
  703. match old {
  704. VNode::Element(el) => {
  705. let id = old
  706. .try_mounted_id()
  707. .unwrap_or_else(|| panic!("broke on {:?}", old));
  708. self.mutations.replace_with(id, nodes_created as u32);
  709. self.remove_nodes(el.children, false);
  710. self.scopes.collect_garbage(id);
  711. }
  712. VNode::Text(_) | VNode::Placeholder(_) => {
  713. let id = old
  714. .try_mounted_id()
  715. .unwrap_or_else(|| panic!("broke on {:?}", old));
  716. self.mutations.replace_with(id, nodes_created as u32);
  717. self.scopes.collect_garbage(id);
  718. }
  719. VNode::Fragment(f) => {
  720. self.replace_inner(&f.children[0], nodes_created);
  721. self.remove_nodes(f.children.iter().skip(1), true);
  722. }
  723. VNode::Component(c) => {
  724. let node = self.scopes.fin_head(c.scope.get().unwrap());
  725. self.replace_node(node, node);
  726. let scope_id = c.scope.get().unwrap();
  727. // we can only remove components if they are actively being diffed
  728. if self.scope_stack.contains(&c.originator) {
  729. self.scopes.try_remove(scope_id).unwrap();
  730. }
  731. }
  732. }
  733. }
  734. pub fn remove_nodes(&mut self, nodes: impl IntoIterator<Item = &'b VNode<'b>>, gen_muts: bool) {
  735. for node in nodes {
  736. match node {
  737. VNode::Text(t) => {
  738. // this check exists because our null node will be removed but does not have an ID
  739. if let Some(id) = t.id.get() {
  740. self.scopes.collect_garbage(id);
  741. if gen_muts {
  742. self.mutations.remove(id.as_u64());
  743. }
  744. }
  745. }
  746. VNode::Placeholder(a) => {
  747. let id = a.id.get().unwrap();
  748. self.scopes.collect_garbage(id);
  749. if gen_muts {
  750. self.mutations.remove(id.as_u64());
  751. }
  752. }
  753. VNode::Element(e) => {
  754. let id = e.id.get().unwrap();
  755. if gen_muts {
  756. self.mutations.remove(id.as_u64());
  757. }
  758. self.scopes.collect_garbage(id);
  759. self.remove_nodes(e.children, false);
  760. }
  761. VNode::Fragment(f) => {
  762. self.remove_nodes(f.children, gen_muts);
  763. }
  764. VNode::Component(c) => {
  765. let scope_id = c.scope.get().unwrap();
  766. let root = self.scopes.root_node(scope_id);
  767. self.remove_nodes([root], gen_muts);
  768. // we can only remove this node if the originator is actively
  769. if self.scope_stack.contains(&c.originator) {
  770. self.scopes.try_remove(scope_id).unwrap();
  771. }
  772. }
  773. }
  774. }
  775. }
  776. fn create_children(&mut self, nodes: &'b [VNode<'b>]) -> usize {
  777. let mut created = 0;
  778. for node in nodes {
  779. created += self.create_node(node);
  780. }
  781. created
  782. }
  783. fn create_and_append_children(&mut self, nodes: &'b [VNode<'b>]) {
  784. let created = self.create_children(nodes);
  785. self.mutations.append_children(created as u32);
  786. }
  787. fn create_and_insert_after(&mut self, nodes: &'b [VNode<'b>], after: &'b VNode<'b>) {
  788. let created = self.create_children(nodes);
  789. let last = self.find_last_element(after).unwrap();
  790. self.mutations.insert_after(last, created as u32);
  791. }
  792. fn create_and_insert_before(&mut self, nodes: &'b [VNode<'b>], before: &'b VNode<'b>) {
  793. let created = self.create_children(nodes);
  794. let first = self.find_first_element(before).unwrap();
  795. self.mutations.insert_before(first, created as u32);
  796. }
  797. fn current_scope(&self) -> Option<ScopeId> {
  798. self.scope_stack.last().copied()
  799. }
  800. fn enter_scope(&mut self, scope: ScopeId) {
  801. self.scope_stack.push(scope);
  802. }
  803. fn leave_scope(&mut self) {
  804. self.scope_stack.pop();
  805. }
  806. fn find_last_element(&self, vnode: &'b VNode<'b>) -> Option<ElementId> {
  807. let mut search_node = Some(vnode);
  808. loop {
  809. match &search_node.take().unwrap() {
  810. VNode::Text(t) => break t.id.get(),
  811. VNode::Element(t) => break t.id.get(),
  812. VNode::Placeholder(t) => break t.id.get(),
  813. VNode::Fragment(frag) => {
  814. search_node = frag.children.last();
  815. }
  816. VNode::Component(el) => {
  817. let scope_id = el.scope.get().unwrap();
  818. search_node = Some(self.scopes.root_node(scope_id));
  819. }
  820. }
  821. }
  822. }
  823. fn find_first_element(&self, vnode: &'b VNode<'b>) -> Option<ElementId> {
  824. let mut search_node = Some(vnode);
  825. loop {
  826. match &search_node.take().unwrap() {
  827. // the ones that have a direct id
  828. VNode::Fragment(frag) => {
  829. search_node = Some(&frag.children[0]);
  830. }
  831. VNode::Component(el) => {
  832. let scope_id = el.scope.get().unwrap();
  833. search_node = Some(self.scopes.root_node(scope_id));
  834. }
  835. VNode::Text(t) => break t.id.get(),
  836. VNode::Element(t) => break t.id.get(),
  837. VNode::Placeholder(t) => break t.id.get(),
  838. }
  839. }
  840. }
  841. // fn replace_node(&mut self, old: &'b VNode<'b>, nodes_created: usize) {
  842. // log::debug!("Replacing node {:?}", old);
  843. // match old {
  844. // VNode::Element(el) => {
  845. // let id = old
  846. // .try_mounted_id()
  847. // .unwrap_or_else(|| panic!("broke on {:?}", old));
  848. // self.mutations.replace_with(id, nodes_created as u32);
  849. // self.remove_nodes(el.children, false);
  850. // }
  851. // VNode::Text(_) | VNode::Placeholder(_) => {
  852. // let id = old
  853. // .try_mounted_id()
  854. // .unwrap_or_else(|| panic!("broke on {:?}", old));
  855. // self.mutations.replace_with(id, nodes_created as u32);
  856. // }
  857. // VNode::Fragment(f) => {
  858. // self.replace_node(&f.children[0], nodes_created);
  859. // self.remove_nodes(f.children.iter().skip(1), true);
  860. // }
  861. // VNode::Component(c) => {
  862. // let node = self.scopes.fin_head(c.scope.get().unwrap());
  863. // self.replace_node(node, nodes_created);
  864. // let scope_id = c.scope.get().unwrap();
  865. // // we can only remove components if they are actively being diffed
  866. // if self.stack.scope_stack.contains(&c.originator) {
  867. // self.scopes.try_remove(scope_id).unwrap();
  868. // }
  869. // }
  870. // }
  871. // }
  872. // /// schedules nodes for garbage collection and pushes "remove" to the mutation stack
  873. // /// remove can happen whenever
  874. // pub(crate) fn remove_nodes(
  875. // &mut self,
  876. // nodes: impl IntoIterator<Item = &'b VNode<'b>>,
  877. // gen_muts: bool,
  878. // ) {
  879. // // or cache the vec on the diff machine
  880. // for node in nodes {
  881. // log::debug!("removing {:?}", node);
  882. // match node {
  883. // VNode::Text(t) => {
  884. // // this check exists because our null node will be removed but does not have an ID
  885. // if let Some(id) = t.id.get() {
  886. // // self.scopes.collect_garbage(id);
  887. // if gen_muts {
  888. // self.mutations.remove(id.as_u64());
  889. // }
  890. // }
  891. // }
  892. // VNode::Placeholder(a) => {
  893. // let id = a.id.get().unwrap();
  894. // // self.scopes.collect_garbage(id);
  895. // if gen_muts {
  896. // self.mutations.remove(id.as_u64());
  897. // }
  898. // }
  899. // VNode::Element(e) => {
  900. // let id = e.id.get().unwrap();
  901. // if gen_muts {
  902. // self.mutations.remove(id.as_u64());
  903. // }
  904. // self.remove_nodes(e.children, false);
  905. // // self.scopes.collect_garbage(id);
  906. // }
  907. // VNode::Fragment(f) => {
  908. // self.remove_nodes(f.children, gen_muts);
  909. // }
  910. // VNode::Component(c) => {
  911. // let scope_id = c.scope.get().unwrap();
  912. // let root = self.scopes.root_node(scope_id);
  913. // self.remove_nodes(Some(root), gen_muts);
  914. // // we can only remove this node if the originator is actively
  915. // if self.stack.scope_stack.contains(&c.originator) {
  916. // self.scopes.try_remove(scope_id).unwrap();
  917. // }
  918. // }
  919. // }
  920. // }
  921. // }
  922. // recursively push all the nodes of a tree onto the stack and return how many are there
  923. fn push_all_nodes(&mut self, node: &'b VNode<'b>) -> usize {
  924. match node {
  925. VNode::Text(_) | VNode::Placeholder(_) => {
  926. self.mutations.push_root(node.mounted_id());
  927. 1
  928. }
  929. VNode::Fragment(_) | VNode::Component(_) => {
  930. //
  931. let mut added = 0;
  932. for child in node.children() {
  933. added += self.push_all_nodes(child);
  934. }
  935. added
  936. }
  937. VNode::Element(el) => {
  938. let mut num_on_stack = 0;
  939. for child in el.children.iter() {
  940. num_on_stack += self.push_all_nodes(child);
  941. }
  942. self.mutations.push_root(el.id.get().unwrap());
  943. num_on_stack + 1
  944. }
  945. }
  946. }
  947. }