/
road.js
623 lines (578 loc) · 25.4 KB
/
road.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
(function() {
//variable local to function scope
function detectMobile() {
var userAgent = navigator.userAgent;
return /iPad/i.test(userAgent) || /iPhone/i.test(userAgent) || /android/i.test(userAgent);
}
var imageInfo = {};
var lanePositionInfo = {};
var nol;
var interval, speedDown = false, TOUCH_STATE = 0, TOUCH_Y;
var eventPlots = {};
var isMobile = detectMobile();
var stopTime = 1500; //1.5s by default. can be overriden by the value from configuration
var eventDialog = null;
function Road(canvasContainer, config) {
var canvas = this.initCanvas(canvasContainer);
this.height = canvas.height;
this.width = canvas.width;
this.context = canvas.getContext("2d");
this.config = config || {};
this.laneHeaders = config.laneHeaders || [];
nol = this.laneHeaders.length;
this.plots = config.plots || [];
this.topWidth = config.topWidth || (this.width/5);
this.eachPathWidth = this.width/nol;
this.eachTopPathWidth = this.topWidth/nol;
this.canvas = canvas;
stopTime = config.stopTime || stopTime;
/*
var config = {
laneHeaders: ["Lane 1", "Lane 2", "Lane 3", "Lane 4", "Lane 5"],
plots: [
{id: 1, date: "July 20, 2008", event: "", lane: 0 //lane index},
{id; 2, date: "Sep 16, 2010", event: "", lane: 1}, ...
]
};
*/
}
Road.prototype = {
initCanvas: function(container) {
var canvas = document.createElement("canvas");
canvas.className = "road";
canvas.id = "road";
canvas.height = container.offsetHeight;
canvas.width = container.offsetWidth;
container.appendChild(canvas);
return canvas;
},
create: function() {
//calculations
this.setScale();
this.drawRoad();
this.plotTheRoad();
this.createNavigator();
},
drawRoad: function() {
//create header div
var headers = document.createElement("div");
headers.className = "headers";
headers.style.width = this.canvas.offsetWidth + "px";
this.canvas.parentNode.appendChild(headers);
//assign colors
var rColors = {"true": "#eeeeee", "false": "#cccccc"};
var hColors = {"true": "#174662", "false": "#8BA2B0"};
var cIdx = true;
//calculate positions
var hHeight = parseInt(headers.offsetHeight);
var pHeight = this.height - hHeight;
var actualPHeight = pHeight - 1;
headers.style.top = (this.canvas.offsetTop + pHeight) + "px";
var xPos = 0, yPos = pHeight;
var topXPos = (this.width - this.topWidth)/2, topYPos = 0;
var t = (actualPHeight/2)/actualPHeight; //keep the formula as we can change the t value for better curve
//the bending angle of each path is proportional to the difference between xPos and topXPos
for (var idx = 0; idx < nol; idx++) {
var grd = this.context.createLinearGradient(xPos, actualPHeight, xPos + this.eachPathWidth, 0);
grd.addColorStop(0.05, rColors[cIdx]);
grd.addColorStop(0.95, "white");
this.context.fillStyle = rColors[cIdx]; //grd;
this.context.beginPath();
this.context.moveTo(xPos, actualPHeight);
this.context.quadraticCurveTo(topXPos, actualPHeight/2, topXPos, topYPos);
this.context.lineTo(topXPos + this.eachTopPathWidth, topYPos);
this.context.quadraticCurveTo(topXPos + this.eachTopPathWidth, actualPHeight/2, xPos + this.eachPathWidth, actualPHeight);
this.context.lineTo(xPos, actualPHeight);
this.context.fill();
//draw header
this.context.fillStyle = hColors[cIdx];
this.context.fillRect(xPos, yPos, this.eachPathWidth, hHeight);
//create header div
var headerDiv = document.createElement("div");
headerDiv.className = "fLeft header";
headerDiv.style.width = this.eachPathWidth + "px";
headerDiv.style.height = hHeight + "px";
//write header text
headers.appendChild(headerDiv);
headerDiv.innerHTML = this.laneHeaders[idx];
lanePositionInfo[idx] = {};
lanePositionInfo[idx].bottomX1 = xPos;
lanePositionInfo[idx].topX1 = topXPos;
//see how the curve is formed
/*for (var k = 0; k <= 1;) {
var firstCurve = calculateCurvePoint(k, {x:xPos, y:0},
{x:topXPos, y:actualPHeight/2},
{x:topXPos, y:actualPHeight});
var secondCurve = calculateCurvePoint(k, {x:xPos + this.eachPathWidth, y:0},
{x:topXPos + this.eachTopPathWidth, y:actualPHeight/2},
{x:topXPos + this.eachTopPathWidth, y:actualPHeight});
this.context.fillStyle = "black";
this.context.fillRect(firstCurve.x, actualPHeight - firstCurve.y, 2, 2);
k += 0.005;
}*/
xPos += this.eachPathWidth;
topXPos += this.eachTopPathWidth;
cIdx = !cIdx;
lanePositionInfo[idx].bottomX2 = xPos;
lanePositionInfo[idx].topX2 = topXPos;
}
this.actualHeight = actualPHeight;
},
setScale: function() {
var scaleDiv = document.createElement("div");
scaleDiv.className = "scale";
this.canvas.parentNode.insertBefore(scaleDiv, this.canvas);
},
plotTheRoad: function() {
//create plot area div element
var plotAreaDiv = document.createElement("div");
plotAreaDiv.className = "plotArea";
applyStyle(plotAreaDiv, {
top: this.canvas.offsetTop + "px",
height: this.actualHeight + "px",
width: this.width + "px"
});
this.canvas.parentNode.appendChild(plotAreaDiv);
//set required constants on EventPlot
EventPlot.bottomPathWidth = this.eachPathWidth;
EventPlot.topPathWidth = this.eachTopPathWidth;
EventPlot.topX = (this.width - this.topWidth)/2;
this.plotArea = new PlotArea(plotAreaDiv, {
height: this.actualHeight,
width: this.width});
var idx = 0, len = this.plots.length;
var eventData, eventPlots = [], eventPlotsMap = {}, eventDateLong;
//analyse data
for (; idx < len; idx++) {
eventData = new Date(this.plots[idx].date);
eventDateLong = eventData.getTime();
if (eventPlotsMap[eventDateLong]) {
eventPlotsMap[eventDateLong].push(this.createEventPlot(this.plots[idx]));
} else {
eventPlotsMap[eventDateLong] = [this.createEventPlot(this.plots[idx])];
eventPlots.push(eventDateLong);
}
}
eventPlots.sort(function(a, b) {
return b - a; //descending
});
var endingYear = (new Date(eventPlots[0])).getFullYear();
var startingYear = (new Date(eventPlots[eventPlots.length - 1])).getFullYear();
var year = endingYear;
var plotElements;
len = eventPlots.length;
for (idx = 0; idx < len; idx++) {
plotElements = eventPlotsMap[eventPlots[idx]];
//later add divider also
if (plotElements[0].date.getFullYear() != year) {
this.plotArea.addPlotElement(new YearDivider(this.plotArea, {year: year, date: new Date("January 1," + year)}));
year = plotElements[0].date.getFullYear();
}
this.plotArea.addPlotElement(plotElements);
}
this.plotArea.addPlotElement(new YearDivider(this.plotArea, {year: startingYear, date: new Date("January 1," + startingYear)}));
this.plotArea.render(startingYear, endingYear);
this.addTouchEvents(plotAreaDiv);
},
createEventPlot: function(plotDetails) {
var eventPlot = new EventPlot(this.plotArea, plotDetails);
eventPlots[plotDetails.id] = eventPlot;
return eventPlot;
},
createNavigator: function() {
if (isMobile) return;
var me = this;
var navigator = document.createElement("div");
navigator.className = "navigator";
var upBtn = document.createElement("button");
upBtn.innerHTML = "Up";
var downBtn = document.createElement("button");
downBtn.innerHTML = "Down";
upBtn.addEventListener("mouseover", (function() {
runInTimer(me.plotArea, "moveUp");
}), false);
upBtn.addEventListener("mouseout", (function() {
me.plotArea.stopMoving();
}), false);
downBtn.addEventListener("mouseover", (function() {
runInTimer(me.plotArea, "moveDown");
}), false);
downBtn.addEventListener("mouseout", (function() {
me.plotArea.stopMoving();
}), false);
navigator.appendChild(upBtn);
navigator.appendChild(downBtn);
this.canvas.parentNode.appendChild(navigator);
},
addTouchEvents: function(element) {
if (isMobile) {
var me = this;
element.addEventListener("touchstart", function(event) {
if (event.targetTouches.length == 1) {
TOUCH_STATE = 1
me.plotarea.restoreMovingState();
TOUCH_Y = event.targetTouches[0].pageY;
}
}, false);
element.addEventListener("touchmove", function(event) {
if (event.targetTouches.length == 1) {
if(TOUCH_STATE == 1) {
TOUCH_STATE = 2;
runInTimer(me.plotArea, event.targetTouches[0].pageY > TOUCH_Y ? "moveDown" : "moveUp");
}
} else {
TOUCH_STATE = 0;
me.plotArea.stopMoving();
}
event.preventDefault();
event.stopPropagation();
}, false);
element.addEventListener("touchend", function(event) {
if (TOUCH_STATE == 2) {
TOUCH_STATE = 0;
me.plotArea.stopMoving();
}
}, false);
//prevent scrolling
document.body.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
}
}
}
function PlotArea(plotAreaDiv, config) {
this.area = plotAreaDiv;
this.height = this.currentHeight = config.height;
this.width = config.width;
this.plotElements = [];
this.firstPlotHeight = this.getFirstPlotHeight();
}
//TODO - make below constant as configs
PlotArea.moveConstant = PlotArea.constant = 5;
PlotArea.factorConstant = 0.73;
PlotArea.prototype = {
render: function(startingYear, endingYear) {
this.startingYear = startingYear;
this.endingYear = endingYear;
this._render(this.height, this.firstPlotHeight);
},
_render: function(height, firstLayerHeight) {
var currentYear = this.endingYear;
var currentDate;
var layerHeight = firstLayerHeight;
var currentAltitude = height;
for (var idx = 0, len = this.plotElements.length; idx < len; idx++) {
currentDate = this.plotElements[idx].date;
if (currentDate.getFullYear() != currentYear) {
var diff = currentYear - currentDate.getFullYear();
while( diff > 0) {
layerHeight *= PlotArea.factorConstant;
currentAltitude -= layerHeight;
diff--;
}
currentYear = currentDate.getFullYear();
}
this.plotElements[idx].setCurrentAltitude(currentAltitude);
this.plotElements[idx].render(currentAltitude, layerHeight);
}
},
_adjust: function(altitudeFunction) {
var factor = PlotArea.moveConstant;
var currentYear = this.endingYear;
var currentDate;
var layerHeight = this.firstPlotHeight;
var currentAltitude = this.currentHeight;
var altitude;
for (var idx = 0, len = this.plotElements.length; idx < len; idx++) {
currentDate = this.plotElements[idx].date;
if (currentDate.getFullYear() != currentYear) {
var diff = currentYear - currentDate.getFullYear();
while( diff > 0) {
factor *= PlotArea.factorConstant;
altitude = altitudeFunction(factor, this.plotElements[idx].getCurrentAltitude());
layerHeight = currentAltitude - altitude;
currentAltitude = altitude;
diff--;
}
currentYear = currentDate.getFullYear();
}
this.plotElements[idx].setCurrentAltitude(currentAltitude);
this.plotElements[idx].render(currentAltitude, layerHeight);
}
},
addPlotElement: function(plotElements) {
this.plotElements = this.plotElements.concat(plotElements);
},
appendChild: function(child) {
this.area.appendChild(child);
},
moveUp: function() {
this.currentHeight -= PlotArea.moveConstant;
this.firstPlotHeight = this.getFirstPlotHeight();
this._adjust(PlotArea_calculateAltitudeMoveUp);
this.controlSpeed();
},
moveDown: function() {
this.currentHeight += PlotArea.moveConstant;
this.firstPlotHeight = this.getFirstPlotHeight();
this._adjust(PlotArea_calculateAltitudeMoveDown);
this.controlSpeed();
},
controlSpeed: function() {
if (speedDown) {
PlotArea.moveConstant -= this.stopConstant;
}
if (PlotArea.moveConstant <= 0) {
this.restoreMovingState();
}
},
restoreMovingState: function() {
clearInterval(interval);
PlotArea.moveConstant = PlotArea.constant;
speedDown = false;
},
stopMoving: function() {
this.stopConstant = PlotArea.moveConstant/(stopTime/this.roundTime);
speedDown = true;
},
getFirstPlotHeight: function() {
return this.currentHeight/PlotArea.factorConstant - this.currentHeight;
}
};
function PlotArea_calculateAltitudeMoveUp(factor, currentAltitude) {
return currentAltitude - factor;
}
function PlotArea_calculateAltitudeMoveDown(factor, currentAltitude) {
return currentAltitude + factor;
}
function MovableElement(parentContainer, config) {
this.parentContainer = parentContainer;
this.config = config;
this.date = new Date(config.date);
this.totalHeight = this.parentContainer.height;
this.isRendered = false;
}
MovableElement.prototype = {
render: function() {},
adjustToHeight: function() {},
getFinalHeight: function() {},
setCurrentAltitude: function(currentAltitude) {
this.currentAltitude = currentAltitude;
},
getCurrentAltitude: function() {
return this.currentAltitude;
}
};
function EventPlot(parentContainer, config) {
MovableElement.call(this, parentContainer, config);
this.positionInfo = lanePositionInfo[this.config.lane - 1];
}
EventPlot.finalHeight = 80;
EventPlot.initialHeight = 10;
extend(EventPlot, MovableElement, {
render: function (baseTop, yearLength) {
var position = this._calculateLeftAndTop(baseTop, yearLength);
if (this.isRendered) {
calculateWidthFactor(this.image, this.element, position)();
} else {
var pDiv = document.createElement("div");
pDiv.className = "plotContainer";
pDiv.id = this.config.id;
var pImage = new Image();
var imgsrc = this.config.icon || "image/pin.png";
pDiv.appendChild(pImage);
pDiv.onmouseover = highlightEventPlot;
pDiv.onmouseout = removeHighlightEventPlot;
this.parentContainer.appendChild(pDiv);
pImage.src = imgsrc;
pImage.onload = calculateWidthFactor(pImage, pDiv, position);
this.element = pDiv;
this.image = pImage;
this.t = position.t;
this.isRendered = true;
}
},
_calculateLeftAndTop: function(baseTop, yearLength) {
var top = baseTop + (yearLength/12 * this.getDate().getMonth());
var t = 1 - (top/this.totalHeight);
var cp1 = this._calculateCP1(t);
var cp2 = this._calculateCP2(t);
var height = this._calculateHeight(top);
var xDiff = (cp2.x - cp1.x)/2;
return {left: cp1.x + xDiff, top: top, height: height, t: t};
},
_calculateHeight: function(top) {
return EventPlot.initialHeight + ((top/this.totalHeight)
* (EventPlot.finalHeight - EventPlot.initialHeight)) ;
},
_calculateCP1: function(t) {
return calculateCurvePoint(t, {x:this.positionInfo.bottomX1, y:0},
{x:this.positionInfo.topX1, y:this.totalHeight/2},
{x:this.positionInfo.topX1, y:this.totalHeight});
},
_calculateCP2: function(t) {
return calculateCurvePoint(t, {x:this.positionInfo.bottomX2, y:0},
{x:this.positionInfo.topX2, y:this.totalHeight/2},
{x:this.positionInfo.topX2, y:this.totalHeight});
},
getFinalHeight: function() {
return EventPlot.finalHeight;
},
getDate: function() {
return this.date;
}
});
function YearDivider(parentContainer, config) {
MovableElement.call(this, parentContainer, config);
this.year = config.year;
this.bottomX1 = lanePositionInfo[0].bottomX1;
this.bottomX2 = lanePositionInfo[nol-1].bottomX2;
this.topX1 = lanePositionInfo[0].topX1;
this.topX2 = lanePositionInfo[nol-1].topX2;
}
extend(YearDivider, MovableElement, {
render: function(baseTop) {
var position = this._calculateWidth(baseTop);
if (this.isRendered) {
} else {
var containerDiv = document.createElement("div");
var yDiv = document.createElement("div");
yDiv.className = "divider";
var tDiv = document.createElement("div");
tDiv.innerHTML = this.year;
tDiv.className = "dividerText";
containerDiv.appendChild(yDiv);
containerDiv.appendChild(tDiv);
this.parentContainer.appendChild(containerDiv);
this.divider = yDiv;
this.text = tDiv;
this.t = position.t;
this.isRendered = true;
}
applyStyle(this.divider, {
left: position.left + "px",
top: position.top + "px",
width: position.width + "px",
display: position.top < 0 ? "none" : ""
});
applyStyle(this.text, {
left: position.left + position.width + "px",
top: position.top + "px",
display: position.top < 0 ? "none" : ""
});
},
_calculateWidth: function(top) {
var t = 1 - (top/this.totalHeight);
var cp1 = this._calculateCP1(t);
var cp2 = this._calculateCP2(t);
return {left: cp1.x, top: top, width: cp2.x - cp1.x, t: t};
},
_calculateCP1: function(t) {
return calculateCurvePoint(t, {x:this.bottomX1, y:0},
{x:this.topX1, y: this.totalHeight/2},
{x: this.topX1, y: this.totalHeight});
},
_calculateCP2: function(t) {
return calculateCurvePoint(t, {x:this.bottomX2, y:0},
{x:this.topX2, y: this.totalHeight/2},
{x: this.topX2, y: this.totalHeight});
}
});
//common functions local to this function scope
function applyStyle(element, styles) {
for (var style in styles) {
element.style[style] = styles[style];
}
}
function calculateWidthFactor(image, div, position) {
return function() {
var widthFactor = imageInfo[image.src];
if (!imageInfo[image.src]) {
var height = image.offsetHeight;
var width = image.offsetWidth;
widthFactor = parseFloat(width/height);
imageInfo[image.src] = widthFactor;
}
image.height = position.height;
image.width = position.height * widthFactor;
applyStyle(div, {
height: position.height + "px",
width: position.height * widthFactor + "px",
top: position.top - position.height + "px",
left: position.left - (position.height * widthFactor/2) + "px",
display: position.top < 0 ? "none" : ""
});
}
}
function calculateCurvePoint(t, P0, P1, P2) {
var t1 = 1-t;
var tsq = t*t;
/* refer http://www.algorithmist.net/bezier2.html */
var Cx = (t1*t1*P0.x) + 2*t*t1*P1.x + (t*t*P2.x);
var Cy = (t1*t1*P0.y) + 2*t*t1*P1.y + (t*t*P2.y);
return {x: Cx, y: Cy};
}
function extend(childClass, parentClass, customObj) {
for (var member in parentClass.prototype) {
customObj[member] = customObj[member] || parentClass.prototype[member];
}
childClass.prototype = customObj;
}
function highlightEventPlot(evt) {
var div = evt.srcElement.parentNode;
var height = parseFloat(div.style.height) * 1.5;
var width = parseFloat(div.style.width) * 1.5;
applyStyle(div, {height: height, width: width});
div.firstChild.height = height;
div.firstChild.width = width;
var eventData = eventPlots[div.id].config;
createDialog(eventData.date, eventData.data, div.offsetLeft, div.offsetTop);
}
function removeHighlightEventPlot(evt) {
var div = evt.srcElement.parentNode;
var height = parseFloat(div.style.height) / 1.5;
var width = parseFloat(div.style.width) / 1.5;
applyStyle(div, {height: height, width: width});
div.firstChild.height = height;
div.firstChild.width = width;
hideDialog();
}
function createDialog(title, data, left, top) {
if (eventDialog == null) {
eventDialog = document.createElement("div");
eventDialog.className = "eventDialog";
var title = document.createElement("div");
title.className = "dialogTitle";
eventDialog.appendChild(title);
var dialogBody = document.createElement("div");
dialogBody.className = "dialogBody";
eventDialog.appendChild(dialogBody);
document.body.appendChild(eventDialog);
}
eventDialog.style.display = "block";
eventDialog.firstChild.innerHTML = title;
eventDialog.lastChild.innerHTML = data;
applyStyle(eventDialog, {
display: "block",
left: left + "px",
top: top + "px"
});
}
function hideDialog() {
if (eventDialog != null) {
applyStyle(eventDialog, {display: "none"});
}
}
function runInTimer(instance, callback) {
interval && clearInterval(interval);
//calculate time required for running a call
var startTime = new Date().getTime();
instance[callback]();
var endTime = new Date().getTime();
instance.roundTime = endTime - startTime;
interval = setInterval(function() {
instance[callback]();
}, 1000/60);
}
window.Road = Road;
})();