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