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