on e461b17 help sign in
dodrio/src/diff.rs
961 lines 32 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// change list stack:
17//
18// [... node]
19//
20// The change list 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 change list stack:
126//
127// [... node]
128//
129// The change list 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 change list stack:
169//
170// [... node]
171//
172// The change list 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 change list stack when this function is
205// entered:
206//
207// [... parent]
208//
209// the change list stack is in the same state when this function returns.
210fn diff_children(
211 cached_set: &CachedSet,
212 change_list: &mut ChangeListBuilder,
213 registry: &mut EventsRegistry,
214 old: &[Node],
215 new: &[Node],
216 cached_roots: &mut FxHashSet<CacheId>,
217) {
218 if new.is_empty() {
219 if !old.is_empty() {
220 remove_all_children(change_list, registry, old);
221 }
222 return;
223 }
225 if old.is_empty() {
226 create_and_append_children(cached_set, change_list, registry, new, cached_roots);
227 return;
228 }
230 let new_is_keyed = new[0].key().is_some();
231 let old_is_keyed = old[0].key().is_some();
233 debug_assert!(
234 new.iter().all(|n| n.key().is_some() == new_is_keyed),
235 "all siblings must be keyed or all siblings must be non-keyed"
236 );
237 debug_assert!(
238 old.iter().all(|o| o.key().is_some() == old_is_keyed),
239 "all siblings must be keyed or all siblings must be non-keyed"
240 );
242 if new_is_keyed && old_is_keyed {
243 let t = change_list.next_temporary();
244 diff_keyed_children(cached_set, change_list, registry, old, new, cached_roots);
245 change_list.set_next_temporary(t);
246 } else {
247 diff_non_keyed_children(cached_set, change_list, registry, old, new, cached_roots);
248 }
251// Diffing "keyed" children.
252//
253// With keyed children, we care about whether we delete, move, or create nodes
254// versus mutate existing nodes in place. Presumably there is some sort of CSS
255// transition animation that makes the virtual DOM diffing algorithm
256// observable. By specifying keys for nodes, we know which virtual DOM nodes
257// must reuse (or not reuse) the same physical DOM nodes.
258//
259// This is loosely based on Inferno's keyed patching implementation. However, we
260// have to modify the algorithm since we are compiling the diff down into change
261// list instructions that will be executed later, rather than applying the
262// changes to the DOM directly as we compare virtual DOMs.
263//
264// https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
265//
266// When entering this function, the parent must be on top of the change list
267// stack:
268//
269// [... parent]
270//
271// Upon exiting, the change list stack is in the same state.
272fn diff_keyed_children(
273 cached_set: &CachedSet,
274 change_list: &mut ChangeListBuilder,
275 registry: &mut EventsRegistry,
276 old: &[Node],
277 new: &[Node],
278 cached_roots: &mut FxHashSet<CacheId>,
279) {
280 if cfg!(debug_assertions) {
281 let mut keys = FxHashSet::default();
282 let mut assert_unique_keys = |children: &[Node]| {
283 keys.clear();
284 for child in children {
285 let key = child.key();
286 debug_assert!(
287 key.is_some(),
288 "if any sibling is keyed, all siblings must be keyed"
289 );
290 keys.insert(key);
291 }
292 debug_assert_eq!(
293 children.len(),
294 keys.len(),
295 "keyed siblings must each have a unique key"
296 );
297 };
298 assert_unique_keys(old);
299 assert_unique_keys(new);
300 }
302 // First up, we diff all the nodes with the same key at the beginning of the
303 // children.
304 //
305 // `shared_prefix_count` is the count of how many nodes at the start of
306 // `new` and `old` share the same keys.
307 let shared_prefix_count =
308 match diff_keyed_prefix(cached_set, change_list, registry, old, new, cached_roots) {
309 KeyedPrefixResult::Finished => return,
310 KeyedPrefixResult::MoreWorkToDo(count) => count,
311 };
313 // Next, we find out how many of the nodes at the end of the children have
314 // the same key. We do _not_ diff them yet, since we want to emit the change
315 // list instructions such that they can be applied in a single pass over the
316 // DOM. Instead, we just save this information for later.
317 //
318 // `shared_suffix_count` is the count of how many nodes at the end of `new`
319 // and `old` share the same keys.
320 let shared_suffix_count = old[shared_prefix_count..]
321 .iter()
322 .rev()
323 .zip(new[shared_prefix_count..].iter().rev())
324 .take_while(|&(old, new)| old.key() == new.key())
325 .count();
327 let old_shared_suffix_start = old.len() - shared_suffix_count;
328 let new_shared_suffix_start = new.len() - shared_suffix_count;
330 // Ok, we now hopefully have a smaller range of children in the middle
331 // within which to re-order nodes with the same keys, remove old nodes with
332 // now-unused keys, and create new nodes with fresh keys.
333 diff_keyed_middle(
334 cached_set,
335 change_list,
336 registry,
337 &old[shared_prefix_count..old_shared_suffix_start],
338 &new[shared_prefix_count..new_shared_suffix_start],
339 cached_roots,
340 shared_prefix_count,
341 shared_suffix_count,
342 old_shared_suffix_start,
343 );
345 // Finally, diff the nodes at the end of `old` and `new` that share keys.
346 let old_suffix = &old[old_shared_suffix_start..];
347 let new_suffix = &new[new_shared_suffix_start..];
348 debug_assert_eq!(old_suffix.len(), new_suffix.len());
349 if !old_suffix.is_empty() {
350 diff_keyed_suffix(
351 cached_set,
352 change_list,
353 registry,
354 old_suffix,
355 new_suffix,
356 cached_roots,
357 new_shared_suffix_start,
358 );
359 }
362enum KeyedPrefixResult {
363 // Fast path: we finished diffing all the children just by looking at the
364 // prefix of shared keys!
365 Finished,
366 // There is more diffing work to do. Here is a count of how many children at
367 // the beginning of `new` and `old` we already processed.
368 MoreWorkToDo(usize),
371// Diff the prefix of children in `new` and `old` that share the same keys in
372// the same order.
373//
374// Upon entry of this function, the change list stack must be:
375//
376// [... parent]
377//
378// Upon exit, the change list stack is the same.
379fn diff_keyed_prefix(
380 cached_set: &CachedSet,
381 change_list: &mut ChangeListBuilder,
382 registry: &mut EventsRegistry,
383 old: &[Node],
384 new: &[Node],
385 cached_roots: &mut FxHashSet<CacheId>,
386) -> KeyedPrefixResult {
387 let mut pushed = false;
388 let mut shared_prefix_count = 0;
390 for (old, new) in old.iter().zip(new.iter()) {
391 if old.key() != new.key() {
392 break;
393 }
395 if pushed {
396 debug_assert!(shared_prefix_count > 0);
397 change_list.pop_push_next_sibling();
398 } else {
399 debug_assert_eq!(shared_prefix_count, 0);
400 change_list.push_first_child();
401 pushed = true;
402 }
404 diff(cached_set, change_list, registry, old, new, cached_roots);
405 shared_prefix_count += 1;
407 // At the end of the loop, the change list stack looks like
408 //
409 // [... parent child_we_just_diffed]
410 debug_assert!(pushed);
411 }
413 // If that was all of the old children, then create and append the remaining
414 // new children and we're finished.
415 if shared_prefix_count == old.len() {
416 debug_assert!(
417 pushed,
418 "we handle the case of empty children before calling this method, so
419 `shared_prefix_count` must be greater than zero, and therefore we
420 must have pushed in the above loop"
421 );
422 change_list.pop();
423 create_and_append_children(
424 cached_set,
425 change_list,
426 registry,
427 &new[shared_prefix_count..],
428 cached_roots,
429 );
430 return KeyedPrefixResult::Finished;
431 }
433 // And if that was all of the new children, then remove all of the remaining
434 // old children and we're finished.
435 if shared_prefix_count == new.len() {
436 // Same as above.
437 debug_assert!(pushed);
438 change_list.pop_push_next_sibling();
439 change_list.remove_self_and_next_siblings();
440 return KeyedPrefixResult::Finished;
441 }
443 if pushed {
444 debug_assert!(shared_prefix_count > 0);
445 change_list.pop();
446 }
447 KeyedPrefixResult::MoreWorkToDo(shared_prefix_count)
450// The most-general, expensive code path for keyed children diffing.
451//
452// We find the longest subsequence within `old` of children that are relatively
453// ordered the same way in `new` (via finding a longest-increasing-subsequence
454// of the old child's index within `new`). The children that are elements of
455// this subsequence will remain in place, minimizing the number of DOM moves we
456// will have to do.
457//
458// Upon entry to this function, the change list stack must be:
459//
460// [... parent]
461//
462// Upon exit from this function, it will be restored to that same state.
463fn diff_keyed_middle(
464 cached_set: &CachedSet,
465 change_list: &mut ChangeListBuilder,
466 registry: &mut EventsRegistry,
467 old: &[Node],
468 new: &[Node],
469 cached_roots: &mut FxHashSet<CacheId>,
470 shared_prefix_count: usize,
471 shared_suffix_count: usize,
472 old_shared_suffix_start: usize,
473) {
474 // Should have already diffed the shared-key prefixes and suffixes.
475 debug_assert_ne!(new.first().map(|n| n.key()), old.first().map(|o| o.key()));
476 debug_assert_ne!(new.last().map(|n| n.key()), old.last().map(|o| o.key()));
478 // The algorithm below relies upon using `u32::MAX` as a sentinel
479 // value, so if we have that many new nodes, it won't work. This
480 // check is a bit academic (hence only enabled in debug), since
481 // wasm32 doesn't have enough address space to hold that many nodes
482 // in memory.
483 debug_assert!(new.len() < u32::MAX as usize);
485 // Map from each `old` node's key to its index within `old`.
486 let mut old_key_to_old_index = FxHashMap::default();
487 old_key_to_old_index.reserve(old.len());
488 old_key_to_old_index.extend(old.iter().enumerate().map(|(i, o)| (o.key(), i)));
490 // The set of shared keys between `new` and `old`.
491 let mut shared_keys = FxHashSet::default();
492 // Map from each index in `new` to the index of the node in `old` that
493 // has the same key.
494 let mut new_index_to_old_index = Vec::with_capacity(new.len());
495 new_index_to_old_index.extend(new.iter().map(|n| {
496 let key = n.key();
497 if let Some(&i) = old_key_to_old_index.get(&key) {
498 shared_keys.insert(key);
499 i
500 } else {
501 u32::MAX as usize
502 }
503 }));
505 // If none of the old keys are reused by the new children, then we
506 // remove all the remaining old children and create the new children
507 // afresh.
508 if shared_suffix_count == 0 && shared_keys.is_empty() {
509 if shared_prefix_count == 0 {
510 remove_all_children(change_list, registry, old);
511 } else {
512 change_list.pop_push_next_sibling();
513 remove_self_and_next_siblings(change_list, registry, &old[shared_prefix_count..]);
514 }
515 create_and_append_children(cached_set, change_list, registry, new, cached_roots);
516 return;
517 }
519 // The longest increasing subsequence within `new_index_to_old_index` in
520 // reverse order (since `lis_with` adds the indices in reverse
521 // order). We will leave these nodes in place in the DOM, and only move
522 // nodes that are not part of the LIS. This results in the minimum
523 // number of DOM nodes moved.
524 let mut reverse_lis = Vec::with_capacity(new_index_to_old_index.len());
525 let mut predecessors = vec![0; new_index_to_old_index.len()];
526 let mut starts = vec![0; new_index_to_old_index.len()];
527 longest_increasing_subsequence::lis_with(
528 &new_index_to_old_index,
529 &mut reverse_lis,
530 |a, b| a < b,
531 &mut predecessors,
532 &mut starts,
533 );
535 // Save each of the old children whose keys are reused in the new
536 // children.
537 let mut old_index_to_temp = vec![u32::MAX; old.len()];
538 let mut start = 0;
539 loop {
540 let end = (start..old.len())
541 .find(|&i| {
542 let key = old[i].key();
543 !shared_keys.contains(&key)
544 })
545 .unwrap_or(old.len());
547 if end - start > 0 {
548 let mut t = change_list.save_children_to_temporaries(
549 shared_prefix_count + start,
550 shared_prefix_count + end,
551 );
552 for i in start..end {
553 old_index_to_temp[i] = t;
554 t += 1;
555 }
556 }
558 debug_assert!(end <= old.len());
559 if end == old.len() {
560 break;
561 } else {
562 start = end + 1;
563 }
564 }
566 // Remove any old children whose keys were not reused in the new
567 // children. Remove from the end first so that we don't mess up indices.
568 let mut removed_count = 0;
569 for (i, old_child) in old.iter().enumerate().rev() {
570 if !shared_keys.contains(&old_child.key()) {
571 change_list.remove_child(i + shared_prefix_count);
572 removed_count += 1;
573 }
574 }
576 // Whether we have pushed a child onto the change list stack or not.
577 let mut pushed = false;
579 // Now iterate from the end of the new children back to the beginning,
580 // moving old children to their new destination, diffing them, and
581 // creating new children as necessary. Note that iterating in reverse
582 // order lets us use `Node.prototype.insertBefore` to move/insert
583 // children.
584 if shared_suffix_count > 0 {
585 change_list.push_child(old_shared_suffix_start - removed_count);
586 pushed = true;
587 }
588 let mut segment_end = new.len();
589 for lis_index in reverse_lis {
590 // Because we use `u32::MAX` as a sentinel value representing "a child
591 // with this key is not a member of `new`", we filter that out here.
592 let old_index = new_index_to_old_index[lis_index];
593 if old_index == u32::MAX as usize {
594 continue;
595 }
597 // A segment begins with a member of the LIS, which will remain in
598 // place in the DOM, followed by zero or more new children that are
599 // not members of the LIS. If one of these new children shares a key
600 // with one of the old children, then we will move that old child in
601 // the DOM. Otherwise, we create the new child afresh.
602 debug_assert!(segment_end - lis_index > 0);
604 // Go through each of the non-LIS child and move-and-diff or create
605 // it.
606 diff_and_move_or_create_segment(
607 cached_set,
608 change_list,
609 registry,
610 old,
611 new,
612 cached_roots,
613 lis_index + 1..segment_end,
614 &new_index_to_old_index,
615 &old_index_to_temp,
616 &mut pushed,
617 );
619 // Now we push the member of the LIS and diff it with its
620 // correspondingly-keyed new child.
621 let new_child = &new[lis_index];
622 let temp = old_index_to_temp[old_index];
623 debug_assert_ne!(temp, u32::MAX);
624 if pushed {
625 change_list.pop();
626 }
627 change_list.push_temporary(temp);
628 pushed = true;
629 diff(
630 cached_set,
631 change_list,
632 registry,
633 &old[old_index],
634 new_child,
635 cached_roots,
636 );
638 segment_end = lis_index;
639 }
641 // And now diff-and-move or create each of the non-LIS children that
642 // appear before the first LIS-member.
643 diff_and_move_or_create_segment(
644 cached_set,
645 change_list,
646 registry,
647 old,
648 new,
649 cached_roots,
650 0..segment_end,
651 &new_index_to_old_index,
652 &old_index_to_temp,
653 &mut pushed,
654 );
656 if pushed {
657 change_list.pop();
658 }
661// Diff-and-then-move or create each new node in the given segment. The
662// segment's nodes must _not_ be members of the LIS (those nodes we will diff in
663// place elsewhere, and we should not move them nor create them afresh).
664//
665// On entering this function, the change list stack has the parent and
666// optionally the next sibling after this segment of children:
667//
668// [... parent next_sibling] if *pushed == true
669// [... parent] otherwise
670//
671// After exiting, if any children were moved or created, then `pushed` is set to
672// true and the change list stack has the first child in this segment on
673// top. Otherwise the stack is left as it was on entering.
674//
675// [... parent child] if *pushed == true
676// [... parent] otherwise
677fn diff_and_move_or_create_segment(
678 cached_set: &CachedSet,
679 change_list: &mut ChangeListBuilder,
680 registry: &mut EventsRegistry,
681 old: &[Node],
682 new: &[Node],
683 cached_roots: &mut FxHashSet<CacheId>,
684 segment: Range<usize>,
685 new_index_to_old_index: &[usize],
686 old_index_to_temp: &[u32],
687 pushed: &mut bool,
688) {
689 for new_index in segment.rev() {
690 let new_child = &new[new_index];
691 let old_index = new_index_to_old_index[new_index];
692 if old_index == u32::MAX as usize {
693 // The key is not reused. Create this new child afresh.
694 create(cached_set, change_list, registry, new_child, cached_roots);
695 } else {
696 // The key is reused. Diff it with the old node and then
697 // move the old node into its final destination.
698 let temp = old_index_to_temp[old_index];
699 debug_assert_ne!(temp, u32::MAX);
700 change_list.push_temporary(temp);
701 diff(
702 cached_set,
703 change_list,
704 registry,
705 new_child,
706 &old[old_index],
707 cached_roots,
708 );
709 }
711 // At this point the change list stack can have one of two shapes.
712 if *pushed {
713 // [... parent next_child new_child]
714 change_list.insert_before();
715 // [... parent new_child]
716 } else {
717 // [... parent new_child]
718 change_list.append_child();
719 // [... parent]
720 change_list.push_last_child();
721 // [... parent new_child]
722 *pushed = true;
723 }
725 // At the end of each loop iteration, the change list stack looks like:
726 //
727 // [... parent new_child]
728 debug_assert!(*pushed);
729 }
732// Diff the suffix of keyed children that share the same keys in the same order.
733//
734// The parent must be on the change list stack when we enter this function:
735//
736// [... parent]
737//
738// When this function exits, the change list stack remains the same.
739fn diff_keyed_suffix(
740 cached_set: &CachedSet,
741 change_list: &mut ChangeListBuilder,
742 registry: &mut EventsRegistry,
743 old: &[Node],
744 new: &[Node],
745 cached_roots: &mut FxHashSet<CacheId>,
746 new_shared_suffix_start: usize,
747) {
748 debug_assert_eq!(old.len(), new.len());
749 debug_assert!(!old.is_empty());
751 // [... parent]
752 change_list.push_child(new_shared_suffix_start);
753 // [... parent new_child]
755 for (old_child, new_child) in old.iter().zip(new.iter()) {
756 diff(
757 cached_set,
758 change_list,
759 registry,
760 old_child,
761 new_child,
762 cached_roots,
763 );
765 // [... parent this_new_child]
766 change_list.pop_push_next_sibling();
767 // [... parent next_new_child]
768 }
770 // [... parent]
771 change_list.pop();
774// Diff children that are not keyed.
775//
776// The parent must be on the top of the change list stack when entering this
777// function:
778//
779// [... parent]
780//
781// the change list stack is in the same state when this function returns.
782fn diff_non_keyed_children(
783 cached_set: &CachedSet,
784 change_list: &mut ChangeListBuilder,
785 registry: &mut EventsRegistry,
786 old: &[Node],
787 new: &[Node],
788 cached_roots: &mut FxHashSet<CacheId>,
789) {
790 // Handled these cases in `diff_children` before calling this function.
791 debug_assert!(!new.is_empty());
792 debug_assert!(!old.is_empty());
794 for (i, (new_child, old_child)) in new.iter().zip(old.iter()).enumerate() {
795 if i == 0 {
796 // [... parent]
797 change_list.push_first_child();
798 // [... parent first_child]
799 } else {
800 // [... parent prev_sibling]
801 change_list.pop_push_next_sibling();
802 // [... parent next_sibling]
803 }
805 diff(
806 cached_set,
807 change_list,
808 registry,
809 old_child,
810 new_child,
811 cached_roots,
812 );
813 }
815 // Note that because `new` and `old` are not empty, the previous loop always
816 // executes at least once, so the change list stack is now:
817 //
818 // [... parent child]
820 match old.len().cmp(&new.len()) {
821 Ordering::Greater => {
822 // [... parent last_shared_child]
823 change_list.pop_push_next_sibling();
824 // [... parent first_child_to_remove]
825 remove_self_and_next_siblings(change_list, registry, &old[new.len()..]);
826 // [... parent]
827 }
828 Ordering::Less => {
829 // [... parent last_child]
830 change_list.pop();
831 // [... parent]
832 create_and_append_children(
833 cached_set,
834 change_list,
835 registry,
836 &new[old.len()..],
837 cached_roots,
838 );
839 }
840 Ordering::Equal => {
841 // [... parent child]
842 change_list.pop();
843 // [... parent]
844 }
845 }
848// Create the given children and append them to the parent node.
849//
850// The parent node must currently be on top of the change list stack:
851//
852// [... parent]
853//
854// When this function returns, the change list stack is in the same state.
855fn create_and_append_children(
856 cached_set: &CachedSet,
857 change_list: &mut ChangeListBuilder,
858 registry: &mut EventsRegistry,
859 new: &[Node],
860 cached_roots: &mut FxHashSet<CacheId>,
861) {
862 for child in new {
863 create(cached_set, change_list, registry, child, cached_roots);
864 change_list.append_child();
865 }
868// Remove all of a node's children.
869//
870// The change list stack must have this shape upon entry to this function:
871//
872// [... parent]
873//
874// When this function returns, the change list stack is in the same state.
875fn remove_all_children(
876 change_list: &mut ChangeListBuilder,
877 registry: &mut EventsRegistry,
878 old: &[Node],
879) {
880 for child in old {
881 registry.remove_subtree(child);
882 }
883 // Fast way to remove all children: set the node's textContent to an empty
884 // string.
885 change_list.set_text("");
888// Remove the current child and all of its following siblings.
889//
890// The change list stack must have this shape upon entry to this function:
891//
892// [... parent child]
893//
894// After the function returns, the child is no longer on the change list stack:
895//
896// [... parent]
897fn remove_self_and_next_siblings(
898 change_list: &mut ChangeListBuilder,
899 registry: &mut EventsRegistry,
900 old: &[Node],
901) {
902 for child in old {
903 registry.remove_subtree(child);
904 }
905 change_list.remove_self_and_next_siblings();
908// Emit instructions to create the given virtual node.
909//
910// The change list stack may have any shape upon entering this function:
911//
912// [...]
913//
914// When this function returns, the new node is on top of the change list stack:
915//
916// [... node]
917fn create(
918 cached_set: &CachedSet,
919 change_list: &mut ChangeListBuilder,
920 registry: &mut EventsRegistry,
921 node: &Node,
922 cached_roots: &mut FxHashSet<CacheId>,
923) {
924 match node.kind {
925 NodeKind::Text(TextNode { text }) => {
926 change_list.create_text_node(text);
927 }
928 NodeKind::Element(&ElementNode {
929 key: _,
930 tag_name,
931 listeners,
932 attributes,
933 children,
934 namespace,
935 }) => {
936 if let Some(namespace) = namespace {
937 change_list.create_element_ns(tag_name, namespace);
938 } else {
939 change_list.create_element(tag_name);
940 }
941 for l in listeners {
942 unsafe {
943 registry.add(l);
944 }
945 change_list.new_event_listener(l);
946 }
947 for attr in attributes {
948 change_list.set_attribute(&attr.name, &attr.value);
949 }
950 for child in children {
951 create(cached_set, change_list, registry, child, cached_roots);
952 change_list.append_child();
953 }
954 }
955 NodeKind::Cached(ref c) => {
956 cached_roots.insert(c.id);
957 let node = cached_set.get(c.id);
958 create(cached_set, change_list, registry, node, cached_roots)
959 }
960 }