iterator.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. use crate::{
  2. innerlude::{ElementRef, WriteMutations},
  3. nodes::VNode,
  4. DynamicNode, ScopeId, VirtualDom,
  5. };
  6. use rustc_hash::{FxHashMap, FxHashSet};
  7. impl VirtualDom {
  8. pub(crate) fn diff_non_empty_fragment(
  9. &mut self,
  10. to: Option<&mut impl WriteMutations>,
  11. old: &[VNode],
  12. new: &[VNode],
  13. parent: Option<ElementRef>,
  14. ) {
  15. let new_is_keyed = new[0].key.is_some();
  16. let old_is_keyed = old[0].key.is_some();
  17. debug_assert!(
  18. new.iter().all(|n| n.key.is_some() == new_is_keyed),
  19. "all siblings must be keyed or all siblings must be non-keyed"
  20. );
  21. debug_assert!(
  22. old.iter().all(|o| o.key.is_some() == old_is_keyed),
  23. "all siblings must be keyed or all siblings must be non-keyed"
  24. );
  25. if new_is_keyed && old_is_keyed {
  26. self.diff_keyed_children(to, old, new, parent);
  27. } else {
  28. self.diff_non_keyed_children(to, old, new, parent);
  29. }
  30. }
  31. // Diff children that are not keyed.
  32. //
  33. // The parent must be on the top of the change list stack when entering this
  34. // function:
  35. //
  36. // [... parent]
  37. //
  38. // the change list stack is in the same state when this function returns.
  39. fn diff_non_keyed_children(
  40. &mut self,
  41. mut to: Option<&mut impl WriteMutations>,
  42. old: &[VNode],
  43. new: &[VNode],
  44. parent: Option<ElementRef>,
  45. ) {
  46. use std::cmp::Ordering;
  47. // Handled these cases in `diff_children` before calling this function.
  48. debug_assert!(!new.is_empty());
  49. debug_assert!(!old.is_empty());
  50. match old.len().cmp(&new.len()) {
  51. Ordering::Greater => self.remove_nodes(to.as_deref_mut(), &old[new.len()..], None),
  52. Ordering::Less => self.create_and_insert_after(
  53. to.as_deref_mut(),
  54. &new[old.len()..],
  55. old.last().unwrap(),
  56. parent,
  57. ),
  58. Ordering::Equal => {}
  59. }
  60. for (new, old) in new.iter().zip(old.iter()) {
  61. old.diff_node(new, self, to.as_deref_mut());
  62. }
  63. }
  64. // Diffing "keyed" children.
  65. //
  66. // With keyed children, we care about whether we delete, move, or create nodes
  67. // versus mutate existing nodes in place. Presumably there is some sort of CSS
  68. // transition animation that makes the virtual DOM diffing algorithm
  69. // observable. By specifying keys for nodes, we know which virtual DOM nodes
  70. // must reuse (or not reuse) the same physical DOM nodes.
  71. //
  72. // This is loosely based on Inferno's keyed patching implementation. However, we
  73. // have to modify the algorithm since we are compiling the diff down into change
  74. // list instructions that will be executed later, rather than applying the
  75. // changes to the DOM directly as we compare virtual DOMs.
  76. //
  77. // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
  78. //
  79. // The stack is empty upon entry.
  80. fn diff_keyed_children(
  81. &mut self,
  82. mut to: Option<&mut impl WriteMutations>,
  83. old: &[VNode],
  84. new: &[VNode],
  85. parent: Option<ElementRef>,
  86. ) {
  87. if cfg!(debug_assertions) {
  88. let mut keys = rustc_hash::FxHashSet::default();
  89. let mut assert_unique_keys = |children: &[VNode]| {
  90. keys.clear();
  91. for child in children {
  92. let key = child.key.clone();
  93. debug_assert!(
  94. key.is_some(),
  95. "if any sibling is keyed, all siblings must be keyed"
  96. );
  97. keys.insert(key);
  98. }
  99. debug_assert_eq!(
  100. children.len(),
  101. keys.len(),
  102. "keyed siblings must each have a unique key"
  103. );
  104. };
  105. assert_unique_keys(old);
  106. assert_unique_keys(new);
  107. }
  108. // First up, we diff all the nodes with the same key at the beginning of the
  109. // children.
  110. //
  111. // `shared_prefix_count` is the count of how many nodes at the start of
  112. // `new` and `old` share the same keys.
  113. let (left_offset, right_offset) =
  114. match self.diff_keyed_ends(to.as_deref_mut(), old, new, parent) {
  115. Some(count) => count,
  116. None => return,
  117. };
  118. // Ok, we now hopefully have a smaller range of children in the middle
  119. // within which to re-order nodes with the same keys, remove old nodes with
  120. // now-unused keys, and create new nodes with fresh keys.
  121. let old_middle = &old[left_offset..(old.len() - right_offset)];
  122. let new_middle = &new[left_offset..(new.len() - right_offset)];
  123. debug_assert!(
  124. !old_middle.is_empty(),
  125. "Old middle returned from `diff_keyed_ends` should not be empty"
  126. );
  127. debug_assert!(
  128. !new_middle.is_empty(),
  129. "New middle returned from `diff_keyed_ends` should not be empty"
  130. );
  131. // A few nodes in the middle were removed, just remove the old nodes
  132. if new_middle.is_empty() {
  133. self.remove_nodes(to, old_middle, None);
  134. } else {
  135. self.diff_keyed_middle(to, old_middle, new_middle, parent);
  136. }
  137. }
  138. /// Diff both ends of the children that share keys.
  139. ///
  140. /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing.
  141. ///
  142. /// If there is no offset, then this function returns None and the diffing is complete.
  143. fn diff_keyed_ends(
  144. &mut self,
  145. mut to: Option<&mut impl WriteMutations>,
  146. old: &[VNode],
  147. new: &[VNode],
  148. parent: Option<ElementRef>,
  149. ) -> Option<(usize, usize)> {
  150. let mut left_offset = 0;
  151. for (old, new) in old.iter().zip(new.iter()) {
  152. // abort early if we finally run into nodes with different keys
  153. if old.key != new.key {
  154. break;
  155. }
  156. old.diff_node(new, self, to.as_deref_mut());
  157. left_offset += 1;
  158. }
  159. // If that was all of the old children, then create and append the remaining
  160. // new children and we're finished.
  161. if left_offset == old.len() {
  162. self.create_and_insert_after(to, &new[left_offset..], &new[left_offset - 1], parent);
  163. return None;
  164. }
  165. // if the shared prefix is less than either length, then we need to walk backwards
  166. let mut right_offset = 0;
  167. for (old, new) in old.iter().rev().zip(new.iter().rev()) {
  168. // abort early if we finally run into nodes with different keys
  169. if old.key != new.key {
  170. break;
  171. }
  172. old.diff_node(new, self, to.as_deref_mut());
  173. right_offset += 1;
  174. }
  175. // If that was all of the old children, then create and prepend the remaining
  176. // new children and we're finished.
  177. if right_offset == old.len() {
  178. self.create_and_insert_before(
  179. to,
  180. &new[..new.len() - right_offset],
  181. &new[new.len() - right_offset],
  182. parent,
  183. );
  184. return None;
  185. }
  186. // If the right offset + the left offset is the same as the new length, then we just need to remove the old nodes
  187. if right_offset + left_offset == new.len() {
  188. self.remove_nodes(to, &old[left_offset..old.len() - right_offset], None);
  189. return None;
  190. }
  191. // If the right offset + the left offset is the same as the old length, then we just need to add the new nodes
  192. if right_offset + left_offset == old.len() {
  193. self.create_and_insert_before(
  194. to,
  195. &new[left_offset..new.len() - right_offset],
  196. &new[new.len() - right_offset],
  197. parent,
  198. );
  199. return None;
  200. }
  201. Some((left_offset, right_offset))
  202. }
  203. // The most-general, expensive code path for keyed children diffing.
  204. //
  205. // We find the longest subsequence within `old` of children that are relatively
  206. // ordered the same way in `new` (via finding a longest-increasing-subsequence
  207. // of the old child's index within `new`). The children that are elements of
  208. // this subsequence will remain in place, minimizing the number of DOM moves we
  209. // will have to do.
  210. //
  211. // Upon entry to this function, the change list stack must be empty.
  212. //
  213. // This function will load the appropriate nodes onto the stack and do diffing in place.
  214. //
  215. // Upon exit from this function, it will be restored to that same self.
  216. #[allow(clippy::too_many_lines)]
  217. fn diff_keyed_middle(
  218. &mut self,
  219. mut to: Option<&mut impl WriteMutations>,
  220. old: &[VNode],
  221. new: &[VNode],
  222. parent: Option<ElementRef>,
  223. ) {
  224. /*
  225. 1. Map the old keys into a numerical ordering based on indices.
  226. 2. Create a map of old key to its index
  227. 3. Map each new key to the old key, carrying over the old index.
  228. - IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3
  229. - if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist
  230. now, we should have a list of integers that indicates where in the old list the new items map to.
  231. 4. Compute the LIS of this list
  232. - this indicates the longest list of new children that won't need to be moved.
  233. 5. Identify which nodes need to be removed
  234. 6. Identify which nodes will need to be diffed
  235. 7. Going along each item in the new list, create it and insert it before the next closest item in the LIS.
  236. - if the item already existed, just move it to the right place.
  237. 8. Finally, generate instructions to remove any old children.
  238. 9. Generate instructions to finally diff children that are the same between both
  239. */
  240. // 0. Debug sanity checks
  241. // Should have already diffed the shared-key prefixes and suffixes.
  242. debug_assert_ne!(new.first().map(|i| &i.key), old.first().map(|i| &i.key));
  243. debug_assert_ne!(new.last().map(|i| &i.key), old.last().map(|i| &i.key));
  244. // 1. Map the old keys into a numerical ordering based on indices.
  245. // 2. Create a map of old key to its index
  246. // IE if the keys were A B C, then we would have (A, 0) (B, 1) (C, 2).
  247. let old_key_to_old_index = old
  248. .iter()
  249. .enumerate()
  250. .map(|(i, o)| (o.key.as_ref().unwrap().as_str(), i))
  251. .collect::<FxHashMap<_, _>>();
  252. let mut shared_keys = FxHashSet::default();
  253. // 3. Map each new key to the old key, carrying over the old index.
  254. let new_index_to_old_index = new
  255. .iter()
  256. .map(|node| {
  257. let key = node.key.as_ref().unwrap();
  258. if let Some(&index) = old_key_to_old_index.get(key.as_str()) {
  259. shared_keys.insert(key);
  260. index
  261. } else {
  262. usize::MAX
  263. }
  264. })
  265. .collect::<Box<[_]>>();
  266. // If none of the old keys are reused by the new children, then we remove all the remaining old children and
  267. // create the new children afresh.
  268. if shared_keys.is_empty() {
  269. debug_assert!(
  270. !old.is_empty(),
  271. "we should never be appending - just creating N"
  272. );
  273. let m = self.create_children(to.as_deref_mut(), new, parent);
  274. self.remove_nodes(to, old, Some(m));
  275. return;
  276. }
  277. // remove any old children that are not shared
  278. for child_to_remove in old
  279. .iter()
  280. .filter(|child| !shared_keys.contains(child.key.as_ref().unwrap()))
  281. {
  282. child_to_remove.remove_node(self, to.as_deref_mut(), None);
  283. }
  284. // 4. Compute the LIS of this list
  285. let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
  286. let mut allocation = vec![0; new_index_to_old_index.len() * 2];
  287. let (predecessors, starts) = allocation.split_at_mut(new_index_to_old_index.len());
  288. longest_increasing_subsequence::lis_with(
  289. &new_index_to_old_index,
  290. &mut lis_sequence,
  291. |a, b| a < b,
  292. predecessors,
  293. starts,
  294. );
  295. // 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)
  296. if lis_sequence.first().map(|f| new_index_to_old_index[*f]) == Some(usize::MAX) {
  297. lis_sequence.remove(0);
  298. }
  299. // Diff each nod in the LIS
  300. for idx in &lis_sequence {
  301. old[new_index_to_old_index[*idx]].diff_node(&new[*idx], self, to.as_deref_mut());
  302. }
  303. /// Create or diff each node in a range depending on whether it is in the LIS or not
  304. /// Returns the number of nodes created on the stack
  305. fn create_or_diff(
  306. vdom: &mut VirtualDom,
  307. new: &[VNode],
  308. old: &[VNode],
  309. mut to: Option<&mut impl WriteMutations>,
  310. parent: Option<ElementRef>,
  311. new_index_to_old_index: &[usize],
  312. range: std::ops::Range<usize>,
  313. ) -> usize {
  314. let range_start = range.start;
  315. new[range]
  316. .iter()
  317. .enumerate()
  318. .map(|(idx, new_node)| {
  319. let new_idx = range_start + idx;
  320. let old_index = new_index_to_old_index[new_idx];
  321. // If the node existed in the old list, diff it
  322. if let Some(old_node) = old.get(old_index) {
  323. old_node.diff_node(new_node, vdom, to.as_deref_mut());
  324. if let Some(to) = to.as_deref_mut() {
  325. new_node.push_all_root_nodes(vdom, to)
  326. } else {
  327. 0
  328. }
  329. } else {
  330. // Otherwise, just add it to the stack
  331. new_node.create(vdom, parent, to.as_deref_mut())
  332. }
  333. })
  334. .sum()
  335. }
  336. // add mount instruction for the items before the LIS
  337. let last = *lis_sequence.first().unwrap();
  338. if last < (new.len() - 1) {
  339. let nodes_created = create_or_diff(
  340. self,
  341. new,
  342. old,
  343. to.as_deref_mut(),
  344. parent,
  345. &new_index_to_old_index,
  346. (last + 1)..new.len(),
  347. );
  348. // Insert all the nodes that we just created after the last node in the LIS
  349. self.insert_after(to.as_deref_mut(), nodes_created, &new[last]);
  350. }
  351. // For each node inside of the LIS, but not included in the LIS, generate a mount instruction
  352. // We loop over the LIS in reverse order and insert any nodes we find in the gaps between indexes
  353. let mut lis_iter = lis_sequence.iter();
  354. let mut last = *lis_iter.next().unwrap();
  355. for next in lis_iter {
  356. if last - next > 1 {
  357. let nodes_created = create_or_diff(
  358. self,
  359. new,
  360. old,
  361. to.as_deref_mut(),
  362. parent,
  363. &new_index_to_old_index,
  364. (next + 1)..last,
  365. );
  366. self.insert_before(to.as_deref_mut(), nodes_created, &new[last]);
  367. }
  368. last = *next;
  369. }
  370. // add mount instruction for the items after the LIS
  371. let first_lis = *lis_sequence.last().unwrap();
  372. if first_lis > 0 {
  373. let nodes_created = create_or_diff(
  374. self,
  375. new,
  376. old,
  377. to.as_deref_mut(),
  378. parent,
  379. &new_index_to_old_index,
  380. 0..first_lis,
  381. );
  382. self.insert_before(to, nodes_created, &new[first_lis]);
  383. }
  384. }
  385. fn create_and_insert_before(
  386. &mut self,
  387. mut to: Option<&mut impl WriteMutations>,
  388. new: &[VNode],
  389. before: &VNode,
  390. parent: Option<ElementRef>,
  391. ) {
  392. let m = self.create_children(to.as_deref_mut(), new, parent);
  393. self.insert_before(to, m, before);
  394. }
  395. fn insert_before(&mut self, to: Option<&mut impl WriteMutations>, new: usize, before: &VNode) {
  396. if let Some(to) = to {
  397. if new > 0 {
  398. let id = before.find_first_element(self);
  399. to.insert_nodes_before(id, new);
  400. }
  401. }
  402. }
  403. fn create_and_insert_after(
  404. &mut self,
  405. mut to: Option<&mut impl WriteMutations>,
  406. new: &[VNode],
  407. after: &VNode,
  408. parent: Option<ElementRef>,
  409. ) {
  410. let m = self.create_children(to.as_deref_mut(), new, parent);
  411. self.insert_after(to, m, after);
  412. }
  413. fn insert_after(&mut self, to: Option<&mut impl WriteMutations>, new: usize, after: &VNode) {
  414. if let Some(to) = to {
  415. if new > 0 {
  416. let id = after.find_last_element(self);
  417. to.insert_nodes_after(id, new);
  418. }
  419. }
  420. }
  421. }
  422. impl VNode {
  423. /// Push all the root nodes on the stack
  424. pub(crate) fn push_all_root_nodes(
  425. &self,
  426. dom: &VirtualDom,
  427. to: &mut impl WriteMutations,
  428. ) -> usize {
  429. let template = self.template;
  430. let mounts = dom.runtime.mounts.borrow();
  431. let mount = mounts.get(self.mount.get().0).unwrap();
  432. template
  433. .roots
  434. .iter()
  435. .enumerate()
  436. .map(
  437. |(root_idx, _)| match self.get_dynamic_root_node_and_id(root_idx) {
  438. Some((_, DynamicNode::Fragment(nodes))) => {
  439. let mut accumulated = 0;
  440. for node in nodes {
  441. accumulated += node.push_all_root_nodes(dom, to);
  442. }
  443. accumulated
  444. }
  445. Some((idx, DynamicNode::Component(_))) => {
  446. let scope = ScopeId(mount.mounted_dynamic_nodes[idx]);
  447. let node = dom.get_scope(scope).unwrap().root_node();
  448. node.push_all_root_nodes(dom, to)
  449. }
  450. // This is a static root node or a single dynamic node, just push it
  451. None | Some((_, DynamicNode::Placeholder(_) | DynamicNode::Text(_))) => {
  452. to.push_root(mount.root_ids[root_idx]);
  453. 1
  454. }
  455. },
  456. )
  457. .sum()
  458. }
  459. }