dioxus/packages/core/src/diff.rs

328 lines
11 KiB
Rust
Raw Normal View History

2021-02-15 04:39:46 +00:00
//! A primitive diffing algorithm
//!
//!
//!
//!
//!
use std::{collections::HashMap, mem};
use crate::innerlude::*;
use crate::patch::Patch;
use fxhash::{FxBuildHasher, FxHashMap, FxHashSet};
use generational_arena::Index;
2021-02-15 04:39:46 +00:00
pub struct DiffMachine {
immediate_queue: Vec<Index>,
diffed: FxHashSet<Index>,
need_to_diff: FxHashSet<Index>,
marked_for_removal: Vec<Index>,
}
2021-02-12 21:11:33 +00:00
2021-02-15 04:39:46 +00:00
impl DiffMachine {
pub fn new() -> Self {
Self {
immediate_queue: vec![],
diffed: FxHashSet::default(),
need_to_diff: FxHashSet::default(),
marked_for_removal: vec![],
}
}
2021-02-15 04:39:46 +00:00
/// Given two VirtualNode's generate Patch's that would turn the old virtual node's
/// real DOM node equivalent into the new VirtualNode's real DOM node equivalent.
pub fn diff<'a>(&mut self, old: &'a VNode, new: &'a VNode) -> Vec<Patch<'a>> {
self.diff_recursive(&old, &new, &mut 0)
}
pub fn diff_recursive<'a, 'b>(
&mut self,
old: &'a VNode,
new: &'a VNode,
cur_node_idx: &'b mut usize,
) -> Vec<Patch<'a>> {
let mut patches = vec![];
let mut replace = false;
// Different enum variants, replace!
if mem::discriminant(old) != mem::discriminant(new) {
replace = true;
}
2021-02-15 04:39:46 +00:00
if let (VNode::Element(old_element), VNode::Element(new_element)) = (old, new) {
// Replace if there are different element tags
if old_element.tag_name != new_element.tag_name {
// if old_element.tag != new_element.tag {
replace = true;
}
2021-02-15 04:39:46 +00:00
// Replace if two elements have different keys
// TODO: More robust key support. This is just an early stopgap to allow you to force replace
// an element... say if it's event changed. Just change the key name for now.
// In the future we want keys to be used to create a Patch::ReOrder to re-order siblings
// todo!
// if old_element.attributes.get("key").is_some()
// && old_element.attrs.get("key") != new_element.attrs.get("key")
// {
// replace = true;
// }
}
// Handle replacing of a node
if replace {
patches.push(Patch::Replace(*cur_node_idx, &new));
if let VNode::Element(old_element_node) = old {
for child in old_element_node.children.iter() {
increment_node_idx_for_children(child, cur_node_idx);
}
}
2021-02-15 04:39:46 +00:00
return patches;
}
2021-02-15 04:39:46 +00:00
// The following comparison can only contain identical variants, other
// cases have already been handled above by comparing variant
// discriminants.
match (old, new) {
// We're comparing two text nodes
(VNode::Text(old_text), VNode::Text(new_text)) => {
if old_text != new_text {
patches.push(Patch::ChangeText(*cur_node_idx, &new_text));
}
}
2021-02-15 04:39:46 +00:00
// We're comparing two element nodes
(VNode::Element(old_element), VNode::Element(new_element)) => {
// let b: HashMap<&str, &str, FxBuildHasher> = HashMap::new()
let old_attrs = old_element
.attributes
.iter()
.map(|f| (f.name, f.value))
.collect::<HashMap<&'static str, &str, FxBuildHasher>>();
let new_attrs = old_element
.attributes
.iter()
.map(|f| (f.name, f.value))
.collect::<HashMap<&'static str, &str, FxBuildHasher>>();
let mut add_attributes = FxHashMap::<&'static str, &str>::default();
// [("blah", "blah")]
// .into_iter()
// .map(|f| (f.0, f.1))
// .collect::<HashMap<&'static str, &str, FxBuildHasher>>();
// let mut add_attribute = HashMap::<&str, &str, FxBuildHasher>::new();
let mut remove_attributes: Vec<&str> = vec![];
// TODO: -> split out into func
for (new_attr_name, new_attr_val) in new_attrs.iter() {
// for (new_attr_name, new_attr_val) in new_element.attrs.iter() {
match old_attrs.get(new_attr_name) {
// match old_element.attrs.get(new_attr_name) {
Some(ref old_attr_val) => {
if old_attr_val != &new_attr_val {
add_attributes.insert(new_attr_name, new_attr_val);
}
}
2021-02-15 04:39:46 +00:00
None => {
add_attributes.insert(new_attr_name, new_attr_val);
}
};
}
2021-02-15 04:39:46 +00:00
// TODO: -> split out into func
for (old_attr_name, old_attr_val) in old_attrs.iter() {
// for (old_attr_name, old_attr_val) in old_element.attrs.iter() {
if add_attributes.get(&old_attr_name[..]).is_some() {
continue;
};
match new_attrs.get(old_attr_name) {
// match new_element.attrs.get(old_attr_name) {
Some(ref new_attr_val) => {
if new_attr_val != &old_attr_val {
remove_attributes.push(old_attr_name);
}
}
None => {
remove_attributes.push(old_attr_name);
}
};
}
2021-02-15 04:39:46 +00:00
if add_attributes.len() > 0 {
patches.push(Patch::AddAttributes(*cur_node_idx, add_attributes));
}
if remove_attributes.len() > 0 {
patches.push(Patch::RemoveAttributes(*cur_node_idx, remove_attributes));
}
2021-02-15 04:39:46 +00:00
let old_child_count = old_element.children.len();
let new_child_count = new_element.children.len();
2021-02-15 04:39:46 +00:00
if new_child_count > old_child_count {
let append_patch: Vec<&'a VNode> =
new_element.children[old_child_count..].iter().collect();
patches.push(Patch::AppendChildren(*cur_node_idx, append_patch))
}
2021-02-15 04:39:46 +00:00
if new_child_count < old_child_count {
patches.push(Patch::TruncateChildren(*cur_node_idx, new_child_count))
}
2021-02-15 04:39:46 +00:00
let min_count = std::cmp::min(old_child_count, new_child_count);
for index in 0..min_count {
*cur_node_idx = *cur_node_idx + 1;
let old_child = &old_element.children[index];
let new_child = &new_element.children[index];
patches.append(&mut self.diff_recursive(&old_child, &new_child, cur_node_idx))
}
if new_child_count < old_child_count {
for child in old_element.children[min_count..].iter() {
increment_node_idx_for_children(child, cur_node_idx);
}
}
}
2021-02-15 04:39:46 +00:00
(VNode::Suspended, _)
| (_, VNode::Suspended)
| (VNode::Component(_), _)
| (_, VNode::Component(_)) => {
todo!("cant yet handle these two")
}
2021-02-15 04:39:46 +00:00
(VNode::Text(_), VNode::Element(_))
| (VirtualNode::Element(_), VirtualNode::Text(_)) => {
unreachable!("Unequal variant discriminants should already have been handled");
}
};
2021-02-15 04:39:46 +00:00
// new_root.create_element()
patches
}
2021-02-15 04:39:46 +00:00
}
2021-02-15 04:39:46 +00:00
fn increment_node_idx_for_children<'a, 'b>(old: &'a VirtualNode, cur_node_idx: &'b mut usize) {
*cur_node_idx += 1;
if let VirtualNode::Element(element_node) = old {
for child in element_node.children.iter() {
increment_node_idx_for_children(&child, cur_node_idx);
}
}
2021-02-15 04:39:46 +00:00
}
2021-02-15 04:39:46 +00:00
// #[cfg(test)]
mod tests {
use bumpalo::Bump;
2021-02-15 04:39:46 +00:00
use super::*;
2021-02-15 04:39:46 +00:00
fn test_diff(
tree1: impl Fn(&Bump) -> VNode<'_>,
tree2: impl Fn(&Bump) -> VNode<'_>,
expected_patches: Vec<Patch>,
description: &'static str,
) {
let bump = Bump::new();
2021-02-15 04:39:46 +00:00
let nodes1 = tree1(&bump);
let nodes2 = tree1(&bump);
2021-02-15 04:39:46 +00:00
let mut machine = DiffMachine::new();
2021-02-15 04:39:46 +00:00
let patches = machine.diff(&nodes1, &nodes2);
2021-02-15 04:39:46 +00:00
patches
.iter()
.zip(expected_patches.iter())
.for_each(|f| assert_eq!(compare_patch(f.0, f.1), true, "{}", description));
}
2021-02-15 04:39:46 +00:00
fn compare_patch(patch1: &Patch, patch2: &Patch) -> bool {
match (patch1, patch2) {
(Patch::AppendChildren(_, _), Patch::AppendChildren(_, _)) => true,
(Patch::AppendChildren(_, _), _) => false,
2021-02-15 04:39:46 +00:00
(Patch::TruncateChildren(_, _), Patch::TruncateChildren(_, _)) => true,
(Patch::TruncateChildren(_, _), _) => false,
2021-02-15 04:39:46 +00:00
(Patch::Replace(_, _), Patch::Replace(_, _)) => true,
(Patch::Replace(_, _), _) => false,
2021-02-15 04:39:46 +00:00
(Patch::AddAttributes(_, _), Patch::AddAttributes(_, _)) => true,
(Patch::AddAttributes(_, _), _) => false,
2021-02-15 04:39:46 +00:00
(Patch::RemoveAttributes(_, _), Patch::RemoveAttributes(_, _)) => true,
(Patch::RemoveAttributes(_, _), _) => false,
2021-02-15 04:39:46 +00:00
(Patch::ChangeText(_, _), Patch::ChangeText(_, _)) => true,
(Patch::ChangeText(_, _), _) => false,
}
}
2021-02-15 04:39:46 +00:00
fn printdiff(
tree1: impl for<'a> Fn(&'a Bump) -> VNode<'a>,
tree2: impl for<'a> Fn(&'a Bump) -> VNode<'a>,
desc: &'static str,
) {
2021-02-15 04:39:46 +00:00
let bump = Bump::new();
2021-02-15 04:39:46 +00:00
let nodes1 = tree1(&bump);
let nodes2 = tree2(&bump);
2021-02-15 04:39:46 +00:00
let mut machine = DiffMachine::new();
2021-02-15 04:39:46 +00:00
let patches = machine.diff(&nodes1, &nodes2);
2021-02-15 04:39:46 +00:00
patches.iter().for_each(|f| match f {
Patch::AppendChildren(idx, a) => {
println!("AppendChildren");
}
2021-02-15 04:39:46 +00:00
Patch::TruncateChildren(idx, a) => {
println!("TruncateChildren");
}
2021-02-15 04:39:46 +00:00
Patch::Replace(idx, a) => {
println!("Replace");
}
2021-02-15 04:39:46 +00:00
Patch::AddAttributes(idx, a) => {
println!("AddAttributes");
}
2021-02-15 04:39:46 +00:00
Patch::RemoveAttributes(idx, a) => {
println!("RemoveAttributes");
}
2021-02-15 04:39:46 +00:00
Patch::ChangeText(idx, a) => {
println!("ChangeText");
}
2021-02-15 04:39:46 +00:00
});
}
2021-02-15 04:39:46 +00:00
#[test]
fn example_diff() {
printdiff(
html! { <div> </div> },
html! { <div>"Hello world!" </div> },
"demo the difference between two simple dom tree",
);
2021-02-15 04:39:46 +00:00
printdiff(
html! {
<div>
"Hello world!"
</div>
},
html! {
<div>
<div>
"Hello world!"
"Hello world!"
"Hello world!"
"Hello world!"
"Hello world!"
</div>
</div>
},
"demo the difference between two simple dom tree",
);
}
}