-
Notifications
You must be signed in to change notification settings - Fork 1
/
javascript.js
629 lines (515 loc) · 18.5 KB
/
javascript.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
//_ Comments
// Invariants:
// - selectedColumn is the index of the closest earth rotation according to goalLongitude in selectedRow
// - on the UI the date shown is always nasaarray[selectedRow].d
// - on the UI the shown image is always the one pointed by selectedRow,selectedColumn in nasaarray
// nasaarray is a global variable coming from a javascript file that
// is loaded via script src before this file, this contains the data
// about the available images.
// Every item in nasaarray represents one day and is a dictionary of:
// n: the number of earth images (with different rotation) this day
// d: date
// i: list of image urls (size n)
// l: list of longitudes (size n)
// nasaarray is ordered ascending by d.
//_ Settings
var defaultGoalLongitude = -74; // starting value is America
//_ Global variables
// index in nasaarray[____]
var selectedRow = nasaarray.length - 1;
// index in nasaarray[selectedRow].{i,l}[____]
var selectedColumn;
// goal longitude of the user
var goalLongitude;
// avoids the usage of an unnecessary date library
var monthNames = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
// start debug with .../pd/debug_location
var debug_location = "";
// store download times in these
var ms_big_image = new DownloadTimeCollector("big_image", 30);
var ms_thumbnail = new DownloadTimeCollector("thumbnail", 50);
var ms_daily_concat = new DownloadTimeCollector("daily_concat", 10);
//_ nasaarray accessor functions
// given a row index, gives us the best column index in that row according to goalLongitude
function getColumnFromLongitude(row) {
trackJs.console.log({ "nasaarray.length": nasaarray.length,
"nasaarray[0]": nasaarray[0],
"row": row });
if (!nasaarray[row]) {
console.error("nasaarray[row] was null");
} else {
var longitudes = nasaarray[row].l;
var longitudeDistances = $.map(longitudes,
function(value) {
return Math.min(Math.abs(value - goalLongitude), 360 - Math.abs(value - goalLongitude));
});
return longitudeDistances.indexOf(Math.min.apply(null, longitudeDistances));
}
}
function getRowForDate(date) {
for (var i = nasaarray.length - 1; i >= 0; --i) {
if (nasaarray[i].d <= date) {
return i;
}
}
return 0;
}
//_ URL handling
function getImageURL(row, col, thumb) {
var date = nasaarray[row].d.split("-");
var imageName = nasaarray[row].i[col];
return 'https://nasa-kj58yy565gqqhv2gx.netdna-ssl.com/images/'
+ date[0] + '/' + date[1] + '/' + date[2] + '/' + imageName + (thumb ? '-thumb' : '') + '.jpg';
}
function getFullSizeImageURL(row, col) {
var date = nasaarray[row].d.split("-");
var imageName = nasaarray[row].i[col];
return 'https://epic.gsfc.nasa.gov/archive/natural/'
+ date[0] + '/' + date[1] + '/' + date[2] + '/png/' + imageName + '.png';
}
function getFullSizeImageName(row, col) {
var date = nasaarray[row].d.split("-");
var imageName = nasaarray[row].i[col];
return imageName + '.png';
}
function getRowURL(row) {
var date = nasaarray[row].d.split("-");
return 'https://nasa-kj58yy565gqqhv2gx.netdna-ssl.com/images/'
+ date[0] + '/' + date[1] + '/' + date[2] + '/' + nasaarray[row].d + '.jpg';
}
function noop() {}
var canvasSingleton = new (function CanvasSingleton() {
var canvasContext = null; // filled by document ready
this.setContext = (function(newContext) {
if (canvasContext) {
console.error("canvascontext supposed to be set only once at program start");
}
canvasContext = newContext;
}).bind(this);
this.displayImage = (function(imgEvent) {
canvasContext.clearRect(0, 0, 1024, 1024);
canvasContext.drawImage(imgEvent.target, 0, 0, 1024, 1024);
}).bind(this);
this.displayImagePart = (function(imgEvent, x, y, w, h) {
canvasContext.clearRect(0, 0, 1024, 1024);
canvasContext.drawImage(imgEvent.target, x, y, w, h, 0, 0, 1024, 1024);
}).bind(this);
});
function eventTypesArray(imageName) {
if (imageName.indexOf("thumb") > 0) {
return ms_thumbnail;
} else if (imageName.indexOf("epic_1b") > 0) {
return ms_big_image;
} else if ((imageName.indexOf("-") > 0) && (imageName.indexOf("jpg") > 0)) {
return ms_daily_concat;
} else {
console.error("Program error: There is no event type for image name: ", imageName);
}
}
function AsyncImage(onload) {
var self = this;
this.downloadStartTime = null;
// If we were to make this function a proper class function in
// prototype, then we would have to remember the onload parameter,
// because that is different for constructor call. Therefore it
// would not be a big speedup and it's just easier to declare a new
// onload function here for every instance.
this.onload = function (event) {
self._phase = "loaded";
var downloadEndTime = new Date().getTime();
var statisticsToPush = eventTypesArray(this.src);
statisticsToPush.addData(downloadEndTime - self.downloadStartTime);
trackJs.console.log({ "image name": this.src,
"download time (ms)": downloadEndTime - self.downloadStartTime });
onload(event);
};
this.img = null;
this._phase = "noimage";
}
AsyncImage.prototype.cancel = function() {
if (this.img) {
this.img.onload = noop;
this.img.onerror = noop;
this.img.src = "";
}
this._phase = "noimage";
this.img = null;
};
AsyncImage.prototype.onerror = function(event) {
console.error("Couldn't load image ", this.src);
};
AsyncImage.prototype.start = function(url, imgProps) {
if (this.img)
console.error("We can't start a new download before you cancel the previous one");
this._phase = "loading";
this.img = new Image();
if (imgProps) {
this.img.row = imgProps.row;
this.img.col = imgProps.col;
}
this.img.onload = this.onload;
this.img.onerror = this.onerror;
this.img.src = url;
this.downloadStartTime = new Date().getTime();
};
AsyncImage.prototype.getPhase = function() {
return this._phase;
};
var showImageSingleton = new (function ShowImageSingleton() {
var prevRow = null;
var prevCol = null;
var fullImage = new AsyncImage(canvasSingleton.displayImage);
var rowImage = new AsyncImage(noop);
var onThumbLoad = function(event) {
canvasSingleton.displayImage(event);
fullImage.start(getImageURL(event.target.row, event.target.col, false));
if (rowImage.getPhase() === "noimage") rowImage.start(getRowURL(event.target.row));
};
var thumbImage = new AsyncImage(onThumbLoad);
this.show = (function(row, col) {
var rowChanged = true;
if (row === prevRow && col === prevCol) return;
prevCol = col;
if (prevRow === row) rowChanged = false;
prevRow = row;
// cancel already inflight thumbnail
thumbImage.cancel();
// cancel already inflight full image
fullImage.cancel();
// cancel and forget already cached row if row changed
if (rowChanged) rowImage.cancel();
if (rowImage.getPhase() === "loaded") {
canvasSingleton.displayImagePart({ target: rowImage.img }, 0, col * 256, 256, 256);
fullImage.start(getImageURL(row, col, false));
} else {
thumbImage.start(getImageURL(row, col, true), { row: row, col: col });
}
}).bind(this);
});
function goodFormatDate(d) {
var date = d.split("-");
var month = date[1];
if (month.length == 1) month = "0" + month;
var day = date[2];
if (day.length == 1) day = "0" + day;
return date[0] + "-" + month + "-" + day;
}
function checkAndFormatDate(d) {
if (/^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/.test(d)) {
return goodFormatDate(d);
};
return false;
}
function isValidLongitude(l) {
return (l != "") && (!isNaN(l)) && (l <= 180) && (l >= -180);
}
function activateByURL(hash, replace) {
// remove the #
hash = hash.slice(1);
hashparts = hash.split("/");
// palebluedot.napszel.com/#2018-01-16/29/debug
if (hashparts[hashparts.length - 1] === "debug") {
hashparts.pop();
console.error("trackjs debug push");
}
// palebluedot.napszel.com/#2018-01-16/29/pd/debug_location
if (hashparts[hashparts.length - 2] === "pd") {
$("body").addClass("perfdebug");
debug_location = hashparts[hashparts.length - 1];
hashparts.pop();
hashparts.pop();
console.error("perf debug enabled with name '" + debug_location + "'");
}
// get the date part
var date = hashparts[0];
date = checkAndFormatDate(date);
if (!date) {
date = nasaarray[nasaarray.length - 1].d;
}
// get the longitude part
var stringLongitude = hashparts[hashparts.length-1];
var longitude = Number(stringLongitude);
if (!isValidLongitude(longitude)) {
longitude = defaultGoalLongitude;
}
selectedRow = getRowForDate(date);
goalLongitude = longitude;
gotoRow(selectedRow);
if (replace) {
replaceURL()
} else {
pushURL();
}
}
function generateTitle() {
return "~ Pale Blue Dot ~ " + nasaarray[selectedRow].d + "/" + goalLongitude;
}
function generateURL() {
if ((nasaarray[selectedRow].d == nasaarray[nasaarray.length - 1].d) && (goalLongitude == defaultGoalLongitude)) {
return window.location.pathname + "#" + "latest";
} else {
return window.location.pathname + "#" + nasaarray[selectedRow].d + "/" + goalLongitude;
}
}
function pushURL() {
document.title = generateTitle();
window.history.pushState(null, "", generateURL());
}
function replaceURL() {
document.title = generateTitle();
window.history.replaceState(null, "", generateURL());
}
//_ UI change
function highlightSelectedDot(col, row) {
// remove previously highlighted
$(".highlighted").removeClass("highlighted");
// add the new one
$("#dotContainer label:nth-of-type(" + (nasaarray[row].n - col) + ")").addClass('highlighted');
}
function gotoRow(newRow) {
selectedColumn = getColumnFromLongitude(newRow);
var date = nasaarray[newRow].d.split("-");
$("#dateLabel").text(date[0] + " " + monthNames[parseInt(date[1] - 1)] + " " + date[2]);
showImageSingleton.show(newRow, selectedColumn);
$("#dotContainer").empty();
for (var i = 0; i < nasaarray[newRow].n; i++) {
$("#dotContainer").append("<label class='dot clickable'>○</label>");
}
$('.dot').click(rotateEarthWithDotClick);
highlightSelectedDot(selectedColumn, newRow);
}
function rotateEarthWithDotClick(event) {
var indexOfDot = $('.dot').index(this);
selectedColumn = nasaarray[selectedRow].n - indexOfDot - 1;
gotoColumn(selectedColumn);
pushURL();
}
function gotoColumn(newColumn) {
goalLongitude = nasaarray[selectedRow].l[newColumn];
showImageSingleton.show(selectedRow, newColumn);
highlightSelectedDot(newColumn, selectedRow);
}
//_ Rotate Earth
// desktop dragdrop api -> rotateEarthAPI converter
var desktopDragToRotateEarthConverter = new (function DesktopDragToRotateEarthConverter() {
var mouseDragColumnWidth = 100; // user has to drag this many pixels with the mouse to start rotating Earth
var desktopHorizontalMouseAt = null;
this.start = (function(event) {
desktopHorizontalMouseAt = event.pageX;
}).bind(this);
this.move = (function(event) {
if (desktopHorizontalMouseAt == null) return;
rotateEarthAPI.move(Math.round((event.pageX - desktopHorizontalMouseAt) / mouseDragColumnWidth));
}).bind(this);
this.end = (function(event) {
desktopHorizontalMouseAt = null;
rotateEarthAPI.end();
}).bind(this);
});
// end of desktop dragdrop api -> rotateEarthAPI converter
// --- Rotate API
var rotateEarthAPI = new (function RotateEarthAPI() {
var newSelectedColumn = null;
this.move = (function(distance) {
var numberOfImagesThisRow = nasaarray[selectedRow].n;
newSelectedColumn = ((selectedColumn + distance) % numberOfImagesThisRow + numberOfImagesThisRow) % numberOfImagesThisRow;
gotoColumn(newSelectedColumn);
}).bind(this);
this.end = (function() {
selectedColumn = newSelectedColumn;
pushURL();
}).bind(this);
});
// --- End of Rotate API
//_ Scroll Earth
var scrollHistoryConverter = new (function ScrollHistoryConverter() {
var scrollEndDelay = 500; // once the user is idle, the scroll is "finished"
var scrollDistanceWithWheelDelta = 240; // Chrome returns a scroll distance with 'delta'
var scrollDistanceWithDetail = 2; // Firefox returns a scroll distance with 'detail'
var scrollDistance = 0; // Different mice return different distances, so we normalize them to get how many days to scroll
var scrollEnd = (function() {
historyAPI.end();
scrollDistance = 0;
}).bind(this);
var timerScrollEndDelayed = null;
var scrollEndDelayed = (function() {
if (timerScrollEndDelayed) {
clearTimeout(timerScrollEndDelayed);
timerScrollEndDelayed = null;
}
timerScrollEndDelayed = setTimeout(scrollEnd, scrollEndDelay);
}).bind(this);
this.scrollHandlerWithWheelDelta = (function(event) {
scrollDistance += event.originalEvent.wheelDelta;
scrollRound = scrollDistance / scrollDistanceWithWheelDelta;
scrollRound = scrollRound - scrollRound % 1;
historyAPI.move(scrollRound);
scrollEndDelayed();
}).bind(this);
this.scrollHandlerWithDetail = (function(event) {
scrollDistance += event.originalEvent.detail;
scrollRound = scrollDistance / scrollDistanceWithDetail;
scrollRound = scrollRound - scrollRound % 1;
historyAPI.move(-scrollRound);
scrollEndDelayed();
}).bind(this);
});
var historyAPI = new (function HistoryAPI() {
var newSelectedRow = null;
this.move = (function(distance) {
this.newSelectedRow = selectedRow + distance;
if (this.newSelectedRow < 0) this.newSelectedRow = 0;
if (this.newSelectedRow > nasaarray.length - 1) this.newSelectedRow = nasaarray.length - 1;
gotoRow(this.newSelectedRow);
}).bind(this);
this.end = (function() {
selectedRow = this.newSelectedRow;
pushURL();
}).bind(this);
});
//_ TouchLib
var ourTouchLib = new (function OurTouchLib() {
var fingerSwipeDistance = 40; // on mobile, user has to swipe this many pixels to start rotating Earth
var inTouch = false; // can be false, "inprogress", then "horizontal" or "vertical"
var baseX = null;
var baseY = null;
this.main = (function (handlers) {
return function(event) {
if (event.touches.length > 0) {
if (inTouch === false) {
inTouch = "inprogress";
baseX = event.touches[0].screenX;
baseY = event.touches[0].screenY;
}
if (inTouch === "inprogress") {
if (Math.abs(event.touches[0].screenX - baseX) > (fingerSwipeDistance / 2)) {
inTouch = "horizontal";
} else if (Math.abs(event.touches[0].screenY - baseY) > (fingerSwipeDistance / 2)) {
inTouch = "vertical";
}
}
if (inTouch === "horizontal") {
var move = Math.round((event.touches[0].screenX - baseX) / fingerSwipeDistance);
handlers.horizontalMove(move);
}
if (inTouch === "vertical") {
var move = Math.round((event.touches[0].screenY - baseY) / fingerSwipeDistance);
handlers.verticalMove(move);
}
}
// 0 means that no finger is touching the screen => swipe ended
if (event.touches.length === 0) {
var prevInTouch = inTouch;
inTouch = false;
baseX = null;
baseY = null;
if (prevInTouch === "horizontal") {
handlers.horizontalEnd();
return false;
}
if (prevInTouch === "vertical") {
handlers.verticalEnd();
return false;
}
}
// Allow default processing of clicks if they are not part of a valid swipe.
return true;
}
}).bind(this);
});
//_ Statistics reporting monitoring metrics
function DownloadTimeCollector(typeName, sendAfterNo) {
var self = this;
this.eventType = typeName;
this.download_times = [];
this.send_after_this_many = sendAfterNo;
}
DownloadTimeCollector.prototype.addData = function(data) {
this.download_times.push(data);
if (this.download_times.length >= this.send_after_this_many) {
this.download_times = [];
}
}
//_ Main
function absorbEvent(event) {
event.preventDefault();
return false;
}
function isTouchDevice() {
return 'ontouchstart' in window // works on most browsers
|| navigator.maxTouchPoints; // works on IE10/11 and Surface
};
$(document).ready(function () {
// used by showImageSingleton.show
canvasSingleton.setContext($("#targetImage")[0].getContext('2d'));
// Check if there is a specific path and load Earth accordingly
var startHash = window.location.hash;
if (!startHash) {
startHash = "#" + nasaarray[nasaarray.length-1].d + "/" + defaultGoalLongitude;
}
activateByURL(startHash, true);
// Catch path editing
window.onpopstate = function () {
activateByURL(window.location.hash, true);
};
// dragging horizontally with mouse
$("#imageContainer").mousedown(desktopDragToRotateEarthConverter.start);
$("#imageContainer").mousemove(desktopDragToRotateEarthConverter.move);
$("#imageContainer").mouseup(desktopDragToRotateEarthConverter.end);
// scrolling vertically with mouse
$(window).bind('mousewheel', scrollHistoryConverter.scrollHandlerWithWheelDelta);
$(window).bind('DOMMouseScroll', scrollHistoryConverter.scrollHandlerWithDetail);
// swiping vertically/horizontally with finger on mobile
imgs = $("#imageContainer").bind('touchstart touchend touchcancel touchmove',
ourTouchLib.main(
{
horizontalMove: rotateEarthAPI.move,
horizontalEnd: rotateEarthAPI.end,
verticalMove: historyAPI.move,
verticalEnd: historyAPI.end
}
));
// prevent image selection on mobile
var node = $('#targetImage')[0];
node.ontouchstart = absorbEvent;
node.ontouchmove = absorbEvent;
node.ontouchend = absorbEvent;
node.ontouchcancel = absorbEvent;
if (isTouchDevice()) {
$('#question-mark').hover(function() {
$('#help-question-mobile').toggle("slide");
});
} else {
$('#question-mark').hover(function() {
$('#help-question-desktop').toggle("slide");
});
}
// click icons
$('#dateLabel').click(function() {
activateByURL("#" + nasaarray[nasaarray.length-1].d + "/" + defaultGoalLongitude, false);
});
$('#satellite-icon').hover(function() {
$('#help-satellite').toggle("slide");
});
$('#dateUp').click(function() {
if (selectedRow < nasaarray.length - 1) {
activateByURL("#" + nasaarray[selectedRow + 1].d + "/" + goalLongitude, false);
}
});
$('#dateDown').click(function() {
if (selectedRow > 0) {
activateByURL("#" + nasaarray[selectedRow - 1].d + "/" + goalLongitude, false);
}
});
$('#downloadLink').hover(function() {
$("#downloadLink").attr("href", getFullSizeImageURL(selectedRow, selectedColumn));
$("#downloadLink").attr("download", getFullSizeImageName(selectedRow, selectedColumn));
});
});
//_ Emacs vars
// Local Variables:
// mode: javascript
// allout-layout: (0 :)
// eval: (allout-mode)
// End: