diff.rs 39 KB

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