-
Notifications
You must be signed in to change notification settings - Fork 187
/
jdd.js
1308 lines (1136 loc) · 48 KB
/
jdd.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
/*******************************************************************************
*
* Copyright 2015-2019 Zack Grossbart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
'use strict';
// utilites
//
/**
* Fixing typeof
* takes value and returns type of value
* @param value
* return typeof value
*/
function getType(value) {
if ((function () { return value && (value !== this); }).call(value)) {
//fallback on 'typeof' for truthy primitive values
return typeof value;
}
return ({}).toString.call(value).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
/**
* Iterate over array of objects and call given callback for each item in the array
* Optionally may take this as scope
*
* @param array
* @param callback
* @param optional scope
*/
function forEach(array, callback, scope) {
for (var idx = 0; idx < array.length; idx++) {
callback.call(scope, array[idx], idx, array);
}
}
/**
* The jdd object handles all of the functions for the main page. It finds the diffs and manages
* the interactions of displaying them.
*/
/*global jdd:true */
var jdd = {
LEFT: 'left',
RIGHT: 'right',
EQUALITY: 'eq',
TYPE: 'type',
MISSING: 'missing',
diffs: [],
SEPARATOR: '/',
requestCount: 0,
/**
* Find the differences between the two objects and recurse into their sub objects.
*/
findDiffs: function (/*Object*/ config1, /*Object*/ data1, /*Object*/ config2, /*Object*/ data2) {
config1.currentPath.push(jdd.SEPARATOR);
config2.currentPath.push(jdd.SEPARATOR);
var key;
// no un-used vars
// var val;
if (data1.length < data2.length) {
/*
* This means the second data has more properties than the first.
* We need to find the extra ones and create diffs for them.
*/
for (key in data2) {
if (data2.hasOwnProperty(key)) {
// no un-used vars
// val = data1[key];
if (!data1.hasOwnProperty(key)) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2, jdd.SEPARATOR + key),
'The right side of this object has more items than the left side', jdd.MISSING));
}
}
}
}
/*
* Now we're going to look for all the properties in object one and
* compare them to object two
*/
for (key in data1) {
if (data1.hasOwnProperty(key)) {
// no un-used vars
// val = data1[key];
config1.currentPath.push(key.replace(jdd.SEPARATOR, '#'));
if (!data2.hasOwnProperty(key)) {
/*
* This means that the first data has a property which
* isn't present in the second data
*/
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Missing property <code>' + key + '</code> from the object on the right side', jdd.MISSING));
} else {
config2.currentPath.push(key.replace(jdd.SEPARATOR, '#'));
jdd.diffVal(data1[key], config1, data2[key], config2);
config2.currentPath.pop();
}
config1.currentPath.pop();
}
}
config1.currentPath.pop();
config2.currentPath.pop();
/*
* Now we want to look at all the properties in object two that
* weren't in object one and generate diffs for them.
*/
for (key in data2) {
if (data2.hasOwnProperty(key)) {
// no un-used vars
// val = data1[key];
if (!data1.hasOwnProperty(key)) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2, key),
'Missing property <code>' + key + '</code> from the object on the left side', jdd.MISSING));
}
}
}
},
/**
* Generate the differences between two values. This handles differences of object
* types and actual values.
*/
diffVal: function (val1, config1, val2, config2) {
if (getType(val1) === 'array') {
jdd.diffArray(val1, config1, val2, config2);
} else if (getType(val1) === 'object') {
if (['array', 'string', 'number', 'boolean', 'null'].indexOf(getType(val2)) > -1) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be objects', jdd.TYPE));
} else {
jdd.findDiffs(config1, val1, config2, val2);
}
} else if (getType(val1) === 'string') {
if (getType(val2) !== 'string') {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be strings', jdd.TYPE));
} else if (val1 !== val2) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both sides should be equal strings', jdd.EQUALITY));
}
} else if (getType(val1) === 'number') {
if (getType(val2) !== 'number') {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be numbers', jdd.TYPE));
} else if (val1 !== val2) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both sides should be equal numbers', jdd.EQUALITY));
}
} else if (getType(val1) === 'boolean') {
jdd.diffBool(val1, config1, val2, config2);
} else if (getType(val1) === 'null' && getType(val2) !== 'null') {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be nulls', jdd.TYPE));
}
},
/**
* Arrays are more complex because we need to recurse into them and handle different length
* issues so we handle them specially in this function.
*/
diffArray: function (val1, config1, val2, config2) {
if (getType(val2) !== 'array') {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be arrays', jdd.TYPE));
return;
}
if (val1.length < val2.length) {
/*
* Then there were more elements on the right side and we need to
* generate those differences.
*/
for (var i = val1.length; i < val2.length; i++) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2, '[' + i + ']'),
'Missing element <code>' + i + '</code> from the array on the left side', jdd.MISSING));
}
}
val1.forEach(function (arrayVal, index) {
if (val2.length <= index) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1, '[' + index + ']'),
config2, jdd.generatePath(config2),
'Missing element <code>' + index + '</code> from the array on the right side', jdd.MISSING));
} else {
config1.currentPath.push(jdd.SEPARATOR + '[' + index + ']');
config2.currentPath.push(jdd.SEPARATOR + '[' + index + ']');
if (getType(val2) === 'array') {
/*
* If both sides are arrays then we want to diff them.
*/
jdd.diffVal(val1[index], config1, val2[index], config2);
}
config1.currentPath.pop();
config2.currentPath.pop();
}
});
},
/**
* We handle boolean values specially because we can show a nicer message for them.
*/
diffBool: function (val1, config1, val2, config2) {
if (getType(val2) !== 'boolean') {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'Both types should be booleans', jdd.TYPE));
} else if (val1 !== val2) {
if (val1) {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'The left side is <code>true</code> and the right side is <code>false</code>', jdd.EQUALITY));
} else {
jdd.diffs.push(jdd.generateDiff(config1, jdd.generatePath(config1),
config2, jdd.generatePath(config2),
'The left side is <code>false</code> and the right side is <code>true</code>', jdd.EQUALITY));
}
}
},
/**
* Format the object into the output stream and decorate the data tree with
* the data about this object.
*/
formatAndDecorate: function (/*Object*/ config, /*Object*/ data) {
if (getType(data) === 'array') {
jdd.formatAndDecorateArray(config, data);
return;
}
jdd.startObject(config);
config.currentPath.push(jdd.SEPARATOR);
var props = jdd.getSortedProperties(data);
/*
* If the first set has more than the second then we will catch it
* when we compare values. However, if the second has more then
* we need to catch that here.
*/
props.forEach(function (key) {
config.out += jdd.newLine(config) + jdd.getTabs(config.indent) + '"' + jdd.unescapeString(key) + '": ';
config.currentPath.push(key.replace(jdd.SEPARATOR, '#'));
config.paths.push({
path: jdd.generatePath(config),
line: config.line
});
jdd.formatVal(data[key], config);
config.currentPath.pop();
});
jdd.finishObject(config);
config.currentPath.pop();
},
/**
* Format the array into the output stream and decorate the data tree with
* the data about this object.
*/
formatAndDecorateArray: function (/*Object*/ config, /*Array*/ data) {
jdd.startArray(config);
/*
* If the first set has more than the second then we will catch it
* when we compare values. However, if the second has more then
* we need to catch that here.
*/
data.forEach(function (arrayVal, index) {
config.out += jdd.newLine(config) + jdd.getTabs(config.indent);
config.paths.push({
path: jdd.generatePath(config, '[' + index + ']'),
line: config.line
});
config.currentPath.push(jdd.SEPARATOR + '[' + index + ']');
jdd.formatVal(arrayVal, config);
config.currentPath.pop();
});
jdd.finishArray(config);
config.currentPath.pop();
},
/**
* Generate the start of the an array in the output stream and push in the new path
*/
startArray: function (config) {
config.indent++;
config.out += '[';
if (config.paths.length === 0) {
/*
* Then we are at the top of the array and we want to add
* a path for it.
*/
config.paths.push({
path: jdd.generatePath(config),
line: config.line
});
}
if (config.indent === 0) {
config.indent++;
}
},
/**
* Finish the array, outdent, and pop off all the path
*/
finishArray: function (config) {
if (config.indent === 0) {
config.indent--;
}
jdd.removeTrailingComma(config);
config.indent--;
config.out += jdd.newLine(config) + jdd.getTabs(config.indent) + ']';
if (config.indent !== 0) {
config.out += ',';
} else {
config.out += jdd.newLine(config);
}
},
/**
* Generate the start of the an object in the output stream and push in the new path
*/
startObject: function (config) {
config.indent++;
config.out += '{';
if (config.paths.length === 0) {
/*
* Then we are at the top of the object and we want to add
* a path for it.
*/
config.paths.push({
path: jdd.generatePath(config),
line: config.line
});
}
if (config.indent === 0) {
config.indent++;
}
},
/**
* Finish the object, outdent, and pop off all the path
*/
finishObject: function (config) {
if (config.indent === 0) {
config.indent--;
}
jdd.removeTrailingComma(config);
config.indent--;
config.out += jdd.newLine(config) + jdd.getTabs(config.indent) + '}';
if (config.indent !== 0) {
config.out += ',';
} else {
config.out += jdd.newLine(config);
}
},
/**
* Format a specific value into the output stream.
*/
formatVal: function (val, config) {
if (getType(val) === 'array') {
config.out += '[';
config.indent++;
val.forEach(function (arrayVal, index) {
config.out += jdd.newLine(config) + jdd.getTabs(config.indent);
config.paths.push({
path: jdd.generatePath(config, '[' + index + ']'),
line: config.line
});
config.currentPath.push(jdd.SEPARATOR + '[' + index + ']');
jdd.formatVal(arrayVal, config);
config.currentPath.pop();
});
jdd.removeTrailingComma(config);
config.indent--;
config.out += jdd.newLine(config) + jdd.getTabs(config.indent) + ']' + ',';
} else if (getType(val) === 'object') {
jdd.formatAndDecorate(config, val);
} else if (getType(val) === 'string') {
config.out += '"' + jdd.unescapeString(val) + '",';
} else if (getType(val) === 'number') {
config.out += val + ',';
} else if (getType(val) === 'boolean') {
config.out += val + ',';
} else if (getType(val) === 'null') {
config.out += 'null,';
}
},
/**
* When we parse the JSON string we end up removing the escape strings when we parse it
* into objects. This results in invalid JSON if we insert those strings back into the
* generated JSON. We also need to look out for characters that change the line count
* like new lines and carriage returns.
*
* This function puts those escaped values back when we generate the JSON output for the
* well known escape strings in JSON. It handles properties and values.
*
* This function does not handle unicode escapes. Unicode escapes are optional in JSON
* and the JSON output is still valid with a unicode character in it.
*/
unescapeString: function (val) {
if (val) {
return val.replace('\\', '\\\\') // Single slashes need to be replaced first
.replace(/\"/g, '\\"') // Then double quotes
.replace(/\n/g, '\\n') // New lines
.replace('\b', '\\b') // Backspace
.replace(/\f/g, '\\f') // Formfeed
.replace(/\r/g, '\\r') // Carriage return
.replace(/\t/g, '\\t'); // Horizontal tabs
} else {
return val;
}
},
/**
* Generate a JSON path based on the specific configuration and an optional property.
*/
generatePath: function (config, prop) {
var s = '';
config.currentPath.forEach(function (path) {
s += path;
});
if (prop) {
s += jdd.SEPARATOR + prop.replace(jdd.SEPARATOR, '#');
}
if (s.length === 0) {
return jdd.SEPARATOR;
} else {
return s;
}
},
/**
* Add a new line to the output stream
*/
newLine: function (config) {
config.line++;
return '\n';
},
/**
* Sort all the relevant properties and return them in an alphabetical sort by property key
*/
getSortedProperties: function (/*Object*/ obj) {
var props = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
props.push(prop);
}
}
props = props.sort(function (a, b) {
return a.localeCompare(b);
});
return props;
},
/**
* Generate the diff and verify that it matches a JSON path
*/
generateDiff: function (config1, path1, config2, path2, /*String*/ msg, type) {
if (path1 !== jdd.SEPARATOR && path1.charAt(path1.length - 1) === jdd.SEPARATOR) {
path1 = path1.substring(0, path1.length - 1);
}
if (path2 !== jdd.SEPARATOR && path2.charAt(path2.length - 1) === jdd.SEPARATOR) {
path2 = path2.substring(0, path2.length - 1);
}
var pathObj1 = config1.paths.find(function (path) {
return path.path === path1;
});
var pathObj2 = config2.paths.find(function (path) {
return path.path === path2;
});
if (!pathObj1) {
throw 'Unable to find line number for (' + msg + '): ' + path1;
}
if (!pathObj2) {
throw 'Unable to find line number for (' + msg + '): ' + path2;
}
return {
path1: pathObj1,
path2: pathObj2,
type: type,
msg: msg
};
},
/**
* Get the current indent level
*/
getTabs: function (/*int*/ indent) {
var s = '';
for (var i = 0; i < indent; i++) {
s += ' ';
}
return s;
},
/**
* Remove the trailing comma from the output.
*/
removeTrailingComma: function (config) {
/*
* Remove the trailing comma
*/
if (config.out.charAt(config.out.length - 1) === ',') {
config.out = config.out.substring(0, config.out.length - 1);
}
},
/**
* Create a config object for holding differences
*/
createConfig: function () {
return {
out: '',
indent: -1,
currentPath: [],
paths: [],
line: 1
};
},
/**
* Format the output pre tags.
*/
formatPRETags: function () {
document.querySelectorAll('pre').forEach(function(pre) {
var lineNumbers = '<div class="gutter">';
var codeLines = '<div>';
// This is used to encode text as fast as possible
var lineDiv = document.createElement('div');
var lineText = document.createTextNode('');
lineDiv.appendChild(lineText);
var addLine = function (line, index) {
lineNumbers += '<span class="line-number">' + (index + 1) + '.</span>';
lineText.nodeValue = line;
codeLines +=
'<div class="codeLine line' +
(index + 1) +
'"><span class="code">' +
lineDiv.innerHTML +
'</span></div>';
};
var lines = pre.textContent.split('\n');
lines.forEach(addLine);
// Combine it all together
codeLines += '</div>';
lineNumbers += '</div>';
var codeBlockElement = '<pre id="'+ pre.id +'" class="codeBlock ' + pre.classList.toString() + '">' + lineNumbers + codeLines + '</pre>';
pre.outerHTML = codeBlockElement;
});
},
handleDiffClick: function (line, side) {
var diffs = jdd.diffs.filter(function (diff) {
if (side === jdd.LEFT) {
return line === diff.path1.line;
} else if (side === jdd.RIGHT) {
return line === diff.path2.line;
} else {
return line === diff.path1.line || line === diff.path2.line;
}
});
document.querySelectorAll('pre.left span.code').forEach(function(val) {
val.classList.remove('selected');
});
document.querySelectorAll('pre.right span.code').forEach(function(val) {
val.classList.remove('selected');
});
document.querySelector('ul.toolbar').replaceChildren();
diffs.forEach(function (diff) {
document.querySelector('pre.left div.line' + diff.path1.line + ' span.code').classList.add('selected');
document.querySelector('pre.right div.line' + diff.path2.line + ' span.code').classList.add('selected');
});
if (side === jdd.LEFT || side === jdd.RIGHT) {
jdd.currentDiff = jdd.diffs.findIndex(function (diff) {
return diff.path1.line === line;
});
}
if (jdd.currentDiff === -1) {
jdd.currentDiff = jdd.diffs.findIndex(function (diff) {
return diff.path2.line === line;
});
}
var buttons = '<div id="buttons">';
var prev = '<a href="#" title="Previous difference" id="prevButton" class="disabled"><</a>';
buttons += prev;
buttons += '<span id="prevNextLabel"></span>';
var next = '<a href="#" title="Next difference" id="nextButton">></a>';
buttons += next;
buttons += '<div>';
document.querySelector('ul.toolbar').insertAdjacentHTML('beforeend', buttons);
document.getElementById('prevButton').addEventListener('click', function (event) {
event.preventDefault();
jdd.highlightPrevDiff();
});
document.getElementById('nextButton').addEventListener('click', function (event) {
event.preventDefault();
jdd.highlightNextDiff();
});
jdd.updateButtonStyles();
jdd.showDiffDetails(diffs);
},
highlightPrevDiff: function () {
if (jdd.currentDiff > 0) {
jdd.currentDiff--;
jdd.highlightDiff(jdd.currentDiff);
jdd.scrollToDiff(jdd.diffs[jdd.currentDiff]);
jdd.updateButtonStyles();
}
},
highlightNextDiff: function () {
if (jdd.currentDiff < jdd.diffs.length - 1) {
jdd.currentDiff++;
jdd.highlightDiff(jdd.currentDiff);
jdd.scrollToDiff(jdd.diffs[jdd.currentDiff]);
jdd.updateButtonStyles();
}
},
updateButtonStyles: function () {
document.getElementById('prevButton').classList.remove('disabled');
document.getElementById('nextButton').classList.remove('disabled');
document.getElementById('prevNextLabel').textContent = (jdd.currentDiff + 1) + ' of ' + (jdd.diffs.length);
if (jdd.currentDiff === 1) {
document.getElementById('prevButton').classList.add('disabled');
} else if (jdd.currentDiff === jdd.diffs.length - 1) {
document.getElementById('nextButton').classList.add('disabled');
}
},
/**
* Highlight the diff at the specified index
*/
highlightDiff: function (index) {
jdd.handleDiffClick(jdd.diffs[index].path1.line, jdd.BOTH);
},
/**
* Show the details of the specified diff
*/
showDiffDetails: function (diffs) {
diffs.forEach(function (diff, index) {
var li = '<li>' + diff.msg + '</li>';
document.querySelector('ul.toolbar').insertAdjacentHTML('beforeend', li);
document.querySelectorAll('ul.toolbar li')[index].addEventListener('click', function(){
jdd.scrollToDiff(diff);
});
});
},
/**
* Scroll the specified diff to be visible
*/
scrollToDiff: function (diff) {
var elementOffsetTop= document.querySelector('pre.left div.line' + diff.path1.line + ' span.code').getBoundingClientRect().top + window.scrollY - document.documentElement.clientTop;
window.scrollTo({
'behavior': 'smooth',
'left': 0,
'top': elementOffsetTop
});
},
/**
* Process the specified diff
*/
processDiffs: function () {
var left = [];
var right = [];
// Cache the lines for fast lookup
var leftLineLookup = {};
var rightLineLookup = {};
// We can use the index to save lookup up the parents class
document.querySelectorAll('pre.left span.code').forEach(function(val, index) {
leftLineLookup[index + 1] = val;
});
document.querySelectorAll('pre.right span.code').forEach(function(val, index) {
rightLineLookup[index + 1] = val;
});
jdd.diffs.forEach(function (diff) {
leftLineLookup[diff.path1.line].classList.add(diff.type, 'diff');
if (left.indexOf(diff.path1.line) === -1) {
leftLineLookup[diff.path1.line].addEventListener('click', function () {
jdd.handleDiffClick(diff.path1.line, jdd.LEFT);
});
left.push(diff.path1.line);
}
rightLineLookup[diff.path2.line].classList.add(diff.type, 'diff');
if (right.indexOf(diff.path2.line) === -1) {
rightLineLookup[diff.path2.line].addEventListener('click', function () {
jdd.handleDiffClick(diff.path2.line, jdd.RIGHT);
});
right.push(diff.path2.line);
}
});
jdd.diffs = jdd.diffs.sort(function (a, b) {
return a.path1.line - b.path1.line;
});
},
/**
* Validate the input against the JSON parser
*/
validateInput: function (json, side) {
try {
jsl.parser.parse(json);
if (side === jdd.LEFT) {
document.getElementById('errorLeft').replaceChildren();
document.getElementById('errorLeft').style.display='none';
document.getElementById('textarealeft').classList.remove('error');
} else {
document.getElementById('errorRight').replaceChildren();
document.getElementById('errorRight').style.display='none';
document.getElementById('textarearight').classList.remove('error');
}
return true;
} catch (parseException) {
if (side === jdd.LEFT) {
document.getElementById('errorLeft').textContent = parseException.message;
document.getElementById('errorLeft').style.display='block';
document.getElementById('textarealeft').classList.add('error');
} else {
document.getElementById('errorRight').textContent = parseException.message;
document.getElementById('errorRight').style.display='block';
document.getElementById('textarearight').classList.add('error');
}
return false;
}
},
/**
* Handle the file uploads
*/
handleFiles: function (files, side) {
var reader = new FileReader();
reader.onload = (function () {
return function (event) {
if (side === jdd.LEFT) {
document.getElementById('textarealeft').value = event.target.result;
} else {
document.getElementById('textarearight').value = event.target.result;
}
};
})(files[0]);
reader.readAsText(files[0]);
},
setupNewDiff: function () {
document.querySelector('.initContainer').style.display = 'block';
document.querySelector('.diffcontainer').style.display = 'none';
document.querySelectorAll('.diffcontainer pre').forEach(function (elem) {
elem.replaceChildren();
});
document.querySelector('.toolbar').replaceChildren();
},
/**
* Generate the report section with the diff
*/
generateReport: function () {
var report = document.getElementById('report');
report.replaceChildren();
report.insertAdjacentHTML('beforeend', '<button>Perform a new diff</button>');
// TODO: add a class/id name to button and use that to select and add event
report.querySelector('button').addEventListener('click', function () {
jdd.setupNewDiff();
});
if (jdd.diffs.length === 0) {
report.insertAdjacentHTML('beforeend', '<span>The two files were semantically identical.</span>');
return;
}
var typeCount = 0;
var eqCount = 0;
var missingCount = 0;
jdd.diffs.forEach(function (diff) {
if (diff.type === jdd.EQUALITY) {
eqCount++;
} else if (diff.type === jdd.MISSING) {
missingCount++;
} else if (diff.type === jdd.TYPE) {
typeCount++;
}
});
var title = '<div class="reportTitle">Found ' + jdd.diffs.length + ' difference';
if (jdd.diffs.length > 1) {
title += 's';
}
title += '</div>';
report.insertAdjacentHTML('afterbegin', title);
var filterBlock = '<span class="filterBlock">Show:';
/*
* The missing checkbox
*/
if (missingCount > 0) {
var missing = '<label><input id="showMissing" type="checkbox" name="checkbox" value="value" checked="true">' + missingCount;
if (missingCount === 1) {
missing += ' missing property';
} else {
missing += ' missing properties';
}
filterBlock += missing + '</label>';
}
/*
* The types checkbox
*/
if (typeCount > 0) {
var types = '<label><input id="showTypes" type="checkbox" name="checkbox" value="value" checked="true">' + typeCount + ' incorrect type';
if (typeCount > 1) {
types += 's';
}
filterBlock += types + '</label>';
}
/*
* The equals checkbox
*/
if (eqCount > 0) {
var eq = '<label><input id="showEq" type="checkbox" name="checkbox" value="value" checked="true">' + eqCount + ' unequal value';
if (eqCount > 1) {
eq += 's';
}
filterBlock += eq + '</label>';
}
filterBlock += '</span>';
report.insertAdjacentHTML('beforeend', filterBlock);
// The missing checkbox event
if (missingCount > 0) {
document.querySelector('#showMissing').addEventListener('change', function (event) {
if (!event.target.checked) {
document.querySelectorAll('span.code.diff.missing').forEach(function (element) {
element.classList.toggle('missing_off');
element.classList.toggle('missing');
});
} else {
document.querySelectorAll('span.code.diff.missing_off').forEach(function (element) {
element.classList.toggle('missing');
element.classList.toggle('missing_off');
});
}
});
}
// The types checkbox event
if (typeCount > 0) {
document.querySelector('#showTypes').addEventListener('change', function (event) {
if (!event.target.checked) {
document.querySelectorAll('span.code.diff.type').forEach(function (element) {
element.classList.toggle('type_off');
element.classList.toggle('type');
});
} else {
document.querySelectorAll('span.code.diff.type_off').forEach(function (element) {
element.classList.toggle('type');
element.classList.toggle('type_off');
});
}
});
}
// The equals checkbox event
if (eqCount > 0) {
document.querySelector('#showEq').addEventListener('change', function(event){
if (!event.target.checked) {
document.querySelectorAll('span.code.diff.eq').forEach(function (element) {
element.classList.toggle('eq_off');
element.classList.toggle('eq');
});
} else {
document.querySelectorAll('span.code.diff.eq_off').forEach(function (element) {
element.classList.toggle('eq');
element.classList.toggle('eq_off');
});
}
});
}
},
/**
* Implement the compare button and complete the compare process
*/
compare: function () {
if (jdd.requestCount !== 0) {
/*
* This means we have a pending request and we just need to wait for that to finish.
*/
return;
}
document.body.classList.add('progress');
document.getElementById('compare').disabled = true;
jdd.diffs = [];
var loadUrl = function (id, errId) {
if (document.getElementById(id).value.trim().substring(0, 4).toLowerCase() === 'http') {
jdd.requestCount++;