on 93bf16d help sign in
dodrio/src/diff.rs
942 lines 31 kB history raw
1use crate::{
2 cached_set::{CacheId, CachedSet},
3 change_list::ChangeListBuilder,
4 events::EventsRegistry,
5 node::{Attribute, ElementNode, Listener, Node, NodeKind, TextNode},
6};
7use fxhash::{FxHashMap, FxHashSet};
8use std::cmp::Ordering;
9use std::ops::Range;
10use std::u32;
12// Diff the `old` node with the `new` node. Emits instructions to modify a
13// physical DOM node that reflects `old` into something that reflects `new`.
14//
15// Upon entry to this function, the physical DOM node must be on the top of the
16// stack:
17//
18// [... node]
19//
20// The stack is in the same state when this function exits.
21pub(crate) fn diff(
22 cached_set: &CachedSet,
23 change_list: &mut ChangeListBuilder,
24 registry: &mut EventsRegistry,
25 old: &Node,
26 new: &Node,
27 cached_roots: &mut FxHashSet<CacheId>,
28) {
29 match (&new.kind, &old.kind) {
30 (
31 &NodeKind::Text(TextNode { text: new_text }),
32 &NodeKind::Text(TextNode { text: old_text }),
33 ) => {
34 if new_text != old_text {
35 change_list.set_text(new_text);
36 }
37 }
39 (&NodeKind::Text(_), &NodeKind::Element(_)) => {
40 create(cached_set, change_list, registry, new, cached_roots);
41 registry.remove_subtree(&old);
42 change_list.replace_with();
43 }
45 (&NodeKind::Element(_), &NodeKind::Text(_)) => {
46 create(cached_set, change_list, registry, new, cached_roots);
47 // Note: text nodes cannot have event listeners, so we don't need to
48 // remove the old node's listeners from our registry her.
49 change_list.replace_with();
50 }
52 (
53 &NodeKind::Element(ElementNode {
54 key: _,
55 tag_name: new_tag_name,
56 listeners: new_listeners,
57 attributes: new_attributes,
58 children: new_children,
59 namespace: new_namespace,
60 }),
61 &NodeKind::Element(ElementNode {
62 key: _,
63 tag_name: old_tag_name,
64 listeners: old_listeners,
65 attributes: old_attributes,
66 children: old_children,
67 namespace: old_namespace,
68 }),
69 ) => {
70 if new_tag_name != old_tag_name || new_namespace != old_namespace {
71 create(cached_set, change_list, registry, new, cached_roots);
72 registry.remove_subtree(&old);
73 change_list.replace_with();
74 return;
75 }
76 diff_listeners(change_list, registry, old_listeners, new_listeners);
77 diff_attributes(change_list, old_attributes, new_attributes);
78 diff_children(
79 cached_set,
80 change_list,
81 registry,
82 old_children,
83 new_children,
84 cached_roots,
85 );
86 }
88 // Both the new and old nodes are cached.
89 (&NodeKind::Cached(ref new), &NodeKind::Cached(ref old)) => {
90 cached_roots.insert(new.id);
92 if new.id == old.id {
93 // This is the same cached node, so nothing has changed!
94 return;
95 }
97 let new = cached_set.get(new.id);
98 let old = cached_set.get(old.id);
99 diff(cached_set, change_list, registry, old, new, cached_roots);
100 }
102 // New cached node when the old node was not cached. In this scenario,
103 // we assume that they are pretty different, and it isn't worth diffing
104 // the subtrees, so we just create the new cached node afresh.
105 (&NodeKind::Cached(ref c), _) => {
106 cached_roots.insert(c.id);
107 let new = cached_set.get(c.id);
108 create(cached_set, change_list, registry, new, cached_roots);
109 registry.remove_subtree(&old);
110 change_list.replace_with();
111 }
113 // Old cached node and new non-cached node. Again, assume that they are
114 // probably pretty different and create the new non-cached node afresh.
115 (_, &NodeKind::Cached(_)) => {
116 create(cached_set, change_list, registry, new, cached_roots);
117 registry.remove_subtree(&old);
118 change_list.replace_with();
119 }
120 }
123// Diff event listeners between `old` and `new`.
124//
125// The listeners' node must be on top of the stack:
126//
127// [... node]
128//
129// The stack is left unchanged.
130fn diff_listeners(
131 change_list: &mut ChangeListBuilder,
132 registry: &mut EventsRegistry,
133 old: &[Listener],
134 new: &[Listener],
135) {
136 'outer1: for new_l in new {
137 unsafe {
138 // Safety relies on removing `new_l` from the registry manually at
139 // the end of its lifetime. This happens below in the `'outer2`
140 // loop, and elsewhere in diffing when removing old dom trees.
141 registry.add(new_l);
142 }
144 for old_l in old {
145 if new_l.event == old_l.event {
146 change_list.update_event_listener(new_l);
147 continue 'outer1;
148 }
149 }
151 change_list.new_event_listener(new_l);
152 }
154 'outer2: for old_l in old {
155 registry.remove(old_l);
157 for new_l in new {
158 if new_l.event == old_l.event {
159 continue 'outer2;
160 }
161 }
162 change_list.remove_event_listener(old_l.event);
163 }
166// Diff a node's attributes.
167//
168// The attributes' node must be on top of the stack:
169//
170// [... node]
171//
172// The stack is left unchanged.
173fn diff_attributes(change_list: &mut ChangeListBuilder, old: &[Attribute], new: &[Attribute]) {
174 // Do O(n^2) passes to add/update and remove attributes, since
175 // there are almost always very few attributes.
176 'outer: for new_attr in new {
177 if new_attr.is_volatile() {
178 change_list.set_attribute(new_attr.name, new_attr.value);
179 } else {
180 for old_attr in old {
181 if old_attr.name == new_attr.name {
182 if old_attr.value != new_attr.value {
183 change_list.set_attribute(new_attr.name, new_attr.value);
184 }
185 continue 'outer;
186 }
187 }
188 change_list.set_attribute(new_attr.name, new_attr.value);
189 }
190 }
192 'outer2: for old_attr in old {
193 for new_attr in new {
194 if old_attr.name == new_attr.name {
195 continue 'outer2;
196 }
197 }
198 change_list.remove_attribute(old_attr.name);
199 }
202// Diff the given set of old and new children.
203//
204// The parent must be on top of the stack when this function is entered:
205//
206// [... parent]
207//
208// The stack is in the same state when this function returns.
209fn diff_children(
210 cached_set: &CachedSet,
211 change_list: &mut ChangeListBuilder,
212 registry: &mut EventsRegistry,
213 old: &[Node],
214 new: &[Node],
215 cached_roots: &mut FxHashSet<CacheId>,
216) {
217 if new.is_empty() {
218 if !old.is_empty() {
219 remove_all_children(change_list, registry, old);
220 }
221 return;
222 }
224 if old.is_empty() {
225 create_and_append_children(cached_set, change_list, registry, new, cached_roots);
226 return;
227 }
229 let new_is_keyed = new[0].key().is_some();
230 let old_is_keyed = old[0].key().is_some();
232 debug_assert!(
233 new.iter().all(|n| n.key().is_some() == new_is_keyed),
234 "all siblings must be keyed or all siblings must be non-keyed"
235 );
236 debug_assert!(
237 old.iter().all(|o| o.key().is_some() == old_is_keyed),
238 "all siblings must be keyed or all siblings must be non-keyed"
239 );
241 if new_is_keyed && old_is_keyed {
242 let t = change_list.next_temporary();
243 diff_keyed_children(cached_set, change_list, registry, old, new, cached_roots);
244 change_list.set_next_temporary(t);
245 } else {
246 diff_non_keyed_children(cached_set, change_list, registry, old, new, cached_roots);
247 }
250// Diffing "keyed" children.
251//
252// With keyed children, we care about whether we delete, move, or create nodes
253// versus mutate existing nodes in place. Presumably there is some sort of CSS
254// transition animation that makes the virtual DOM diffing algorithm
255// observable. By specifying keys for nodes, we know which virtual DOM nodes
256// must reuse (or not reuse) the same physical DOM nodes.
257//
258// This is loosely based on Inferno's keyed patching implementation. However, we
259// have to modify the algorithm since we are compiling the diff down into change
260// list instructions that will be executed later, rather than applying the
261// changes to the DOM directly as we compare virtual DOMs.
262//
263// https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
264//
265// When entering this function, the parent must be on top of the stack:
266//
267// [... parent]
268//
269// Upon exiting, the stack is in the same state.
270fn diff_keyed_children(
271 cached_set: &CachedSet,
272 change_list: &mut ChangeListBuilder,
273 registry: &mut EventsRegistry,
274 old: &[Node],
275 new: &[Node],
276 cached_roots: &mut FxHashSet<CacheId>,
277) {
278 if cfg!(debug_assertions) {
279 let mut keys = FxHashSet::default();
280 let mut assert_unique_keys = |children: &[Node]| {
281 keys.clear();
282 for child in children {
283 let key = child.key();
284 debug_assert!(
285 key.is_some(),
286 "if any sibling is keyed, all siblings must be keyed"
287 );
288 keys.insert(key);
289 }
290 debug_assert_eq!(
291 children.len(),
292 keys.len(),
293 "keyed siblings must each have a unique key"
294 );
295 };
296 assert_unique_keys(old);
297 assert_unique_keys(new);
298 }
300 // First up, we diff all the nodes with the same key at the beginning of the
301 // children.
302 //
303 // `shared_prefix_count` is the count of how many nodes at the start of
304 // `new` and `old` share the same keys.
305 let shared_prefix_count =
306 match diff_keyed_prefix(cached_set, change_list, registry, old, new, cached_roots) {
307 KeyedPrefixResult::Finished => return,
308 KeyedPrefixResult::MoreWorkToDo(count) => count,
309 };
311 // Next, we find out how many of the nodes at the end of the children have
312 // the same key. We do _not_ diff them yet, since we want to emit the change
313 // list instructions such that they can be applied in a single pass over the
314 // DOM. Instead, we just save this information for later.
315 //
316 // `shared_suffix_count` is the count of how many nodes at the end of `new`
317 // and `old` share the same keys.
318 let shared_suffix_count = old[shared_prefix_count..]
319 .iter()
320 .rev()
321 .zip(new[shared_prefix_count..].iter().rev())
322 .take_while(|&(old, new)| old.key() == new.key())
323 .count();
325 let old_shared_suffix_start = old.len() - shared_suffix_count;
326 let new_shared_suffix_start = new.len() - shared_suffix_count;
328 // Ok, we now hopefully have a smaller range of children in the middle
329 // within which to re-order nodes with the same keys, remove old nodes with
330 // now-unused keys, and create new nodes with fresh keys.
331 diff_keyed_middle(
332 cached_set,
333 change_list,
334 registry,
335 &old[shared_prefix_count..old_shared_suffix_start],
336 &new[shared_prefix_count..new_shared_suffix_start],
337 cached_roots,
338 shared_prefix_count,
339 shared_suffix_count,
340 old_shared_suffix_start,
341 );
343 // Finally, diff the nodes at the end of `old` and `new` that share keys.
344 let old_suffix = &old[old_shared_suffix_start..];
345 let new_suffix = &new[new_shared_suffix_start..];
346 debug_assert_eq!(old_suffix.len(), new_suffix.len());
347 if !old_suffix.is_empty() {
348 diff_keyed_suffix(
349 cached_set,
350 change_list,
351 registry,
352 old_suffix,
353 new_suffix,
354 cached_roots,
355 new_shared_suffix_start,
356 );
357 }
360enum KeyedPrefixResult {
361 // Fast path: we finished diffing all the children just by looking at the
362 // prefix of shared keys!
363 Finished,
364 // There is more diffing work to do. Here is a count of how many children at
365 // the beginning of `new` and `old` we already processed.
366 MoreWorkToDo(usize),
369// Diff the prefix of children in `new` and `old` that share the same keys in
370// the same order.
371//
372// Upon entry of this function, the stack must be:
373//
374// [... parent]
375//
376// Upon exit, the stack is the same.
377fn diff_keyed_prefix(
378 cached_set: &CachedSet,
379 change_list: &mut ChangeListBuilder,
380 registry: &mut EventsRegistry,
381 old: &[Node],
382 new: &[Node],
383 cached_roots: &mut FxHashSet<CacheId>,
384) -> KeyedPrefixResult {
385 let mut pushed = false;
386 let mut shared_prefix_count = 0;
388 for (old, new) in old.iter().zip(new.iter()) {
389 if old.key() != new.key() {
390 break;
391 }
393 if pushed {
394 debug_assert!(shared_prefix_count > 0);
395 change_list.pop_push_next_sibling();
396 } else {
397 debug_assert_eq!(shared_prefix_count, 0);
398 change_list.push_first_child();
399 pushed = true;
400 }
402 diff(cached_set, change_list, registry, old, new, cached_roots);
403 shared_prefix_count += 1;
405 // At the end of the loop, the stack looks like
406 //
407 // [... parent child_we_just_diffed]
408 debug_assert!(pushed);
409 }
411 // If that was all of the old children, then create and append the remaining
412 // new children and we're finished.
413 if shared_prefix_count == old.len() {
414 debug_assert!(
415 pushed,
416 "we handle the case of empty children before calling this method, so
417 `shared_prefix_count` must be greater than zero, and therefore we
418 must have pushed in the above loop"
419 );
420 change_list.pop();
421 create_and_append_children(
422 cached_set,
423 change_list,
424 registry,
425 &new[shared_prefix_count..],
426 cached_roots,
427 );
428 return KeyedPrefixResult::Finished;
429 }
431 // And if that was all of the new children, then remove all of the remaining
432 // old children and we're finished.
433 if shared_prefix_count == new.len() {
434 // Same as above.
435 debug_assert!(pushed);
436 change_list.pop_push_next_sibling();
437 change_list.remove_self_and_next_siblings();
438 return KeyedPrefixResult::Finished;
439 }
441 if pushed {
442 debug_assert!(shared_prefix_count > 0);
443 change_list.pop();
444 }
445 KeyedPrefixResult::MoreWorkToDo(shared_prefix_count)
448// The most-general, expensive code path for keyed children diffing.
449//
450// We find the longest subsequence within `old` of children that are relatively
451// ordered the same way in `new` (via finding a longest-increasing-subsequence
452// of the old child's index within `new`). The children that are elements of
453// this subsequence will remain in place, minimizing the number of DOM moves we
454// will have to do.
455//
456// Upon entry to this function, the stack must be:
457//
458// [... parent]
459//
460// Upon exit from this function, it will be restored to that same state.
461fn diff_keyed_middle(
462 cached_set: &CachedSet,
463 change_list: &mut ChangeListBuilder,
464 registry: &mut EventsRegistry,
465 old: &[Node],
466 new: &[Node],
467 cached_roots: &mut FxHashSet<CacheId>,
468 shared_prefix_count: usize,
469 shared_suffix_count: usize,
470 old_shared_suffix_start: usize,
471) {
472 // Should have already diffed the shared-key prefixes and suffixes.
473 debug_assert_ne!(new.first().map(|n| n.key()), old.first().map(|o| o.key()));
474 debug_assert_ne!(new.last().map(|n| n.key()), old.last().map(|o| o.key()));
476 // The algorithm below relies upon using `u32::MAX` as a sentinel
477 // value, so if we have that many new nodes, it won't work. This
478 // check is a bit academic (hence only enabled in debug), since
479 // wasm32 doesn't have enough address space to hold that many nodes
480 // in memory.
481 debug_assert!(new.len() < u32::MAX as usize);
483 // Map from each `old` node's key to its index within `old`.
484 let mut old_key_to_old_index = FxHashMap::default();
485 old_key_to_old_index.reserve(old.len());
486 old_key_to_old_index.extend(old.iter().enumerate().map(|(i, o)| (o.key(), i)));
488 // The set of shared keys between `new` and `old`.
489 let mut shared_keys = FxHashSet::default();
490 // Map from each index in `new` to the index of the node in `old` that
491 // has the same key.
492 let mut new_index_to_old_index = Vec::with_capacity(new.len());
493 new_index_to_old_index.extend(new.iter().map(|n| {
494 let key = n.key();
495 if let Some(&i) = old_key_to_old_index.get(&key) {
496 shared_keys.insert(key);
497 i
498 } else {
499 u32::MAX as usize
500 }
501 }));
503 // If none of the old keys are reused by the new children, then we
504 // remove all the remaining old children and create the new children
505 // afresh.
506 if shared_suffix_count == 0 && shared_keys.is_empty() {
507 if shared_prefix_count == 0 {
508 remove_all_children(change_list, registry, old);
509 } else {
510 change_list.pop_push_next_sibling();
511 remove_self_and_next_siblings(change_list, registry, &old[shared_prefix_count..]);
512 }
513 create_and_append_children(cached_set, change_list, registry, new, cached_roots);
514 return;
515 }
517 // The longest increasing subsequence within `new_index_to_old_index` in
518 // reverse order (since `lis_with` adds the indices in reverse
519 // order). We will leave these nodes in place in the DOM, and only move
520 // nodes that are not part of the LIS. This results in the minimum
521 // number of DOM nodes moved.
522 let mut reverse_lis = Vec::with_capacity(new_index_to_old_index.len());
523 let mut predecessors = vec![0; new_index_to_old_index.len()];
524 let mut starts = vec![0; new_index_to_old_index.len()];
525 longest_increasing_subsequence::lis_with(
526 &new_index_to_old_index,
527 &mut reverse_lis,
528 |a, b| a < b,
529 &mut predecessors,
530 &mut starts,
531 );
533 // Save each of the old children whose keys are reused in the new
534 // children.
535 let mut old_index_to_temp = vec![u32::MAX; old.len()];
536 let mut start = 0;
537 loop {
538 let end = (start..old.len())
539 .find(|&i| {
540 let key = old[i].key();
541 !shared_keys.contains(&key)
542 })
543 .unwrap_or(old.len());
545 if end - start > 0 {
546 let mut t = change_list.save_children_to_temporaries(
547 shared_prefix_count + start,
548 shared_prefix_count + end,
549 );
550 for i in start..end {
551 old_index_to_temp[i] = t;
552 t += 1;
553 }
554 }
556 debug_assert!(end <= old.len());
557 if end == old.len() {
558 break;
559 } else {
560 start = end + 1;
561 }
562 }
564 // Remove any old children whose keys were not reused in the new
565 // children. Remove from the end first so that we don't mess up indices.
566 let mut removed_count = 0;
567 for (i, old_child) in old.iter().enumerate().rev() {
568 if !shared_keys.contains(&old_child.key()) {
569 change_list.remove_child(i + shared_prefix_count);
570 removed_count += 1;
571 }
572 }
574 // Whether we have pushed a child onto the stack or not.
575 let mut pushed = false;
577 // Now iterate from the end of the new children back to the beginning,
578 // moving old children to their new destination, diffing them, and
579 // creating new children as necessary. Note that iterating in reverse
580 // order lets us use `Node.prototype.insertBefore` to move/insert
581 // children.
582 if shared_suffix_count > 0 {
583 change_list.push_child(old_shared_suffix_start - removed_count);
584 pushed = true;
585 }
586 let mut segment_end = new.len();
587 for lis_index in reverse_lis {
588 // Because we use `u32::MAX` as a sentinel value representing "a child
589 // with this key is not a member of `new`", we filter that out here.
590 let old_index = new_index_to_old_index[lis_index];
591 if old_index == u32::MAX as usize {
592 continue;
593 }
595 // A segment begins with a member of the LIS, which will remain in
596 // place in the DOM, followed by zero or more new children that are
597 // not members of the LIS. If one of these new children shares a key
598 // with one of the old children, then we will move that old child in
599 // the DOM. Otherwise, we create the new child afresh.
600 debug_assert!(segment_end - lis_index > 0);
602 // Go through each of the non-LIS child and move-and-diff or create
603 // it.
604 diff_and_move_or_create_segment(
605 cached_set,
606 change_list,
607 registry,
608 old,
609 new,
610 cached_roots,
611 lis_index + 1..segment_end,
612 &new_index_to_old_index,
613 &old_index_to_temp,
614 &mut pushed,
615 );
617 // Now we push the member of the LIS and diff it with its
618 // correspondingly-keyed new child.
619 let new_child = &new[lis_index];
620 let temp = old_index_to_temp[old_index];
621 debug_assert_ne!(temp, u32::MAX);
622 if pushed {
623 change_list.pop();
624 }
625 change_list.push_temporary(temp);
626 pushed = true;
627 diff(
628 cached_set,
629 change_list,
630 registry,
631 &old[old_index],
632 new_child,
633 cached_roots,
634 );
636 segment_end = lis_index;
637 }
639 // And now diff-and-move or create each of the non-LIS children that
640 // appear before the first LIS-member.
641 diff_and_move_or_create_segment(
642 cached_set,
643 change_list,
644 registry,
645 old,
646 new,
647 cached_roots,
648 0..segment_end,
649 &new_index_to_old_index,
650 &old_index_to_temp,
651 &mut pushed,
652 );
654 if pushed {
655 change_list.pop();
656 }
659// Diff-and-then-move or create each new node in the given segment. The
660// segment's nodes must _not_ be members of the LIS (those nodes we will diff in
661// place elsewhere, and we should not move them nor create them afresh).
662//
663// On entering this function, the stack has the parent and optionally the next
664// sibling after this segment of children:
665//
666// [... parent next_sibling] if *pushed == true
667// [... parent] otherwise
668//
669// After exiting, if any children were moved or created, then `pushed` is set to
670// true and the stack has the first child in this segment on top. Otherwise the
671// stack is left as it was on entering.
672//
673// [... parent child] if *pushed == true
674// [... parent] otherwise
675fn diff_and_move_or_create_segment(
676 cached_set: &CachedSet,
677 change_list: &mut ChangeListBuilder,
678 registry: &mut EventsRegistry,
679 old: &[Node],
680 new: &[Node],
681 cached_roots: &mut FxHashSet<CacheId>,
682 segment: Range<usize>,
683 new_index_to_old_index: &[usize],
684 old_index_to_temp: &[u32],
685 pushed: &mut bool,
686) {
687 for new_index in segment.rev() {
688 let new_child = &new[new_index];
689 let old_index = new_index_to_old_index[new_index];
690 if old_index == u32::MAX as usize {
691 // The key is not reused. Create this new child afresh.
692 create(cached_set, change_list, registry, new_child, cached_roots);
693 } else {
694 // The key is reused. Diff it with the old node and then
695 // move the old node into its final destination.
696 let temp = old_index_to_temp[old_index];
697 debug_assert_ne!(temp, u32::MAX);
698 change_list.push_temporary(temp);
699 diff(
700 cached_set,
701 change_list,
702 registry,
703 new_child,
704 &old[old_index],
705 cached_roots,
706 );
707 }
709 // At this point the stack can have one of two shapes.
710 if *pushed {
711 // [... parent next_child new_child]
712 change_list.insert_before();
713 // [... parent new_child]
714 } else {
715 // [... parent new_child]
716 change_list.append_child();
717 // [... parent]
718 change_list.push_last_child();
719 // [... parent new_child]
720 *pushed = true;
721 }
723 // At the end of each loop iteration, the stack looks like:
724 //
725 // [... parent new_child]
726 debug_assert!(*pushed);
727 }
730// Diff the suffix of keyed children that share the same keys in the same order.
731//
732// The parent must be on the stack when we enter this function:
733//
734// [... parent]
735//
736// When this function exits, the stack remains the same.
737fn diff_keyed_suffix(
738 cached_set: &CachedSet,
739 change_list: &mut ChangeListBuilder,
740 registry: &mut EventsRegistry,
741 old: &[Node],
742 new: &[Node],
743 cached_roots: &mut FxHashSet<CacheId>,
744 new_shared_suffix_start: usize,
745) {
746 debug_assert_eq!(old.len(), new.len());
747 debug_assert!(!old.is_empty());
749 // [... parent]
750 change_list.push_child(new_shared_suffix_start);
751 // [... parent new_child]
753 for (old_child, new_child) in old.iter().zip(new.iter()) {
754 diff(
755 cached_set,
756 change_list,
757 registry,
758 old_child,
759 new_child,
760 cached_roots,
761 );
763 // [... parent this_new_child]
764 change_list.pop_push_next_sibling();
765 // [... parent next_new_child]
766 }
768 // [... parent]
769 change_list.pop();
772// Diff children that are not keyed.
773//
774// The parent must be on the top of the stack when entering this function:
775//
776// [... parent]
777//
778// The stack is in the same state when this function returns.
779fn diff_non_keyed_children(
780 cached_set: &CachedSet,
781 change_list: &mut ChangeListBuilder,
782 registry: &mut EventsRegistry,
783 old: &[Node],
784 new: &[Node],
785 cached_roots: &mut FxHashSet<CacheId>,
786) {
787 // Handled these cases in `diff_children` before calling this function.
788 debug_assert!(!new.is_empty());
789 debug_assert!(!old.is_empty());
791 for (i, (new_child, old_child)) in new.iter().zip(old.iter()).enumerate() {
792 if i == 0 {
793 change_list.push_first_child();
794 } else {
795 change_list.pop_push_next_sibling();
796 }
798 diff(
799 cached_set,
800 change_list,
801 registry,
802 old_child,
803 new_child,
804 cached_roots,
805 );
806 }
808 match old.len().cmp(&new.len()) {
809 Ordering::Greater => {
810 change_list.pop_push_next_sibling();
811 remove_self_and_next_siblings(change_list, registry, &old[new.len()..]);
812 }
813 Ordering::Less => {
814 change_list.pop();
815 create_and_append_children(
816 cached_set,
817 change_list,
818 registry,
819 &new[old.len()..],
820 cached_roots,
821 );
822 }
823 Ordering::Equal => {
824 change_list.pop();
825 }
826 }
829// Create the given children and append them to the parent node.
830//
831// The parent node must currently be on top of the stack:
832//
833// [... parent]
834//
835// When this function returns, the stack is in the same state.
836fn create_and_append_children(
837 cached_set: &CachedSet,
838 change_list: &mut ChangeListBuilder,
839 registry: &mut EventsRegistry,
840 new: &[Node],
841 cached_roots: &mut FxHashSet<CacheId>,
842) {
843 for child in new {
844 create(cached_set, change_list, registry, child, cached_roots);
845 change_list.append_child();
846 }
849// Remove all of a node's children.
850//
851// The stack must have this shape upon entry to this function:
852//
853// [... parent]
854//
855// When this function returns, the stack is in the same state.
856fn remove_all_children(
857 change_list: &mut ChangeListBuilder,
858 registry: &mut EventsRegistry,
859 old: &[Node],
860) {
861 for child in old {
862 registry.remove_subtree(child);
863 }
864 // Fast way to remove all children: set the node's textContent to an empty
865 // string.
866 change_list.set_text("");
869// Remove the current child and all of its following siblings.
870//
871// The stack must have this shape upon entry to this function:
872//
873// [... parent child]
874//
875// After the function returns, the child is no longer on the stack:
876//
877// [... parent]
878fn remove_self_and_next_siblings(
879 change_list: &mut ChangeListBuilder,
880 registry: &mut EventsRegistry,
881 old: &[Node],
882) {
883 for child in old {
884 registry.remove_subtree(child);
885 }
886 change_list.remove_self_and_next_siblings();
889// Emit instructions to create the given virtual node.
890//
891// The stack may have any shape upon entering this function:
892//
893// [...]
894//
895// When this function returns, the new node is on top of the stack:
896//
897// [... node]
898fn create(
899 cached_set: &CachedSet,
900 change_list: &mut ChangeListBuilder,
901 registry: &mut EventsRegistry,
902 node: &Node,
903 cached_roots: &mut FxHashSet<CacheId>,
904) {
905 match node.kind {
906 NodeKind::Text(TextNode { text }) => {
907 change_list.create_text_node(text);
908 }
909 NodeKind::Element(ElementNode {
910 key: _,
911 tag_name,
912 listeners,
913 attributes,
914 children,
915 namespace,
916 }) => {
917 if let Some(namespace) = namespace {
918 change_list.create_element_ns(tag_name, namespace);
919 } else {
920 change_list.create_element(tag_name);
921 }
922 for l in listeners {
923 unsafe {
924 registry.add(l);
925 }
926 change_list.new_event_listener(l);
927 }
928 for attr in attributes {
929 change_list.set_attribute(&attr.name, &attr.value);
930 }
931 for child in children {
932 create(cached_set, change_list, registry, child, cached_roots);
933 change_list.append_child();
934 }
935 }
936 NodeKind::Cached(ref c) => {
937 cached_roots.insert(c.id);
938 let node = cached_set.get(c.id);
939 create(cached_set, change_list, registry, node, cached_roots)
940 }
941 }