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