Merge pull request #199 from witsa/master
[dygraphs.git] / plugins / range-selector.js
CommitLineData
0d216a60 1/**
41da6a86 2 * @license
ec475f44 3 * Copyright 2011 Paul Felix (paul.eric.felix@gmail.com)
41da6a86
DV
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
0cd1ad15 6/*global Dygraph:false,TouchEvent:false */
ccd9d7c2
PF
7
8/**
0d216a60 9 * @fileoverview This file contains the RangeSelector plugin used to provide
ccd9d7c2
PF
10 * a timeline range selector widget for dygraphs.
11 */
12
0d216a60
PF
13Dygraph.Plugins.RangeSelector = (function() {
14
758a629f
DV
15/*jshint globalstrict: true */
16/*global Dygraph:false */
c0f54d4f
DV
17"use strict";
18
ec475f44
PF
19// Range selector status values
20var NOT_CREATED = 0; // Range selector interface has not been created
21var CREATED = 1 << 0; // Range selector interface has been created
22var ADDED_TO_GRAPH = 1 << 1; // Range selector elements have been added to the graph
0d216a60
PF
23
24var rangeSelector = function() {
ccd9d7c2 25 this.isIE_ = /MSIE/.test(navigator.userAgent) && !window.opera;
73c5deff 26 this.hasTouchInterface_ = typeof(TouchEvent) != 'undefined';
0c76da8d 27 this.isMobileDevice_ = /mobile|android/gi.test(navigator.appVersion);
0d216a60
PF
28 this.status_ = NOT_CREATED;
29};
30
31rangeSelector.prototype.toString = function() {
32 return "RangeSelector Plugin";
33};
34
35rangeSelector.prototype.activate = function(dygraph) {
36 this.dygraph_ = dygraph;
ec475f44
PF
37 this.layout_ = dygraph.layout_;
38 this.graphDiv_ = dygraph.graphDiv;
0d216a60 39 this.isUsingExcanvas_ = dygraph.isUsingExcanvas_;
ec475f44 40 if (this.getOption_('showRangeSelector')) {
0d216a60
PF
41 this.createInterface_();
42 }
43 return {
44 layout: this.reserveSpace_,
45 predraw: this.renderStaticLayer_,
46 didDrawChart: this.renderInteractiveLayer_
47 };
48};
49
50rangeSelector.prototype.destroy = function() {
51 this.bgcanvas_ = null;
52 this.fgcanvas_ = null;
53 this.leftZoomHandle_ = null;
54 this.rightZoomHandle_ = null;
55 this.iePanOverlay_ = null;
56};
57
58//------------------------------------------------------------------
59// Private methods
60//------------------------------------------------------------------
61
ec475f44
PF
62rangeSelector.prototype.getOption_ = function(name) {
63 return this.dygraph_.getOption(name);
64};
65
66rangeSelector.prototype.setDefaultOption_ = function(name, value) {
67 return this.dygraph_.attrs_[name] = value;
0d216a60
PF
68};
69
70/**
71 * @private
72 * Creates the range selector elements and adds them to the graph.
73 */
74rangeSelector.prototype.createInterface_ = function() {
ccd9d7c2 75 this.createCanvases_();
920208fb
PF
76 if (this.isUsingExcanvas_) {
77 this.createIEPanOverlay_();
78 }
ccd9d7c2
PF
79 this.createZoomHandles_();
80 this.initInteraction_();
0d216a60
PF
81
82 // Range selector and animatedZooms have a bad interaction. See issue 359.
ec475f44
PF
83 if (this.getOption_('animatedZooms')) {
84 this.dygraph_.warn('Animated zooms and range selector are not compatible; disabling animatedZooms.');
85 this.dygraph_.updateOptions({animatedZooms: false}, true);
0d216a60
PF
86 }
87
88 this.addToGraph_();
89 this.status_ = CREATED;
ccd9d7c2
PF
90};
91
92/**
0d216a60
PF
93 * @private
94 * Adds the range selector to the graph.
ccd9d7c2 95 */
0d216a60 96rangeSelector.prototype.addToGraph_ = function() {
ec475f44 97 var graphDiv = this.graphDiv_;
ccd9d7c2
PF
98 graphDiv.appendChild(this.bgcanvas_);
99 graphDiv.appendChild(this.fgcanvas_);
100 graphDiv.appendChild(this.leftZoomHandle_);
101 graphDiv.appendChild(this.rightZoomHandle_);
0d216a60
PF
102 this.status_ |= ADDED_TO_GRAPH;
103};
104
105/**
106 * @private
107 * Removes the range selector from the graph.
108 */
109rangeSelector.prototype.removeFromGraph_ = function() {
ec475f44 110 var graphDiv = this.graphDiv_;
0d216a60
PF
111 graphDiv.removeChild(this.bgcanvas_);
112 graphDiv.removeChild(this.fgcanvas_);
113 graphDiv.removeChild(this.leftZoomHandle_);
114 graphDiv.removeChild(this.rightZoomHandle_);
115 this.status_ ^= ADDED_TO_GRAPH;
116};
117
118/**
119 * @private
120 * Called by Layout to allow range selector to reserve its space.
121 */
122rangeSelector.prototype.reserveSpace_ = function(e) {
ec475f44
PF
123 if (this.getOption_('showRangeSelector')) {
124 e.reserveSpaceBottom(this.getOption_('rangeSelectorHeight') + 4);
0d216a60 125 }
ccd9d7c2
PF
126};
127
128/**
0d216a60
PF
129 * @private
130 * Renders the static portion of the range selector at the predraw stage.
ccd9d7c2 131 */
0d216a60 132rangeSelector.prototype.renderStaticLayer_ = function() {
ec475f44 133 if (!this.updateInterfaceStatus_()) {
0d216a60
PF
134 return;
135 }
ccd9d7c2
PF
136 this.resize_();
137 this.drawStaticLayer_();
138};
139
140/**
0d216a60
PF
141 * @private
142 * Renders the interactive portion of the range selector after the chart has been drawn.
ccd9d7c2 143 */
0d216a60 144rangeSelector.prototype.renderInteractiveLayer_ = function() {
ec475f44 145 if (!this.updateInterfaceStatus_() || this.isChangingRange_) {
ccd9d7c2
PF
146 return;
147 }
ccd9d7c2
PF
148 this.placeZoomHandles_();
149 this.drawInteractiveLayer_();
150};
151
152/**
153 * @private
ec475f44 154 * Check to see if the range selector is enabled/disabled and update interface accordingly.
0d216a60 155 */
ec475f44
PF
156rangeSelector.prototype.updateInterfaceStatus_ = function() {
157 var enabled = this.getOption_('showRangeSelector');
0d216a60
PF
158 if (enabled) {
159 if (!(this.status_ & CREATED)) {
160 this.createInterface_();
161 } else if (!(this.status_ & ADDED_TO_GRAPH)) {
162 this.addToGraph_();
163 }
164 } else if (this.status_ & ADDED_TO_GRAPH) {
165 this.removeFromGraph_();
166 var dygraph = this.dygraph_;
167 setTimeout(function() { dygraph.width_ = 0; dygraph.resize(); }, 1);
168 }
169 return enabled;
83b0c192 170};
0d216a60
PF
171
172/**
173 * @private
ccd9d7c2
PF
174 * Resizes the range selector.
175 */
0d216a60 176rangeSelector.prototype.resize_ = function() {
920208fb 177 function setElementRect(canvas, rect) {
ccd9d7c2
PF
178 canvas.style.top = rect.y + 'px';
179 canvas.style.left = rect.x + 'px';
180 canvas.width = rect.w;
181 canvas.height = rect.h;
182 canvas.style.width = canvas.width + 'px'; // for IE
183 canvas.style.height = canvas.height + 'px'; // for IE
758a629f 184 }
ccd9d7c2 185
70be5ed1 186 var plotArea = this.layout_.getPlotArea();
ec475f44 187 var xAxisLabelHeight = this.getOption_('xAxisHeight') || (this.getOption_('axisLabelFontSize') + 2 * this.getOption_('axisTickSize'));
ccd9d7c2
PF
188 this.canvasRect_ = {
189 x: plotArea.x,
190 y: plotArea.y + plotArea.h + xAxisLabelHeight + 4,
191 w: plotArea.w,
ec475f44 192 h: this.getOption_('rangeSelectorHeight')
ccd9d7c2
PF
193 };
194
920208fb
PF
195 setElementRect(this.bgcanvas_, this.canvasRect_);
196 setElementRect(this.fgcanvas_, this.canvasRect_);
ccd9d7c2
PF
197};
198
ccd9d7c2
PF
199/**
200 * @private
201 * Creates the background and foreground canvases.
202 */
0d216a60 203rangeSelector.prototype.createCanvases_ = function() {
ccd9d7c2 204 this.bgcanvas_ = Dygraph.createCanvas();
88c4a47e 205 this.bgcanvas_.className = 'dygraph-rangesel-bgcanvas';
ccd9d7c2 206 this.bgcanvas_.style.position = 'absolute';
920208fb 207 this.bgcanvas_.style.zIndex = 9;
ccd9d7c2
PF
208 this.bgcanvas_ctx_ = Dygraph.getContext(this.bgcanvas_);
209
210 this.fgcanvas_ = Dygraph.createCanvas();
88c4a47e 211 this.fgcanvas_.className = 'dygraph-rangesel-fgcanvas';
ccd9d7c2 212 this.fgcanvas_.style.position = 'absolute';
920208fb 213 this.fgcanvas_.style.zIndex = 9;
ccd9d7c2
PF
214 this.fgcanvas_.style.cursor = 'default';
215 this.fgcanvas_ctx_ = Dygraph.getContext(this.fgcanvas_);
216};
217
218/**
219 * @private
920208fb
PF
220 * Creates overlay divs for IE/Excanvas so that mouse events are handled properly.
221 */
0d216a60 222rangeSelector.prototype.createIEPanOverlay_ = function() {
920208fb
PF
223 this.iePanOverlay_ = document.createElement("div");
224 this.iePanOverlay_.style.position = 'absolute';
225 this.iePanOverlay_.style.backgroundColor = 'white';
226 this.iePanOverlay_.style.filter = 'alpha(opacity=0)';
227 this.iePanOverlay_.style.display = 'none';
228 this.iePanOverlay_.style.cursor = 'move';
229 this.fgcanvas_.appendChild(this.iePanOverlay_);
230};
231
232/**
233 * @private
ccd9d7c2
PF
234 * Creates the zoom handle elements.
235 */
0d216a60 236rangeSelector.prototype.createZoomHandles_ = function() {
ccd9d7c2 237 var img = new Image();
88c4a47e 238 img.className = 'dygraph-rangesel-zoomhandle';
ccd9d7c2 239 img.style.position = 'absolute';
920208fb 240 img.style.zIndex = 10;
ccd9d7c2
PF
241 img.style.visibility = 'hidden'; // Initially hidden so they don't show up in the wrong place.
242 img.style.cursor = 'col-resize';
73c5deff 243
920208fb 244 if (/MSIE 7/.test(navigator.userAgent)) { // IE7 doesn't support embedded src data.
73c5deff
PF
245 img.width = 7;
246 img.height = 14;
247 img.style.backgroundColor = 'white';
248 img.style.border = '1px solid #333333'; // Just show box in IE7.
920208fb 249 } else {
73c5deff
PF
250 img.width = 9;
251 img.height = 16;
252 img.src = 'data:image/png;base64,' +
758a629f
DV
253'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAA' +
254'zwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENv' +
255'bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl' +
256'6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7s' +
257'qSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII=';
920208fb 258 }
ccd9d7c2 259
0c76da8d 260 if (this.isMobileDevice_) {
73c5deff
PF
261 img.width *= 2;
262 img.height *= 2;
263 }
264
ccd9d7c2
PF
265 this.leftZoomHandle_ = img;
266 this.rightZoomHandle_ = img.cloneNode(false);
267};
268
269/**
270 * @private
271 * Sets up the interaction for the range selector.
272 */
0d216a60 273rangeSelector.prototype.initInteraction_ = function() {
ccd9d7c2
PF
274 var self = this;
275 var topElem = this.isIE_ ? document : window;
276 var xLast = 0;
277 var handle = null;
278 var isZooming = false;
279 var isPanning = false;
73c5deff 280 var dynamic = !this.isMobileDevice_ && !this.isUsingExcanvas_;
ccd9d7c2 281
2bad4d92
DV
282 // We cover iframes during mouse interactions. See comments in
283 // dygraph-utils.js for more info on why this is a good idea.
284 var tarp = new Dygraph.IFrameTarp();
285
758a629f
DV
286 // functions, defined below. Defining them this way (rather than with
287 // "function foo() {...}" makes JSHint happy.
288 var toXDataWindow, onZoomStart, onZoom, onZoomEnd, doZoom, isMouseInPanZone,
0c76da8d 289 onPanStart, onPan, onPanEnd, doPan, onCanvasMouseMove, applyBrowserZoomLevel;
758a629f 290
73c5deff
PF
291 // Touch event functions
292 var onZoomHandleTouchEvent, onCanvasTouchEvent, addTouchEvents;
293
758a629f 294 toXDataWindow = function(zoomHandleStatus) {
ccd9d7c2
PF
295 var xDataLimits = self.dygraph_.xAxisExtremes();
296 var fact = (xDataLimits[1] - xDataLimits[0])/self.canvasRect_.w;
297 var xDataMin = xDataLimits[0] + (zoomHandleStatus.leftHandlePos - self.canvasRect_.x)*fact;
298 var xDataMax = xDataLimits[0] + (zoomHandleStatus.rightHandlePos - self.canvasRect_.x)*fact;
299 return [xDataMin, xDataMax];
300 };
301
0c76da8d
PF
302 applyBrowserZoomLevel = function(delX) {
303 var zoom = window.outerWidth/document.documentElement.clientWidth;
304 if (!isNaN(zoom)) {
305 return delX/zoom;
306 } else {
307 return delX;
308 }
309 };
310
758a629f 311 onZoomStart = function(e) {
ccd9d7c2
PF
312 Dygraph.cancelEvent(e);
313 isZooming = true;
314 xLast = e.screenX;
315 handle = e.target ? e.target : e.srcElement;
6a4587ac
RK
316 self.dygraph_.addEvent(topElem, 'mousemove', onZoom);
317 self.dygraph_.addEvent(topElem, 'mouseup', onZoomEnd);
ccd9d7c2 318 self.fgcanvas_.style.cursor = 'col-resize';
2bad4d92 319 tarp.cover();
0c76da8d 320 return true;
ccd9d7c2
PF
321 };
322
758a629f 323 onZoom = function(e) {
ccd9d7c2 324 if (!isZooming) {
0c76da8d 325 return false;
ccd9d7c2 326 }
0c76da8d 327 Dygraph.cancelEvent(e);
ccd9d7c2 328 var delX = e.screenX - xLast;
42a9ebb8
DV
329 if (Math.abs(delX) < 4 || e.screenX === 0) {
330 // First iPad move event seems to have screenX = 0
0c76da8d 331 return true;
ccd9d7c2
PF
332 }
333 xLast = e.screenX;
0c76da8d
PF
334 delX = applyBrowserZoomLevel(delX);
335
336 // Move handle.
ccd9d7c2 337 var zoomHandleStatus = self.getZoomHandleStatus_();
758a629f 338 var newPos;
ccd9d7c2 339 if (handle == self.leftZoomHandle_) {
758a629f 340 newPos = zoomHandleStatus.leftHandlePos + delX;
ccd9d7c2
PF
341 newPos = Math.min(newPos, zoomHandleStatus.rightHandlePos - handle.width - 3);
342 newPos = Math.max(newPos, self.canvasRect_.x);
343 } else {
758a629f 344 newPos = zoomHandleStatus.rightHandlePos + delX;
ccd9d7c2
PF
345 newPos = Math.min(newPos, self.canvasRect_.x + self.canvasRect_.w);
346 newPos = Math.max(newPos, zoomHandleStatus.leftHandlePos + handle.width + 3);
347 }
920208fb 348 var halfHandleWidth = handle.width/2;
ccd9d7c2
PF
349 handle.style.left = (newPos - halfHandleWidth) + 'px';
350 self.drawInteractiveLayer_();
351
352 // Zoom on the fly (if not using excanvas).
73c5deff 353 if (dynamic) {
ccd9d7c2
PF
354 doZoom();
355 }
0c76da8d 356 return true;
ccd9d7c2
PF
357 };
358
758a629f 359 onZoomEnd = function(e) {
ccd9d7c2 360 if (!isZooming) {
0c76da8d 361 return false;
ccd9d7c2
PF
362 }
363 isZooming = false;
2bad4d92 364 tarp.uncover();
ccd9d7c2
PF
365 Dygraph.removeEvent(topElem, 'mousemove', onZoom);
366 Dygraph.removeEvent(topElem, 'mouseup', onZoomEnd);
367 self.fgcanvas_.style.cursor = 'default';
368
369 // If using excanvas, Zoom now.
73c5deff 370 if (!dynamic) {
ccd9d7c2
PF
371 doZoom();
372 }
0c76da8d 373 return true;
ccd9d7c2
PF
374 };
375
758a629f 376 doZoom = function() {
ccd9d7c2
PF
377 try {
378 var zoomHandleStatus = self.getZoomHandleStatus_();
379 self.isChangingRange_ = true;
380 if (!zoomHandleStatus.isZoomed) {
e4f6e11a 381 self.dygraph_.resetZoom();
ccd9d7c2
PF
382 } else {
383 var xDataWindow = toXDataWindow(zoomHandleStatus);
384 self.dygraph_.doZoomXDates_(xDataWindow[0], xDataWindow[1]);
385 }
386 } finally {
387 self.isChangingRange_ = false;
388 }
389 };
390
758a629f 391 isMouseInPanZone = function(e) {
920208fb
PF
392 if (self.isUsingExcanvas_) {
393 return e.srcElement == self.iePanOverlay_;
394 } else {
73c5deff
PF
395 var rect = self.leftZoomHandle_.getBoundingClientRect();
396 var leftHandleClientX = rect.left + rect.width/2;
397 rect = self.rightZoomHandle_.getBoundingClientRect();
398 var rightHandleClientX = rect.left + rect.width/2;
399 return (e.clientX > leftHandleClientX && e.clientX < rightHandleClientX);
920208fb 400 }
ccd9d7c2
PF
401 };
402
758a629f 403 onPanStart = function(e) {
ccd9d7c2
PF
404 if (!isPanning && isMouseInPanZone(e) && self.getZoomHandleStatus_().isZoomed) {
405 Dygraph.cancelEvent(e);
406 isPanning = true;
407 xLast = e.screenX;
6a4587ac
RK
408 self.dygraph_.addEvent(topElem, 'mousemove', onPan);
409 self.dygraph_.addEvent(topElem, 'mouseup', onPanEnd);
0c76da8d 410 return true;
ccd9d7c2 411 }
0c76da8d 412 return false;
ccd9d7c2
PF
413 };
414
758a629f 415 onPan = function(e) {
ccd9d7c2 416 if (!isPanning) {
0c76da8d 417 return false;
ccd9d7c2 418 }
920208fb 419 Dygraph.cancelEvent(e);
ccd9d7c2
PF
420
421 var delX = e.screenX - xLast;
422 if (Math.abs(delX) < 4) {
0c76da8d 423 return true;
ccd9d7c2
PF
424 }
425 xLast = e.screenX;
0c76da8d 426 delX = applyBrowserZoomLevel(delX);
ccd9d7c2
PF
427
428 // Move range view
429 var zoomHandleStatus = self.getZoomHandleStatus_();
430 var leftHandlePos = zoomHandleStatus.leftHandlePos;
431 var rightHandlePos = zoomHandleStatus.rightHandlePos;
432 var rangeSize = rightHandlePos - leftHandlePos;
433 if (leftHandlePos + delX <= self.canvasRect_.x) {
434 leftHandlePos = self.canvasRect_.x;
435 rightHandlePos = leftHandlePos + rangeSize;
436 } else if (rightHandlePos + delX >= self.canvasRect_.x + self.canvasRect_.w) {
437 rightHandlePos = self.canvasRect_.x + self.canvasRect_.w;
438 leftHandlePos = rightHandlePos - rangeSize;
439 } else {
440 leftHandlePos += delX;
441 rightHandlePos += delX;
442 }
920208fb 443 var halfHandleWidth = self.leftZoomHandle_.width/2;
ccd9d7c2
PF
444 self.leftZoomHandle_.style.left = (leftHandlePos - halfHandleWidth) + 'px';
445 self.rightZoomHandle_.style.left = (rightHandlePos - halfHandleWidth) + 'px';
446 self.drawInteractiveLayer_();
447
448 // Do pan on the fly (if not using excanvas).
73c5deff 449 if (dynamic) {
ccd9d7c2
PF
450 doPan();
451 }
0c76da8d 452 return true;
ccd9d7c2
PF
453 };
454
758a629f 455 onPanEnd = function(e) {
ccd9d7c2 456 if (!isPanning) {
0c76da8d 457 return false;
ccd9d7c2
PF
458 }
459 isPanning = false;
460 Dygraph.removeEvent(topElem, 'mousemove', onPan);
461 Dygraph.removeEvent(topElem, 'mouseup', onPanEnd);
462 // If using excanvas, do pan now.
73c5deff 463 if (!dynamic) {
ccd9d7c2
PF
464 doPan();
465 }
0c76da8d 466 return true;
ccd9d7c2
PF
467 };
468
758a629f 469 doPan = function() {
ccd9d7c2
PF
470 try {
471 self.isChangingRange_ = true;
472 self.dygraph_.dateWindow_ = toXDataWindow(self.getZoomHandleStatus_());
473 self.dygraph_.drawGraph_(false);
474 } finally {
475 self.isChangingRange_ = false;
476 }
477 };
478
758a629f 479 onCanvasMouseMove = function(e) {
ccd9d7c2
PF
480 if (isZooming || isPanning) {
481 return;
482 }
483 var cursor = isMouseInPanZone(e) ? 'move' : 'default';
484 if (cursor != self.fgcanvas_.style.cursor) {
485 self.fgcanvas_.style.cursor = cursor;
486 }
487 };
488
73c5deff 489 onZoomHandleTouchEvent = function(e) {
0c76da8d
PF
490 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
491 if (onZoomStart(e.targetTouches[0])) {
492 Dygraph.cancelEvent(e);
493 }
494 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
495 if (onZoom(e.targetTouches[0])) {
496 Dygraph.cancelEvent(e);
497 }
73c5deff
PF
498 } else {
499 onZoomEnd(e);
500 }
501 };
502
503 onCanvasTouchEvent = function(e) {
0c76da8d
PF
504 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
505 if (onPanStart(e.targetTouches[0])) {
506 Dygraph.cancelEvent(e);
507 }
508 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
509 if (onPan(e.targetTouches[0])) {
510 Dygraph.cancelEvent(e);
511 }
73c5deff
PF
512 } else {
513 onPanEnd(e);
514 }
515 };
516
517 addTouchEvents = function(elem, fn) {
6a4587ac
RK
518 var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel'];
519 for (var i = 0; i < types.length; i++) {
520 self.dygraph_.addEvent(elem, types[i], fn);
521 }
73c5deff
PF
522 };
523
ec475f44
PF
524 this.setDefaultOption_('interactionModel', Dygraph.Interaction.dragIsPanInteractionModel);
525 this.setDefaultOption_('panEdgeFraction', 0.0001);
ccd9d7c2 526
920208fb 527 var dragStartEvent = window.opera ? 'mousedown' : 'dragstart';
6a4587ac
RK
528 this.dygraph_.addEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart);
529 this.dygraph_.addEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart);
920208fb
PF
530
531 if (this.isUsingExcanvas_) {
6a4587ac 532 this.dygraph_.addEvent(this.iePanOverlay_, 'mousedown', onPanStart);
920208fb 533 } else {
6a4587ac
RK
534 this.dygraph_.addEvent(this.fgcanvas_, 'mousedown', onPanStart);
535 this.dygraph_.addEvent(this.fgcanvas_, 'mousemove', onCanvasMouseMove);
920208fb 536 }
73c5deff
PF
537
538 // Touch events
539 if (this.hasTouchInterface_) {
540 addTouchEvents(this.leftZoomHandle_, onZoomHandleTouchEvent);
541 addTouchEvents(this.rightZoomHandle_, onZoomHandleTouchEvent);
542 addTouchEvents(this.fgcanvas_, onCanvasTouchEvent);
543 }
ccd9d7c2
PF
544};
545
546/**
547 * @private
548 * Draws the static layer in the background canvas.
549 */
0d216a60 550rangeSelector.prototype.drawStaticLayer_ = function() {
ccd9d7c2
PF
551 var ctx = this.bgcanvas_ctx_;
552 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
ccd9d7c2
PF
553 try {
554 this.drawMiniPlot_();
555 } catch(ex) {
5061b42f 556 Dygraph.warn(ex);
ccd9d7c2 557 }
920208fb 558
758a629f 559 var margin = 0.5;
920208fb
PF
560 this.bgcanvas_ctx_.lineWidth = 1;
561 ctx.strokeStyle = 'gray';
562 ctx.beginPath();
563 ctx.moveTo(margin, margin);
564 ctx.lineTo(margin, this.canvasRect_.h-margin);
565 ctx.lineTo(this.canvasRect_.w-margin, this.canvasRect_.h-margin);
566 ctx.lineTo(this.canvasRect_.w-margin, margin);
567 ctx.stroke();
ccd9d7c2
PF
568};
569
570
571/**
572 * @private
573 * Draws the mini plot in the background canvas.
574 */
0d216a60 575rangeSelector.prototype.drawMiniPlot_ = function() {
ec475f44
PF
576 var fillStyle = this.getOption_('rangeSelectorPlotFillColor');
577 var strokeStyle = this.getOption_('rangeSelectorPlotStrokeColor');
ccd9d7c2
PF
578 if (!fillStyle && !strokeStyle) {
579 return;
580 }
581
ec475f44 582 var stepPlot = this.getOption_('stepPlot');
e03d443c 583
ccd9d7c2
PF
584 var combinedSeriesData = this.computeCombinedSeriesAndLimits_();
585 var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin;
586
587 // Draw the mini plot.
588 var ctx = this.bgcanvas_ctx_;
758a629f 589 var margin = 0.5;
ccd9d7c2
PF
590
591 var xExtremes = this.dygraph_.xAxisExtremes();
592 var xRange = Math.max(xExtremes[1] - xExtremes[0], 1.e-30);
593 var xFact = (this.canvasRect_.w - margin)/xRange;
594 var yFact = (this.canvasRect_.h - margin)/yRange;
595 var canvasWidth = this.canvasRect_.w - margin;
596 var canvasHeight = this.canvasRect_.h - margin;
597
e03d443c
WB
598 var prevX = null, prevY = null;
599
ccd9d7c2
PF
600 ctx.beginPath();
601 ctx.moveTo(margin, canvasHeight);
602 for (var i = 0; i < combinedSeriesData.data.length; i++) {
603 var dataPoint = combinedSeriesData.data[i];
e03d443c
WB
604 var x = ((dataPoint[0] !== null) ? ((dataPoint[0] - xExtremes[0])*xFact) : NaN);
605 var y = ((dataPoint[1] !== null) ? (canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact) : NaN);
ccd9d7c2 606 if (isFinite(x) && isFinite(y)) {
e03d443c 607 if(prevX === null) {
87196f1b
WB
608 ctx.lineTo(x, canvasHeight);
609 }
610 else if (stepPlot) {
611 ctx.lineTo(x, prevY);
612 }
ccd9d7c2 613 ctx.lineTo(x, y);
e03d443c 614 prevX = x;
87196f1b 615 prevY = y;
ccd9d7c2 616 }
e03d443c 617 else {
87196f1b
WB
618 if(prevX !== null) {
619 if (stepPlot) {
620 ctx.lineTo(x, prevY);
621 ctx.lineTo(x, canvasHeight);
622 }
623 else {
624 ctx.lineTo(prevX, canvasHeight);
625 }
626 }
627 prevX = prevY = null;
628 }
ccd9d7c2
PF
629 }
630 ctx.lineTo(canvasWidth, canvasHeight);
631 ctx.closePath();
632
633 if (fillStyle) {
634 var lingrad = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, canvasHeight);
635 lingrad.addColorStop(0, 'white');
636 lingrad.addColorStop(1, fillStyle);
637 this.bgcanvas_ctx_.fillStyle = lingrad;
638 ctx.fill();
639 }
640
641 if (strokeStyle) {
642 this.bgcanvas_ctx_.strokeStyle = strokeStyle;
643 this.bgcanvas_ctx_.lineWidth = 1.5;
644 ctx.stroke();
645 }
646};
647
648/**
649 * @private
650 * Computes and returns the combinded series data along with min/max for the mini plot.
651 * @return {Object} An object containing combinded series array, ymin, ymax.
652 */
0d216a60 653rangeSelector.prototype.computeCombinedSeriesAndLimits_ = function() {
ccd9d7c2 654 var data = this.dygraph_.rawData_;
ec475f44 655 var logscale = this.getOption_('logscale');
ccd9d7c2
PF
656
657 // Create a combined series (average of all series values).
658 var combinedSeries = [];
659 var sum;
660 var count;
3810c27a 661 var mutipleValues;
758a629f 662 var i, j, k;
73c5deff 663 var xVal, yVal;
ccd9d7c2 664
3810c27a
PF
665 // Find out if data has multiple values per datapoint.
666 // Go to first data point that actually has values (see http://code.google.com/p/dygraphs/issues/detail?id=246)
667 for (i = 0; i < data.length; i++) {
73c5deff 668 if (data[i].length > 1 && data[i][1] !== null) {
3810c27a
PF
669 mutipleValues = typeof data[i][1] != 'number';
670 if (mutipleValues) {
671 sum = [];
672 count = [];
0826981a 673 for (k = 0; k < data[i][1].length; k++) {
3810c27a
PF
674 sum.push(0);
675 count.push(0);
676 }
677 }
678 break;
ccd9d7c2 679 }
ccd9d7c2
PF
680 }
681
758a629f 682 for (i = 0; i < data.length; i++) {
ccd9d7c2 683 var dataPoint = data[i];
73c5deff 684 xVal = dataPoint[0];
ccd9d7c2
PF
685
686 if (mutipleValues) {
758a629f 687 for (k = 0; k < sum.length; k++) {
ccd9d7c2
PF
688 sum[k] = count[k] = 0;
689 }
690 } else {
691 sum = count = 0;
692 }
693
758a629f 694 for (j = 1; j < dataPoint.length; j++) {
ccd9d7c2 695 if (this.dygraph_.visibility()[j-1]) {
73c5deff 696 var y;
ccd9d7c2 697 if (mutipleValues) {
758a629f
DV
698 for (k = 0; k < sum.length; k++) {
699 y = dataPoint[j][k];
700 if (y === null || isNaN(y)) continue;
ccd9d7c2
PF
701 sum[k] += y;
702 count[k]++;
703 }
704 } else {
758a629f
DV
705 y = dataPoint[j];
706 if (y === null || isNaN(y)) continue;
ccd9d7c2
PF
707 sum += y;
708 count++;
709 }
710 }
711 }
712
713 if (mutipleValues) {
758a629f 714 for (k = 0; k < sum.length; k++) {
ccd9d7c2
PF
715 sum[k] /= count[k];
716 }
717 yVal = sum.slice(0);
718 } else {
719 yVal = sum/count;
720 }
721
722 combinedSeries.push([xVal, yVal]);
723 }
724
725 // Account for roll period, fractions.
726 combinedSeries = this.dygraph_.rollingAverage(combinedSeries, this.dygraph_.rollPeriod_);
727
728 if (typeof combinedSeries[0][1] != 'number') {
758a629f
DV
729 for (i = 0; i < combinedSeries.length; i++) {
730 yVal = combinedSeries[i][1];
ccd9d7c2
PF
731 combinedSeries[i][1] = yVal[0];
732 }
733 }
734
735 // Compute the y range.
736 var yMin = Number.MAX_VALUE;
737 var yMax = -Number.MAX_VALUE;
758a629f
DV
738 for (i = 0; i < combinedSeries.length; i++) {
739 yVal = combinedSeries[i][1];
740 if (yVal !== null && isFinite(yVal) && (!logscale || yVal > 0)) {
ccd9d7c2
PF
741 yMin = Math.min(yMin, yVal);
742 yMax = Math.max(yMax, yVal);
743 }
744 }
745
746 // Convert Y data to log scale if needed.
747 // Also, expand the Y range to compress the mini plot a little.
758a629f 748 var extraPercent = 0.25;
ccd9d7c2
PF
749 if (logscale) {
750 yMax = Dygraph.log10(yMax);
751 yMax += yMax*extraPercent;
752 yMin = Dygraph.log10(yMin);
758a629f 753 for (i = 0; i < combinedSeries.length; i++) {
ccd9d7c2
PF
754 combinedSeries[i][1] = Dygraph.log10(combinedSeries[i][1]);
755 }
756 } else {
757 var yExtra;
5061b42f 758 var yRange = yMax - yMin;
ccd9d7c2
PF
759 if (yRange <= Number.MIN_VALUE) {
760 yExtra = yMax*extraPercent;
761 } else {
762 yExtra = yRange*extraPercent;
763 }
764 yMax += yExtra;
765 yMin -= yExtra;
766 }
767
768 return {data: combinedSeries, yMin: yMin, yMax: yMax};
769};
770
771/**
772 * @private
773 * Places the zoom handles in the proper position based on the current X data window.
774 */
0d216a60 775rangeSelector.prototype.placeZoomHandles_ = function() {
ccd9d7c2
PF
776 var xExtremes = this.dygraph_.xAxisExtremes();
777 var xWindowLimits = this.dygraph_.xAxisRange();
778 var xRange = xExtremes[1] - xExtremes[0];
779 var leftPercent = Math.max(0, (xWindowLimits[0] - xExtremes[0])/xRange);
780 var rightPercent = Math.max(0, (xExtremes[1] - xWindowLimits[1])/xRange);
781 var leftCoord = this.canvasRect_.x + this.canvasRect_.w*leftPercent;
782 var rightCoord = this.canvasRect_.x + this.canvasRect_.w*(1 - rightPercent);
920208fb
PF
783 var handleTop = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height)/2);
784 var halfHandleWidth = this.leftZoomHandle_.width/2;
785 this.leftZoomHandle_.style.left = (leftCoord - halfHandleWidth) + 'px';
ccd9d7c2 786 this.leftZoomHandle_.style.top = handleTop + 'px';
920208fb 787 this.rightZoomHandle_.style.left = (rightCoord - halfHandleWidth) + 'px';
ccd9d7c2
PF
788 this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top;
789
790 this.leftZoomHandle_.style.visibility = 'visible';
791 this.rightZoomHandle_.style.visibility = 'visible';
792};
793
794/**
795 * @private
796 * Draws the interactive layer in the foreground canvas.
797 */
0d216a60 798rangeSelector.prototype.drawInteractiveLayer_ = function() {
ccd9d7c2
PF
799 var ctx = this.fgcanvas_ctx_;
800 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
801 var margin = 1;
802 var width = this.canvasRect_.w - margin;
803 var height = this.canvasRect_.h - margin;
804 var zoomHandleStatus = this.getZoomHandleStatus_();
805
806 ctx.strokeStyle = 'black';
807 if (!zoomHandleStatus.isZoomed) {
808 ctx.beginPath();
809 ctx.moveTo(margin, margin);
810 ctx.lineTo(margin, height);
811 ctx.lineTo(width, height);
812 ctx.lineTo(width, margin);
813 ctx.stroke();
920208fb
PF
814 if (this.iePanOverlay_) {
815 this.iePanOverlay_.style.display = 'none';
816 }
ccd9d7c2 817 } else {
5061b42f
DV
818 var leftHandleCanvasPos = Math.max(margin, zoomHandleStatus.leftHandlePos - this.canvasRect_.x);
819 var rightHandleCanvasPos = Math.min(width, zoomHandleStatus.rightHandlePos - this.canvasRect_.x);
ccd9d7c2
PF
820
821 ctx.fillStyle = 'rgba(240, 240, 240, 0.6)';
920208fb
PF
822 ctx.fillRect(0, 0, leftHandleCanvasPos, this.canvasRect_.h);
823 ctx.fillRect(rightHandleCanvasPos, 0, this.canvasRect_.w - rightHandleCanvasPos, this.canvasRect_.h);
ccd9d7c2
PF
824
825 ctx.beginPath();
826 ctx.moveTo(margin, margin);
827 ctx.lineTo(leftHandleCanvasPos, margin);
828 ctx.lineTo(leftHandleCanvasPos, height);
829 ctx.lineTo(rightHandleCanvasPos, height);
830 ctx.lineTo(rightHandleCanvasPos, margin);
831 ctx.lineTo(width, margin);
832 ctx.stroke();
920208fb
PF
833
834 if (this.isUsingExcanvas_) {
835 this.iePanOverlay_.style.width = (rightHandleCanvasPos - leftHandleCanvasPos) + 'px';
836 this.iePanOverlay_.style.left = leftHandleCanvasPos + 'px';
837 this.iePanOverlay_.style.height = height + 'px';
838 this.iePanOverlay_.style.display = 'inline';
839 }
ccd9d7c2
PF
840 }
841};
842
843/**
844 * @private
845 * Returns the current zoom handle position information.
846 * @return {Object} The zoom handle status.
847 */
0d216a60 848rangeSelector.prototype.getZoomHandleStatus_ = function() {
920208fb 849 var halfHandleWidth = this.leftZoomHandle_.width/2;
088be40b
PF
850 var leftHandlePos = parseFloat(this.leftZoomHandle_.style.left) + halfHandleWidth;
851 var rightHandlePos = parseFloat(this.rightZoomHandle_.style.left) + halfHandleWidth;
ccd9d7c2
PF
852 return {
853 leftHandlePos: leftHandlePos,
854 rightHandlePos: rightHandlePos,
855 isZoomed: (leftHandlePos - 1 > this.canvasRect_.x || rightHandlePos + 1 < this.canvasRect_.x+this.canvasRect_.w)
856 };
857};
0d216a60
PF
858
859return rangeSelector;
860
861})();