Fix a problem with NodeRefs and vtags, ref (#2279)

* fix #2206
This commit is contained in:
WorldSEnder 2021-12-20 10:45:39 +01:00 committed by GitHub
parent d8ec50150e
commit 47364b667a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -476,7 +476,11 @@ impl VDiff for VTag {
if parent.remove_child(&node).is_err() { if parent.remove_child(&node).is_err() {
console::warn!("Node not found to remove VTag"); console::warn!("Node not found to remove VTag");
} }
self.node_ref.set(None); // It could be that the ref was already reused when rendering another element.
// Only unset the ref it still belongs to our node
if self.node_ref.get().as_ref() == Some(&node) {
self.node_ref.set(None);
}
} }
/// Renders virtual tag over DOM [Element], but it also compares this with an ancestor [VTag] /// Renders virtual tag over DOM [Element], but it also compares this with an ancestor [VTag]
@ -514,7 +518,9 @@ impl VDiff for VTag {
VNode::VTag(mut a) => { VNode::VTag(mut a) => {
// Preserve the reference that already exists // Preserve the reference that already exists
let el = a.reference.take().unwrap(); let el = a.reference.take().unwrap();
a.node_ref.set(None); if self.node_ref.get().as_ref() == self.reference.as_deref() {
a.node_ref.set(None);
}
(Some(a), el) (Some(a), el)
} }
_ => unsafe { unreachable_unchecked() }, _ => unsafe { unreachable_unchecked() },
@ -1130,6 +1136,41 @@ mod tests {
"node_ref_a should have been reset when the element was reused." "node_ref_a should have been reset when the element was reused."
); );
} }
#[test]
fn vtag_should_not_touch_newly_bound_refs() {
let scope = test_scope();
let parent = document().create_element("div").unwrap();
document().body().unwrap().append_child(&parent).unwrap();
let test_ref = NodeRef::default();
let mut before = html! {
<>
<div ref={&test_ref} id="before" />
</>
};
let mut after = html! {
<>
<h6 />
<div ref={&test_ref} id="after" />
</>
};
// The point of this diff is to first render the "after" div and then detach the "before" div,
// while both should be bound to the same node ref
before.apply(&scope, &parent, NodeRef::default(), None);
after.apply(&scope, &parent, NodeRef::default(), Some(before));
assert_eq!(
test_ref
.get()
.unwrap()
.dyn_ref::<web_sys::Element>()
.unwrap()
.outer_html(),
"<div id=\"after\"></div>"
);
}
} }
#[cfg(test)] #[cfg(test)]