forked from fiduswriter/diffDOM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiffDOM.js
1434 lines (1290 loc) · 54.5 KB
/
diffDOM.js
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(root, factory) {
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = factory();
} else {
exports.diffDOM = factory();
}
} else if (typeof define === 'function') {
// AMD loader
define(factory);
} else {
// `window` in the browser, or `exports` on the server
root.diffDOM = factory();
}
})(this, function() {
"use strict";
var diffcount;
var Diff = function(options) {
var diff = this;
if (options) {
var keys = Object.keys(options),
length = keys.length,
i;
for (i = 0; i < length; i++) {
diff[keys[i]] = options[keys[i]];
}
}
};
Diff.prototype = {
toString: function() {
return JSON.stringify(this);
},
setValue: function(aKey, aValue) {
this[aKey] = aValue;
return this;
}
};
var SubsetMapping = function SubsetMapping(a, b) {
this.oldValue = a;
this.newValue = b;
};
SubsetMapping.prototype = {
contains: function contains(subset) {
if (subset.length < this.length) {
return subset.newValue >= this.newValue && subset.newValue < this.newValue + this.length;
}
return false;
},
toString: function toString() {
return this.length + " element subset, first mapping: old " + this.oldValue + " → new " + this.newValue;
}
};
var elementDescriptors = function(el) {
var output = [];
if (el.nodeName !== '#text' && el.nodeName !== '#comment') {
output.push(el.nodeName);
if (el.attributes) {
if (el.attributes['class']) {
output.push(el.nodeName + '.' + el.attributes['class'].replace(/ /g, '.'));
}
if (el.attributes.id) {
output.push(el.nodeName + '#' + el.attributes.id);
}
}
}
return output;
};
var findUniqueDescriptors = function(li) {
var uniqueDescriptors = {},
duplicateDescriptors = {},
liLength = li.length,
nodeLength, node, descriptors, descriptor, inUnique, inDupes, i, j;
for (i = 0; i < liLength; i++) {
node = li[i];
nodeLength = node.length;
descriptors = elementDescriptors(node);
for (j = 0; j < nodeLength; j++) {
descriptor = descriptors[j];
inUnique = descriptor in uniqueDescriptors;
inDupes = descriptor in duplicateDescriptors;
if (!inUnique && !inDupes) {
uniqueDescriptors[descriptor] = true;
} else if (inUnique) {
delete uniqueDescriptors[descriptor];
duplicateDescriptors[descriptor] = true;
}
}
}
return uniqueDescriptors;
};
var uniqueInBoth = function(l1, l2) {
var l1Unique = findUniqueDescriptors(l1),
l2Unique = findUniqueDescriptors(l2),
inBoth = {},
keys = Object.keys(l1Unique),
length = keys.length,
key,
i;
for (i = 0; i < length; i++) {
key = keys[i];
if (l2Unique[key]) {
inBoth[key] = true;
}
}
return inBoth;
};
var removeDone = function(tree) {
delete tree.outerDone;
delete tree.innerDone;
delete tree.valueDone;
if (tree.childNodes) {
return tree.childNodes.every(removeDone);
} else {
return true;
}
};
var isEqual = function(e1, e2) {
var e1Attributes, e2Attributes;
if (!['nodeName', 'value', 'checked', 'selected', 'data'].every(function(element) {
if (e1[element] !== e2[element]) {
return false;
}
return true;
})) {
return false;
}
if (Boolean(e1.attributes) !== Boolean(e2.attributes)) {
return false;
}
if (Boolean(e1.childNodes) !== Boolean(e2.childNodes)) {
return false;
}
if (e1.attributes) {
e1Attributes = Object.keys(e1.attributes);
e2Attributes = Object.keys(e2.attributes);
if (e1Attributes.length !== e2Attributes.length) {
return false;
}
if (!e1Attributes.every(function(attribute) {
if (e1.attributes[attribute] !== e2.attributes[attribute]) {
return false;
}
})) {
return false;
}
}
if (e1.childNodes) {
if (e1.childNodes.length !== e2.childNodes.length) {
return false;
}
if (!e1.childNodes.every(function(childNode, index) {
return isEqual(childNode, e2.childNodes[index]);
})) {
return false;
}
}
return true;
};
var roughlyEqual = function(e1, e2, uniqueDescriptors, sameSiblings, preventRecursion) {
var childUniqueDescriptors, nodeList1, nodeList2;
if (!e1 || !e2) {
return false;
}
if (e1.nodeName !== e2.nodeName) {
return false;
}
if (e1.nodeName === '#text') {
// Note that we initially don't care what the text content of a node is,
// the mere fact that it's the same tag and "has text" means it's roughly
// equal, and then we can find out the true text difference later.
return preventRecursion ? true : e1.data === e2.data;
}
if (e1.nodeName in uniqueDescriptors) {
return true;
}
if (e1.attributes && e2.attributes) {
if (e1.attributes.id && e1.attributes.id === e2.attributes.id) {
var idDescriptor = e1.nodeName + '#' + e1.attributes.id;
if (idDescriptor in uniqueDescriptors) {
return true;
}
}
if (e1.attributes['class'] && e1.attributes['class'] === e2.attributes['class']) {
var classDescriptor = e1.nodeName + '.' + e1.attributes['class'].replace(/ /g, '.');
if (classDescriptor in uniqueDescriptors) {
return true;
}
}
}
if (sameSiblings) {
return true;
}
nodeList1 = e1.childNodes ? e1.childNodes.slice().reverse() : [];
nodeList2 = e2.childNodes ? e2.childNodes.slice().reverse() : [];
if (nodeList1.length !== nodeList2.length) {
return false;
}
if (preventRecursion) {
return nodeList1.every(function(element, index) {
return element.nodeName === nodeList2[index].nodeName;
});
} else {
// note: we only allow one level of recursion at any depth. If 'preventRecursion'
// was not set, we must explicitly force it to true for child iterations.
childUniqueDescriptors = uniqueInBoth(nodeList1, nodeList2);
return nodeList1.every(function(element, index) {
return roughlyEqual(element, nodeList2[index], childUniqueDescriptors, true, true);
});
}
};
var cloneObj = function(obj) {
// TODO: Do we really need to clone here? Is it not enough to just return the original object?
return JSON.parse(JSON.stringify(obj));
};
/**
* based on https://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#JavaScript
*/
var findCommonSubsets = function(c1, c2, marked1, marked2) {
var lcsSize = 0,
index = [],
c1Length = c1.length,
c2Length = c2.length,
matches = Array.apply(null, new Array(c1Length + 1)).map(function() {
return [];
}), // set up the matching table
uniqueDescriptors = uniqueInBoth(c1, c2),
// If all of the elements are the same tag, id and class, then we can
// consider them roughly the same even if they have a different number of
// children. This will reduce removing and re-adding similar elements.
subsetsSame = c1Length === c2Length,
origin, ret, c1Index, c2Index, c1Element, c2Element;
if (subsetsSame) {
c1.some(function(element, i) {
var c1Desc = elementDescriptors(element),
c2Desc = elementDescriptors(c2[i]);
if (c1Desc.length !== c2Desc.length) {
subsetsSame = false;
return true;
}
c1Desc.some(function(description, i) {
if (description !== c2Desc[i]) {
subsetsSame = false;
return true;
}
});
if (!subsetsSame) {
return true;
}
});
}
// fill the matches with distance values
for (c1Index = 0; c1Index < c1Length; c1Index++) {
c1Element = c1[c1Index];
for (c2Index = 0; c2Index < c2Length; c2Index++) {
c2Element = c2[c2Index];
if (!marked1[c1Index] && !marked2[c2Index] && roughlyEqual(c1Element, c2Element, uniqueDescriptors, subsetsSame)) {
matches[c1Index + 1][c2Index + 1] = (matches[c1Index][c2Index] ? matches[c1Index][c2Index] + 1 : 1);
if (matches[c1Index + 1][c2Index + 1] >= lcsSize) {
lcsSize = matches[c1Index + 1][c2Index + 1];
index = [c1Index + 1, c2Index + 1];
}
} else {
matches[c1Index + 1][c2Index + 1] = 0;
}
}
}
if (lcsSize === 0) {
return false;
}
origin = [index[0] - lcsSize, index[1] - lcsSize];
ret = new SubsetMapping(origin[0], origin[1]);
ret.length = lcsSize;
return ret;
};
/**
* This should really be a predefined function in Array...
*/
var makeArray = function(n, v) {
return Array.apply(null, new Array(n)).map(function() {
return v;
});
};
/**
* Generate arrays that indicate which node belongs to which subset,
* or whether it's actually an orphan node, existing in only one
* of the two trees, rather than somewhere in both.
*
* So if t1 = <img><canvas><br>, t2 = <canvas><br><img>.
* The longest subset is "<canvas><br>" (length 2), so it will group 0.
* The second longest is "<img>" (length 1), so it will be group 1.
* gaps1 will therefore be [1,0,0] and gaps2 [0,0,1].
*
* If an element is not part of any group, it will stay being 'true', which
* is the initial value. For example:
* t1 = <img><p></p><br><canvas>, t2 = <b></b><br><canvas><img>
*
* The "<p></p>" and "<b></b>" do only show up in one of the two and will
* therefore be marked by "true". The remaining parts are parts of the
* groups 0 and 1:
* gaps1 = [1, true, 0, 0], gaps2 = [true, 0, 0, 1]
*
*/
var getGapInformation = function(t1, t2, stable) {
var gaps1 = t1.childNodes ? makeArray(t1.childNodes.length, true) : [],
gaps2 = t2.childNodes ? makeArray(t2.childNodes.length, true) : [],
group = 0,
length = stable.length,
i, j, endOld, endNew, subset;
// give elements from the same subset the same group number
for (i = 0; i < length; i++) {
subset = stable[i];
endOld = subset.oldValue + subset.length;
endNew = subset.newValue + subset.length;
for (j = subset.oldValue; j < endOld; j += 1) {
gaps1[j] = group;
}
for (j = subset.newValue; j < endNew; j += 1) {
gaps2[j] = group;
}
group += 1;
}
return {
gaps1: gaps1,
gaps2: gaps2
};
};
/**
* Find all matching subsets, based on immediate child differences only.
*/
var markSubTrees = function(oldTree, newTree) {
// note: the child lists are views, and so update as we update old/newTree
var oldChildren = oldTree.childNodes ? oldTree.childNodes : [],
newChildren = newTree.childNodes ? newTree.childNodes : [],
marked1 = makeArray(oldChildren.length, false),
marked2 = makeArray(newChildren.length, false),
subsets = [],
subset = true,
returnIndex = function() {
return arguments[1];
},
markBoth = function(i) {
marked1[subset.oldValue + i] = true;
marked2[subset.newValue + i] = true;
},
length, subsetArray, i;
while (subset) {
subset = findCommonSubsets(oldChildren, newChildren, marked1, marked2);
if (subset) {
subsets.push(subset);
subsetArray = Array.apply(null, new Array(subset.length)).map(returnIndex);
length = subsetArray.length;
for (i = 0; i < length; i++) {
markBoth(subsetArray[i]);
}
}
}
return subsets;
};
function swap(obj, p1, p2) {
var tmp = obj[p1];
obj[p1] = obj[p2];
obj[p2] = tmp;
}
var DiffTracker = function() {
this.list = [];
};
DiffTracker.prototype = {
list: false,
add: function(diffs) {
this.list.push.apply(this.list, diffs);
},
forEach: function(fn) {
var length = this.list.length,
i;
for (i = 0; i < length; i++) {
fn(this.list[i]);
}
}
};
var diffDOM = function(options) {
var defaults = {
debug: false,
diffcap: 10, // Limit for how many diffs are accepting when debugging. Inactive when debug is false.
maxDepth: false, // False or a numeral. If set to a numeral, limits the level of depth that the the diff mechanism looks for differences. If false, goes through the entire tree.
valueDiffing: true, // Whether to take into consideration the values of forms that differ from auto assigned values (when a user fills out a form).
// syntax: textDiff: function (node, currentValue, expectedValue, newValue)
textDiff: function() {
arguments[0].data = arguments[3];
return;
},
// empty functions were benchmarked as running faster than both
// `f && f()` and `if (f) { f(); }`
preVirtualDiffApply: function() {},
postVirtualDiffApply: function() {},
preDiffApply: function() {},
postDiffApply: function() {},
filterOuterDiff: null,
compress: false // Whether to work with compressed diffs
},
varNames, i, j;
if (typeof options === "undefined") {
options = {};
}
for (i in defaults) {
if (typeof options[i] === "undefined") {
this[i] = defaults[i];
} else {
this[i] = options[i];
}
}
var varNames = {
'addAttribute': 'addAttribute',
'modifyAttribute': 'modifyAttribute',
'removeAttribute': 'removeAttribute',
'modifyTextElement': 'modifyTextElement',
'relocateGroup': 'relocateGroup',
'removeElement': 'removeElement',
'addElement': 'addElement',
'removeTextElement': 'removeTextElement',
'addTextElement': 'addTextElement',
'replaceElement': 'replaceElement',
'modifyValue': 'modifyValue',
'modifyChecked': 'modifyChecked',
'modifySelected': 'modifySelected',
'modifyComment': 'modifyComment',
'action': 'action',
'route': 'route',
'oldValue': 'oldValue',
'newValue': 'newValue',
'element': 'element',
'group': 'group',
'from': 'from',
'to': 'to',
'name': 'name',
'value': 'value',
'data': 'data',
'attributes': 'attributes',
'nodeName': 'nodeName',
'childNodes': 'childNodes',
'checked': 'checked',
'selected': 'selected'
};
if (this.compress) {
j = 0;
this._const = {};
for (i in varNames) {
this._const[i] = j;
j++;
}
} else {
this._const = varNames;
}
};
diffDOM.Diff = Diff;
diffDOM.prototype = {
// ===== Create a diff =====
diff: function(t1Node, t2Node) {
var t1 = this.nodeToObj(t1Node),
t2 = this.nodeToObj(t2Node);
diffcount = 0;
if (this.debug) {
this.t1Orig = this.nodeToObj(t1Node);
this.t2Orig = this.nodeToObj(t2Node);
}
this.tracker = new DiffTracker();
return this.findDiffs(t1, t2);
},
findDiffs: function(t1, t2) {
var diffs;
do {
if (this.debug) {
diffcount += 1;
if (diffcount > this.diffcap) {
window.diffError = [this.t1Orig, this.t2Orig];
throw new Error("surpassed diffcap:" + JSON.stringify(this.t1Orig) + " -> " + JSON.stringify(this.t2Orig));
}
}
diffs = this.findNextDiff(t1, t2, []);
if (diffs.length === 0) {
// Last check if the elements really are the same now.
// If not, remove all info about being done and start over.
// Somtimes a node can be marked as done, but the creation of subsequent diffs means that it has to be changed anyway.
if (!isEqual(t1, t2)) {
removeDone(t1);
diffs = this.findNextDiff(t1, t2, []);
}
}
if (diffs.length > 0) {
this.tracker.add(diffs);
this.applyVirtual(t1, diffs);
}
} while (diffs.length > 0);
return this.tracker.list;
},
findNextDiff: function(t1, t2, route) {
var diffs, fdiffs;
if (this.maxDepth && route.length > this.maxDepth) {
return [];
}
// outer differences?
if (!t1.outerDone) {
diffs = this.findOuterDiff(t1, t2, route);
if (this.filterOuterDiff) {
fdiffs = this.filterOuterDiff(t1, t2, diffs);
if (fdiffs) diffs = fdiffs;
}
if (diffs.length > 0) {
t1.outerDone = true;
return diffs;
} else {
t1.outerDone = true;
}
}
// inner differences?
if (!t1.innerDone) {
diffs = this.findInnerDiff(t1, t2, route);
if (diffs.length > 0) {
return diffs;
} else {
t1.innerDone = true;
}
}
if (this.valueDiffing && !t1.valueDone) {
// value differences?
diffs = this.findValueDiff(t1, t2, route);
if (diffs.length > 0) {
t1.valueDone = true;
return diffs;
} else {
t1.valueDone = true;
}
}
// no differences
return [];
},
findOuterDiff: function(t1, t2, route) {
var t = this;
var diffs = [],
attr,
attr1, attr2, attrLength, pos, i;
if (t1.nodeName !== t2.nodeName) {
return [new Diff()
.setValue(t._const.action, t._const.replaceElement)
.setValue(t._const.oldValue, cloneObj(t1))
.setValue(t._const.newValue, cloneObj(t2))
.setValue(t._const.route, route)
];
}
if (t1.data !== t2.data) {
// Comment or text node.
if (t1.nodeName === '#text') {
return [new Diff()
.setValue(t._const.action, t._const.modifyTextElement)
.setValue(t._const.route, route)
.setValue(t._const.oldValue, t1.data)
.setValue(t._const.newValue, t2.data)
];
} else {
return [new Diff()
.setValue(t._const.action, t._const.modifyComment)
.setValue(t._const.route, route)
.setValue(t._const.oldValue, t1.data)
.setValue(t._const.newValue, t2.data)
];
}
}
attr1 = t1.attributes ? Object.keys(t1.attributes).sort() : [];
attr2 = t2.attributes ? Object.keys(t2.attributes).sort() : [];
attrLength = attr1.length;
for (i = 0; i < attrLength; i++) {
attr = attr1[i];
pos = attr2.indexOf(attr);
if (pos === -1) {
diffs.push(new Diff()
.setValue(t._const.action, t._const.removeAttribute)
.setValue(t._const.route, route)
.setValue(t._const.name, attr)
.setValue(t._const.value, t1.attributes[attr])
);
} else {
attr2.splice(pos, 1);
if (t1.attributes[attr] !== t2.attributes[attr]) {
diffs.push(new Diff()
.setValue(t._const.action, t._const.modifyAttribute)
.setValue(t._const.route, route)
.setValue(t._const.name, attr)
.setValue(t._const.oldValue, t1.attributes[attr])
.setValue(t._const.newValue, t2.attributes[attr])
);
}
}
}
attrLength = attr2.length;
for (i = 0; i < attrLength; i++) {
attr = attr2[i];
diffs.push(new Diff()
.setValue(t._const.action, t._const.addAttribute)
.setValue(t._const.route, route)
.setValue(t._const.name, attr)
.setValue(t._const.value, t2.attributes[attr])
);
}
return diffs;
},
nodeToObj: function(aNode) {
var objNode = {},
dobj = this,
nodeArray, childNode, length, attribute, i;
objNode.nodeName = aNode.nodeName;
if (objNode.nodeName === '#text' || objNode.nodeName === '#comment') {
objNode.data = aNode.data;
} else {
if (aNode.attributes && aNode.attributes.length > 0) {
objNode.attributes = {};
nodeArray = Array.prototype.slice.call(aNode.attributes);
length = nodeArray.length;
for (i = 0; i < length; i++) {
attribute = nodeArray[i];
objNode.attributes[attribute.name] = attribute.value;
}
}
if (aNode.childNodes && aNode.childNodes.length > 0) {
objNode.childNodes = [];
nodeArray = Array.prototype.slice.call(aNode.childNodes);
length = nodeArray.length;
for (i = 0; i < length; i++) {
childNode = nodeArray[i];
objNode.childNodes.push(dobj.nodeToObj(childNode));
}
}
if (this.valueDiffing) {
if (aNode.value !== undefined) {
objNode.value = aNode.value;
}
if (aNode.checked !== undefined) {
objNode.checked = aNode.checked;
}
if (aNode.selected !== undefined) {
objNode.selected = aNode.selected;
}
}
}
return objNode;
},
objToNode: function(objNode, insideSvg) {
var node, dobj = this,
attribute, attributeArray, childNode, childNodeArray, length, i;
if (objNode.nodeName === '#text') {
node = document.createTextNode(objNode.data);
} else if (objNode.nodeName === '#comment') {
node = document.createComment(objNode.data);
} else {
if (objNode.nodeName === 'svg' || insideSvg) {
node = document.createElementNS('http://www.w3.org/2000/svg', objNode.nodeName);
insideSvg = true;
} else {
node = document.createElement(objNode.nodeName);
}
if (objNode.attributes) {
attributeArray = Object.keys(objNode.attributes);
length = attributeArray.length;
for (i = 0; i < length; i++) {
attribute = attributeArray[i];
node.setAttribute(attribute, objNode.attributes[attribute]);
}
}
if (objNode.childNodes) {
childNodeArray = objNode.childNodes;
length = childNodeArray.length;
for (i = 0; i < length; i++) {
childNode = childNodeArray[i];
node.appendChild(dobj.objToNode(childNode, insideSvg));
}
}
if (this.valueDiffing) {
if (objNode.value) {
node.value = objNode.value;
}
if (objNode.checked) {
node.checked = objNode.checked;
}
if (objNode.selected) {
node.selected = objNode.selected;
}
}
}
return node;
},
findInnerDiff: function(t1, t2, route) {
var t = this;
var subtrees = (t1.childNodes && t2.childNodes) ? markSubTrees(t1, t2) : [],
t1ChildNodes = t1.childNodes ? t1.childNodes : [],
t2ChildNodes = t2.childNodes ? t2.childNodes : [],
childNodesLengthDifference, diffs = [],
index = 0,
last, e1, e2, i;
if (subtrees.length > 0) {
/* One or more groups have been identified among the childnodes of t1
* and t2.
*/
diffs = this.attemptGroupRelocation(t1, t2, subtrees, route);
if (diffs.length > 0) {
return diffs;
}
}
/* 0 or 1 groups of similar child nodes have been found
* for t1 and t2. 1 If there is 1, it could be a sign that the
* contents are the same. When the number of groups is below 2,
* t1 and t2 are made to have the same length and each of the
* pairs of child nodes are diffed.
*/
last = Math.max(t1ChildNodes.length, t2ChildNodes.length);
if (t1ChildNodes.length !== t2ChildNodes.length) {
childNodesLengthDifference = true;
}
for (i = 0; i < last; i += 1) {
e1 = t1ChildNodes[i];
e2 = t2ChildNodes[i];
if (childNodesLengthDifference) {
/* t1 and t2 have different amounts of childNodes. Add
* and remove as necessary to obtain the same length */
if (e1 && !e2) {
if (e1.nodeName === '#text') {
diffs.push(new Diff()
.setValue(t._const.action, t._const.removeTextElement)
.setValue(t._const.route, route.concat(index))
.setValue(t._const.value, e1.data)
);
index -= 1;
} else {
diffs.push(new Diff()
.setValue(t._const.action, t._const.removeElement)
.setValue(t._const.route, route.concat(index))
.setValue(t._const.element, cloneObj(e1))
);
index -= 1;
}
} else if (e2 && !e1) {
if (e2.nodeName === '#text') {
diffs.push(new Diff()
.setValue(t._const.action, t._const.addTextElement)
.setValue(t._const.route, route.concat(index))
.setValue(t._const.value, e2.data)
);
} else {
diffs.push(new Diff()
.setValue(t._const.action, t._const.addElement)
.setValue(t._const.route, route.concat(index))
.setValue(t._const.element, cloneObj(e2))
);
}
}
}
/* We are now guaranteed that childNodes e1 and e2 exist,
* and that they can be diffed.
*/
/* Diffs in child nodes should not affect the parent node,
* so we let these diffs be submitted together with other
* diffs.
*/
if (e1 && e2) {
diffs = diffs.concat(this.findNextDiff(e1, e2, route.concat(index)));
}
index += 1;
}
t1.innerDone = true;
return diffs;
},
attemptGroupRelocation: function(t1, t2, subtrees, route) {
/* Either t1.childNodes and t2.childNodes have the same length, or
* there are at least two groups of similar elements can be found.
* attempts are made at equalizing t1 with t2. First all initial
* elements with no group affiliation (gaps=true) are removed (if
* only in t1) or added (if only in t2). Then the creation of a group
* relocation diff is attempted.
*/
var t = this;
var gapInformation = getGapInformation(t1, t2, subtrees),
gaps1 = gapInformation.gaps1,
gaps2 = gapInformation.gaps2,
shortest = Math.min(gaps1.length, gaps2.length),
destinationDifferent, toGroup,
group, node, similarNode, testI, diffs = [],
index1, index2, j;
for (index2 = 0, index1 = 0; index2 < shortest; index1 += 1, index2 += 1) {
if (gaps1[index2] === true) {
node = t1.childNodes[index1];
if (node.nodeName === '#text') {
if (t2.childNodes[index2].nodeName === '#text' && node.data !== t2.childNodes[index2].data) {
testI = index1;
while (t1.childNodes.length > testI + 1 && t1.childNodes[testI + 1].nodeName === '#text') {
testI += 1;
if (t2.childNodes[index2].data === t1.childNodes[testI].data) {
similarNode = true;
break;
}
}
if (!similarNode) {
diffs.push(new Diff()
.setValue(t._const.action, t._const.modifyTextElement)
.setValue(t._const.route, route.concat(index2))
.setValue(t._const.oldValue, node.data)
.setValue(t._const.newValue, t2.childNodes[index2].data)
);
return diffs;
}
}
diffs.push(new Diff()
.setValue(t._const.action, t._const.removeTextElement)
.setValue(t._const.route, route.concat(index2))
.setValue(t._const.value, node.data)
);
gaps1.splice(index2, 1);
shortest = Math.min(gaps1.length, gaps2.length);
index2 -= 1;
} else {
diffs.push(new Diff()
.setValue(t._const.action, t._const.removeElement)
.setValue(t._const.route, route.concat(index2))
.setValue(t._const.element, cloneObj(node))
);
gaps1.splice(index2, 1);
shortest = Math.min(gaps1.length, gaps2.length);
index2 -= 1;
}
} else if (gaps2[index2] === true) {
node = t2.childNodes[index2];
if (node.nodeName === '#text') {
diffs.push(new Diff()
.setValue(t._const.action, t._const.addTextElement)
.setValue(t._const.route, route.concat(index2))
.setValue(t._const.value, node.data)
);
gaps1.splice(index2, 0, true);
shortest = Math.min(gaps1.length, gaps2.length);
index1 -= 1;
} else {
diffs.push(new Diff()
.setValue(t._const.action, t._const.addElement)
.setValue(t._const.route, route.concat(index2))
.setValue(t._const.element, cloneObj(node))
);
gaps1.splice(index2, 0, true);
shortest = Math.min(gaps1.length, gaps2.length);
index1 -= 1;
}
} else if (gaps1[index2] !== gaps2[index2]) {
if (diffs.length > 0) {
return diffs;
}
// group relocation
group = subtrees[gaps1[index2]];
toGroup = Math.min(group.newValue, (t1.childNodes.length - group.length));
if (toGroup !== group.oldValue) {
// Check whether destination nodes are different than originating ones.
destinationDifferent = false;
for (j = 0; j < group.length; j += 1) {
if (!roughlyEqual(t1.childNodes[toGroup + j], t1.childNodes[group.oldValue + j], [], false, true)) {
destinationDifferent = true;
}
}
if (destinationDifferent) {
return [new Diff()
.setValue(t._const.action, t._const.relocateGroup)
.setValue('groupLength', group.length)
.setValue(t._const.from, group.oldValue)
.setValue(t._const.to, toGroup)
.setValue(t._const.route, route)
];
}
}
}
}
return diffs;
},
findValueDiff: function(t1, t2, route) {
// Differences of value. Only useful if the value/selection/checked value
// differs from what is represented in the DOM. For example in the case
// of filled out forms, etc.
var diffs = [];
var t = this;
if (t1.selected !== t2.selected) {
diffs.push(new Diff()
.setValue(t._const.action, t._const.modifySelected)
.setValue(t._const.oldValue, t1.selected)
.setValue(t._const.newValue, t2.selected)
.setValue(t._const.route, route)
);
}
if ((t1.value || t2.value) && t1.value !== t2.value && t1.nodeName !== 'OPTION') {
diffs.push(new Diff()
.setValue(t._const.action, t._const.modifyValue)