Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a problem with NodeRefs and vtags, ref #2206 #2279

Merged
merged 1 commit into from Dec 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 43 additions & 2 deletions packages/yew/src/virtual_dom/vtag.rs
Expand Up @@ -476,7 +476,11 @@ impl VDiff for VTag {
if parent.remove_child(&node).is_err() {
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]
Expand Down Expand Up @@ -514,7 +518,9 @@ impl VDiff for VTag {
VNode::VTag(mut a) => {
// Preserve the reference that already exists
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)
}
_ => unsafe { unreachable_unchecked() },
Expand Down Expand Up @@ -1130,6 +1136,41 @@ mod tests {
"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)]
Expand Down