1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::Patch;
use crate::Value;
use crate::{Callback, Element, Event, Node};
use std::cmp::min;
use std::collections::BTreeMap;
use std::mem;

/// Given two Node's generate Patch's that would turn the old virtual node's
/// real DOM node equivalent into the new Node's real DOM node equivalent.
pub fn diff<'a, T>(old: &'a Node<T>, new: &'a Node<T>) -> Vec<Patch<'a, T>>
where
    T: PartialEq,
{
    diff_recursive(&old, &new, &mut 0)
}

fn diff_recursive<'a, 'b, T>(
    old: &'a Node<T>,
    new: &'a Node<T>,
    cur_node_idx: &'b mut usize,
) -> Vec<Patch<'a, T>>
where
    T: PartialEq,
{
    let mut patches = vec![];
    // Different enum variants, replace!
    let mut replace = mem::discriminant(old) != mem::discriminant(new);

    if let (Node::Element(old_element), Node::Element(new_element)) = (old, new) {
        // Replace if there are different element tags
        if old_element.tag != new_element.tag {
            replace = true;
        }

        // 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
        if old_element.attrs.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 Node::Element(old_element_node) = old {
            for child in old_element_node.children.iter() {
                increment_node_idx_for_children(child, cur_node_idx);
            }
        }
        return patches;
    }

    // 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
        (Node::Text(old_text), Node::Text(new_text)) => {
            if old_text != new_text {
                patches.push(Patch::ChangeText(*cur_node_idx, &new_text));
            }
        }

        // We're comparing two element nodes
        (Node::Element(old_element), Node::Element(new_element)) => {
            let attributes_patches = diff_attributes(old_element, new_element, cur_node_idx);
            patches.extend(attributes_patches);

            let listener_patches = diff_event_listener(old_element, new_element, cur_node_idx);
            patches.extend(listener_patches);

            let old_child_count = old_element.children.len();
            let new_child_count = new_element.children.len();

            if new_child_count > old_child_count {
                let append_patch: Vec<&'a Node<T>> =
                    new_element.children[old_child_count..].iter().collect();
                patches.push(Patch::AppendChildren(*cur_node_idx, append_patch))
            }

            if new_child_count < old_child_count {
                patches.push(Patch::TruncateChildren(*cur_node_idx, new_child_count))
            }

            let min_count = min(old_child_count, new_child_count);
            for index in 0..min_count {
                *cur_node_idx += 1;
                let old_child = &old_element.children[index];
                let new_child = &new_element.children[index];
                patches.append(&mut 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);
                }
            }
        }
        (Node::Text(_), Node::Element(_)) | (Node::Element(_), Node::Text(_)) => {
            unreachable!("Unequal variant discriminants should already have been handled");
        }
    };

    patches
}

// diff the attributes of old element to the new element at this cur_node_idx
fn diff_attributes<'a, 'b, T>(
    old_element: &'a Element<T>,
    new_element: &'a Element<T>,
    cur_node_idx: &'b mut usize,
) -> Vec<Patch<'a, T>> {
    let mut patches = vec![];
    let mut add_attributes: BTreeMap<&str, &Value> = BTreeMap::new();
    let mut remove_attributes: Vec<&str> = vec![];

    // TODO: -> split out into func
    for (new_attr_name, new_attr_val) in new_element.attrs.iter() {
        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);
                }
            }
            None => {
                add_attributes.insert(new_attr_name, new_attr_val);
            }
        };
    }

    // TODO: -> split out into func
    for (old_attr_name, old_attr_val) in old_element.attrs.iter() {
        if add_attributes.get(&old_attr_name[..]).is_some() {
            continue;
        };

        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);
            }
        };
    }

    if !add_attributes.is_empty() {
        patches.push(Patch::AddAttributes(*cur_node_idx, add_attributes));
    }
    if !remove_attributes.is_empty() {
        patches.push(Patch::RemoveAttributes(*cur_node_idx, remove_attributes));
    }
    patches
}

// diff the events of the old element compared to the new element at this cur_node_idx
fn diff_event_listener<'a, 'b, T>(
    old_element: &'a Element<T>,
    new_element: &'a Element<T>,
    cur_node_idx: &'b mut usize,
) -> Vec<Patch<'a, T>> {
    let mut patches = vec![];
    let mut add_event_listener: BTreeMap<&str, &Callback<Event>> = BTreeMap::new();
    let mut remove_event_listener: Vec<&str> = vec![];

    // TODO: -> split out into func
    for (new_attr_name, new_attr_val) in new_element.events.iter() {
        match old_element.events.get(new_attr_name) {
            Some(ref old_attr_val) => {
                if old_attr_val != &new_attr_val {
                    add_event_listener.insert(new_attr_name, new_attr_val);
                }
            }
            None => {
                add_event_listener.insert(new_attr_name, new_attr_val);
            }
        };
    }

    // TODO: -> split out into func
    for (old_attr_name, old_attr_val) in old_element.events.iter() {
        if add_event_listener.get(&old_attr_name[..]).is_some() {
            continue;
        };

        match new_element.events.get(old_attr_name) {
            Some(ref new_attr_val) => {
                if new_attr_val != &old_attr_val {
                    remove_event_listener.push(old_attr_name);
                }
            }
            None => {
                remove_event_listener.push(old_attr_name);
            }
        };
    }

    if !add_event_listener.is_empty() {
        patches.push(Patch::AddEventListener(*cur_node_idx, add_event_listener));
    }
    if !remove_event_listener.is_empty() {
        patches.push(Patch::RemoveEventListener(
            *cur_node_idx,
            remove_event_listener,
        ));
    }
    patches
}

fn increment_node_idx_for_children<T>(old: &Node<T>, cur_node_idx: &mut usize) {
    *cur_node_idx += 1;
    if let Node::Element(element_node) = old {
        for child in element_node.children.iter() {
            increment_node_idx_for_children(&child, cur_node_idx);
        }
    }
}

#[cfg(test)]
mod tests {
    #![deny(warnings)]
    use super::*;
    use crate::*;
    use maplit::btreemap;

    #[test]
    fn test_replace_node() {
        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            ..Default::default()
        });
        let new = Node::Element::<&'static str>(Element {
            tag: "span".into(),
            ..Default::default()
        });

        let diff = diff::diff(&old, &new);
        assert_eq!(
            diff,
            vec![Patch::Replace(0, &new)],
            "Should replace the first node"
        );
    }

    #[test]
    fn test_simple_diff() {
        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
                "class".into() => "some-class".into(),
            },
            ..Default::default()
        });

        let new = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
                "class".into() => "some-class".into(),
            },
            ..Default::default()
        });

        let diff = diff(&old, &new);
        assert_eq!(diff, vec![])
    }

    #[test]
    fn test_class_changed() {
        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
                "class".into() => "some-class".into(),
            },
            ..Default::default()
        });

        let new = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
                "class".into() => "some-class2".into(),
            },
            ..Default::default()
        });

        let diff = diff(&old, &new);
        let class2 = Value::String("some-class2".to_string());
        assert_eq!(
            diff,
            vec![Patch::AddAttributes(0, {
                let mut hm = BTreeMap::new();
                hm.insert("class", &class2);
                hm
            })]
        )
    }

    #[test]
    fn test_class_removed() {
        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
                "class".into() => "some-class".into(),
            },
            ..Default::default()
        });

        let new = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            attrs: btreemap! {
                "id".into() => "some-id".into(),
            },
            ..Default::default()
        });

        let diff = diff(&old, &new);
        assert_eq!(diff, vec![Patch::RemoveAttributes(0, vec!["class"])])
    }

    #[test]
    fn no_change_event() {
        let func = |_| println!("Clicked!");
        let cb: Callback<Event> = func.into();
        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            events: btreemap! {
                "click".into() => cb.clone(),
            },
            ..Default::default()
        });

        let new = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            events: btreemap! {
                "click".into() => cb,
            },
            ..Default::default()
        });

        let diff = diff(&old, &new);
        assert_eq!(diff, vec![])
    }

    #[test]
    fn add_event() {
        let func = |_| println!("Clicked!");
        let cb: Callback<Event> = func.into();

        let old = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            ..Default::default()
        });

        let new = Node::Element::<&'static str>(Element {
            tag: "div".into(),
            events: btreemap! {
                "click".into() => cb.clone(),
            },
            ..Default::default()
        });

        let diff = diff(&old, &new);
        assert_eq!(
            diff,
            vec![Patch::AddEventListener(0, btreemap! {"click" => &cb})]
        )
    }
}