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