-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiffer.js
1731 lines (1534 loc) · 59.1 KB
/
differ.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
// A utility to draw and compare Tangram maps.
// Uses Vladimir Agafonkin's pixelmatch: https://github.com/mapbox/pixelmatch
// (c) 2016-2018 Peter Richardson, MIT license
// "use strict";
/*jslint browser: true*/
/*global Tangram */
//
// initialize variables
//
// set preferences
var imgType = ".png";
var size = 250; // physical pixels
var writeScreenshots = false; // write new map images to disk?
var defaultFile = "tests/default.json"; // default view locations
// var defaultFile = "tests/default-coordinate.json"; // default view locations
document.getElementById("content").style.maxWidth = size*4+'px';
// other internal variables
var slots = {}, images = {},
diffImg = new Image(), diffData, diffCanvas, diffCtx,
slot1depth = {val: 0},
slot2depth = {val: 0};
var slot1tests = {tests: []},
slot2tests = {tests: []};
var lsize = size * window.devicePixelRatio; // logical pixels
var numTests, scores = [], totalScore = 0;
var data, metadata;
var startTime, loadTime = Date();
var defaultScene = "simple.yaml";
var defaultWarning = false;
var running = false;
// shortcuts to elements
function get(id) {
return document.getElementById(id);
}
var slot1 = get("slot1");
var slot2 = get("slot2");
var library1 = get("library1");
var library2 = get("library2");
var useImages1 = get("useImages1");
var useImages2 = get("useImages2");
var tests = get("tests");
// two iframes to hold maps
var frame1 = {
'iframe': get("map1"),
'window': get("map1").contentWindow,
'document': get("map1").contentDocument
};
var frame2 = {
'iframe': get("map2"),
'window': get("map2").contentWindow,
'document': get("map2").contentDocument
};
frame1.iframe.style.height = size+"px";
frame1.iframe.style.width = size+"px";
frame2.iframe.style.height = size+"px";
frame2.iframe.style.width = size+"px";
// browser check
var ua = navigator.userAgent.toLowerCase();
var chrome = false;
var safari = false;
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
chrome = true;
} else {
safari = true;
}
}
// can only use saveButton if running on a local node server
if (window.location.hostname != "localhost" ) get('saveButton').setAttribute("style", "display:none");
//
// helper functions
//
// useragent.innerHTML = "useragent: "+navigator.userAgent+"<br>Device pixel ratio: "+window.devicePixelRatio;
// parse URL to check for test json passed in the query
// eg: http://localhost:8080/?test.json
// http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
return "";
}
function isPathAbsolute(path) {
return /^(?:\/|[a-z]+:\/\/)/.test(path);
}
// find query terms in the URL
function parseQuery() {
// test or yaml file?
var url = getQueryVariable("1");
if (url !== "") {
slot1.value = url;
}
url = getQueryVariable("2");
if (url !== "") {
slot2.value = url;
}
// tangram version
var lib = getQueryVariable("lib1");
if (lib !== "") {
library1.value = lib;
}
lib = getQueryVariable("lib2");
if (lib !== "") {
library2.value = lib;
}
// use prerendered images checkbox
var check = getQueryVariable("useimages1");
if (check) {
useImages1.checked = true;
}
check = getQueryVariable("useimages2");
if (check) {
useImages2.checked = true;
}
// start immediately
url = getQueryVariable("go");
if (url !== "") {
get('goButton').click();
}
}
// add text to the output div
function diffAdd(txt) {
setTimeout(function() {
get('alert').innerHTML += txt;
get('alert').scrollTop = get('alert').scrollHeight;
}, 50);
}
function diffSay(txt) {
diffAdd(txt+"<br>");
}
// convert github links to raw github files
function convertGithub(url) {
var a = document.createElement('a');
a.href = url;
if (a.hostname == "github.com") {
a.hostname = "raw.githubusercontent.com";
a.pathname = a.pathname.replace("/blob", "");
}
return a.href;
}
// handle enter key in filename input
function catchEnter(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') { // Enter pressed
get('goButton').click();
return false;
}
}
// split a URL string into pieces
function splitURL(url) {
if (typeof url == 'undefined') return 'undefined';
var dir = url.substring(0, url.lastIndexOf('/')) + "/";
var file = url.substring(url.lastIndexOf('/')+1, url.length);
var ext = url.substring(url.lastIndexOf('.')+1, url.length);
return {"dir" : dir, "file": file, "ext": ext};
}
// parse a URL
function parseURL(url) {
var parser = document.createElement('a');
parser.href = url;
return parser;
}
// load a file from a URL
function readTextFile(file, callback, errorback) {
var filename = splitURL(file).file;
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
try {
rawFile.open("GET", file, true);
} catch (e) {
console.error("Error opening file:", e);
}
rawFile.onreadystatechange = function() {
// readyState 4 = done
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
} else if (rawFile.readyState === 4 && rawFile.status == "404") {
console.error("404 – can't load file", file);
errorback("404 – can't load file "+ file);
} else if (rawFile.readyState === 4 && rawFile.status == "401") {
// diffSay("401 - can't load file <a href='"+file+"'>"+filename+"</a>");
console.error("401 – can't load file", file);
errorback("401 – can't load file "+ file);
diffSay("401 Not authorized to load the file: <a href='"+file+"'>"+filename+"</a>");
return false;
} else if (rawFile.readyState === 4) {
diffSay("Had trouble loading the file: <a href='"+file+"'>"+filename+"</a>");
if (parseURL.host == "github.com") {
diffSay("I notice you're trying to load a file from github, make sure you're using the \"raw\" file!");
}
errorback("Problem with "+ file);
return false;
}
};
rawFile.send(null);
}
// set URL in location bar
function updateURL() {
var parser = document.createElement('a');
parser.href = window.location;
var url = parser.pathname+"?1="+encodeURI(slot1.value)+"&2="+encodeURI(slot2.value)+"&lib1="+encodeURI(library1.value)+"&lib2="+encodeURI(library2.value)+(useImages1.checked ? "&useimages1" : "")+(useImages2.checked ? "&useimages2" : "")+"&go";
if (parser.origin+url+"&go" != window.location) {
var currentstate = history.state;
window.history.pushState(currentstate, "", url);
}
}
// get link for blob
function linkFromBlob(blob) {
var urlCreator = window.URL || window.webkitURL;
return urlCreator.createObjectURL( blob );
}
// update progress bar, remaining = number of tests left to do
function updateProgress(remaining) {
var percent = 100 - (remaining / numTests) * 100;
get('progressbar').setAttribute("style", "width:"+percent + "%");
get('progressbarTop').setAttribute("style", "width:"+percent + "%");
}
function setEither(var1, var2) {
if (typeof var1 == 'undefined' || typeof var2 == 'undefined') {
if (typeof var1 == 'undefined' && typeof var2 == 'undefined') {
return(null);
} else if (typeof var1 == 'undefined') {
var1 = var2;
} else if (typeof var2 == 'undefined') {
var2 = var1;
}
}
return [var1, var2];
}
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
// flash background color
function flashDone() {
var steps = 25;
for (var x = 1; x < steps; x++) {
setColorDelay(x, steps);
}
}
function setColorDelay(x, steps) {
var ms = 20; // delay between steps in ms
setTimeout(function() {
var step = 255 / steps;
var c = step * x;
var color = rgbToHex(parseInt(c), 255, parseInt(c));
document.body.style.background = color;
}, x * ms);
// reset to white
setTimeout(function() {
document.body.style.background = 'white';
}, ms * (steps + 1));
}
// first add raf shim
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// keep scroll at the bottom if already at the bottom
function scrollToY(scrollTargetY, speed, easing) {
// scrollTargetY: the target scrollY property of the window
// speed: time in pixels per second
// easing: easing equation to use
var scrollY = window.scrollY,
scrollTargetY = scrollTargetY || 0,
speed = speed || 2000,
easing = easing || 'easeOutSine',
currentTime = 0;
// min time .1, max time .8 seconds
var time = Math.max(0.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, 0.8));
// easing equations from https://github.com/danro/easing-js/blob/master/easing.js
var easingEquations = {
easeOutSine: function (pos) {
return Math.sin(pos * (Math.PI / 2));
},
easeInOutSine: function (pos) {
return (-0.5 * (Math.cos(Math.PI * pos) - 1));
},
easeInOutQuint: function (pos) {
if ((pos /= 0.5) < 1) {
return 0.5 * Math.pow(pos, 5);
}
return 0.5 * (Math.pow((pos - 2), 5) + 2);
}
};
// add animation loop
function tick() {
currentTime += 1 / 60;
var p = currentTime / time;
var t = easingEquations[easing](p);
if (p < 1) {
requestAnimFrame(tick);
window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
} else {
window.scrollTo(0, scrollTargetY);
}
}
// call it once to get started
tick();
}
//
// prep scene
//
function prepMap(which) {
return new Promise(function(resolve, reject) {
var frame = which.iframe;
var mapWindow = which.window;
// check that frame initialized
if (typeof mapWindow.map === 'undefined') {
diffSay("Couldn't load <a href='"+frame.src+"'>"+frame.src+"</a>");
stopClick();
}
// not sure why the others hit a race condition but this doesn't ಠ_ಠ
var map = frame.contentDocument.getElementById("map");
// var map = which['document'].getElementById("map");
// var map = which.document.getElementById("map");
map.style.height = size+"px";
map.style.width = size+"px";
// remove weird 2px border Leaflet adds to map when you resize it
mapWindow.map.invalidateSize();
resolve(mapWindow.map);
});
}
// parse url and load the appropriate file, then create tests
function loadFile(url, args) {
var useImages = args.useImages;
var depth = args.depth;
var tests = args.tests;
var scene = args.scene;
if (typeof depth == 'undefined') depth = {val: 0};
// increment depth value
depth.val++;
return new Promise(function(resolve, reject) {
if (url === "") {
throw new Error("Empty slot.");
reject();
}
var originalurl = url.slice();
// if it's a github url, get the raw file
url = convertGithub(url);
var urlname = splitURL(url).file;
var urlext = splitURL(url).ext;
// populate slots array
var slot = {};
slot.originalurl = originalurl;
slot.url = url;
slot.dir = splitURL(url).dir;
slot.file = urlname;
if (typeof slot.tests === 'undefined') slot.tests = [];
if (typeof tests === 'undefined') tests = {};
if (typeof tests.tests === 'undefined') tests.tests = [];
if (urlext == "yaml" || urlext == "zip") {
slot.defaultScene = url;
// set a global default scene
defaultScene = url;
// decrement depth value
depth.val--;
if (depth.val === 0) {
// resolving with a yaml
defaultScene = url;
resolve(slot);
}
} else if (urlext == "json") {
// load and parse test json
try {
readTextFile(url, function(text){
try {
data = JSON.parse(text);
} catch(e) {
console.warn('Error parsing json:', e);
// set page title
diffSay("Can't parse JSON: <a href='"+url+"'>"+urlname+"</a><br>"+e);
return stopClick();
}
// extract test origin metadata
try {
metadata = data.origin;
} catch (e) {
diffSay("Can't parse JSON metadata: <a href='"+url+"'>"+urlname+"</a>");
console.warn('metadata problem, continuing', e);
}
// convert tests to an array for easier traversal
var newTests = Object.keys(data.tests).map(function (key) {
if (typeof data.tests[key].url === 'undefined') {
if (typeof scene !== 'undefined') data.tests[key].url = scene;
else {
if (!defaultWarning) {
diffSay("No scene specified, using "+defaultScene);
defaultWarning = true;
}
data.tests[key].url = defaultScene;
}
}
var r = new RegExp('^(?:[a-z]+:)?//', 'i');
var testUrl, slotUrl;
// if the test url is a json, load it recursively
if (data.tests[key].url.split('.').pop() == "json"){
testUrl = data.tests[key].url;
if (typeof tests != 'undefined') {
}
// if the test url is relative, prepend the parent's root directory
// test for relative urls
if (r.test(data.tests[key].url) === false ) {
// make sure there's only one slash at the join:
// remove any trailing slash from parent url
slotUrl = slot.dir.replace(/\/$/, "");
// remove any leading slash from test url
testUrl = testUrl.replace(/^\/|\/$/g, '');
// prepend slot.dir to path
testUrl = slotUrl + '/' + testUrl;
}
loadFile(testUrl, {useImages: false, depth: depth, tests: tests}).then(function(result) {
});
} else {
// add test's name as a property of the test
data.tests[key].name = key;
testUrl = data.tests[key].url;
// if the test url is relative, prepend the parent's root directory
// set full path of scene file
if (r.test(data.tests[key].url) === false ) {
// make sure there's only one slash at the join:
// remove any trailing slash from parent url
slotUrl = slot.dir.replace(/\/$/, "");
// remove any leading slash from test url
testUrl = testUrl.replace(/^\/|\/$/g, '');
// prepend slot.dir to path
data.tests[key].url = slot.dir + data.tests[key].url;
}
// if checkbox is checked
if (useImages) {
// add path of pre-rendered image to look for
data.tests[key].imageURL = slot.dir + data.tests[key].name + imgType;
}
return data.tests[key];
}
});
// add new tests to slot test list
tests.tests = tests.tests.concat(newTests);
depth.val--;
if (depth.val === 0) {
slot.tests = slot.tests.concat(tests.tests);
}
resolve(slot);
}, function(error) {
console.log('plobrem:', error);
reject(error);
});
} catch (err) {
if (typeof err == 'undefined') {
err = "File load failed.";
} else {
console.log('whups', err);
}
}
} else {
console.log("Unexpected filetype: "+url);
diffSay("Unexpected filetype: <a href='"+url+"'>"+urlname+"</a>");
reject();
}
}).catch(function(error) {
if (typeof error == 'undefined') error = "File load failed.";
throw error;
});
}
// copy locations from a collection
function copyTestsFrom(tests) {
var copy = [];
for (var i = 0; i < tests.length; i++) {
copy[i] = {};
if (typeof copy[i].location != 'undefined') copy[i].location = tests[i].location;
if (typeof copy[i].name != 'undefined') copy[i].name = tests[i].name;
}
return copy;
}
// load some default tests if none are provided
function loadDefaults(scene) {
return new Promise(function(resolve, reject) {
loadFile(defaultFile, {scene: scene}).then(function(result){
resolve(result.tests);
});
});
}
// make sure tests are ready, fill in any gaps
function prepTests() {
// clear stored images
images = {};
// copy required properties from one test if undefined in the other
return new Promise(function(resolve, reject) {
if ((typeof slots.slot1.tests == 'undefined' || slots.slot1.tests.length === 0) && (typeof slots.slot2.tests == 'undefined' || slots.slot2.tests.length === 0)) {
diffSay('No views defined in either test file, using default views in <a href="'+defaultFile+'">'+defaultFile+'</a>');
Promise.all([
loadDefaults(slots.slot1.url).then(function(val){
slots.slot1.tests = val;
}),
loadDefaults(slots.slot2.url).then(function(val){
slots.slot2.tests = val;
})
]).then(function(){
resolve();
});
} else if (typeof slots.slot1.tests == 'undefined' || slots.slot1.tests.length === 0) {
diffSay('Using views in '+slots.slot2.file+'.');
slots.slot1.tests = copyTestsFrom(slots.slot2.tests);
resolve();
} else if (typeof slots.slot2.tests == 'undefined' || slots.slot2.tests.length === 0) {
diffSay('Using views in '+slots.slot1.file+'.');
slots.slot2.tests = copyTestsFrom(slots.slot1.tests);
resolve();
} else {
resolve();
}
}).then(function(){
// convert any coordinates to locations
for (var s in slots) {
for (var t in slots[s].tests) {
var test = slots[s].tests[t];
if (typeof test.coordinate != 'undefined') {
test.location = parseCoordinate(test.coordinate)
delete test.coordinate;
}
}
}
return;
}).then(function(){
// count tests
if (slots.slot1.tests.length != slots.slot2.tests.length) {
numTests = Math.min(slots.slot1.tests.length, slots.slot2.tests.length);
diffSay("Note: The two tests have a different number of views.");
} else {
numTests = slots.slot1.tests.length;
}
return;
});
}
// setup output divs and canvases, and wire up connections to differ code
function prepPage() {
if (typeof frame1.window.scene == 'undefined') {
throw new Error("Frame 1 failed to load, check library url: \""+library1.value+"\"");
}
if (typeof frame2.window.scene == 'undefined') {
throw new Error("Frame 2 failed to load, check library url: \""+library2.value+"\"");
}
// subscribe to Tangram's published view_complete event
frame1.window.scene.subscribe({
// trigger promise resolution
view_complete: function () {
// console.log('frame1 view_complete triggered');
// call a function which resolves a promise
viewComplete1Resolve();
},
warning: function(e) {
console.log('frame1 scene warning:', e);
}
});
frame2.window.scene.subscribe({
view_complete: function () {
// console.log('frame2 view_complete triggered');
// call a function which resolves a promise
viewComplete2Resolve();
},
warning: function(e) {
console.log('frame2 scene warning:', e);
}
});
// reset view_complete triggers if the frames are still loading
if (frame1.window.scene.initialized !== true) {
resetViewComplete(frame1);
resetViewComplete(frame2);
}
// set status message
var msg = "Now diffing: <a href='"+slots.slot1.originalurl+"'>"+slots.slot1.file+"</a> vs. <a href='"+slots.slot2.originalurl+"'>"+slots.slot2.file+"</a><br>" + numTests + " tests:<br>";
get('statustext').innerHTML = msg;
// make diffing canvas
if (typeof diffCanvas != 'undefined') return; // if it already exists, skip the rest
diffCanvas = document.createElement('canvas');
diffCanvas.height = size;
diffCanvas.width = size;
diffCtx = diffCanvas.getContext('2d');
diffData = diffCtx.createImageData(size, size);
}
//
// test functions
//
// parse a location in a varity of formats and return a standardized [lon, lat, z]
function parseLocation(loc) {
if (Object.prototype.toString.call(loc) === '[object Array]') {
return loc; // no parsing needed
} else if (typeof(loc) === "string") {
// parse string location as array of floats
var location;
if (loc.indexOf(',') > 0 ) { // comma-delimited
// expect format: "lon,lat,z"
location = loc.split(/[ ,]+/);
} else if (loc.indexOf('/') > 0 ) { // slash-delimited
// expect format: "z/lon/lat"
location = loc.split(/[\/]+/);
location = [location[1], location[2], location[0]]; // re-order
}
try {
location = location.map(parseFloat);
} catch(e) {
// console.warn("Can't parse location:", loc);
throw new Error("Can't parse location:", ''+loc);
}
// return updated location
return location;
} else {
console.warn("Can't parse location:", ''+loc);
}
}
// parse a tile coordinate and return a standardized [lon, lat, z]
// tile coordinates: [z, x, y]
function parseCoordinate(coord) {
var location, coordinate;
// expect format: "z/lon/lat" or "z,lon,lat"
if (typeof(coord) === "string") {
if (coord.indexOf(',') > 0 ) { // comma-delimited
coordinate = coord.split(/[ ,]+/);
} else if (coord.indexOf('/') > 0 ) { // slash-delimited
coordinate = coord.split(/[\/]+/);
}
} else {
coordinate = coord.slice();
}
try {
coordinate = coordinate.map(parseFloat);
location = [tile2lat(coordinate[2], coordinate[0]), tile2long(coordinate[1], coordinate[0]), coordinate[0]]
location = location.map(parseFloat);
} catch(e) {
throw new Error("Can't parse coordinate:", ''+coord, e);
}
console.log('Coordinate:', coord, '=', location)
// return updated location
return location;
}
// convert tile coordinates to latlon
function tile2long(x,z) { return ((x+.5)/Math.pow(2,z)*360-180); }
function tile2lat(y,z) {
var n=Math.PI-2*Math.PI*(y+.5)/Math.pow(2,z);
return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
}
// load an image from a file
function loadImage (url) {
if (typeof url == 'undefined') {
return new Promise(function(resolve, reject) {reject();});
}
// console.log('loadImage:', url);
return new Promise(function(resolve, reject) {
// if (typeof url == "undefined") {
// return reject("image url undefined");
// }
var image = new Image();
// set up events
image.onload = function(r) {
return resolve(this);
};
image.onerror = function(e) {
return reject(url);
};
image.crossOrigin = 'anonymous';
url = convertGithub(url);
// force-refresh any local images with a cache-buster
if (url.slice(-4) == imgType) url += "?" + String(new Date().getTime()).slice(-5);
// try to load the image
image.src = url;
}).catch(function(error){
// console.warn("couldn't load image: "+error);
throw error;
});
}
// get image data object using a canvas
function imageData (img, canvas) {
return new Promise(function(resolve, reject) {
var context = canvas.getContext("2d");
// prep the canvas - prevent pixelmatch alpha bug
context.clearRect(0, 0, canvas.width, canvas.height);
// draw image to the canvas
context.drawImage(img,
0, 0, img.width, img.height,
0, 0, canvas.width, canvas.height);
// make the data available to pixelmatch
var data = context.getImageData(0, 0, size, size);
resolve(data);
}, function(err) {
console.warn('imageData err:', err);
data = null;
reject(data);
});
}
// capture the current tangram map
function screenshot (save, name, frame) {
// console.log(name, 'screenshot:')
var scene = frame.window.scene;
return scene.screenshot().then(function(data) {
// console.log(name, 'screenshot success:', data)
// save it to a file
if (save) saveImage(data.blob, name);
return loadImage(linkFromBlob( data.blob ));
}).catch(function(err){
// console.warn('screenshot fail:', err);
return Promise.reject();
});
}
// use Tangram's view_complete event to resolve a promise
var viewComplete1, viewComplete1Resolve, viewComplete1Reject;
var viewComplete2, viewComplete2Resolve, viewComplete2Reject;
// reset the triggers on the viewComplete events to wait for the next ones
function resetViewComplete(frame) {
if (frame.iframe.id == "map1") {
viewComplete1 = new Promise(function(resolve, reject){
viewComplete1Resolve = function(){
resolve();
};
viewComplete1Reject = function(e){
reject();
};
});
} else if (frame.iframe.id == "map2") {
viewComplete2 = new Promise(function(resolve, reject){
viewComplete2Resolve = function(){
resolve();
};
viewComplete2Reject = function(e){
reject();
};
});
}
}
var api_key = 'DtiDR_SqTwOtflSZielr2Q'; // nextzen tile key (dedicated for Differ use)
// load a map position and zoom
function loadView (view, location, frame) {
return new Promise(function(resolve, reject) {
if (!view) reject('no view');
// if (!view.url) reject('no view url');
// if (!view.location) reject('no view location');
// load and draw scene
var url = convertGithub(view.url);
// reset the view_complete triggers
resetViewComplete(frame);
var scene = frame.window.scene;
var map = frame.window.map;
scene.last_valid_config_source = null; // overriding a Tangram fail-safe
// ensure there's an api key
scene.subscribe({
load(event) {
// Modify the scene config object here. This mutates the original scene
// config object directly and will not be returned. Tangram does not expect
// the object to be passed back, and will render with the mutated object.
injectAPIKey(event.config, api_key);
// Force animation off for consistent testing
if (typeof event.config.scene != 'undefined') event.config.scene.animated = false;
// unsubscribe so it doesn't keep doing this
// may also need to be more specific about "scene"
scene.unsubscribe(this);
}
});
return scene.load(url).then(function(r) {
map.setView([location[0], location[1]], location[2], { animate: false});
// scene.requestRedraw(); // necessary? guess not
// set timeout timer in case something hangs
var timeout = setTimeout(function() {
diffSay(view.name+": timed out.");
console.log(view.name+": timed out");
resolve("timeout");
}, 6000);
// wait for map to finish drawing, then return
if (frame.iframe.id == "map1") {
return viewComplete1.then(function(){
// reset timeout
clearTimeout(timeout);
resolve();
}).catch(function(error) {
clearTimeout(timeout);
console.log('map1 scene load error');
reject(error);
});
} else if (frame.iframe.id == "map2") {
return viewComplete2.then(function(){
// reset timeout
clearTimeout(timeout);
resolve();
}).catch(function(error) {
clearTimeout(timeout);
console.log('map2 scene load error');
reject(error);
});
}
}).catch(function(error) {
// console.log('scene.load() error:', error)
reject(error);
});
});
}
// if url is a schemeless alphanumeric string, add a scheme
function ensureScheme(url) {
if (/[a-z]+/.test(url)) {
if (url.search(/^(http|https|data|blob):/) === -1) url = window.location.protocol + "//" + url;
}
return url;
}
// go time
function goClick() {
startTime = new Date().getTime();
// console.clear();
// reset progress bar
updateProgress(numTests);
get('alert').innerHTML = '';
diffSay("Starting Diff.");
get("goButton").blur();
// reset iframe promises
frame1Ready = new Promise(function(resolve, reject) {
frame1Loaded = resolve;
});
frame2Ready = new Promise(function(resolve, reject) {
frame2Loaded = resolve;
});
// check for schemes
library1.value = ensureScheme(library1.value);
library2.value = ensureScheme(library2.value);
slot1.value = ensureScheme(slot1.value);
slot2.value = ensureScheme(slot2.value);
updateURL();
// reload iframes with specified versions of Tangram
frame1.iframe.src = "map.html?url="+library1.value;
frame2.iframe.src = "map.html?url="+library2.value;
var buttonloc = get("goButton").offsetTop;
document.body.style.height = window.innerHeight + buttonloc - 50 + "px";
// scroll to stop button
scrollToY(getHeight() - window.innerHeight);
// clear out any existing tests
tests.innerHTML = "";
data = null;
metadata = null;
var slot1Val = slot1.value, slot2Val = slot2.value;
// make master list of tests for each slot, to be used in case of recursive jsons
slot1tests = {tests: []};
slot2tests = {tests: []};
// if one slot is empty, assume the value of the other
if (slot1.value === "" && slot2.value !== "") slot1Val = slot2.value;
if (slot2.value === "" && slot1.value !== "") slot2Val = slot1.value;
// load any files in the file inputs and parse their contents
return Promise.all([loadFile(slot1Val, {useImages: useImages1.checked, depth: slot1depth, tests: slot1tests}), loadFile(slot2Val, {useImages: useImages2.checked, depth: slot2depth, tests: slot2tests}), frame1Ready, frame2Ready]).then(function(result){
slots.slot1 = result[0];
slots.slot2 = result[1];
// removes nulls
function cleanArray(actual) {
var newArray = [];
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
// copy tests from the master lists and clean up
slots.slot1.tests = JSON.parse(JSON.stringify(cleanArray(slot1tests.tests)));
slots.slot2.tests = JSON.parse(JSON.stringify(cleanArray(slot2tests.tests)));
// sort to ensure test order matches between slots
slots.slot1.tests = sortByKey(slots.slot1.tests, "name");
slots.slot2.tests = sortByKey(slots.slot2.tests, "name");
get("goButton").setAttribute("style","display:none");
get("stopButton").setAttribute("style","display:inline");
get("stopButtonTop").setAttribute("style","display:inline");
proceed();
}).catch(function(err){
if (typeof err != "undefined") {
console.log(err);
diffSay(err);
}